repo
stringclasses
1 value
instance_id
stringlengths
22
24
problem_statement
stringlengths
24
24.1k
patch
stringlengths
0
1.9M
test_patch
stringclasses
1 value
created_at
stringdate
2022-11-25 05:12:07
2025-10-09 08:44:51
hints_text
stringlengths
11
235k
base_commit
stringlengths
40
40
juspay/hyperswitch
juspay__hyperswitch-6165
Bug: [FIX] use batch encryption/decryption for payment intent table
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index bd4707243ce..562e5d205c0 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1,14 +1,14 @@ use common_enums as storage_enums; use common_utils::{ consts::{PAYMENTS_LIST_MAX_LIMIT_V1, PAYMENTS_LIST_MAX_LIMIT_V2}, - crypto::Encryptable, + crypto::{self, Encryptable}, encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii::{self, Email}, type_name, types::{ - keymanager::{self, KeyManagerState}, + keymanager::{self, KeyManagerState, ToEncryptable}, MinorUnit, }, }; @@ -17,6 +17,7 @@ use diesel_models::{ }; use error_stack::ResultExt; use masking::{Deserialize, PeekInterface, Secret}; +use rustc_hash::FxHashMap; use serde::Serialize; use time::PrimitiveDateTime; @@ -26,7 +27,7 @@ use super::PaymentIntent; use crate::{ behaviour, errors, merchant_key_store::MerchantKeyStore, - type_encryption::{crypto_operation, AsyncLift, CryptoOperation}, + type_encryption::{crypto_operation, CryptoOperation}, RemoteStorageObject, }; #[async_trait::async_trait] @@ -1568,17 +1569,25 @@ impl behaviour::Conversion for PaymentIntent { Self: Sized, { async { - let inner_decrypt = |inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }; + let decrypted_data = crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::BatchDecrypt(EncryptedPaymentIntentAddress::to_encryptable( + EncryptedPaymentIntentAddress { + billing: storage_model.billing_address, + shipping: storage_model.shipping_address, + customer_details: storage_model.customer_details, + }, + )), + key_manager_identifier, + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation())?; + + let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data) + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Invalid batch operation data")?; let amount_details = super::AmountDetails { order_amount: storage_model.amount, @@ -1628,18 +1637,9 @@ impl behaviour::Conversion for PaymentIntent { storage_model.request_external_three_ds_authentication, ), frm_metadata: storage_model.frm_metadata, - customer_details: storage_model - .customer_details - .async_lift(inner_decrypt) - .await?, - billing_address: storage_model - .billing_address - .async_lift(inner_decrypt) - .await?, - shipping_address: storage_model - .shipping_address - .async_lift(inner_decrypt) - .await?, + customer_details: data.customer_details, + billing_address: data.billing, + shipping_address: data.shipping, capture_method: storage_model.capture_method, id: storage_model.id, merchant_reference_id: storage_model.merchant_reference_id, @@ -1796,17 +1796,26 @@ impl behaviour::Conversion for PaymentIntent { Self: Sized, { async { - let inner_decrypt = |inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - key_manager_identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }; + let decrypted_data = crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::BatchDecrypt(EncryptedPaymentIntentAddress::to_encryptable( + EncryptedPaymentIntentAddress { + billing: storage_model.billing_details, + shipping: storage_model.shipping_details, + customer_details: storage_model.customer_details, + }, + )), + key_manager_identifier, + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation())?; + + let data = EncryptedPaymentIntentAddress::from_encryptable(decrypted_data) + .change_context(common_utils::errors::CryptoError::DecodingFailed) + .attach_printable("Invalid batch operation data")?; + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, @@ -1854,19 +1863,10 @@ impl behaviour::Conversion for PaymentIntent { frm_metadata: storage_model.frm_metadata, shipping_cost: storage_model.shipping_cost, tax_details: storage_model.tax_details, - customer_details: storage_model - .customer_details - .async_lift(inner_decrypt) - .await?, - billing_details: storage_model - .billing_details - .async_lift(inner_decrypt) - .await?, + customer_details: data.customer_details, + billing_details: data.billing, merchant_order_reference_id: storage_model.merchant_order_reference_id, - shipping_details: storage_model - .shipping_details - .async_lift(inner_decrypt) - .await?, + shipping_details: data.shipping, is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow, organization_id: storage_model.organization_id, skip_external_tax_calculation: storage_model.skip_external_tax_calculation, @@ -1935,3 +1935,73 @@ impl behaviour::Conversion for PaymentIntent { }) } } + +pub struct EncryptedPaymentIntentAddress { + pub shipping: Option<Encryption>, + pub billing: Option<Encryption>, + pub customer_details: Option<Encryption>, +} + +pub struct PaymentAddressFromRequest { + pub shipping: Option<Secret<serde_json::Value>>, + pub billing: Option<Secret<serde_json::Value>>, + pub customer_details: Option<Secret<serde_json::Value>>, +} + +pub struct DecryptedPaymentIntentAddress { + pub shipping: crypto::OptionalEncryptableValue, + pub billing: crypto::OptionalEncryptableValue, + pub customer_details: crypto::OptionalEncryptableValue, +} + +impl ToEncryptable<DecryptedPaymentIntentAddress, Secret<serde_json::Value>, Encryption> + for EncryptedPaymentIntentAddress +{ + fn from_encryptable( + mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, + ) -> CustomResult<DecryptedPaymentIntentAddress, common_utils::errors::ParsingError> { + Ok(DecryptedPaymentIntentAddress { + shipping: hashmap.remove("shipping"), + billing: hashmap.remove("billing"), + customer_details: hashmap.remove("customer_details"), + }) + } + + fn to_encryptable(self) -> FxHashMap<String, Encryption> { + let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); + + self.shipping.map(|s| map.insert("shipping".to_string(), s)); + self.billing.map(|s| map.insert("billing".to_string(), s)); + self.customer_details + .map(|s| map.insert("customer_details".to_string(), s)); + map + } +} + +impl + ToEncryptable< + DecryptedPaymentIntentAddress, + Secret<serde_json::Value>, + Secret<serde_json::Value>, + > for PaymentAddressFromRequest +{ + fn from_encryptable( + mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, + ) -> CustomResult<DecryptedPaymentIntentAddress, common_utils::errors::ParsingError> { + Ok(DecryptedPaymentIntentAddress { + shipping: hashmap.remove("shipping"), + billing: hashmap.remove("billing"), + customer_details: hashmap.remove("customer_details"), + }) + } + + fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> { + let mut map = FxHashMap::with_capacity_and_hasher(9, Default::default()); + + self.shipping.map(|s| map.insert("shipping".to_string(), s)); + self.billing.map(|s| map.insert("billing".to_string(), s)); + self.customer_details + .map(|s| map.insert("customer_details".to_string(), s)); + map + } +} diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 31cfae49875..5becef839d5 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -17,7 +17,7 @@ email = ["external_services/email", "scheduler/email", "olap"] # keymanager_create, keymanager_mtls, encryption_service should not be removed or added to default feature. Once this features were enabled it can't be disabled as these are breaking changes. keymanager_create = [] keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"] -encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] +encryption_service = ["keymanager_create","hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] km_forward_x_request_id = ["common_utils/km_forward_x_request_id"] frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"] stripe = [] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index d27b6b82fd4..099ce4aced1 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -194,7 +194,7 @@ pub async fn create_merchant_account( let master_key = db.get_master_key(); - let key_manager_state = &(&state).into(); + let key_manager_state: &KeyManagerState = &(&state).into(); let merchant_id = req.get_merchant_reference_id(); let identifier = km_types::Identifier::Merchant(merchant_id.clone()); #[cfg(feature = "keymanager_create")] @@ -203,16 +203,18 @@ pub async fn create_merchant_account( use crate::consts::BASE64_ENGINE; - keymanager::transfer_key_to_key_manager( - key_manager_state, - EncryptionTransferRequest { - identifier: identifier.clone(), - key: BASE64_ENGINE.encode(key), - }, - ) - .await - .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) - .attach_printable("Failed to insert key to KeyManager")?; + if key_manager_state.enabled { + keymanager::transfer_key_to_key_manager( + key_manager_state, + EncryptionTransferRequest { + identifier: identifier.clone(), + key: BASE64_ENGINE.encode(key), + }, + ) + .await + .change_context(errors::ApiErrorResponse::DuplicateMerchantAccount) + .attach_printable("Failed to insert key to KeyManager")?; + } } let key_store = domain::MerchantKeyStore { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 51f2de51f26..0921e38317a 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -7,13 +7,20 @@ use api_models::{ use async_trait::async_trait; use common_utils::{ ext_traits::{AsyncExt, Encode, ValueExt}, - types::{keymanager::KeyManagerState, MinorUnit}, + type_name, + types::{ + keymanager::{Identifier, KeyManagerState, ToEncryptable}, + MinorUnit, + }, }; use diesel_models::ephemeral_key; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ mandates::{MandateData, MandateDetails}, - payments::{payment_attempt::PaymentAttempt, payment_intent::CustomerData}, + payments::{ + payment_attempt::PaymentAttempt, + payment_intent::{CustomerData, PaymentAddressFromRequest}, + }, }; use masking::{ExposeInterface, PeekInterface, Secret}; use router_derive::PaymentOperation; @@ -1280,28 +1287,6 @@ impl PaymentCreate { .change_context(errors::ApiErrorResponse::InternalServerError)? .map(Secret::new); - // Derivation of directly supplied Billing Address data in our Payment Create Request - // Encrypting our Billing Address Details to be stored in Payment Intent - let billing_details = request - .billing - .clone() - .async_map(|billing_details| create_encrypted_data(state, key_store, billing_details)) - .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt billing details")?; - - // Derivation of directly supplied Shipping Address data in our Payment Create Request - // Encrypting our Shipping Address Details to be stored in Payment Intent - let shipping_details = request - .shipping - .clone() - .async_map(|shipping_details| create_encrypted_data(state, key_store, shipping_details)) - .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt shipping details")?; - // Derivation of directly supplied Customer data in our Payment Create Request let raw_customer_details = if request.customer_id.is_none() && (request.name.is_some() @@ -1325,13 +1310,53 @@ impl PaymentCreate { }, ); - // Encrypting our Customer Details to be stored in Payment Intent - let customer_details = raw_customer_details - .async_map(|customer_details| create_encrypted_data(state, key_store, customer_details)) - .await + let key = key_store.key.get_inner().peek(); + let identifier = Identifier::Merchant(key_store.merchant_id.clone()); + let key_manager_state: KeyManagerState = state.into(); + + let shipping_details_encoded = request + .shipping + .clone() + .map(|shipping| Encode::encode_to_value(&shipping).map(Secret::new)) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt customer details")?; + .attach_printable("Unable to encode billing details to serde_json::Value")?; + + let billing_details_encoded = request + .billing + .clone() + .map(|billing| Encode::encode_to_value(&billing).map(Secret::new)) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encode billing details to serde_json::Value")?; + + let customer_details_encoded = raw_customer_details + .map(|customer| Encode::encode_to_value(&customer).map(Secret::new)) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encode shipping details to serde_json::Value")?; + + let encrypted_data = domain::types::crypto_operation( + &key_manager_state, + type_name!(storage::PaymentIntent), + domain::types::CryptoOperation::BatchEncrypt( + PaymentAddressFromRequest::to_encryptable(PaymentAddressFromRequest { + shipping: shipping_details_encoded, + billing: billing_details_encoded, + customer_details: customer_details_encoded, + }), + ), + identifier.clone(), + key, + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt data")?; + + let encrypted_data = PaymentAddressFromRequest::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt the payment intent data")?; let skip_external_tax_calculation = request.skip_external_tax_calculation; @@ -1382,10 +1407,10 @@ impl PaymentCreate { .request_external_three_ds_authentication, charges, frm_metadata: request.frm_metadata.clone(), - billing_details, - customer_details, + billing_details: encrypted_data.billing, + customer_details: encrypted_data.customer_details, merchant_order_reference_id: request.merchant_order_reference_id.clone(), - shipping_details, + shipping_details: encrypted_data.shipping, is_payment_processor_token_flow, organization_id: merchant_account.organization_id.clone(), shipping_cost: request.shipping_cost, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 7444fea0c3b..197c1e4c52a 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -496,7 +496,7 @@ pub async fn send_request( )) }; - // We cannot clone the request type, because it has Form trait which is not clonable. So we are cloning the request builder here. + // We cannot clone the request type, because it has Form trait which is not cloneable. So we are cloning the request builder here. let cloned_send_request = request.try_clone().map(|cloned_request| async { cloned_request .send() @@ -570,7 +570,7 @@ pub async fn send_request( .await } None => { - logger::info!("Retrying request due to connection closed before message could complete failed as request is not clonable"); + logger::info!("Retrying request due to connection closed before message could complete failed as request is not cloneable"); Err(error) } }
2024-09-30T16:08:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> Batch Encrypt/Decrypt fields in Payment Intent table ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Currently all the encryption/Decryption operation is happening serially. Which adds additional latency, So this PR fixes it by using the Batch encryption/decryption API of Keymanager ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ### How to test it in deployed environments Basic sanity testing of `PaymentsCreate` and `PaymentsList`. ### How did I test it locally 1. Call /payments from postman ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_BPQpf0oItObooOxXtmyACTUJD9TpwU3jjs3YCkStXbCDwMKYCauROqOqqRBQpJLi' \ --data-raw '{ "amount": 600, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "HScustomer1234", "email": "p143@example.com", "amount_to_capture": 600, "description": "Its my first payment request", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "name": "Preetam", "phone": "999999999", "setup_future_usage": "off_session", "phone_country_code": "+65", "authentication_type": "three_ds", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "connector_metadata": { "noon": { "order_category": "applepay" } }, "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": "US", "first_name": "preetam", "last_name": "revankar" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6540, "account_name": "transaction_processing" } ], "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 3. Check if the encryption/decryption call happening only once in the logs. <img width="1354" alt="Screenshot 2024-10-01 at 1 19 45 PM" src="https://github.com/user-attachments/assets/09ba719a-4ef7-4c17-9dd4-cc9cbb6dbe57"> <img width="1354" alt="Screenshot 2024-10-01 at 1 18 59 PM" src="https://github.com/user-attachments/assets/b8e185fd-22ca-4b11-aab0-74da4a3cd604"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
6b0f7e4870886997ca300935e727283c739be486
juspay/hyperswitch
juspay__hyperswitch-6205
Bug: [FIX] batch encrypt decrypt for mca fetch/insert/update This adds batch encryption/decryption support for fetch/insert/update of the Merchant Connector Account.
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs index a281c553a13..66b98389818 100644 --- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs @@ -4,14 +4,15 @@ use common_utils::{ encryption::Encryption, errors::{CustomResult, ValidationError}, id_type, pii, type_name, - types::keymanager::{Identifier, KeyManagerState}, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, }; use diesel_models::{enums, merchant_connector_account::MerchantConnectorAccountUpdateInternal}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; +use rustc_hash::FxHashMap; use super::behaviour; -use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation}; +use crate::type_encryption::{crypto_operation, CryptoOperation}; #[cfg(feature = "v1")] #[derive(Clone, Debug)] @@ -175,21 +176,33 @@ impl behaviour::Conversion for MerchantConnectorAccount { _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); + let decrypted_data = crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::BatchDecrypt(EncryptedMca::to_encryptable(EncryptedMca { + connector_account_details: other.connector_account_details, + additional_merchant_data: other.additional_merchant_data, + connector_wallets_details: other.connector_wallets_details, + })), + identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting connector account details".to_string(), + })?; + + let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context( + ValidationError::InvalidValue { + message: "Failed while decrypting connector account details".to_string(), + }, + )?; + Ok(Self { merchant_id: other.merchant_id, connector_name: other.connector_name, - connector_account_details: crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::Decrypt(other.connector_account_details), - identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting connector account details".to_string(), - })?, + connector_account_details: decrypted_data.connector_account_details, test_mode: other.test_mode, disabled: other.disabled, merchant_connector_id: other.merchant_connector_id, @@ -213,41 +226,8 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, - connector_wallets_details: other - .connector_wallets_details - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await - .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting connector wallets details".to_string(), - })?, - additional_merchant_data: if let Some(data) = other.additional_merchant_data { - Some( - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::Decrypt(data), - identifier, - key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting additional_merchant_data".to_string(), - })?, - ) - } else { - None - }, + connector_wallets_details: decrypted_data.connector_wallets_details, + additional_merchant_data: decrypted_data.additional_merchant_data, version: other.version, }) } @@ -324,22 +304,35 @@ impl behaviour::Conversion for MerchantConnectorAccount { _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); + + let decrypted_data = crypto_operation( + state, + type_name!(Self::DstType), + CryptoOperation::BatchDecrypt(EncryptedMca::to_encryptable(EncryptedMca { + connector_account_details: other.connector_account_details, + additional_merchant_data: other.additional_merchant_data, + connector_wallets_details: other.connector_wallets_details, + })), + identifier.clone(), + key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting connector account details".to_string(), + })?; + + let decrypted_data = EncryptedMca::from_encryptable(decrypted_data).change_context( + ValidationError::InvalidValue { + message: "Failed while decrypting connector account details".to_string(), + }, + )?; + Ok(Self { id: other.id, merchant_id: other.merchant_id, connector_name: other.connector_name, - connector_account_details: crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::Decrypt(other.connector_account_details), - identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting connector account details".to_string(), - })?, + connector_account_details: decrypted_data.connector_account_details, disabled: other.disabled, payment_methods_enabled: other.payment_methods_enabled, connector_type: other.connector_type, @@ -354,41 +347,8 @@ impl behaviour::Conversion for MerchantConnectorAccount { applepay_verified_domains: other.applepay_verified_domains, pm_auth_config: other.pm_auth_config, status: other.status, - connector_wallets_details: other - .connector_wallets_details - .async_lift(|inner| async { - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::DecryptOptional(inner), - identifier.clone(), - key.peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await - .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting connector wallets details".to_string(), - })?, - additional_merchant_data: if let Some(data) = other.additional_merchant_data { - Some( - crypto_operation( - state, - type_name!(Self::DstType), - CryptoOperation::Decrypt(data), - identifier, - key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(ValidationError::InvalidValue { - message: "Failed while decrypting additional_merchant_data".to_string(), - })?, - ) - } else { - None - }, + connector_wallets_details: decrypted_data.connector_wallets_details, + additional_merchant_data: decrypted_data.additional_merchant_data, version: other.version, }) } @@ -542,3 +502,121 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte } } } + +pub struct McaFromRequestfromUpdate { + pub connector_account_details: Option<pii::SecretSerdeValue>, + pub connector_wallets_details: Option<pii::SecretSerdeValue>, + pub additional_merchant_data: Option<pii::SecretSerdeValue>, +} +pub struct McaFromRequest { + pub connector_account_details: pii::SecretSerdeValue, + pub connector_wallets_details: Option<pii::SecretSerdeValue>, + pub additional_merchant_data: Option<pii::SecretSerdeValue>, +} + +pub struct DecryptedMca { + pub connector_account_details: Encryptable<pii::SecretSerdeValue>, + pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, + pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, +} + +pub struct EncryptedMca { + pub connector_account_details: Encryption, + pub connector_wallets_details: Option<Encryption>, + pub additional_merchant_data: Option<Encryption>, +} + +pub struct DecryptedUpdateMca { + pub connector_account_details: Option<Encryptable<pii::SecretSerdeValue>>, + pub connector_wallets_details: Option<Encryptable<pii::SecretSerdeValue>>, + pub additional_merchant_data: Option<Encryptable<pii::SecretSerdeValue>>, +} + +impl ToEncryptable<DecryptedMca, Secret<serde_json::Value>, Encryption> for EncryptedMca { + fn from_encryptable( + mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, + ) -> CustomResult<DecryptedMca, common_utils::errors::ParsingError> { + Ok(DecryptedMca { + connector_account_details: hashmap.remove("connector_account_details").ok_or( + error_stack::report!(common_utils::errors::ParsingError::EncodeError( + "Unable to convert from HashMap to DecryptedMca", + )), + )?, + connector_wallets_details: hashmap.remove("connector_wallets_details"), + additional_merchant_data: hashmap.remove("additional_merchant_data"), + }) + } + + fn to_encryptable(self) -> FxHashMap<String, Encryption> { + let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); + + map.insert( + "connector_account_details".to_string(), + self.connector_account_details, + ); + self.connector_wallets_details + .map(|s| map.insert("connector_wallets_details".to_string(), s)); + self.additional_merchant_data + .map(|s| map.insert("additional_merchant_data".to_string(), s)); + map + } +} + +impl ToEncryptable<DecryptedUpdateMca, Secret<serde_json::Value>, Secret<serde_json::Value>> + for McaFromRequestfromUpdate +{ + fn from_encryptable( + mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, + ) -> CustomResult<DecryptedUpdateMca, common_utils::errors::ParsingError> { + Ok(DecryptedUpdateMca { + connector_account_details: hashmap.remove("connector_account_details"), + connector_wallets_details: hashmap.remove("connector_wallets_details"), + additional_merchant_data: hashmap.remove("additional_merchant_data"), + }) + } + + fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> { + let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); + + self.connector_account_details + .map(|cad| map.insert("connector_account_details".to_string(), cad)); + + self.connector_wallets_details + .map(|s| map.insert("connector_wallets_details".to_string(), s)); + self.additional_merchant_data + .map(|s| map.insert("additional_merchant_data".to_string(), s)); + map + } +} + +impl ToEncryptable<DecryptedMca, Secret<serde_json::Value>, Secret<serde_json::Value>> + for McaFromRequest +{ + fn from_encryptable( + mut hashmap: FxHashMap<String, Encryptable<Secret<serde_json::Value>>>, + ) -> CustomResult<DecryptedMca, common_utils::errors::ParsingError> { + Ok(DecryptedMca { + connector_account_details: hashmap.remove("connector_account_details").ok_or( + error_stack::report!(common_utils::errors::ParsingError::EncodeError( + "Unable to convert from HashMap to DecryptedMca", + )), + )?, + connector_wallets_details: hashmap.remove("connector_wallets_details"), + additional_merchant_data: hashmap.remove("additional_merchant_data"), + }) + } + + fn to_encryptable(self) -> FxHashMap<String, Secret<serde_json::Value>> { + let mut map = FxHashMap::with_capacity_and_hasher(3, Default::default()); + + map.insert( + "connector_account_details".to_string(), + self.connector_account_details, + ); + self.connector_wallets_details + .map(|s| map.insert("connector_wallets_details".to_string(), s)); + self.additional_merchant_data + .map(|s| map.insert("additional_merchant_data".to_string(), s)); + map + } +} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index b988578d35e..fed284955b3 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -8,12 +8,15 @@ use common_utils::{ date_time, ext_traits::{AsyncExt, Encode, OptionExt, ValueExt}, id_type, pii, type_name, - types::keymanager::{self as km_types, KeyManagerState}, + types::keymanager::{self as km_types, KeyManagerState, ToEncryptable}, }; use diesel_models::configs; #[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] use diesel_models::organization::OrganizationBridge; use error_stack::{report, FutureExt, ResultExt}; +use hyperswitch_domain_models::merchant_connector_account::{ + McaFromRequest, McaFromRequestfromUpdate, +}; use masking::{ExposeInterface, PeekInterface, Secret}; use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types}; use regex::Regex; @@ -2089,25 +2092,37 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; + let encrypted_data = domain_types::crypto_operation( + key_manager_state, + type_name!(domain::MerchantConnectorAccount), + domain_types::CryptoOperation::BatchEncrypt(McaFromRequestfromUpdate::to_encryptable( + McaFromRequestfromUpdate { + connector_account_details: self.connector_account_details, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + )), + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key_store.key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details".to_string())?; + + let encrypted_data = McaFromRequestfromUpdate::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; + Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), connector_label: self.connector_label.clone(), - connector_account_details: self - .connector_account_details - .async_lift(|inner| async { - domain_types::crypto_operation( - key_manager_state, - type_name!(storage::MerchantConnectorAccount), - domain_types::CryptoOperation::EncryptOptional(inner), - km_types::Identifier::Merchant(key_store.merchant_id.clone()), - key_store.key.get_inner().peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while encrypting data")?, + connector_account_details: encrypted_data.connector_account_details, disabled, payment_methods_enabled, metadata: self.metadata, @@ -2123,31 +2138,8 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect applepay_verified_domains: None, pm_auth_config: self.pm_auth_config, status: Some(connector_status), - additional_merchant_data: if let Some(mcd) = merchant_recipient_data { - Some( - domain_types::crypto_operation( - key_manager_state, - type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::Encrypt(Secret::new(mcd)), - km_types::Identifier::Merchant(key_store.merchant_id.clone()), - key_store.key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt additional_merchant_data")?, - ) - } else { - None - }, - connector_wallets_details: - helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates( - state, - &key_store, - &metadata, - &self.connector_wallets_details, - ) - .await?, + additional_merchant_data: encrypted_data.additional_merchant_data, + connector_wallets_details: encrypted_data.connector_wallets_details, }) } } @@ -2267,27 +2259,39 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; + let encrypted_data = domain_types::crypto_operation( + key_manager_state, + type_name!(domain::MerchantConnectorAccount), + domain_types::CryptoOperation::BatchEncrypt(McaFromRequestfromUpdate::to_encryptable( + McaFromRequestfromUpdate { + connector_account_details: self.connector_account_details, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + )), + km_types::Identifier::Merchant(key_store.merchant_id.clone()), + key_store.key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details".to_string())?; + + let encrypted_data = McaFromRequestfromUpdate::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; + Ok(storage::MerchantConnectorAccountUpdate::Update { connector_type: Some(self.connector_type), connector_name: None, merchant_connector_id: None, connector_label: self.connector_label.clone(), - connector_account_details: self - .connector_account_details - .async_lift(|inner| async { - domain_types::crypto_operation( - key_manager_state, - type_name!(storage::MerchantConnectorAccount), - domain_types::CryptoOperation::EncryptOptional(inner), - km_types::Identifier::Merchant(key_store.merchant_id.clone()), - key_store.key.get_inner().peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while encrypting data")?, + connector_account_details: encrypted_data.connector_account_details, test_mode: self.test_mode, disabled, payment_methods_enabled, @@ -2304,31 +2308,8 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect applepay_verified_domains: None, pm_auth_config: self.pm_auth_config, status: Some(connector_status), - additional_merchant_data: if let Some(mcd) = merchant_recipient_data { - Some( - domain_types::crypto_operation( - key_manager_state, - type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::Encrypt(Secret::new(mcd)), - km_types::Identifier::Merchant(key_store.merchant_id.clone()), - key_store.key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt additional_merchant_data")?, - ) - } else { - None - }, - connector_wallets_details: - helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates( - state, - &key_store, - &metadata, - &self.connector_wallets_details, - ) - .await?, + additional_merchant_data: encrypted_data.additional_merchant_data, + connector_wallets_details: encrypted_data.connector_wallets_details, }) } } @@ -2417,25 +2398,43 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; + + let encrypted_data = domain_types::crypto_operation( + key_manager_state, + type_name!(domain::MerchantConnectorAccount), + domain_types::CryptoOperation::BatchEncrypt(McaFromRequest::to_encryptable( + McaFromRequest { + connector_account_details: self.connector_account_details.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "connector_account_details", + }, + )?, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + )), + identifier.clone(), + key_store.key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details".to_string())?; + + let encrypted_data = McaFromRequest::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; + Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name.to_string(), - connector_account_details: domain_types::crypto_operation( - key_manager_state, - type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::Encrypt(self.connector_account_details.ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_account_details", - }, - )?), - identifier.clone(), - key_store.key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt connector account details")?, + connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), @@ -2459,22 +2458,8 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, - connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?, - additional_merchant_data: if let Some(mcd) = merchant_recipient_data { - Some(domain_types::crypto_operation( - key_manager_state, - type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::Encrypt(Secret::new(mcd)), - km_types::Identifier::Merchant(key_store.merchant_id.clone()), - key_store.key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt additional_merchant_data")?) - } else { - None - }, + connector_wallets_details: encrypted_data.connector_wallets_details, + additional_merchant_data: encrypted_data.additional_merchant_data, version: hyperswitch_domain_models::consts::API_VERSION, }) } @@ -2582,26 +2567,44 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize MerchantRecipientData")?; + + let encrypted_data = domain_types::crypto_operation( + key_manager_state, + type_name!(domain::MerchantConnectorAccount), + domain_types::CryptoOperation::BatchEncrypt(McaFromRequest::to_encryptable( + McaFromRequest { + connector_account_details: self.connector_account_details.ok_or( + errors::ApiErrorResponse::MissingRequiredField { + field_name: "connector_account_details", + }, + )?, + connector_wallets_details: + helpers::get_connector_wallets_details_with_apple_pay_certificates( + &self.metadata, + &self.connector_wallets_details, + ) + .await?, + additional_merchant_data: merchant_recipient_data.map(Secret::new), + }, + )), + identifier.clone(), + key_store.key.peek(), + ) + .await + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details".to_string())?; + + let encrypted_data = McaFromRequest::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while decrypting connector account details")?; + Ok(domain::MerchantConnectorAccount { merchant_id: business_profile.merchant_id.clone(), connector_type: self.connector_type, connector_name: self.connector_name.to_string(), merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(), - connector_account_details: domain_types::crypto_operation( - key_manager_state, - type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::Encrypt(self.connector_account_details.ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "connector_account_details", - }, - )?), - identifier.clone(), - key_store.key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt connector account details")?, + connector_account_details: encrypted_data.connector_account_details, payment_methods_enabled, disabled, metadata: self.metadata.clone(), @@ -2624,26 +2627,12 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, - connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?, + connector_wallets_details: encrypted_data.connector_wallets_details, test_mode: self.test_mode, business_country: self.business_country, business_label: self.business_label.clone(), business_sub_label: self.business_sub_label.clone(), - additional_merchant_data: if let Some(mcd) = merchant_recipient_data { - Some(domain_types::crypto_operation( - key_manager_state, - type_name!(domain::MerchantConnectorAccount), - domain_types::CryptoOperation::Encrypt(Secret::new(mcd)), - identifier, - key_store.key.peek(), - ) - .await - .and_then(|val| val.try_into_operation()) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unable to encrypt additional_merchant_data")?) - } else { - None - }, + additional_merchant_data: encrypted_data.additional_merchant_data, version: hyperswitch_domain_models::consts::API_VERSION, }) } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 3782026835b..f0b1e9ca86e 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -76,10 +76,7 @@ use crate::{ services, types::{ api::{self, admin, enums as api_enums, MandateValidationFieldsExt}, - domain::{ - self, - types::{self, AsyncLift}, - }, + domain::{self, types}, storage::{self, enums as storage_enums, ephemeral_key, CardTokenData}, transformers::{ForeignFrom, ForeignTryFrom}, AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse, @@ -4534,12 +4531,10 @@ pub fn is_apple_pay_simplified_flow( // As part of migration fallback this function checks apple pay details are present in connector_wallets_details // If yes, it will encrypt connector_wallets_details and store it in the database. // If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it. -pub async fn get_encrypted_connector_wallets_details_with_apple_pay_certificates( - state: &SessionState, - key_store: &domain::MerchantKeyStore, +pub async fn get_connector_wallets_details_with_apple_pay_certificates( connector_metadata: &Option<masking::Secret<tera::Value>>, connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>, -) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> { +) -> RouterResult<Option<masking::Secret<serde_json::Value>>> { let connector_wallet_details_with_apple_pay_metadata_optional = get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional) .await?; @@ -4553,25 +4548,7 @@ pub async fn get_encrypted_connector_wallets_details_with_apple_pay_certificates .transpose()? .map(masking::Secret::new); - let key_manager_state: KeyManagerState = state.into(); - let encrypted_connector_wallets_details = connector_wallets_details - .clone() - .async_lift(|wallets_details| async { - types::crypto_operation( - &key_manager_state, - type_name!(domain::MerchantConnectorAccount), - types::CryptoOperation::EncryptOptional(wallets_details), - Identifier::Merchant(key_store.merchant_id.clone()), - key_store.key.get_inner().peek(), - ) - .await - .and_then(|val| val.try_into_optionaloperation()) - }) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while encrypting connector wallets details")?; - - Ok(encrypted_connector_wallets_details) + Ok(connector_wallets_details) } async fn get_apple_pay_metadata_if_needed(
2024-10-03T07:30:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> This adds batch encrypt/decrypt support for Merchant Connector account create/fetch/update ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6205 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Create MerchantConnector Account ```bash { "connector_type": "fiz_operations", "connector_name": "checkout_test", "connector_label": "checkout_test_US_default", "merchant_connector_id": "mca_1nx2lpMSrHoJZ0Xiw3CM", "profile_id": "pro_1tS3symGpqUT5zGglYyI", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "pk*******************************u5" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "eps", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sofort", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "giropay", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "ideal", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": null, "maximum_amount": null, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": null, "metadata": { "google_pay": { "merchant_info": { "merchant_id": "sundari", "merchant_name": "gpay" }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ] }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "checkoutltd", "gateway_merchant_id": "pk_sbox_ivbndwrrb35t67wrveqic347ii4" } } } ] }, "payment_request_data": { "label": "applepay", "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ] } } } }, "test_mode": false, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": { "apple_pay_combined": { "manual": { "payment_request_data": { "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_capabilities": [ "supports3DS" ], "label": "applepay" }, "merchant_identifier": "merchant.com.hyperswitch.checkout", "display_name": "checkoutapple", "initiative": "web", "initiative_context": "sdk-test-app.netlify.app", "merchant_business_country": null } } } } } ``` 2. Update MerchantConnectorAccount ```bash curl --location 'http://localhost:8080/account/merchant_123_1727938790/connectors/mca_1nx2lpMSrHoJZ0Xiw3CM' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "fiz_operations", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_countries": { "type": "disable_only", "list": [ "US", "GB", "IN" ] }, "accepted_currencies": { "type": "enable_only", "list": [ "USD", "GBP", "INR" ] } }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "accepted_countries": { "type": "enable_only", "list": [ "US", "GB", "IN" ] }, "accepted_currencies": { "type": "disable_only", "list": [ "USD", "GBP", "INR" ] } } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "business_country": "US", "business_label": "default" }' ``` 3. Sanity test on `/payments` ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: router-custom' \ --header 'api-key: dev_BPQpf0oItObooOxXtmyACTUJD9TpwU3jjs3YCkStXbCDwMKYCauROqOqqRBQpJLi' \ --data-raw '{ "amount": 600, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "HScustomer1234", "email": "p143@example.com", "amount_to_capture": 600, "description": "Its my first payment request", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "name": "Preetam", "phone": "999999999", "setup_future_usage": "off_session", "phone_country_code": "+65", "authentication_type": "three_ds", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "connector_metadata": { "noon": { "order_category": "applepay" } }, "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": "US", "first_name": "preetam", "last_name": "revankar" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6540, "account_name": "transaction_processing" } ], "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
a3c2694943a985d27b5bc8b0371884d17a6ca34d
juspay/hyperswitch
juspay__hyperswitch-6184
Bug: refactor(users): Remove v1 insertions for user_roles Currently, we are inserting user_roles in v1 version and v2 version. Since we moved all the APIs to work with v2 data, we can stop inserting v1 data. This will also help in migrating v1 data to v2.
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index 1cd25e54cb3..f4142842e21 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -5,7 +5,6 @@ use diesel::{ BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; -use router_env::logger; use crate::{ enums::{UserRoleVersion, UserStatus}, @@ -23,21 +22,6 @@ impl UserRoleNew { } impl UserRole { - pub async fn insert_multiple_user_roles( - conn: &PgPooledConn, - user_roles: Vec<UserRoleNew>, - ) -> StorageResult<Vec<Self>> { - let query = diesel::insert_into(<Self>::table()).values(user_roles); - - logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); - - query - .get_results_async(conn) - .await - .change_context(errors::DatabaseError::Others) - .attach_printable("Error while inserting user_roles") - } - pub async fn find_by_user_id( conn: &PgPooledConn, user_id: String, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index f36ecc18116..a1a78656de1 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -67,7 +67,6 @@ pub async fn signup_with_merchant_id( state.clone(), common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), UserStatus::Active, - None, ) .await?; @@ -146,7 +145,6 @@ pub async fn signup_token_only_flow( state.clone(), common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), UserStatus::Active, - None, ) .await?; @@ -247,7 +245,6 @@ pub async fn connect_account( state.clone(), common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), UserStatus::Active, - None, ) .await?; @@ -657,7 +654,7 @@ async fn handle_existing_user_invitation( org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) - .insert_in_v1_and_v2(state) + .insert_in_v2(state) .await? } EntityType::Profile => { @@ -767,14 +764,21 @@ async fn handle_new_user_invitation( }; let _user_role = match role_info.get_entity_type() { - EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()), + EntityType::Organization => { + user_role + .add_entity(domain::OrganizationLevel { + org_id: user_from_token.org_id.clone(), + }) + .insert_in_v2(state) + .await? + } EntityType::Merchant => { user_role .add_entity(domain::MerchantLevel { org_id: user_from_token.org_id.clone(), merchant_id: user_from_token.merchant_id.clone(), }) - .insert_in_v1_and_v2(state) + .insert_in_v2(state) .await? } EntityType::Profile => { @@ -1128,7 +1132,7 @@ pub async fn create_internal_user( org_id: internal_merchant.organization_id, merchant_id: internal_merchant_id, }) - .insert_in_v1_and_v2(&state) + .insert_in_v2(&state) .await .change_context(UserErrors::InternalServerError)?; @@ -1257,28 +1261,11 @@ pub async fn create_merchant_account( ) -> UserResponse<()> { let user_from_db = user_from_token.get_user_from_db(&state).await?; - let new_user = domain::NewUser::try_from((user_from_db, req, user_from_token))?; - let new_merchant = new_user.get_new_merchant(); + let new_merchant = domain::NewUserMerchant::try_from((user_from_db, req, user_from_token))?; new_merchant .create_new_merchant_and_insert_in_db(state.to_owned()) .await?; - let role_insertion_res = new_user - .insert_org_level_user_role_in_db( - state.clone(), - common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(), - UserStatus::Active, - Some(UserRoleVersion::V1), - ) - .await; - if let Err(e) = role_insertion_res { - let _ = state - .store - .delete_merchant_account_by_merchant_id(&new_merchant.get_merchant_id()) - .await; - return Err(e); - } - Ok(ApplicationResponse::StatusOk) } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index de10b70f507..11082a65a49 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -37,10 +37,7 @@ use super::{ user::{sample_data::BatchSampleDataInterface, UserInterface}, user_authentication_method::UserAuthenticationMethodInterface, user_key_store::UserKeyStoreInterface, - user_role::{ - InsertUserRolePayload, ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, - UserRoleInterface, - }, + user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface}, }; #[cfg(feature = "payouts")] use crate::services::kafka::payout::KafkaPayout; @@ -3018,8 +3015,8 @@ impl RedisConnInterface for KafkaStore { impl UserRoleInterface for KafkaStore { async fn insert_user_role( &self, - user_role: InsertUserRolePayload, - ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { + user_role: storage::UserRoleNew, + ) -> CustomResult<user_storage::UserRole, errors::StorageError> { self.diesel_store.insert_user_role(user_role).await } diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index d511010e6b5..e9e7cafa3fd 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -13,21 +13,6 @@ use crate::{ services::Store, }; -pub enum InsertUserRolePayload { - OnlyV1(storage::UserRoleNew), - OnlyV2(storage::UserRoleNew), - V1AndV2(Box<[storage::UserRoleNew; 2]>), -} - -impl InsertUserRolePayload { - fn convert_to_vec(self) -> Vec<storage::UserRoleNew> { - match self { - Self::OnlyV1(user_role) | Self::OnlyV2(user_role) => vec![user_role], - Self::V1AndV2(user_roles) => user_roles.to_vec(), - } - } -} - pub struct ListUserRolesByOrgIdPayload<'a> { pub user_id: Option<&'a String>, pub org_id: &'a id_type::OrganizationId, @@ -51,8 +36,8 @@ pub struct ListUserRolesByUserIdPayload<'a> { pub trait UserRoleInterface { async fn insert_user_role( &self, - user_role: InsertUserRolePayload, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; + user_role: storage::UserRoleNew, + ) -> CustomResult<storage::UserRole, errors::StorageError>; async fn find_user_role_by_user_id( &self, @@ -123,11 +108,12 @@ impl UserRoleInterface for Store { #[instrument(skip_all)] async fn insert_user_role( &self, - user_role: InsertUserRolePayload, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { + user_role: storage::UserRoleNew, + ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::insert_multiple_user_roles(&conn, user_role.convert_to_vec()) + user_role + .insert(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -295,44 +281,38 @@ impl UserRoleInterface for Store { impl UserRoleInterface for MockDb { async fn insert_user_role( &self, - user_role: InsertUserRolePayload, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { + user_role: storage::UserRoleNew, + ) -> CustomResult<storage::UserRole, errors::StorageError> { let mut db_user_roles = self.user_roles.lock().await; - user_role - .convert_to_vec() - .into_iter() - .map(|user_role| { - if db_user_roles - .iter() - .any(|user_role_inner| user_role_inner.user_id == user_role.user_id) - { - Err(errors::StorageError::DuplicateValue { - entity: "user_id", - key: None, - })? - } - let user_role = storage::UserRole { - id: i32::try_from(db_user_roles.len()) - .change_context(errors::StorageError::MockDbError)?, - user_id: user_role.user_id, - merchant_id: user_role.merchant_id, - role_id: user_role.role_id, - status: user_role.status, - created_by: user_role.created_by, - created_at: user_role.created_at, - last_modified: user_role.last_modified, - last_modified_by: user_role.last_modified_by, - org_id: user_role.org_id, - profile_id: None, - entity_id: None, - entity_type: None, - version: enums::UserRoleVersion::V1, - }; - db_user_roles.push(user_role.clone()); - Ok(user_role) - }) - .collect::<Result<Vec<_>, _>>() + if db_user_roles + .iter() + .any(|user_role_inner| user_role_inner.user_id == user_role.user_id) + { + Err(errors::StorageError::DuplicateValue { + entity: "user_id", + key: None, + })? + } + let user_role = storage::UserRole { + id: i32::try_from(db_user_roles.len()) + .change_context(errors::StorageError::MockDbError)?, + user_id: user_role.user_id, + merchant_id: user_role.merchant_id, + role_id: user_role.role_id, + status: user_role.status, + created_by: user_role.created_by, + created_at: user_role.created_at, + last_modified: user_role.last_modified, + last_modified_by: user_role.last_modified_by, + org_id: user_role.org_id, + profile_id: None, + entity_id: None, + entity_type: None, + version: enums::UserRoleVersion::V1, + }; + db_user_roles.push(user_role.clone()); + Ok(user_role) } async fn find_user_role_by_user_id( diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index b271abd1eff..33a1d5f53ca 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -83,9 +83,9 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| role_name: "organization_admin".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Organization, - is_invitable: false, - is_deletable: false, - is_updatable: false, + is_invitable: true, + is_deletable: true, + is_updatable: true, is_internal: false, }, ); diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 19d682aeef1..a664fc84978 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -30,7 +30,7 @@ use crate::{ admin, errors::{UserErrors, UserResult}, }, - db::{user_role::InsertUserRolePayload, GlobalStorageInterface}, + db::GlobalStorageInterface, routes::SessionState, services::{self, authentication::UserFromToken, authorization::info}, types::transformers::ForeignFrom, @@ -661,26 +661,17 @@ impl NewUser { state: SessionState, role_id: String, user_status: UserStatus, - version: Option<UserRoleVersion>, ) -> UserResult<UserRole> { let org_id = self .get_new_merchant() .get_new_organization() .get_organization_id(); - let merchant_id = self.get_new_merchant().get_merchant_id(); let org_user_role = self .get_no_level_user_role(role_id, user_status) - .add_entity(OrganizationLevel { - org_id, - merchant_id, - }); - - match version { - Some(UserRoleVersion::V1) => org_user_role.insert_in_v1(&state).await, - Some(UserRoleVersion::V2) => org_user_role.insert_in_v2(&state).await, - None => org_user_role.insert_in_v1_and_v2(&state).await, - } + .add_entity(OrganizationLevel { org_id }); + + org_user_role.insert_in_v2(&state).await } } @@ -1119,8 +1110,6 @@ pub struct NoLevel; #[derive(Clone)] pub struct OrganizationLevel { pub org_id: id_type::OrganizationId, - // Keeping this to allow insertion of org_admins in V1 - pub merchant_id: id_type::MerchantId, } #[derive(Clone)] @@ -1174,32 +1163,46 @@ pub struct EntityInfo { entity_type: EntityType, } -impl<E> NewUserRole<E> -where - E: Clone, -{ - fn convert_to_new_v1_role( - self, - org_id: id_type::OrganizationId, - merchant_id: id_type::MerchantId, - ) -> UserRoleNew { - UserRoleNew { - user_id: self.user_id, - role_id: self.role_id, - status: self.status, - created_by: self.created_by, - last_modified_by: self.last_modified_by, - created_at: self.created_at, - last_modified: self.last_modified, - org_id: Some(org_id), - merchant_id: Some(merchant_id), +impl From<OrganizationLevel> for EntityInfo { + fn from(value: OrganizationLevel) -> Self { + Self { + entity_id: value.org_id.get_string_repr().to_owned(), + entity_type: EntityType::Organization, + org_id: value.org_id, + merchant_id: None, + profile_id: None, + } + } +} + +impl From<MerchantLevel> for EntityInfo { + fn from(value: MerchantLevel) -> Self { + Self { + entity_id: value.merchant_id.get_string_repr().to_owned(), + entity_type: EntityType::Merchant, + org_id: value.org_id, profile_id: None, - entity_id: None, - entity_type: None, - version: UserRoleVersion::V1, + merchant_id: Some(value.merchant_id), } } +} +impl From<ProfileLevel> for EntityInfo { + fn from(value: ProfileLevel) -> Self { + Self { + entity_id: value.profile_id.get_string_repr().to_owned(), + entity_type: EntityType::Profile, + org_id: value.org_id, + merchant_id: Some(value.merchant_id), + profile_id: Some(value.profile_id), + } + } +} + +impl<E> NewUserRole<E> +where + E: Clone + Into<EntityInfo>, +{ fn convert_to_new_v2_role(self, entity: EntityInfo) -> UserRoleNew { UserRoleNew { user_id: self.user_id, @@ -1218,116 +1221,15 @@ where } } - async fn insert_v1_and_v2_in_db_and_get_v2( - state: &SessionState, - v1_role: UserRoleNew, - v2_role: UserRoleNew, - ) -> UserResult<UserRole> { - let inserted_roles = state - .store - .insert_user_role(InsertUserRolePayload::V1AndV2(Box::new([v1_role, v2_role]))) - .await - .change_context(UserErrors::InternalServerError)?; - - inserted_roles - .into_iter() - .find(|role| role.version == UserRoleVersion::V2) - .ok_or(report!(UserErrors::InternalServerError)) - } -} - -impl NewUserRole<OrganizationLevel> { - pub async fn insert_in_v1(self, state: &SessionState) -> UserResult<UserRole> { - let entity = self.entity.clone(); - - let new_v1_role = self - .clone() - .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone()); - - state - .store - .insert_user_role(InsertUserRolePayload::OnlyV1(new_v1_role)) - .await - .change_context(UserErrors::InternalServerError)? - .pop() - .ok_or(report!(UserErrors::InternalServerError)) - } - pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> { let entity = self.entity.clone(); - let new_v2_role = self.convert_to_new_v2_role(EntityInfo { - org_id: entity.org_id.clone(), - merchant_id: None, - profile_id: None, - entity_id: entity.org_id.get_string_repr().to_owned(), - entity_type: EntityType::Organization, - }); - state - .store - .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role)) - .await - .change_context(UserErrors::InternalServerError)? - .pop() - .ok_or(report!(UserErrors::InternalServerError)) - } - - pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> { - let entity = self.entity.clone(); - - let new_v1_role = self - .clone() - .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone()); + let new_v2_role = self.convert_to_new_v2_role(entity.into()); - let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo { - org_id: entity.org_id.clone(), - merchant_id: None, - profile_id: None, - entity_id: entity.org_id.get_string_repr().to_owned(), - entity_type: EntityType::Organization, - }); - - Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await - } -} - -impl NewUserRole<MerchantLevel> { - pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> { - let entity = self.entity.clone(); - - let new_v1_role = self - .clone() - .convert_to_new_v1_role(entity.org_id.clone(), entity.merchant_id.clone()); - - let new_v2_role = self.clone().convert_to_new_v2_role(EntityInfo { - org_id: entity.org_id.clone(), - merchant_id: Some(entity.merchant_id.clone()), - profile_id: None, - entity_id: entity.merchant_id.get_string_repr().to_owned(), - entity_type: EntityType::Merchant, - }); - - Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await - } -} - -impl NewUserRole<ProfileLevel> { - pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> { - let entity = self.entity.clone(); - - let new_v2_role = self.convert_to_new_v2_role(EntityInfo { - org_id: entity.org_id.clone(), - merchant_id: Some(entity.merchant_id.clone()), - profile_id: Some(entity.profile_id.clone()), - entity_id: entity.profile_id.get_string_repr().to_owned(), - entity_type: EntityType::Profile, - }); state .store - .insert_user_role(InsertUserRolePayload::OnlyV2(new_v2_role)) + .insert_user_role(new_v2_role) .await - .change_context(UserErrors::InternalServerError)? - .pop() - .ok_or(report!(UserErrors::InternalServerError)) + .change_context(UserErrors::InternalServerError) } }
2024-10-01T10:27:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently we are inserting user_roles in v1 version and v2 version. Since we have completely moved the APIs to support v2, we don't have to insert v1 anymore. Allow inviting, updating and deleting org_admins. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6184 Closes #6186 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> All the following APIs will insert only v2 user_roles from now on. ```curl curl --location 'https://integ-api.hyperswitch.io/user/signup' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "new email", "password": "password" }' ``` ``` curl --location 'https://integ-api.hyperswitch.io/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "new email" }' ``` ``` curl --location 'https://integ-api.hyperswitch.io/user/internal_signup' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --data '{ "name" : "name", "email" : "new email", "password": "password" }' ``` ``` curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \ --header 'Content-Type: application/json' \ --data-raw '[ { "email": "email", "name": "name", "role_id": "merchant_view_only" }, { "email": "email 2", "name": "name", "role_id": "merchant_admin" } ]' ``` ``` curl --location 'https://integ-api.hyperswitch.io/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: ••••••' \ --data '{ "company_name": "Juspay" }' ``` You will now be able to invite org_admin ``` curl --location 'https://integ-api.hyperswitch.io/user/user/invite_multiple' \ --header 'Content-Type: application/json' \ --header 'Authorization: ••••••' \ --data-raw '[ { "email": "email", "name": "name", "role_id": "org_admin" } ]' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4dae29221f2d24a0f4299e641cfe22ab705fae25
juspay/hyperswitch
juspay__hyperswitch-6160
Bug: fix(payments): remove time range filter from payment attempt We don't need time range filters since created at is not indexed in payments attempts, we are already getting filtered payments intents and using its active attempt ids. It is further slowing down 'IN' query performance.
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index e07d716fb6c..ad056aef6d0 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -369,7 +369,6 @@ impl PaymentAttempt { payment_method: Option<Vec<enums::PaymentMethod>>, payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, ) -> StorageResult<i64> { @@ -379,14 +378,6 @@ impl PaymentAttempt { .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); - if let Some(time_range) = time_range { - filter = filter.filter(dsl::created_at.ge(time_range.start_time)); - - if let Some(end_time) = time_range.end_time { - filter = filter.filter(dsl::created_at.le(end_time)); - } - } - if let Some(connector) = connector { filter = filter.filter(dsl::connector.eq_any(connector)); } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 5f0894566ad..c71e08c79e8 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -157,7 +157,6 @@ pub trait PaymentAttemptInterface { payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, errors::StorageError>; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d00d4b7b259..6e785b55a3f 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3243,7 +3243,6 @@ pub async fn apply_filters_on_payments( constraints.payment_method_type, constraints.authentication_type, constraints.merchant_connector_id, - constraints.time_range, pi_fetch_constraints.get_profile_id_list(), merchant.storage_scheme, ) diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 73d05528634..de10b70f507 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1604,7 +1604,6 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, - time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::DataStorageError> { @@ -1617,7 +1616,6 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type, authentication_type, merchant_connector_id, - time_range, profile_id_list, storage_scheme, ) diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 44c089932d9..c37f9f6d3da 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -52,7 +52,6 @@ impl PaymentAttemptInterface for MockDb { _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>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 6d669437efd..63f5a0ff9f8 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -403,7 +403,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { 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>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { @@ -427,7 +426,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method, payment_method_type, authentication_type, - time_range, profile_id_list, merchant_connector_id, ) @@ -1289,7 +1287,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { 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>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { @@ -1302,7 +1299,6 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type, authentication_type, merchant_connector_id, - time_range, profile_id_list, storage_scheme, )
2024-09-30T13:32:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Currently `created_at` is not indexed in payment attempt table, when applying filtering with active attempt ids. We are adding extra overhead of checking time_range, though we need not to as we will be already getting filtered attempt ids from intent table. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#6160](https://github.com/juspay/hyperswitch/issues/6160) ## How did you test it? We can hit test api ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "limit": 50, }' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e4a35d366b7db151378d6c1f61e4d01d1c7ed37f
juspay/hyperswitch
juspay__hyperswitch-6174
Bug: [FEATURE] integrate card payouts for Adyen ### Feature Description Adyen's Balance Platform is integrated as `Adyenplatform` in HyperSwitch. This is specifically integrated for processing payouts via Adyen through their Balance Platform product. Currently, only bank payouts (SEPA) is integrated. Adyen has rolled out card payouts through this platform as well. The same needs to be integrated in HyperSwitch for processing card payouts via Adyen. ### Possible Implementation Payout APIs to integrate for card payouts - PoEligibility - PoFulfill Flow looks something like this for card payouts through Adyen - Check if the given card is eligible (using their zero-auth payment flow) - PoEligibility in HyperSwitch - Fulfill the card payout - PoFulfill in HyperSwitch References - https://docs.adyen.com/payouts/payout-service/pay-out-to-cards/ ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs index 1b1f2b42b77..7262ec9f3ff 100644 --- a/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs +++ b/crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs @@ -1,6 +1,4 @@ -use api_models::payouts; -#[cfg(feature = "payouts")] -use api_models::webhooks; +use api_models::{payouts, webhooks}; use common_enums::enums; use common_utils::pii; use error_stack::{report, ResultExt}; @@ -13,7 +11,7 @@ use super::{AdyenPlatformRouterData, Error}; use crate::{ connectors::adyen::transformers as adyen, types::PayoutsResponseRouterData, - utils::{self, PayoutsData as _, RouterData as _}, + utils::{self, AddressDetailsData, PayoutsData as _, RouterData as _}, }; #[derive(Debug, Default, Serialize, Deserialize)] @@ -38,7 +36,7 @@ pub struct AdyenTransferRequest { balance_account_id: Secret<String>, category: AdyenPayoutMethod, counterparty: AdyenPayoutMethodDetails, - priority: AdyenPayoutPriority, + priority: Option<AdyenPayoutPriority>, reference: String, reference_for_beneficiary: String, description: Option<String>, @@ -48,32 +46,50 @@ pub struct AdyenTransferRequest { #[serde(rename_all = "camelCase")] pub enum AdyenPayoutMethod { Bank, + Card, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] -pub struct AdyenPayoutMethodDetails { - bank_account: AdyenBankAccountDetails, +pub enum AdyenPayoutMethodDetails { + BankAccount(AdyenBankAccountDetails), + Card(AdyenCardDetails), + #[serde(rename = "card")] + CardToken(AdyenCardTokenDetails), } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenBankAccountDetails { - account_holder: AdyenBankAccountHolder, + account_holder: AdyenAccountHolder, account_identification: AdyenBankAccountIdentification, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AdyenBankAccountHolder { - address: Option<adyen::Address>, - full_name: Secret<String>, +pub struct AdyenAccountHolder { + address: AdyenAddress, + first_name: Option<Secret<String>>, + last_name: Option<Secret<String>>, + full_name: Option<Secret<String>>, #[serde(rename = "reference")] customer_id: Option<String>, #[serde(rename = "type")] entity_type: Option<EntityType>, } +#[serde_with::skip_serializing_none] +#[derive(Default, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenAddress { + line1: Secret<String>, + line2: Secret<String>, + postal_code: Option<Secret<String>>, + state_or_province: Option<Secret<String>>, + city: String, + country: enums::CountryAlpha2, +} + #[derive(Debug, Serialize, Deserialize)] pub struct AdyenBankAccountIdentification { #[serde(rename = "type")] @@ -93,6 +109,38 @@ pub struct SepaDetails { iban: Secret<String>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenCardDetails { + card_holder: AdyenAccountHolder, + card_identification: AdyenCardIdentification, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenCardIdentification { + #[serde(rename = "number")] + card_number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + issue_number: Option<String>, + start_month: Option<String>, + start_year: Option<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenCardTokenDetails { + card_holder: AdyenAccountHolder, + card_identification: AdyenCardTokenIdentification, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenCardTokenIdentification { + stored_payment_method_id: Secret<String>, +} + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenPayoutPriority { @@ -120,7 +168,7 @@ pub struct AdyenTransferResponse { amount: adyen::Amount, balance_account: AdyenBalanceAccount, category: AdyenPayoutMethod, - category_data: AdyenCategoryData, + category_data: Option<AdyenCategoryData>, direction: AdyenTransactionDirection, reference: String, reference_for_beneficiary: String, @@ -168,25 +216,101 @@ pub enum AdyenTransferStatus { #[serde(rename_all = "camelCase")] pub enum AdyenTransactionType { BankTransfer, + CardTransfer, InternalTransfer, Payment, Refund, } +impl TryFrom<&hyperswitch_domain_models::address::AddressDetails> for AdyenAddress { + type Error = Error; + + fn try_from( + address: &hyperswitch_domain_models::address::AddressDetails, + ) -> Result<Self, Self::Error> { + let line1 = address + .get_line1() + .change_context(ConnectorError::MissingRequiredField { + field_name: "billing.address.line1", + })? + .clone(); + let line2 = address + .get_line2() + .change_context(ConnectorError::MissingRequiredField { + field_name: "billing.address.line2", + })? + .clone(); + Ok(Self { + line1, + line2, + postal_code: address.get_optional_zip(), + state_or_province: address.get_optional_state(), + city: address.get_city()?.to_owned(), + country: address.get_country()?.to_owned(), + }) + } +} + +impl<F> TryFrom<(&types::PayoutsRouterData<F>, enums::PayoutType)> for AdyenAccountHolder { + type Error = Error; + + fn try_from( + (router_data, payout_type): (&types::PayoutsRouterData<F>, enums::PayoutType), + ) -> Result<Self, Self::Error> { + let billing_address = router_data.get_billing_address()?; + let (first_name, last_name, full_name) = match payout_type { + enums::PayoutType::Card => ( + Some(router_data.get_billing_first_name()?), + Some(router_data.get_billing_last_name()?), + None, + ), + enums::PayoutType::Bank => (None, None, Some(router_data.get_billing_full_name()?)), + _ => Err(ConnectorError::NotSupported { + message: "Payout method not supported".to_string(), + connector: "Adyen", + })?, + }; + Ok(Self { + address: billing_address.try_into()?, + first_name, + last_name, + full_name, + customer_id: Some(router_data.get_customer_id()?.get_string_repr().to_owned()), + entity_type: Some(EntityType::from(router_data.request.entity_type)), + }) + } +} + impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for AdyenTransferRequest { type Error = Error; fn try_from( item: &AdyenPlatformRouterData<&types::PayoutsRouterData<F>>, ) -> Result<Self, Self::Error> { - let request = item.router_data.request.to_owned(); - match item.router_data.get_payout_method_data()? { - payouts::PayoutMethodData::Card(_) | payouts::PayoutMethodData::Wallet(_) => { - Err(ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Adyenplatform"), - ))? + let request = &item.router_data.request; + let (counterparty, priority) = match item.router_data.get_payout_method_data()? { + payouts::PayoutMethodData::Wallet(_) => Err(ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Adyenplatform"), + ))?, + payouts::PayoutMethodData::Card(c) => { + let card_holder: AdyenAccountHolder = + (item.router_data, enums::PayoutType::Card).try_into()?; + let card_identification = AdyenCardIdentification { + card_number: c.card_number, + expiry_month: c.expiry_month, + expiry_year: c.expiry_year, + issue_number: None, + start_month: None, + start_year: None, + }; + let counterparty = AdyenPayoutMethodDetails::Card(AdyenCardDetails { + card_holder, + card_identification, + }); + (counterparty, None) } - payouts::PayoutMethodData::Bank(bd) => { + let account_holder: AdyenAccountHolder = + (item.router_data, enums::PayoutType::Bank).try_into()?; let bank_details = match bd { payouts::Bank::Sepa(b) => AdyenBankAccountIdentification { bank_type: "iban".to_string(), @@ -207,56 +331,39 @@ impl<F> TryFrom<&AdyenPlatformRouterData<&types::PayoutsRouterData<F>>> for Adye connector: "Adyenplatform", })?, }; - let billing_address = item.router_data.get_optional_billing(); - let address = adyen::get_address_info(billing_address).transpose()?; - let account_holder = AdyenBankAccountHolder { - address, - full_name: item.router_data.get_billing_full_name()?, - customer_id: Some( - item.router_data - .get_customer_id()? - .get_string_repr() - .to_owned(), - ), - entity_type: Some(EntityType::from(request.entity_type)), - }; - let counterparty = AdyenPayoutMethodDetails { - bank_account: AdyenBankAccountDetails { - account_holder, - account_identification: bank_details, - }, - }; - - let adyen_connector_metadata_object = - AdyenPlatformConnectorMetadataObject::try_from( - &item.router_data.connector_meta_data, - )?; - let balance_account_id = adyen_connector_metadata_object - .source_balance_account - .ok_or(ConnectorError::InvalidConnectorConfig { - config: "metadata.source_balance_account", - })?; + let counterparty = AdyenPayoutMethodDetails::BankAccount(AdyenBankAccountDetails { + account_holder, + account_identification: bank_details, + }); let priority = request .priority .ok_or(ConnectorError::MissingRequiredField { field_name: "priority", })?; - let payout_type = request.get_payout_type()?; - Ok(Self { - amount: adyen::Amount { - value: item.amount, - currency: request.destination_currency, - }, - balance_account_id, - category: AdyenPayoutMethod::try_from(payout_type)?, - counterparty, - priority: AdyenPayoutPriority::from(priority), - reference: item.router_data.connector_request_reference_id.clone(), - reference_for_beneficiary: request.payout_id, - description: item.router_data.description.clone(), - }) + (counterparty, Some(AdyenPayoutPriority::from(priority))) } - } + }; + let adyen_connector_metadata_object = + AdyenPlatformConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; + let balance_account_id = adyen_connector_metadata_object + .source_balance_account + .ok_or(ConnectorError::InvalidConnectorConfig { + config: "metadata.source_balance_account", + })?; + let payout_type = request.get_payout_type()?; + Ok(Self { + amount: adyen::Amount { + value: item.amount, + currency: request.destination_currency, + }, + balance_account_id, + category: AdyenPayoutMethod::try_from(payout_type)?, + counterparty, + priority, + reference: item.router_data.connector_request_reference_id.clone(), + reference_for_beneficiary: request.payout_id.clone(), + description: item.router_data.description.clone(), + }) } } @@ -332,17 +439,15 @@ impl TryFrom<enums::PayoutType> for AdyenPayoutMethod { fn try_from(payout_type: enums::PayoutType) -> Result<Self, Self::Error> { match payout_type { enums::PayoutType::Bank => Ok(Self::Bank), - enums::PayoutType::Card | enums::PayoutType::Wallet => { - Err(report!(ConnectorError::NotSupported { - message: "Card or wallet payouts".to_string(), - connector: "Adyenplatform", - })) - } + enums::PayoutType::Card => Ok(Self::Card), + enums::PayoutType::Wallet => Err(report!(ConnectorError::NotSupported { + message: "Card or wallet payouts".to_string(), + connector: "Adyenplatform", + })), } } } -#[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformIncomingWebhook { @@ -351,7 +456,6 @@ pub struct AdyenplatformIncomingWebhook { pub webhook_type: AdyenplatformWebhookEventType, } -#[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformIncomingWebhookData { @@ -360,7 +464,6 @@ pub struct AdyenplatformIncomingWebhookData { pub tracking: Option<AdyenplatformInstantStatus>, } -#[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AdyenplatformInstantStatus { @@ -368,7 +471,6 @@ pub struct AdyenplatformInstantStatus { estimated_arrival_time: Option<String>, } -#[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum InstantPriorityStatus { @@ -376,7 +478,6 @@ pub enum InstantPriorityStatus { Credited, } -#[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] pub enum AdyenplatformWebhookEventType { #[serde(rename = "balancePlatform.transfer.created")] @@ -385,7 +486,6 @@ pub enum AdyenplatformWebhookEventType { PayoutUpdated, } -#[cfg(feature = "payouts")] #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum AdyenplatformWebhookStatus { @@ -396,7 +496,6 @@ pub enum AdyenplatformWebhookStatus { Returned, Received, } -#[cfg(feature = "payouts")] pub fn get_adyen_webhook_event( event_type: AdyenplatformWebhookEventType, status: AdyenplatformWebhookStatus, @@ -434,4 +533,13 @@ pub struct AdyenTransferErrorResponse { pub title: String, pub detail: Option<String>, pub request_id: Option<String>, + pub invalid_fields: Option<Vec<AdyenInvalidField>>, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AdyenInvalidField { + pub name: Option<String>, + pub value: Option<String>, + pub message: Option<String>, } diff --git a/crates/router/src/configs/defaults/payout_required_fields.rs b/crates/router/src/configs/defaults/payout_required_fields.rs index 5ec8161c594..a056a3ac931 100644 --- a/crates/router/src/configs/defaults/payout_required_fields.rs +++ b/crates/router/src/configs/defaults/payout_required_fields.rs @@ -437,15 +437,6 @@ fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredF value: None, }, ), - ( - "billing.address.zip".to_string(), - RequiredFieldInfo { - required_field: "billing.address.zip".to_string(), - display_name: "billing_address_zip".to_string(), - field_type: FieldType::Text, - value: None, - }, - ), ( "billing.address.country".to_string(), RequiredFieldInfo { @@ -469,6 +460,15 @@ fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredF value: None, }, ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "billing_address_last_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), ]), PayoutConnectors::Wise => HashMap::from([ (
2025-06-30T14:25:21Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR enables card payouts through AdyenPlatform connector. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Allows merchants to process card payouts through Adyen's Balance Platform. ## How did you test it? <details> <summary>1. Card payouts via API</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_lAISInmiO4UNrMmvkJogzRVKEGKlBKQbRCBFOkLJTXmq6nsD5G1H65BjOd4H72H8' \ --data '{"amount":100,"currency":"EUR","profile_id":"pro_vVSlzCG7M1GSX9SyssY8","customer_id":"cus_WULwykbL8laUbxDUeGEB","connector":["adyenplatform"],"description":"Its my first payout request","payout_type":"card","payout_method_data":{"card":{"card_number":"4111111111111111","expiry_month":"03","expiry_year":"2030"}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"FR","first_name":"John","last_name":"Doe"}},"entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"confirm":true,"auto_fulfill":true}' Response {"payout_id":"ff21b89d-3cfd-4f0f-b3ff-c468d90d7074","merchant_id":"merchant_1751292662","amount":100,"currency":"EUR","connector":"adyenplatform","payout_type":"card","payout_method_data":{"card":{"card_issuer":null,"card_network":null,"card_type":null,"card_issuing_country":null,"bank_code":null,"last4":"1111","card_isin":"411111","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null}},"billing":{"address":{"city":"San Fransico","country":"FR","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"auto_fulfill":true,"customer_id":"cus_WULwykbL8laUbxDUeGEB","customer":{"id":"cus_WULwykbL8laUbxDUeGEB","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_ff21b89d-3cfd-4f0f-b3ff-c468d90d7074_secret_qzFALtOg6ZhYAOAUr2qY","return_url":null,"business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":true,"metadata":{"ref":"123"},"merchant_connector_id":"mca_SfssFvg5RBT2k7iKRRsS","status":"initiated","error_message":null,"error_code":null,"profile_id":"pro_vVSlzCG7M1GSX9SyssY8","created":"2025-06-30T14:12:47.886Z","connector_transaction_id":"38EBIX67HBSYZ30V","priority":null,"payout_link":null,"email":null,"name":"John Nether","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":"pm_wScFhCfxELZ7gN13Nbxz"} </details> <details> <summary>2. Card payouts via Payout Links</summary> cURL curl --location --request POST 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_lAISInmiO4UNrMmvkJogzRVKEGKlBKQbRCBFOkLJTXmq6nsD5G1H65BjOd4H72H8' \ --data '{"amount":1,"currency":"EUR","customer_id":"cus_WULwykbL8laUbxDUeGEB","description":"Its my first payout request","entity_type":"Individual","confirm":false,"auto_fulfill":true,"session_expiry":1000000,"profile_id":"pro_vVSlzCG7M1GSX9SyssY8","payout_link":true,"return_url":"https://www.google.com","payout_link_config":{"form_layout":"journey","theme":"#0066ff","logo":"https://hyperswitch.io/favicon.ico","merchant_name":"HyperSwitch Inc.","test_mode":true}}' Response {"payout_id":"2371746b-df3d-41da-8fa2-455faf921ea9","merchant_id":"merchant_1751292662","amount":1,"currency":"EUR","connector":null,"payout_type":null,"payout_method_data":null,"billing":null,"auto_fulfill":true,"customer_id":"cus_WULwykbL8laUbxDUeGEB","customer":{"id":"cus_WULwykbL8laUbxDUeGEB","name":"John Nether","email":null,"phone":"6168205362","phone_country_code":"+1"},"client_secret":"payout_2371746b-df3d-41da-8fa2-455faf921ea9_secret_VwDeIScMTLFzG7Iz1DZU","return_url":"https://www.google.com","business_country":null,"business_label":null,"description":"Its my first payout request","entity_type":"Individual","recurring":false,"metadata":{},"merchant_connector_id":null,"status":"requires_payout_method_data","error_message":null,"error_code":null,"profile_id":"pro_vVSlzCG7M1GSX9SyssY8","created":"2025-06-30T14:14:48.897Z","connector_transaction_id":null,"priority":null,"payout_link":{"payout_link_id":"payout_link_vITmtOWGkaUfeXopruRs","link":"http://localhost:8080/payout_link/merchant_1751292662/2371746b-df3d-41da-8fa2-455faf921ea9?locale=en"},"email":null,"name":"John Nether","phone":"6168205362","phone_country_code":"+1","unified_code":null,"unified_message":null,"payout_method_id":null} <img width="1719" alt="Screenshot 2025-06-30 at 7 45 32 PM" src="https://github.com/user-attachments/assets/f7ff9bbd-2dbc-4f70-bc3d-a043cec22327" /> <img width="1721" alt="Screenshot 2025-06-30 at 7 45 48 PM" src="https://github.com/user-attachments/assets/9f833415-afa1-4dd5-b699-834e7a768a7a" /> <img width="913" alt="Screenshot 2025-06-30 at 7 45 54 PM" src="https://github.com/user-attachments/assets/27b3634b-5cd1-4ae8-8db3-e68116858a70" /> </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d305fad2e6c403fde11b9eea785fddefbf3477df
juspay/hyperswitch
juspay__hyperswitch-6176
Bug: [PLUGIN] - WooCommerce - Refactor Code for Clarity and Readability The [WooCommerce-Payments-Plugin](https://docs.hyperswitch.io/features/e-commerce-platform-plugins/woocommerce-plugin) connect with multiple payment processors with a single API to improve payment conversions, reduce costs and ops. It supports multiple currencies, offers fraud protection, and provides an easy-to-use dashboard for managing transactions and tracking sales. ### Getting started 1. Get familiar with [Php](https://www.php.net/manual/en/index.php) and [Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript). 2. Check the [README.md](https://github.com/juspay/hyperswitch-woocommerce-plugin/blob/main/README.md) for project structure and setup instructions. 3. To setup locally, follow the steps provided [here](https://github.com/juspay/hyperswitch-woocommerce-plugin/blob/main/README.md) ### **Description:** You are provided with a code snippet that performs a specific function. Your task is to refactor the code to improve its readability, performance, and maintainability. Consider applying best practices such as input validation, descriptive variable naming, reducing complexity, and handling edge cases. The goal is to make the code more efficient, cleaner, and easier to understand while maintaining its core functionality. Code Snippet - This provided code snippet is a part of [WooCommerce-Plugin](https://github.com/juspay/hyperswitch-woocommerce-plugin/blob/main/js/hyperswitch-hyperservice.js). ```javascript async function hyperswitchPaymentHandleSubmit(isOneClickPaymentMethod, result) { if (result || isOneClickPaymentMethod) { let err; if (!isOneClickPaymentMethod && result) { const { error } = await hyper.confirmPayment({ confirmParams: { return_url: hyperswitchReturnUrl, }, redirect: "if_required", }); err = error; } else { const { error } = await hyper.confirmOneClickPayment( { confirmParams: { return_url: hyperswitchReturnUrl, }, redirect: "if_required", }, result ); err = error; } if (err) { if (err.type) { if (err.type == "validation_error") { jQuery([document.documentElement, document.body]).animate( { scrollTop: jQuery( ".payment_box.payment_method_hyperswitch_checkout" ).offset().top, }, 500 ); } else { location.href = hyperswitchReturnUrl; } } else { location.href = hyperswitchReturnUrl; } jQuery(".payment_method_hyperswitch_checkout").unblock(); } else { location.href = hyperswitchReturnUrl; } } } ```` --- ## Contribution Guidelines: - Fork the repository and create a new branch for your work. - Ensure the WebSDK follows best practices for API integration and field rendering. - Write clean, well-documented code with clear commit messages. - Add unit tests to ensure the dynamic field rendering works as expected. - Make sure to follow our coding standards and contribution guidelines. --- ## Helpful Resources: - Link to WooCommerce-Plugin documentation: [WooCommerce](https://docs.hyperswitch.io/features/e-commerce-platform-plugins/woocommerce-plugin) ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). - For this issue, please submit a PR on [@juspay/hyperswitch-woocommerce-plugin](https://github.com/juspay/hyperswitch-woocommerce-plugin) repo, and link it to the issue. Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. If you have any questions or need help getting started, feel free to ask in the comments!
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index c7dfe239526..4eecc3c1eeb 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -56,6 +56,7 @@ pub enum PaymentDetails { BankAccount(BankDetails), Wallet, Klarna, + Paypal, } #[derive(Clone, Eq, PartialEq, Serialize)] @@ -112,6 +113,7 @@ impl TryFrom<&types::PaymentsRouterData> for AciPaymentsRequest { }), api::PaymentMethod::PayLater(_) => PaymentDetails::Klarna, api::PaymentMethod::Wallet => PaymentDetails::Wallet, + api::PaymentMethod::Paypal => PaymentDetails::Paypal, }; let auth = AciAuthType::try_from(&item.connector_auth_type)?; diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 381ef3412aa..81bfb2807ff 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -209,6 +209,7 @@ impl TryFrom<&types::PaymentsRouterData> for AdyenPaymentRequest { api::PaymentMethod::BankTransfer => None, api::PaymentMethod::Wallet => None, api::PaymentMethod::PayLater(_) => None, + api::PaymentMethod::Paypal => None, }; let shopper_interaction = match item.request.off_session { diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index bda7718fdb5..c6eed4a5d88 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -59,6 +59,7 @@ enum PaymentDetails { BankAccount(BankAccountDetails), Wallet, Klarna, + Paypal, } #[derive(Serialize, PartialEq)] @@ -146,6 +147,7 @@ impl TryFrom<&types::PaymentsRouterData> for CreateTransactionRequest { }), api::PaymentMethod::PayLater(_) => PaymentDetails::Klarna, api::PaymentMethod::Wallet => PaymentDetails::Wallet, + api::PaymentMethod::Paypal => PaymentDetails::Paypal, }; let authorization_indicator_type = item.request.capture_method.map(|c| AuthorizationIndicator { @@ -350,6 +352,7 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for CreateRefundRequest { }), api::PaymentMethod::PayLater(_) => PaymentDetails::Klarna, api::PaymentMethod::Wallet => PaymentDetails::Wallet, + api::PaymentMethod::Paypal => PaymentDetails::Paypal, }; merchant_authentication = MerchantAuthentication::try_from(&item.connector_auth_type)?; diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 7359599822d..a1deedf9ac2 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -75,6 +75,7 @@ impl TryFrom<&types::PaymentsRouterData> for PaymentsRequest { api::PaymentMethod::BankTransfer => None, api::PaymentMethod::Wallet => None, api::PaymentMethod::PayLater(_) => None, + api::PaymentMethod::Paypal => None, }; let three_ds = match item.auth_type { diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 897953d226c..b376adef59b 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -123,6 +123,7 @@ pub enum StripePaymentMethodData { Klarna(StripeKlarnaData), Bank, Wallet, + Paypal, } impl TryFrom<&types::PaymentsRouterData> for PaymentIntentRequest { @@ -160,6 +161,7 @@ impl TryFrom<&types::PaymentsRouterData> for PaymentIntentRequest { }) } api::PaymentMethod::Wallet => StripePaymentMethodData::Wallet, + api::PaymentMethod::Paypal => StripePaymentMethodData::Paypal, }; let shipping_address = match item.address.shipping.clone() { Some(mut shipping) => Address { diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index d69db679042..bdd79cd6410 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -153,6 +153,8 @@ pub enum PaymentMethod { Wallet, #[serde(rename(deserialize = "pay_later"))] PayLater(PayLaterData), + #[serde(rename(deserialize = "paypal"))] + Paypal, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize)] @@ -170,6 +172,7 @@ pub enum PaymentMethodDataResponse { BankTransfer, Wallet, PayLater(PayLaterData), + Paypal, } impl Default for PaymentMethod { @@ -541,6 +544,7 @@ impl From<PaymentMethod> for PaymentMethodDataResponse { PaymentMethodDataResponse::PayLater(pay_later_data) } PaymentMethod::Wallet => PaymentMethodDataResponse::Wallet, + PaymentMethod::Paypal => PaymentMethodDataResponse::Paypal, } } } diff --git a/crates/router/src/types/storage/enums.rs b/crates/router/src/types/storage/enums.rs index d76267ec2d9..72fae43632a 100644 --- a/crates/router/src/types/storage/enums.rs +++ b/crates/router/src/types/storage/enums.rs @@ -470,6 +470,7 @@ pub enum PaymentMethodType { ConsumerFinance, Wallet, Klarna, + Paypal, } #[derive( diff --git a/migrations/2022-11-25-121143_add_paypal_pmt/down.sql b/migrations/2022-11-25-121143_add_paypal_pmt/down.sql new file mode 100644 index 00000000000..4c5dda8ed30 --- /dev/null +++ b/migrations/2022-11-25-121143_add_paypal_pmt/down.sql @@ -0,0 +1,6 @@ +-- This file should undo anything in `up.sql` +DELETE FROM pg_enum +WHERE enumlabel = 'paypal' +AND enumtypid = ( + SELECT oid FROM pg_type WHERE typname = 'PaymentMethodType' +) diff --git a/migrations/2022-11-25-121143_add_paypal_pmt/up.sql b/migrations/2022-11-25-121143_add_paypal_pmt/up.sql new file mode 100644 index 00000000000..732ed26504b --- /dev/null +++ b/migrations/2022-11-25-121143_add_paypal_pmt/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TYPE "PaymentMethodType" ADD VALUE 'paypal' after 'pay_later';
2022-11-25T12:46:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates ## Description Add paypal as payment method type ### Additional Changes - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> Earlier, when PayPal was merged, we were using wallet as the payment method; however, because PayPal is the payment method when we are integrating PayPal through Adyen, the payment method should be changed to PayPal. Thus, this is resolved. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manually tested (No DB error when payment method is paypal) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d41159591e81f7674e87f333b9056702df74c52b
juspay/hyperswitch
juspay__hyperswitch-6146
Bug: fix(user_roles): Send only same and below Entity Level Users in List Users API Currently in user list api, for merchants we show org admin. This is happening because in V1 data, we have merchant_id in org level users as well, because of why the filtering is not correct.
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index b841f88eca1..e10fa0eb81c 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -736,6 +736,16 @@ pub async fn list_users_in_lineage( } }; + // This filtering is needed because for org level users in V1, merchant_id is present. + // Due to this, we get org level users in merchant level users list. + let user_roles_set = user_roles_set + .into_iter() + .filter_map(|user_role| { + let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; + (entity_type <= requestor_role_info.get_entity_type()).then_some(user_role) + }) + .collect::<HashSet<_>>(); + let mut email_map = state .global_store .find_users_by_user_ids( diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index f2aae68fcbc..b6db8340775 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,4 +1,4 @@ -use std::collections::HashSet; +use std::{cmp, collections::HashSet}; use api_models::user_role as user_role_api; use common_enums::{EntityType, PermissionGroup}; @@ -418,28 +418,16 @@ pub fn get_min_entity( user_entity: EntityType, filter_entity: Option<EntityType>, ) -> UserResult<EntityType> { - match (user_entity, filter_entity) { - (EntityType::Organization, None) - | (EntityType::Organization, Some(EntityType::Organization)) => { - Ok(EntityType::Organization) - } + let Some(filter_entity) = filter_entity else { + return Ok(user_entity); + }; - (EntityType::Merchant, None) - | (EntityType::Organization, Some(EntityType::Merchant)) - | (EntityType::Merchant, Some(EntityType::Merchant)) => Ok(EntityType::Merchant), - - (EntityType::Profile, None) - | (EntityType::Organization, Some(EntityType::Profile)) - | (EntityType::Merchant, Some(EntityType::Profile)) - | (EntityType::Profile, Some(EntityType::Profile)) => Ok(EntityType::Profile), - - (EntityType::Merchant, Some(EntityType::Organization)) - | (EntityType::Profile, Some(EntityType::Organization)) - | (EntityType::Profile, Some(EntityType::Merchant)) => { - Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( - "{} level user requesting data for {:?} level", - user_entity, filter_entity - )) - } + if user_entity < filter_entity { + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "{} level user requesting data for {:?} level", + user_entity, filter_entity + )); } + + Ok(cmp::min(user_entity, filter_entity)) }
2024-09-27T11:56:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Send only same and below Entity Level Users in List Users API. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes [#6146](https://github.com/juspay/hyperswitch/issues/6146). ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl 'http://localhost:8080/user/user/v2/list' \ -H 'authorization: Bearer JWT' \ ``` This API when called with merchant level users, it should not send org level users in response. Can be tested via control center. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
67d6d2247bb53dc25831d65305269ba6889c99de
juspay/hyperswitch
juspay__hyperswitch-6141
Bug: fix(admin): jwt added for organization update and retrieve Previously, updating and retrieving organization details required authentication using the admin API key. With the recent change, the dashboard JWT can now be used to update the org_name directly through the dashboard.
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index e5a18fba536..78238d3af07 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -39,14 +39,24 @@ pub async fn organization_update( ) -> HttpResponse { let flow = Flow::OrganizationUpdate; let organization_id = org_id.into_inner(); - let org_id = admin::OrganizationId { organization_id }; + let org_id = admin::OrganizationId { + organization_id: organization_id.clone(), + }; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| update_organization(state, org_id.clone(), req), - &auth::AdminApiAuth, + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthOrganizationFromRoute { + organization_id, + required_permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Organization, + }, + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await @@ -61,14 +71,25 @@ pub async fn organization_retrieve( ) -> HttpResponse { let flow = Flow::OrganizationRetrieve; let organization_id = org_id.into_inner(); - let payload = admin::OrganizationId { organization_id }; + let payload = admin::OrganizationId { + organization_id: organization_id.clone(), + }; + Box::pin(api::server_wrap( flow, state, &req, payload, |state, _, req, _| get_organization(state, req), - &auth::AdminApiAuth, + auth::auth_type( + &auth::AdminApiAuth, + &auth::JWTAuthOrganizationFromRoute { + organization_id, + required_permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Organization, + }, + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index d8318ce9517..225d6a783fc 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -88,6 +88,10 @@ pub enum AuthenticationType { AdminApiAuthWithMerchantId { merchant_id: id_type::MerchantId, }, + OrganizationJwt { + org_id: id_type::OrganizationId, + user_id: String, + }, MerchantJwt { merchant_id: id_type::MerchantId, user_id: Option<String>, @@ -149,6 +153,7 @@ impl AuthenticationType { | Self::MerchantJwtWithProfileId { merchant_id, .. } | Self::WebhookAuth { merchant_id } => Some(merchant_id), Self::AdminApiKey + | Self::OrganizationJwt { .. } | Self::UserJwt { .. } | Self::SinglePurposeJwt { .. } | Self::SinglePurposeOrLoginJwt { .. } @@ -1134,6 +1139,45 @@ where } } +pub struct JWTAuthOrganizationFromRoute { + pub organization_id: id_type::OrganizationId, + pub required_permission: Permission, + pub minimum_entity_level: EntityType, +} + +#[async_trait] +impl<A> AuthenticateAndFetch<(), A> for JWTAuthOrganizationFromRoute +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 role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + + // Check if token has access to Organization that has been requested in the route + if payload.org_id != self.organization_id { + return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); + } + Ok(( + (), + AuthenticationType::OrganizationJwt { + org_id: payload.org_id, + user_id: payload.user_id, + }, + )) + } +} + pub struct JWTAuthMerchantFromRoute { pub merchant_id: id_type::MerchantId, pub required_permission: Permission,
2024-09-27T07:14:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [X] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Previously, updating and retrieving organization details required authentication using the admin API key. With the recent change, the dashboard JWT can now be used to update the org_name directly through the dashboard. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #6141 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request : ``` curl --location --request PUT 'http://localhost:8080/organization/${org_id}' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "organization_name":"RiddhiTest3" }' ``` Response: ``` { "organization_id": "org_id", "organization_name": "RiddhiTest3", "organization_details": null, "metadata": null, "modified_at": "2024-09-27 07:13:13.074956", "created_at": "2024-09-19 12:46:25.990045" } ``` Request : ``` curl --location 'http://localhost:8080/organization/${org_id}' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '' ``` Response: ``` { "organization_id": "org_id", "organization_name": "RiddhiTest3", "organization_details": null, "metadata": null, "modified_at": "2024-09-27 07:13:13.074956", "created_at": "2024-09-19 12:46:25.990045" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
67d6d2247bb53dc25831d65305269ba6889c99de
juspay/hyperswitch
juspay__hyperswitch-6135
Bug: [REFACTOR]: [OPAYO] Add amount conversion framework to Opayo ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.recurly.com/docs/opayo) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/connector/opayo.rs b/crates/router/src/connector/opayo.rs index cd1ef67f662..3e7edba2128 100644 --- a/crates/router/src/connector/opayo.rs +++ b/crates/router/src/connector/opayo.rs @@ -1,8 +1,9 @@ mod transformers; -use std::fmt::Debug; - -use common_utils::request::RequestContent; +use common_utils::{ + request::RequestContent, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; use diesel_models::enums; use error_stack::{report, ResultExt}; use masking::ExposeInterface; @@ -10,7 +11,7 @@ use transformers as opayo; use crate::{ configs::settings, - connector::utils as connector_utils, + connector::{utils as connector_utils, utils::convert_amount}, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, headers, @@ -27,8 +28,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Opayo; +#[derive(Clone)] +pub struct Opayo { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Opayo { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl api::Payment for Opayo {} impl api::PaymentSession for Opayo {} @@ -197,7 +208,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = opayo::OpayoPaymentsRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_router_data = opayo::OpayoRouterData::from((amount, req)); + let connector_req = opayo::OpayoPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -433,7 +450,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = opayo::OpayoRefundRequest::try_from(req)?; + let refund_amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + let connector_router_data = opayo::OpayoRouterData::from((refund_amount, req)); + let connector_req = opayo::OpayoRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs index 16a76301ede..44069f3650b 100644 --- a/crates/router/src/connector/opayo/transformers.rs +++ b/crates/router/src/connector/opayo/transformers.rs @@ -1,3 +1,4 @@ +use common_utils::types::MinorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -6,10 +7,24 @@ use crate::{ core::errors, types::{self, api, domain, storage::enums}, }; +#[derive(Debug, Serialize)] +pub struct OpayoRouterData<T> { + pub amount: MinorUnit, + pub router_data: T, +} + +impl<T> From<(MinorUnit, T)> for OpayoRouterData<T> { + fn from((amount, router_data): (MinorUnit, T)) -> Self { + Self { + amount, + router_data, + } + } +} #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct OpayoPaymentsRequest { - amount: i64, + amount: MinorUnit, card: OpayoCard, } @@ -23,9 +38,12 @@ pub struct OpayoCard { complete: bool, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { +impl TryFrom<&OpayoRouterData<&types::PaymentsAuthorizeRouterData>> for OpayoPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item_data: &OpayoRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data.clone(); match item.request.payment_method_data.clone() { domain::PaymentMethodData::Card(req_card) => { let card = OpayoCard { @@ -39,7 +57,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest { complete: item.request.is_auto_capture()?, }; Ok(Self { - amount: item.request.amount, + amount: item_data.amount, card, }) } @@ -143,14 +161,14 @@ impl<F, T> // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct OpayoRefundRequest { - pub amount: i64, + pub amount: MinorUnit, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for OpayoRefundRequest { +impl<F> TryFrom<&OpayoRouterData<&types::RefundsRouterData<F>>> for OpayoRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &OpayoRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { - amount: item.request.refund_amount, + amount: item.amount, }) } } diff --git a/crates/router/tests/connectors/opayo.rs b/crates/router/tests/connectors/opayo.rs index 6bca86fa813..585a6f4486b 100644 --- a/crates/router/tests/connectors/opayo.rs +++ b/crates/router/tests/connectors/opayo.rs @@ -15,7 +15,7 @@ impl utils::Connector for OpayoTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Opayo; utils::construct_connector_data_old( - Box::new(&Opayo), + Box::new(Opayo::new()), // Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant types::Connector::DummyConnector1, types::api::GetToken::Connector,
2024-10-16T22:13:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds amount conversion framework to Opayo. Opayo accepts amount in MinorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Amount conversion for Opayo Fixes #6135 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
881f5fd0149cb5573eb31451fceb596092eab79a
juspay/hyperswitch
juspay__hyperswitch-6117
Bug: [FEATURE] Generate Random Disputes for sample data ### Feature Description The issue is sub part of issue: #5991 (Please refer to this First) The current implementation of the generate_sample_data_for_user function generates sample data for payments and refunds. However, there is no functionality to generate sample disputes. This issue is about extending the generate_sample_data_for_user function to generate random disputes based on the sample payments created. Current Behavior - The /sample_data API generates sample payments and refunds. - No disputes are generated as part of the sample data generation process. Expected Behavior - The generate_sample_data_for_user function should also generate random disputes along with payments and refunds. - The number of disputes generated should be based on the number of payments created: 2 disputes if the number of payments is between 50 and 100. 1 dispute if the number of payments is less than 50. ### Possible Implementation Modify generate_sample_data_for_user Function: Update the function in `utils::user::sample_data::generate_sample_data` to create sample disputes based on the number of generated payments. The Data should be random and fields should be related to sample payments/refunds for which we are creating dispute. Call the Db function inside `generate_sample_data_for_user` to Batch insert sample disputes Call the Db function inside `delete_sample_data_for_user` to Delete sample disputes Test To generate Sample Data: ``` curl --location 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` To Delete Sample Data: ``` curl --location --request DELETE 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs index 453b3edf00f..d098d1f76d9 100644 --- a/crates/router/src/core/user/sample_data.rs +++ b/crates/router/src/core/user/sample_data.rs @@ -1,6 +1,6 @@ use api_models::user::sample_data::SampleDataRequest; use common_utils::errors::ReportSwitchExt; -use diesel_models::RefundNew; +use diesel_models::{DisputeNew, RefundNew}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; @@ -39,19 +39,23 @@ pub async fn generate_sample_data_for_user( .change_context(SampleDataError::InternalServerError) .attach_printable("Not able to fetch merchant key store")?; // If not able to fetch merchant key store for any reason, this should be an internal server error - let (payment_intents, payment_attempts, refunds): ( + let (payment_intents, payment_attempts, refunds, disputes): ( Vec<PaymentIntent>, Vec<diesel_models::user::sample_data::PaymentAttemptBatchNew>, Vec<RefundNew>, + Vec<DisputeNew>, ) = sample_data.into_iter().fold( - (Vec::new(), Vec::new(), Vec::new()), - |(mut pi, mut pa, mut rf), (payment_intent, payment_attempt, refund)| { + (Vec::new(), Vec::new(), Vec::new(), Vec::new()), + |(mut pi, mut pa, mut rf, mut dp), (payment_intent, payment_attempt, refund, dispute)| { pi.push(payment_intent); pa.push(payment_attempt); if let Some(refund) = refund { rf.push(refund); } - (pi, pa, rf) + if let Some(dispute) = dispute { + dp.push(dispute); + } + (pi, pa, rf, dp) }, ); @@ -70,6 +74,11 @@ pub async fn generate_sample_data_for_user( .insert_refunds_batch_for_sample_data(refunds) .await .switch()?; + state + .store + .insert_disputes_batch_for_sample_data(disputes) + .await + .switch()?; Ok(ApplicationResponse::StatusOk) } @@ -109,6 +118,11 @@ pub async fn delete_sample_data_for_user( .delete_refunds_for_sample_data(&merchant_id_del) .await .switch()?; + state + .store + .delete_disputes_for_sample_data(&merchant_id_del) + .await + .switch()?; Ok(ApplicationResponse::StatusOk) } diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index ea2556a5151..4f859d8e56a 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -8,7 +8,7 @@ use common_utils::{ }; #[cfg(feature = "v1")] use diesel_models::user::sample_data::PaymentAttemptBatchNew; -use diesel_models::RefundNew; +use diesel_models::{enums as storage_enums, DisputeNew, RefundNew}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; use rand::{prelude::SliceRandom, thread_rng, Rng}; @@ -27,7 +27,14 @@ pub async fn generate_sample_data( req: SampleDataRequest, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, -) -> SampleDataResult<Vec<(PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>)>> { +) -> SampleDataResult< + Vec<( + PaymentIntent, + PaymentAttemptBatchNew, + Option<RefundNew>, + Option<DisputeNew>, + )>, +> { let sample_data_size: usize = req.record.unwrap_or(100); let key_manager_state = &state.into(); if !(10..=100).contains(&sample_data_size) { @@ -120,13 +127,23 @@ pub async fn generate_sample_data( let mut refunds_count = 0; + // 2 disputes if generated data size is between 50 and 100, 1 dispute if it is less than 50. + let number_of_disputes: usize = if sample_data_size >= 50 { 2 } else { 1 }; + + let mut disputes_count = 0; + let mut random_array: Vec<usize> = (1..=sample_data_size).collect(); // Shuffle the array let mut rng = thread_rng(); random_array.shuffle(&mut rng); - let mut res: Vec<(PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>)> = Vec::new(); + let mut res: Vec<( + PaymentIntent, + PaymentAttemptBatchNew, + Option<RefundNew>, + Option<DisputeNew>, + )> = Vec::new(); let start_time = req .start_time .unwrap_or(common_utils::date_time::now() - time::Duration::days(7)) @@ -353,7 +370,7 @@ pub async fn generate_sample_data( internal_reference_id: common_utils::generate_id_with_default_len("test"), external_reference_id: None, payment_id: payment_id.clone(), - attempt_id, + attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_transaction_id, connector_refund_id: None, @@ -387,7 +404,43 @@ pub async fn generate_sample_data( None }; - res.push((payment_intent, payment_attempt, refund)); + let dispute = + if disputes_count < number_of_disputes && !is_failed_payment && refund.is_none() { + disputes_count += 1; + Some(DisputeNew { + dispute_id: common_utils::generate_id_with_default_len("test"), + amount: (amount * 100).to_string(), + currency: payment_intent + .currency + .unwrap_or(common_enums::Currency::USD) + .to_string(), + dispute_stage: storage_enums::DisputeStage::Dispute, + dispute_status: storage_enums::DisputeStatus::DisputeOpened, + payment_id: payment_id.clone(), + attempt_id: attempt_id.clone(), + merchant_id: merchant_id.clone(), + connector_status: "Sample connector status".into(), + connector_dispute_id: common_utils::generate_id_with_default_len("test"), + connector_reason: Some("Sample Dispute".into()), + connector_reason_code: Some("123".into()), + challenge_required_by: None, + connector_created_at: None, + connector_updated_at: None, + connector: payment_attempt + .connector + .clone() + .unwrap_or(DummyConnector4.to_string()), + evidence: None, + profile_id: payment_intent.profile_id.clone(), + merchant_connector_id: payment_attempt.merchant_connector_id.clone(), + dispute_amount: amount * 100, + organization_id: org_id.clone(), + }) + } else { + None + }; + + res.push((payment_intent, payment_attempt, refund, dispute)); } Ok(res) }
2024-10-16T19:47:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> I added dispute generation to function `generate_sample_data` in `utils/user/sample_data.rs`. The number of disputes generated is based on the number of payments created: 2 disputes if the number of payments is between 50 and 100. 1 dispute if the number of payments is less than 50. Other changes I made is just to accommodate the dispute generation code changes. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #6117 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested manually. Initial state for both Case1 and Case2: Before sending POST request to `sample_data`, there are 18 non-generated `payment_attempt` records, and 0 `dispute` record. <img width="1384" alt="image" src="https://github.com/user-attachments/assets/a97abf7e-34d4-4bc2-b5e6-fd7ff2908c94"> <img width="1146" alt="image" src="https://github.com/user-attachments/assets/31dddc64-7063-41e3-80d0-c57d378debcf"> #### Case 1: 2 disputes if the number of payments is between 50 and 100. We send a POST request without payload to `sample_data`, by default, 100 `payment_attempt` records will be generated, along with 2 `dispute`. Now there are 118 generated `pyament_attempt` records, and 2 `dispute` records with `test_` prefixed `dispute_id`. <img width="1107" alt="image" src="https://github.com/user-attachments/assets/df612a03-dc3d-4af2-9588-a5b4381f7c09"> <img width="1384" alt="image" src="https://github.com/user-attachments/assets/16d5f449-4f92-417f-991e-8ddb4e9f2548"> #### Case 2: 1 dispute if the number of payments is less than 50. We send a POST request with payload `{ "record": 30 }` to `sample_data`, 30 `payment_attempt` records will be generated, along with 1 `dispute`. Now there are 48 generated `pyament_attempt` records, and 1 `dispute` records with `test_` prefixed `dispute_id`. <img width="1364" alt="image" src="https://github.com/user-attachments/assets/5e9f1712-3be2-4b88-acac-08ac866e64df"> <img width="1385" alt="image" src="https://github.com/user-attachments/assets/a2efec0a-cbec-4154-8d86-98aa5aecb3de"> #### Case Delete: When there exists data generated by `sample_api`, sending a `DELETE` request to `sample_api` deletes all the generated sample data (back to initial state in this example). <img width="1076" alt="image" src="https://github.com/user-attachments/assets/42414fe0-11d0-40ae-987d-7d0c8fd19d4b"> <img width="1057" alt="image" src="https://github.com/user-attachments/assets/4fe4cbba-21de-4b69-82f6-5049e61f69a6"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c3b0f7c1d6ad95034535048aa50ff6abe9ed6aa0
juspay/hyperswitch
juspay__hyperswitch-6121
Bug: [REFACTOR]: [WISE] Add amount conversion framework to Wise ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.wise.com/api-docs/api-reference/card) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/wise.rs b/crates/router/src/connector/wise.rs index 8123ae7ec79..9f41651b2f9 100644 --- a/crates/router/src/connector/wise.rs +++ b/crates/router/src/connector/wise.rs @@ -1,8 +1,8 @@ pub mod transformers; -use std::fmt::Debug; #[cfg(feature = "payouts")] use common_utils::request::RequestContent; +use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use error_stack::{report, ResultExt}; #[cfg(feature = "payouts")] use masking::PeekInterface; @@ -10,6 +10,7 @@ use masking::PeekInterface; use router_env::{instrument, tracing}; use self::transformers as wise; +use super::utils::convert_amount; use crate::{ configs::settings, core::errors::{self, CustomResult}, @@ -27,8 +28,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Wise; +#[derive(Clone)] +pub struct Wise { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Wise { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wise where @@ -362,7 +373,13 @@ impl services::ConnectorIntegration<api::PoQuote, types::PayoutsData, types::Pay req: &types::PayoutsRouterData<api::PoQuote>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = wise::WisePayoutQuoteRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.source_currency, + )?; + let connector_router_data = wise::WiseRouterData::from((amount, req)); + let connector_req = wise::WisePayoutQuoteRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -441,7 +458,13 @@ impl req: &types::PayoutsRouterData<api::PoRecipient>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = wise::WiseRecipientCreateRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.source_currency, + )?; + let connector_router_data = wise::WiseRouterData::from((amount, req)); + let connector_req = wise::WiseRecipientCreateRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/wise/transformers.rs b/crates/router/src/connector/wise/transformers.rs index fe82ffa5954..94849f2b1ca 100644 --- a/crates/router/src/connector/wise/transformers.rs +++ b/crates/router/src/connector/wise/transformers.rs @@ -2,6 +2,7 @@ use api_models::payouts::PayoutMethodData; #[cfg(feature = "payouts")] use common_utils::pii::Email; +use common_utils::types::MinorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -16,6 +17,20 @@ use crate::{ }, }; use crate::{core::errors, types}; +#[derive(Debug, Serialize)] +pub struct WiseRouterData<T> { + pub amount: MinorUnit, + pub router_data: T, +} + +impl<T> From<(MinorUnit, T)> for WiseRouterData<T> { + fn from((amount, router_data): (MinorUnit, T)) -> Self { + Self { + amount, + router_data, + } + } +} pub struct WiseAuthType { pub(super) api_key: Secret<String>, @@ -156,8 +171,8 @@ pub struct WiseRecipientCreateResponse { pub struct WisePayoutQuoteRequest { source_currency: String, target_currency: String, - source_amount: Option<i64>, - target_amount: Option<i64>, + source_amount: Option<MinorUnit>, + target_amount: Option<MinorUnit>, pay_out: WisePayOutOption, } @@ -348,9 +363,12 @@ fn get_payout_bank_details( // Payouts recipient create request transform #[cfg(feature = "payouts")] -impl<F> TryFrom<&types::PayoutsRouterData<F>> for WiseRecipientCreateRequest { +impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WiseRecipientCreateRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data; let request = item.request.to_owned(); let customer_details = request.customer_details.to_owned(); let payout_method_data = item.get_payout_method_data()?; @@ -420,14 +438,17 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, WiseRecipientCreateResponse> // Payouts quote request transform #[cfg(feature = "payouts")] -impl<F> TryFrom<&types::PayoutsRouterData<F>> for WisePayoutQuoteRequest { +impl<F> TryFrom<&WiseRouterData<&types::PayoutsRouterData<F>>> for WisePayoutQuoteRequest { type Error = Error; - fn try_from(item: &types::PayoutsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item_data: &WiseRouterData<&types::PayoutsRouterData<F>>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data; let request = item.request.to_owned(); let payout_type = request.get_payout_type()?; match payout_type { storage_enums::PayoutType::Bank => Ok(Self { - source_amount: Some(request.amount), + source_amount: Some(item_data.amount), source_currency: request.source_currency.to_string(), target_amount: None, target_currency: request.destination_currency.to_string(), diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index a3046213272..681dd8ee2b0 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -480,7 +480,7 @@ impl ConnectorData { enums::Connector::Stripe => { Ok(ConnectorEnum::Old(Box::new(connector::Stripe::new()))) } - enums::Connector::Wise => Ok(ConnectorEnum::Old(Box::new(&connector::Wise))), + 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/tests/connectors/wise.rs b/crates/router/tests/connectors/wise.rs index 76167804670..984a43d48a7 100644 --- a/crates/router/tests/connectors/wise.rs +++ b/crates/router/tests/connectors/wise.rs @@ -28,7 +28,7 @@ impl utils::Connector for WiseTest { fn get_payout_data(&self) -> Option<api::ConnectorData> { use router::connector::Wise; Some(utils::construct_connector_data_old( - Box::new(&Wise), + Box::new(Wise::new()), types::Connector::Wise, api::GetToken::Connector, None,
2024-10-30T14:13:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pull request introduces significant changes to the Wise connector in the `crates/router` module, focusing on the integration of a new amount conversion utility and refactoring to utilize a new `WiseRouterData` struct. The changes enhance how amounts are handled and improve the overall structure and clarity of the code. ### Refactoring and Enhancements: * **Amount Conversion Utility Integration:** - Added `amount_converter` to the `Wise` struct and integrated it into the `new` method. - Updated `convert_amount` usage in `WisePayoutQuoteRequest` and `WiseRecipientCreateRequest` implementations to use the new `amount_converter`. [[1]](diffhunk://#diff-a149ab1c35f89dd3b0eed2fca15df170708e81962550226b958ae6c367515043L365-R382) [[2]](diffhunk://#diff-a149ab1c35f89dd3b0eed2fca15df170708e81962550226b958ae6c367515043L444-R467) * **Introduction of `WiseRouterData` Struct:** - Added `WiseRouterData` struct to encapsulate amount and router data, and implemented conversion from a tuple. - Modified `WisePayoutQuoteRequest` and `WiseRecipientCreateRequest` to use `WiseRouterData` for transformations. [[1]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L351-R371) [[2]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L423-R451) ### Codebase Simplification: * **Removal of Unnecessary Debug Trait:** - Removed the `Debug` trait from the `Wise` struct. * **Update in Connector Initialization:** - Updated the initialization of the `Wise` connector to use the `new` method in `api.rs` and test files. [[1]](diffhunk://#diff-71935350b305eb696195bc45f26e6f2a16097fb17bd5ac55192eb1d03558bf9aL483-R483) [[2]](diffhunk://#diff-0177b5efcc163c3f657a8c60b0162bf272a68a5e22beb13f6eb309bd34d54166L31-R31) ### Minor Enhancements: * **Type Adjustments:** - Changed various fields in `WiseRecipientCreateRequest` and `WisePayoutQuoteRequest` to use `StringMajorUnit` instead of `String` or `i64`. [[1]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L64-R79) [[2]](diffhunk://#diff-1e46db110c015ea743fbbe850bf756011b4311a1ef56fe5ee75c911bb4960b15L159-R175) These changes collectively improve the robustness and maintainability of the Wise connector, ensuring better handling of amount conversions and a cleaner code structure. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #6121 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
72ee434003eef744d516343a2f803264f226d92a
juspay/hyperswitch
juspay__hyperswitch-6157
Bug: [FEATURE] [DLOCAL, SQUARE] Move connector code to crate hyperswitch_connectors ### Feature Description Connector code for `dlocal` and `square` needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### Possible Implementation Connector code for `dlocal` and `square` needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index f057b7d4a33..9406353a1ee 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -4,6 +4,7 @@ pub mod cashtocode; pub mod coinbase; pub mod cryptopay; pub mod deutschebank; +pub mod dlocal; pub mod fiserv; pub mod fiservemea; pub mod fiuu; @@ -13,6 +14,7 @@ pub mod mollie; pub mod nexixpay; pub mod novalnet; pub mod powertranz; +pub mod square; pub mod stax; pub mod taxjar; pub mod thunes; @@ -22,8 +24,8 @@ pub mod worldline; pub use self::{ bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase, - cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea, - fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay, - novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes, - tsys::Tsys, volt::Volt, worldline::Worldline, + cryptopay::Cryptopay, deutschebank::Deutschebank, dlocal::Dlocal, fiserv::Fiserv, + fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, + nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, square::Square, stax::Stax, + taxjar::Taxjar, thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline, }; diff --git a/crates/router/src/connector/dlocal.rs b/crates/hyperswitch_connectors/src/connectors/dlocal.rs similarity index 68% rename from crates/router/src/connector/dlocal.rs rename to crates/hyperswitch_connectors/src/connectors/dlocal.rs index dc99619e9da..78d3ad4f63e 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal.rs @@ -2,36 +2,51 @@ pub mod transformers; use std::fmt::Debug; +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::enums; use common_utils::{ crypto::{self, SignMessage}, date_time, - request::RequestContent, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, }; -use diesel_models::enums; use error_stack::{report, ResultExt}; use hex::encode; -use masking::PeekInterface; -use transformers as dlocal; - -use crate::{ - configs::settings, - connector::utils as connector_utils, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, logger, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + router_data::{AccessToken, 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::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, - utils::BytesExt, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{Mask, Maskable, PeekInterface}; +use transformers as dlocal; +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{self}, +}; #[derive(Debug, Clone)] pub struct Dlocal; @@ -54,9 +69,9 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let dlocal_req = self.get_request_body(req, connectors)?; let date = date_time::date_as_yyyymmddthhmmssmmmz() @@ -110,7 +125,7 @@ impl ConnectorCommon for Dlocal { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.dlocal.base_url.as_ref() } @@ -148,49 +163,30 @@ impl ConnectorValidation for Dlocal { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Dlocal +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Dlocal { // Not Implemented (R) } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dlocal { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Dlocal -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dlocal {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Dlocal -{ +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dlocal { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Dlocal".to_string()) .into(), @@ -198,14 +194,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -215,16 +209,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}secure_payments", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = dlocal::DlocalRouterData::try_from(( &self.get_currency_unit(), @@ -238,12 +232,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) @@ -260,11 +254,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payments_authorize_response=?res); + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payments_authorize_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal PaymentsAuthorizeResponse") @@ -273,7 +267,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -290,14 +284,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -307,8 +299,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let sync_data = dlocal::DlocalPaymentsSyncRequest::try_from(req)?; Ok(format!( @@ -320,12 +312,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) @@ -343,18 +335,18 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payment_sync_response=?res); + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payment_sync_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal PaymentsSyncResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -363,14 +355,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -380,16 +370,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - _req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, + _req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payments", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, + req: &PaymentsCaptureRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = dlocal::DlocalPaymentsCaptureRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -397,12 +387,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( @@ -417,18 +407,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payments_capture_response=?res); + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payments_capture_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal PaymentsCaptureResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -445,14 +435,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Dlocal -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Dlocal { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -462,8 +450,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_url( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, + req: &PaymentsCancelRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let cancel_data = dlocal::DlocalPaymentsCancelRequest::try_from(req)?; Ok(format!( @@ -475,12 +463,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) @@ -490,11 +478,11 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { - logger::debug!(dlocal_payments_cancel_response=?res); + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_payments_cancel_response=?res); let response: dlocal::DlocalPaymentsResponse = res .response .parse_struct("Dlocal PaymentsCancelResponse") @@ -502,7 +490,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -519,12 +507,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Dlocal { +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Dlocal { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -534,16 +522,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}refunds", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_router_data = dlocal::DlocalRouterData::try_from(( &self.get_currency_unit(), @@ -557,11 +545,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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) + 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( @@ -576,18 +564,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { - logger::debug!(dlocal_refund_response=?res); + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { + router_env::logger::debug!(dlocal_refund_response=?res); let response: dlocal::RefundResponse = res.response .parse_struct("Dlocal RefundResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -604,12 +592,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Dlocal { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Dlocal { fn get_headers( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -619,8 +607,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let sync_data = dlocal::DlocalRefundsSyncRequest::try_from(req)?; Ok(format!( @@ -632,12 +620,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn build_request( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) @@ -647,18 +635,18 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, - data: &types::RefundSyncRouterData, + data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { - logger::debug!(dlocal_refund_sync_response=?res); + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { + router_env::logger::debug!(dlocal_refund_sync_response=?res); let response: dlocal::RefundResponse = res .response .parse_struct("Dlocal RefundSyncResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -676,24 +664,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } #[async_trait::async_trait] -impl api::IncomingWebhook for Dlocal { +impl webhooks::IncomingWebhook for Dlocal { fn get_webhook_object_reference_id( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Ok(api::IncomingWebhookEvent::EventNotSupported) + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { + Ok(IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs similarity index 77% rename from crates/router/src/connector/dlocal/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs index a613cdb2054..385601294b3 100644 --- a/crates/router/src/connector/dlocal/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/dlocal/transformers.rs @@ -1,15 +1,23 @@ use api_models::payments::AddressDetails; -use common_utils::pii::Email; +use common_enums::enums; +use common_utils::{pii::Email, request::Method}; use error_stack::ResultExt; +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, RedirectForm, RefundsResponseData}, + types, +}; +use hyperswitch_interfaces::{api::CurrencyUnit, errors}; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; use crate::{ - connector::utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - services, - types::{self, api, domain, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as _}, }; #[derive(Debug, Default, Eq, PartialEq, Serialize)] @@ -57,16 +65,11 @@ pub struct DlocalRouterData<T> { pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> { +impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for DlocalRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, router_data): ( - &api::CurrencyUnit, - enums::Currency, - i64, - T, - ), + (_currency_unit, _currency, amount, router_data): (&CurrencyUnit, enums::Currency, i64, T), ) -> Result<Self, Self::Error> { Ok(Self { amount, @@ -100,7 +103,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP let country = address.get_country()?; let name = get_payer_name(address); match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Card(ref ccard) => { + PaymentMethodData::Card(ref ccard) => { let should_capture = matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) @@ -143,38 +146,34 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP }), order_id: item.router_data.connector_request_reference_id.clone(), three_dsecure: match item.router_data.auth_type { - diesel_models::enums::AuthenticationType::ThreeDs => { + enums::AuthenticationType::ThreeDs => { Some(ThreeDSecureReqData { force: true }) } - diesel_models::enums::AuthenticationType::NoThreeDs => None, + enums::AuthenticationType::NoThreeDs => None, }, callback_url: Some(item.router_data.request.get_router_return_url()?), description: item.router_data.description.clone(), }; Ok(payment_request) } - 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::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - crate::connector::utils::get_unimplemented_payment_method_error_message( - "Dlocal", - ), - ))? - } + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | 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( + crate::utils::get_unimplemented_payment_method_error_message("Dlocal"), + ))?, } } } @@ -252,10 +251,10 @@ pub struct DlocalAuthType { pub(super) secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for DlocalAuthType { +impl TryFrom<&ConnectorAuthType> for DlocalAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::SignatureKey { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, @@ -309,24 +308,21 @@ pub struct DlocalPaymentsResponse { order_id: Option<String>, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, DlocalPaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, DlocalPaymentsResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, DlocalPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let redirection_data = item .response .three_dsecure .and_then(|three_secure_data| three_secure_data.redirect_url) - .map(|redirect_url| { - services::RedirectForm::from((redirect_url, services::Method::Get)) - }); + .map(|redirect_url| RedirectForm::from((redirect_url, Method::Get))); - let response = types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()), + let response = PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, @@ -350,24 +346,17 @@ pub struct DlocalPaymentsSyncResponse { order_id: Option<String>, } -impl<F, T> - TryFrom< - types::ResponseRouterData<F, DlocalPaymentsSyncResponse, T, types::PaymentsResponseData>, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - DlocalPaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, DlocalPaymentsSyncResponse, T, 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.clone()), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -388,24 +377,17 @@ pub struct DlocalPaymentsCaptureResponse { order_id: Option<String>, } -impl<F, T> - TryFrom< - types::ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, types::PaymentsResponseData>, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - DlocalPaymentsCaptureResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, DlocalPaymentsCaptureResponse, T, 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.clone()), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -424,26 +406,17 @@ pub struct DlocalPaymentsCancelResponse { order_id: String, } -impl<F, T> - TryFrom< - types::ResponseRouterData<F, DlocalPaymentsCancelResponse, T, types::PaymentsResponseData>, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, DlocalPaymentsCancelResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - DlocalPaymentsCancelResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, DlocalPaymentsCancelResponse, T, 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.order_id.clone(), - ), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -509,16 +482,16 @@ pub struct RefundResponse { pub status: RefundStatus, } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> + for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }), @@ -545,16 +518,14 @@ impl TryFrom<&types::RefundSyncRouterData> for DlocalRefundsSyncRequest { } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let refund_status = enums::RefundStatus::from(item.response.status); Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.id, refund_status, }), diff --git a/crates/router/src/connector/square.rs b/crates/hyperswitch_connectors/src/connectors/square.rs similarity index 65% rename from crates/router/src/connector/square.rs rename to crates/hyperswitch_connectors/src/connectors/square.rs index 9b9c68a5f2b..bf2cd4e1ace 100644 --- a/crates/router/src/connector/square.rs +++ b/crates/hyperswitch_connectors/src/connectors/square.rs @@ -2,31 +2,54 @@ pub mod transformers; use std::fmt::Debug; -use api_models::enums; +use api_models::{ + enums, + webhooks::{IncomingWebhookEvent, ObjectReferenceId}, +}; use base64::Engine; -use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{ + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; use error_stack::ResultExt; -use masking::PeekInterface; -use transformers as square; - -use super::utils::{self as super_utils, RefundsRequestData}; -use crate::{ - configs::settings, - consts, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +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}, + AuthorizeSessionToken, }, + router_request_types::{ + AccessTokenRequestData, AuthorizeSessionTokenData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, RefundsData, SetupMandateRequestData, + }, + router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData, + PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundSyncRouterData, RefundsRouterData, TokenizationRouterData, }, - utils::BytesExt, +}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + consts, errors, + events::connector_api_logs::ConnectorEvent, + types::{self, PaymentsAuthorizeType, Response}, + webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, +}; +use masking::{Mask, Maskable, PeekInterface}; +use transformers::{ + self as square, SquareAuthType, SquarePaymentsRequest, SquareRefundRequest, SquareTokenRequest, +}; + +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{self, get_header_key_value, RefundsRequestData}, }; #[derive(Debug, Clone)] @@ -52,12 +75,12 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]; @@ -76,15 +99,15 @@ impl ConnectorCommon for Square { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.square.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let auth = square::SquareAuthType::try_from(auth_type) + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { + let auth = SquareAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), @@ -142,39 +165,24 @@ impl ConnectorValidation for Square { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - super::utils::construct_not_implemented_error_report(capture_method, self.id()), + utils::construct_not_implemented_error_report(capture_method, self.id()), ), } } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Square { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Square -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Square {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Square -{ +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Square { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Square".to_string()) .into(), @@ -183,18 +191,14 @@ impl } #[async_trait::async_trait] -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Square +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Square { fn get_headers( &self, - _req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + _req: &TokenizationRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), types::TokenizationType::get_content_type(self) @@ -209,8 +213,8 @@ impl fn get_url( &self, - _req: &types::TokenizationRouterData, - connectors: &settings::Connectors, + _req: &TokenizationRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/card-nonce", @@ -224,22 +228,22 @@ impl fn get_request_body( &self, - req: &types::TokenizationRouterData, - _connectors: &settings::Connectors, + req: &TokenizationRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = square::SquareTokenRequest::try_from(req)?; + let connector_req = SquareTokenRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::TokenizationRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &TokenizationRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::TokenizationType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::TokenizationType::get_headers(self, req, connectors)?) @@ -252,12 +256,12 @@ impl fn handle_response( &self, - data: &types::TokenizationRouterData, + data: &TokenizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError> + ) -> CustomResult<TokenizationRouterData, errors::ConnectorError> where - types::PaymentsResponseData: Clone, + PaymentsResponseData: Clone, { let response: square::SquareTokenResponse = res .response @@ -267,7 +271,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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -282,21 +286,17 @@ impl } } -impl - ConnectorIntegration< - api::AuthorizeSessionToken, - types::AuthorizeSessionTokenData, - types::PaymentsResponseData, - > for Square +impl ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> + for Square { fn get_headers( &self, - _req: &types::PaymentsAuthorizeSessionTokenRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + _req: &PaymentsAuthorizeSessionTokenRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), )]) @@ -308,10 +308,10 @@ impl fn get_url( &self, - req: &types::PaymentsAuthorizeSessionTokenRouterData, - connectors: &settings::Connectors, + req: &PaymentsAuthorizeSessionTokenRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let auth = square::SquareAuthType::try_from(&req.connector_auth_type) + let auth = SquareAuthType::try_from(&req.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( @@ -327,12 +327,12 @@ impl fn build_request( &self, - req: &types::PaymentsAuthorizeSessionTokenRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeSessionTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::PaymentsPreAuthorizeType::get_url( self, req, connectors, )?) @@ -346,10 +346,10 @@ impl fn handle_response( &self, - data: &types::PaymentsAuthorizeSessionTokenRouterData, + data: &PaymentsAuthorizeSessionTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { let response: square::SquareSessionResponse = res .response .parse_struct("SquareSessionResponse") @@ -358,7 +358,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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -374,14 +374,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -391,38 +389,34 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/payments", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = square::SquarePaymentsRequest::try_from(req)?; + let connector_req = SquarePaymentsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -431,10 +425,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsAuthorizeResponse") @@ -443,7 +437,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -459,14 +453,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -476,8 +468,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req .request @@ -493,12 +485,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) @@ -508,10 +500,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsSyncResponse") @@ -520,7 +512,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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -536,14 +528,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -553,8 +543,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_url( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/payments/{}/complete", @@ -565,9 +555,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn build_request( &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCaptureRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { if req.request.amount_to_capture != req.request.payment_amount { Err(errors::ConnectorError::NotSupported { message: "Partial Capture".to_string(), @@ -575,8 +565,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme })? } Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( @@ -588,10 +578,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn handle_response( &self, - data: &types::PaymentsCaptureRouterData, + data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsCaptureResponse") @@ -600,7 +590,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -616,14 +606,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Square -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Square { fn get_headers( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -633,8 +621,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_url( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, + req: &PaymentsCancelRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/payments/{}/cancel", @@ -645,12 +633,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn build_request( &self, - req: &types::PaymentsCancelRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) + RequestBuilder::new() + .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) @@ -660,10 +648,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn handle_response( &self, - data: &types::PaymentsCancelRouterData, + data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: square::SquarePaymentsResponse = res .response .parse_struct("SquarePaymentsVoidResponse") @@ -672,7 +660,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -688,12 +676,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } } -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Square { +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Square { fn get_headers( &self, - req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundsRouterData<Execute>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -703,28 +691,28 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_url( &self, - _req: &types::RefundsRouterData<api::Execute>, - connectors: &settings::Connectors, + _req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}v2/refunds", self.base_url(connectors),)) } fn get_request_body( &self, - req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, + req: &RefundsRouterData<Execute>, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = square::SquareRefundRequest::try_from(req)?; + let connector_req = SquareRefundRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_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) + 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( @@ -739,10 +727,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn handle_response( &self, - data: &types::RefundsRouterData<api::Execute>, + data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> { + ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: square::RefundResponse = res .response .parse_struct("SquareRefundResponse") @@ -751,7 +739,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -767,12 +755,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Square { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Square { fn get_headers( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -782,8 +770,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_url( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/refunds/{}", @@ -794,12 +782,12 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn build_request( &self, - req: &types::RefundSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &RefundSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) + RequestBuilder::new() + .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) @@ -809,10 +797,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn handle_response( &self, - data: &types::RefundSyncRouterData, + data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: square::RefundResponse = res .response .parse_struct("SquareRefundSyncResponse") @@ -821,7 +809,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -838,10 +826,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse } #[async_trait::async_trait] -impl api::IncomingWebhook for Square { +impl IncomingWebhook for Square { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn common_utils::crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(common_utils::crypto::HmacSha256)) @@ -849,12 +837,12 @@ impl api::IncomingWebhook for Square { fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let encoded_signature = - super_utils::get_header_key_value("x-square-hmacsha256-signature", request.headers)?; - let signature = consts::BASE64_ENGINE + get_header_key_value("x-square-hmacsha256-signature", request.headers)?; + let signature = common_utils::consts::BASE64_ENGINE .decode(encoded_signature) .change_context(errors::ConnectorError::WebhookSignatureNotFound)?; Ok(signature) @@ -862,7 +850,7 @@ impl api::IncomingWebhook for Square { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -885,43 +873,37 @@ impl api::IncomingWebhook for Square { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> { let webhook_body: square::SquareWebhookBody = request .body .parse_struct("SquareWebhookBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match webhook_body.data.object { - square::SquareWebhookObject::Payment(_) => { - Ok(api_models::webhooks::ObjectReferenceId::PaymentId( - api_models::payments::PaymentIdType::ConnectorTransactionId( - webhook_body.data.id, - ), - )) - } - square::SquareWebhookObject::Refund(_) => { - Ok(api_models::webhooks::ObjectReferenceId::RefundId( - api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id), - )) - } + square::SquareWebhookObject::Payment(_) => Ok(ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId(webhook_body.data.id), + )), + square::SquareWebhookObject::Refund(_) => Ok(ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.data.id), + )), } } fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { let details: square::SquareWebhookBody = request .body .parse_struct("SquareWebhookEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; - Ok(api::IncomingWebhookEvent::from(details.data.object)) + Ok(IncomingWebhookEvent::from(details.data.object)) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let details: square::SquareWebhookBody = request diff --git a/crates/router/src/connector/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs similarity index 59% rename from crates/router/src/connector/square/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/square/transformers.rs index db7058f3384..4e2b30a574b 100644 --- a/crates/router/src/connector/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -1,38 +1,44 @@ +use api_models::webhooks::IncomingWebhookEvent; +use common_enums::enums; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + payment_method_data::{BankDebitData, Card, PayLaterData, PaymentMethodData, WalletData}, + router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, + router_flow_types::{refunds::Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types, +}; +use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - types::{self, api, domain, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, + utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _}, }; -impl TryFrom<(&types::TokenizationRouterData, domain::BankDebitData)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, BankDebitData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - value: (&types::TokenizationRouterData, domain::BankDebitData), + value: (&types::TokenizationRouterData, BankDebitData), ) -> Result<Self, Self::Error> { let (_item, bank_debit_data) = value; match bank_debit_data { - domain::BankDebitData::AchBankDebit { .. } - | domain::BankDebitData::SepaBankDebit { .. } - | domain::BankDebitData::BecsBankDebit { .. } - | domain::BankDebitData::BacsBankDebit { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + BankDebitData::AchBankDebit { .. } + | BankDebitData::SepaBankDebit { .. } + | BankDebitData::BecsBankDebit { .. } + | BankDebitData::BacsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } -impl TryFrom<(&types::TokenizationRouterData, domain::Card)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, Card)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - value: (&types::TokenizationRouterData, domain::Card), - ) -> Result<Self, Self::Error> { + fn try_from(value: (&types::TokenizationRouterData, Card)) -> Result<Self, Self::Error> { let (item, card_data) = value; let auth = SquareAuthType::try_from(&item.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; @@ -69,63 +75,59 @@ impl TryFrom<(&types::TokenizationRouterData, domain::Card)> for SquareTokenRequ } } -impl TryFrom<(&types::TokenizationRouterData, domain::PayLaterData)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - value: (&types::TokenizationRouterData, domain::PayLaterData), + value: (&types::TokenizationRouterData, PayLaterData), ) -> Result<Self, Self::Error> { let (_item, pay_later_data) = value; match pay_later_data { - domain::PayLaterData::AfterpayClearpayRedirect { .. } - | domain::PayLaterData::KlarnaRedirect { .. } - | domain::PayLaterData::KlarnaSdk { .. } - | domain::PayLaterData::AffirmRedirect { .. } - | domain::PayLaterData::PayBrightRedirect { .. } - | domain::PayLaterData::WalleyRedirect { .. } - | domain::PayLaterData::AlmaRedirect { .. } - | domain::PayLaterData::AtomeRedirect { .. } => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + PayLaterData::AfterpayClearpayRedirect { .. } + | PayLaterData::KlarnaRedirect { .. } + | PayLaterData::KlarnaSdk { .. } + | PayLaterData::AffirmRedirect { .. } + | PayLaterData::PayBrightRedirect { .. } + | PayLaterData::WalleyRedirect { .. } + | PayLaterData::AlmaRedirect { .. } + | PayLaterData::AtomeRedirect { .. } => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } -impl TryFrom<(&types::TokenizationRouterData, domain::WalletData)> for SquareTokenRequest { +impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - value: (&types::TokenizationRouterData, domain::WalletData), - ) -> Result<Self, Self::Error> { + fn try_from(value: (&types::TokenizationRouterData, WalletData)) -> Result<Self, Self::Error> { let (_item, wallet_data) = value; match wallet_data { - domain::WalletData::ApplePay(_) - | domain::WalletData::GooglePay(_) - | domain::WalletData::AliPayQr(_) - | domain::WalletData::AliPayRedirect(_) - | domain::WalletData::AliPayHkRedirect(_) - | domain::WalletData::MomoRedirect(_) - | domain::WalletData::KakaoPayRedirect(_) - | domain::WalletData::GoPayRedirect(_) - | domain::WalletData::GcashRedirect(_) - | domain::WalletData::ApplePayRedirect(_) - | domain::WalletData::ApplePayThirdPartySdk(_) - | domain::WalletData::DanaRedirect {} - | domain::WalletData::GooglePayRedirect(_) - | domain::WalletData::GooglePayThirdPartySdk(_) - | domain::WalletData::MbWayRedirect(_) - | domain::WalletData::MobilePayRedirect(_) - | domain::WalletData::PaypalRedirect(_) - | domain::WalletData::PaypalSdk(_) - | domain::WalletData::SamsungPay(_) - | domain::WalletData::TwintRedirect {} - | domain::WalletData::VippsRedirect {} - | domain::WalletData::TouchNGoRedirect(_) - | domain::WalletData::WeChatPayRedirect(_) - | domain::WalletData::WeChatPayQr(_) - | domain::WalletData::CashappQr(_) - | domain::WalletData::SwishQr(_) - | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( + WalletData::ApplePay(_) + | WalletData::GooglePay(_) + | WalletData::AliPayQr(_) + | WalletData::AliPayRedirect(_) + | WalletData::AliPayHkRedirect(_) + | WalletData::MomoRedirect(_) + | WalletData::KakaoPayRedirect(_) + | WalletData::GoPayRedirect(_) + | WalletData::GcashRedirect(_) + | WalletData::ApplePayRedirect(_) + | WalletData::ApplePayThirdPartySdk(_) + | WalletData::DanaRedirect {} + | WalletData::GooglePayRedirect(_) + | WalletData::GooglePayThirdPartySdk(_) + | WalletData::MbWayRedirect(_) + | WalletData::MobilePayRedirect(_) + | WalletData::PaypalRedirect(_) + | WalletData::PaypalSdk(_) + | WalletData::SamsungPay(_) + | WalletData::TwintRedirect {} + | WalletData::VippsRedirect {} + | WalletData::TouchNGoRedirect(_) + | WalletData::WeChatPayRedirect(_) + | WalletData::WeChatPayQr(_) + | WalletData::CashappQr(_) + | WalletData::SwishQr(_) + | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Square"), ))?, } @@ -156,31 +158,27 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest { 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::BankDebit(bank_debit_data) => { + PaymentMethodData::BankDebit(bank_debit_data) => { Self::try_from((item, bank_debit_data)) } - domain::PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)), - domain::PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)), - domain::PaymentMethodData::PayLater(pay_later_data) => { - Self::try_from((item, pay_later_data)) - } - domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + PaymentMethodData::Card(card_data) => Self::try_from((item, card_data)), + PaymentMethodData::Wallet(wallet_data) => Self::try_from((item, wallet_data)), + PaymentMethodData::PayLater(pay_later_data) => Self::try_from((item, pay_later_data)), + PaymentMethodData::GiftCard(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -191,18 +189,17 @@ pub struct SquareSessionResponse { session_id: Secret<String>, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, SquareSessionResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SquareSessionResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Pending, session_token: Some(item.response.session_id.clone().expose()), - response: Ok(types::PaymentsResponseData::SessionTokenResponse { + response: Ok(PaymentsResponseData::SessionTokenResponse { session_token: item.response.session_id.expose(), }), ..item.data @@ -215,16 +212,15 @@ pub struct SquareTokenResponse { card_nonce: Secret<String>, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, SquareTokenResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, SquareTokenResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SquareTokenResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::PaymentsResponseData::TokenizationResponse { + response: Ok(PaymentsResponseData::TokenizationResponse { token: item.response.card_nonce.expose(), }), ..item.data @@ -258,13 +254,13 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { let autocomplete = item.request.is_auto_capture()?; match item.request.payment_method_data.clone() { - domain::PaymentMethodData::Card(_) => { + PaymentMethodData::Card(_) => { let pm_token = item.get_payment_method_token()?; Ok(Self { idempotency_key: Secret::new(item.attempt_id.clone()), source_id: match pm_token { - types::PaymentMethodToken::Token(token) => token, - types::PaymentMethodToken::ApplePayDecrypt(_) => Err( + PaymentMethodToken::Token(token) => token, + PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Square"), )?, }, @@ -279,26 +275,24 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { }, }) } - domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Crypto(_) - | domain::PaymentMethodData::MandatePayment - | domain::PaymentMethodData::Reward - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("Square"), - ))? - } + PaymentMethodData::BankDebit(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::Reward + | PaymentMethodData::RealTimePayment(_) + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("Square"), + ))?, } } } @@ -309,21 +303,21 @@ pub struct SquareAuthType { pub(super) key1: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for SquareAuthType { +impl TryFrom<&ConnectorAuthType> for SquareAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self { + ConnectorAuthType::BodyKey { api_key, key1, .. } => Ok(Self { api_key: api_key.to_owned(), key1: key1.to_owned(), }), - types::ConnectorAuthType::HeaderKey { .. } - | types::ConnectorAuthType::SignatureKey { .. } - | types::ConnectorAuthType::MultiAuthKey { .. } - | types::ConnectorAuthType::CurrencyAuthKey { .. } - | types::ConnectorAuthType::TemporaryAuth { .. } - | types::ConnectorAuthType::NoKey { .. } - | types::ConnectorAuthType::CertificateAuth { .. } => { + ConnectorAuthType::HeaderKey { .. } + | ConnectorAuthType::SignatureKey { .. } + | ConnectorAuthType::MultiAuthKey { .. } + | ConnectorAuthType::CurrencyAuthKey { .. } + | ConnectorAuthType::TemporaryAuth { .. } + | ConnectorAuthType::NoKey { .. } + | ConnectorAuthType::CertificateAuth { .. } => { Err(errors::ConnectorError::FailedToObtainAuthType.into()) } } @@ -364,13 +358,12 @@ pub struct SquarePaymentsResponse { payment: SquarePaymentsResponseDetails, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, SquarePaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, SquarePaymentsResponse, T, types::PaymentsResponseData>, + item: ResponseRouterData<F, SquarePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { //Since this try_from is being used in Authorize, Sync, Capture & Void flow. Field amount_captured should only be updated in case of Charged status. let status = enums::AttemptStatus::from(item.response.payment.status); @@ -380,8 +373,8 @@ impl<F, T> }; Ok(Self { status, - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(item.response.payment.id), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.payment.id), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -448,15 +441,15 @@ pub struct RefundResponse { refund: SquareRefundResponseDetails, } -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> + for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.refund.id, refund_status: enums::RefundStatus::from(item.response.refund.status), }), @@ -465,15 +458,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { - response: Ok(types::RefundsResponseData { + response: Ok(RefundsResponseData { connector_refund_id: item.response.refund.id, refund_status: enums::RefundStatus::from(item.response.refund.status), }), @@ -513,7 +504,7 @@ pub struct SquareWebhookBody { pub data: SquareWebhookData, } -impl From<SquareWebhookObject> for api::IncomingWebhookEvent { +impl From<SquareWebhookObject> for IncomingWebhookEvent { fn from(item: SquareWebhookObject) -> Self { match item { SquareWebhookObject::Payment(payment_data) => match payment_data.status { diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index 4c27e11fc45..5b71a1bd29c 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -12,7 +12,11 @@ pub(crate) mod headers { pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key"; pub(crate) const X_CC_VERSION: &str = "X-CC-Version"; + pub(crate) const X_DATE: &str = "X-Date"; + pub(crate) const X_LOGIN: &str = "X-Login"; pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key"; + pub(crate) const X_TRANS_KEY: &str = "X-Trans-Key"; pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue"; pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate"; + pub(crate) const X_VERSION: &str = "X-Version"; } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 31052ab0df2..0d43c263f97 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -95,6 +95,7 @@ default_imp_for_authorize_session_token!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -132,10 +133,12 @@ default_imp_for_calculate_tax!( connectors::Cashtocode, connectors::Coinbase, connectors::Cryptopay, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, connectors::Stax, + connectors::Square, connectors::Novalnet, connectors::Mollie, connectors::Nexixpay, @@ -169,10 +172,12 @@ default_imp_for_session_update!( connectors::Cashtocode, connectors::Coinbase, connectors::Cryptopay, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Mollie, connectors::Novalnet, @@ -208,6 +213,7 @@ default_imp_for_complete_authorize!( connectors::Cashtocode, connectors::Coinbase, connectors::Cryptopay, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -216,6 +222,7 @@ default_imp_for_complete_authorize!( connectors::Novalnet, connectors::Nexixpay, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -245,6 +252,7 @@ default_imp_for_incremental_authorization!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -255,6 +263,7 @@ default_imp_for_incremental_authorization!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -284,6 +293,7 @@ default_imp_for_create_customer!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -293,6 +303,7 @@ default_imp_for_create_customer!( connectors::Novalnet, connectors::Nexixpay, connectors::Powertranz, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -323,6 +334,7 @@ default_imp_for_connector_redirect_response!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -331,6 +343,7 @@ default_imp_for_connector_redirect_response!( connectors::Nexixpay, connectors::Powertranz, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -360,6 +373,7 @@ default_imp_for_pre_processing_steps!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -370,6 +384,7 @@ default_imp_for_pre_processing_steps!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -399,6 +414,7 @@ default_imp_for_post_processing_steps!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -409,6 +425,7 @@ default_imp_for_post_processing_steps!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -438,6 +455,7 @@ default_imp_for_approve!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -448,6 +466,7 @@ default_imp_for_approve!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -477,6 +496,7 @@ default_imp_for_reject!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -487,6 +507,7 @@ default_imp_for_reject!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -516,6 +537,7 @@ default_imp_for_webhook_source_verification!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -526,6 +548,7 @@ default_imp_for_webhook_source_verification!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -556,6 +579,7 @@ default_imp_for_accept_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -566,6 +590,7 @@ default_imp_for_accept_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -595,6 +620,7 @@ default_imp_for_submit_evidence!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -605,6 +631,7 @@ default_imp_for_submit_evidence!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -634,6 +661,7 @@ default_imp_for_defend_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -644,6 +672,7 @@ default_imp_for_defend_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -682,6 +711,7 @@ default_imp_for_file_upload!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -692,6 +722,7 @@ default_imp_for_file_upload!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -723,6 +754,7 @@ default_imp_for_payouts_create!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -733,6 +765,7 @@ default_imp_for_payouts_create!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -764,6 +797,7 @@ default_imp_for_payouts_retrieve!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -774,6 +808,7 @@ default_imp_for_payouts_retrieve!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -805,6 +840,7 @@ default_imp_for_payouts_eligibility!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -815,6 +851,7 @@ default_imp_for_payouts_eligibility!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -846,6 +883,7 @@ default_imp_for_payouts_fulfill!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -856,6 +894,7 @@ default_imp_for_payouts_fulfill!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -887,6 +926,7 @@ default_imp_for_payouts_cancel!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -897,6 +937,7 @@ default_imp_for_payouts_cancel!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -928,6 +969,7 @@ default_imp_for_payouts_quote!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -938,6 +980,7 @@ default_imp_for_payouts_quote!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -969,6 +1012,7 @@ default_imp_for_payouts_recipient!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -979,6 +1023,7 @@ default_imp_for_payouts_recipient!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1010,6 +1055,7 @@ default_imp_for_payouts_recipient_account!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1020,6 +1066,7 @@ default_imp_for_payouts_recipient_account!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1051,6 +1098,7 @@ default_imp_for_frm_sale!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1061,6 +1109,7 @@ default_imp_for_frm_sale!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1092,6 +1141,7 @@ default_imp_for_frm_checkout!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1102,6 +1152,7 @@ default_imp_for_frm_checkout!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1133,6 +1184,7 @@ default_imp_for_frm_transaction!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1143,6 +1195,7 @@ default_imp_for_frm_transaction!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1174,6 +1227,7 @@ default_imp_for_frm_fulfillment!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1184,6 +1238,7 @@ default_imp_for_frm_fulfillment!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1215,6 +1270,7 @@ default_imp_for_frm_record_return!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1225,6 +1281,7 @@ default_imp_for_frm_record_return!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1253,6 +1310,7 @@ default_imp_for_revoking_mandates!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1263,6 +1321,7 @@ default_imp_for_revoking_mandates!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, 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 16e592688ac..d4e1836ac5f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -202,6 +202,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -212,6 +213,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -242,6 +244,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -252,6 +255,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -277,6 +281,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -287,6 +292,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -318,6 +324,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -328,6 +335,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -358,6 +366,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -368,6 +377,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -398,6 +408,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -408,6 +419,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -448,6 +460,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -458,6 +471,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -490,6 +504,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -500,6 +515,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -532,6 +548,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -542,6 +559,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -574,6 +592,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -584,6 +603,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -616,6 +636,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -626,6 +647,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -658,6 +680,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -668,6 +691,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -700,6 +724,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -710,6 +735,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -742,6 +768,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -752,6 +779,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -784,6 +812,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -794,6 +823,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -824,6 +854,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -834,6 +865,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -866,6 +898,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -876,6 +909,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -908,6 +942,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -918,6 +953,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -950,6 +986,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -960,6 +997,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -992,6 +1030,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1002,6 +1041,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1034,6 +1074,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1044,6 +1085,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, @@ -1073,6 +1115,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Coinbase, connectors::Cryptopay, connectors::Deutschebank, + connectors::Dlocal, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -1083,6 +1126,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Powertranz, connectors::Mollie, connectors::Stax, + connectors::Square, connectors::Taxjar, connectors::Thunes, connectors::Tsys, diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index 3d47afb9b82..a6be862403d 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -1,14 +1,15 @@ use crate::{ router_data::{AccessToken, RouterData}, router_flow_types::{ - AccessTokenAuth, Authorize, CalculateTax, Capture, CompleteAuthorize, - CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate, Void, + AccessTokenAuth, Authorize, AuthorizeSessionToken, CalculateTax, Capture, + CompleteAuthorize, CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate, + Void, }, router_request_types::{ - AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData, - PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, - PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, - SetupMandateRequestData, + AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, + ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData, + RefundsData, SetupMandateRequestData, }, router_response_types::{ PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, @@ -17,6 +18,8 @@ use crate::{ pub type PaymentsAuthorizeRouterData = RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>; +pub type PaymentsAuthorizeSessionTokenRouterData = + RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>; pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>; pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>; pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 116fc67320f..390d5de1513 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -12,7 +12,6 @@ pub mod braintree; pub mod checkout; pub mod cybersource; pub mod datatrans; -pub mod dlocal; #[cfg(feature = "dummy_connector")] pub mod dummyconnector; pub mod ebanx; @@ -46,7 +45,6 @@ pub mod razorpay; pub mod riskified; pub mod shift4; pub mod signifyd; -pub mod square; pub mod stripe; pub mod threedsecureio; pub mod trustpay; @@ -61,11 +59,11 @@ pub mod zsl; pub use hyperswitch_connectors::connectors::{ bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode, coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank, - deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, - fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, - nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, - stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, - volt::Volt, worldline, worldline::Worldline, + deutschebank::Deutschebank, dlocal, dlocal::Dlocal, fiserv, fiserv::Fiserv, fiservemea, + fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, + mollie, mollie::Mollie, nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, + powertranz::Powertranz, square, square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, + thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline, }; #[cfg(feature = "dummy_connector")] @@ -74,14 +72,13 @@ pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout, - cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte, + cybersource::Cybersource, datatrans::Datatrans, ebanx::Ebanx, forte::Forte, globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox, payeezy::Payeezy, payme::Payme, payone::Payone, paypal::Paypal, payu::Payu, placetopay::Placetopay, plaid::Plaid, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, riskified::Riskified, shift4::Shift4, signifyd::Signifyd, - square::Square, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, - wellsfargo::Wellsfargo, wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay, - zen::Zen, zsl::Zsl, + stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay, wellsfargo::Wellsfargo, + wellsfargopayout::Wellsfargopayout, wise::Wise, worldpay::Worldpay, zen::Zen, 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 3ff93cf9bf0..5c350f3a475 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -685,7 +685,6 @@ default_imp_for_new_connector_integration_payment!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -715,7 +714,6 @@ default_imp_for_new_connector_integration_payment!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -760,7 +758,6 @@ default_imp_for_new_connector_integration_refund!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -790,7 +787,6 @@ default_imp_for_new_connector_integration_refund!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -829,7 +825,6 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -859,7 +854,6 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -920,7 +914,6 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -950,7 +943,6 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -993,7 +985,6 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1023,7 +1014,6 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1050,7 +1040,6 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1080,7 +1069,6 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1134,7 +1122,6 @@ default_imp_for_new_connector_integration_file_upload!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1164,7 +1151,6 @@ default_imp_for_new_connector_integration_file_upload!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1297,7 +1283,6 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1327,7 +1312,6 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1373,7 +1357,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1403,7 +1386,6 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1449,7 +1431,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1479,7 +1460,6 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1525,7 +1505,6 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1555,7 +1534,6 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1601,7 +1579,6 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1631,7 +1608,6 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1677,7 +1653,6 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1707,7 +1682,6 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1753,7 +1727,6 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1784,7 +1757,6 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Riskified, connector::Signifyd, connector::Stripe, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1829,7 +1801,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1859,7 +1830,6 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -1903,7 +1873,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1933,7 +1902,6 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2066,7 +2034,6 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2096,7 +2063,6 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2142,7 +2108,6 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2172,7 +2137,6 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2218,7 +2182,6 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2248,7 +2211,6 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2294,7 +2256,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2324,7 +2285,6 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2370,7 +2330,6 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2400,7 +2359,6 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, @@ -2443,7 +2401,6 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2473,7 +2430,6 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Trustpay, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 79ed9e25259..677c7968f45 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -211,7 +211,6 @@ default_imp_for_complete_authorize!( connector::Boku, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Gocardless, @@ -235,7 +234,6 @@ default_imp_for_complete_authorize!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -287,7 +285,6 @@ default_imp_for_webhook_source_verification!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -318,7 +315,6 @@ default_imp_for_webhook_source_verification!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -372,7 +368,6 @@ default_imp_for_create_customer!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -403,7 +398,6 @@ default_imp_for_create_customer!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Trustpay, connector::Wellsfargo, @@ -453,7 +447,6 @@ default_imp_for_connector_redirect_response!( connector::Boku, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Gocardless, @@ -478,7 +471,6 @@ default_imp_for_connector_redirect_response!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Wellsfargo, connector::Wellsfargopayout, @@ -618,7 +610,6 @@ default_imp_for_accept_dispute!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -650,7 +641,6 @@ default_imp_for_accept_dispute!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -724,7 +714,6 @@ default_imp_for_file_upload!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -755,7 +744,6 @@ default_imp_for_file_upload!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Trustpay, connector::Opennode, @@ -807,7 +795,6 @@ default_imp_for_submit_evidence!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -838,7 +825,6 @@ default_imp_for_submit_evidence!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Trustpay, connector::Opennode, @@ -890,7 +876,6 @@ default_imp_for_defend_dispute!( connector::Braintree, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Globalpay, connector::Forte, @@ -921,7 +906,6 @@ default_imp_for_defend_dispute!( connector::Riskified, connector::Shift4, connector::Signifyd, - connector::Square, connector::Stripe, connector::Threedsecureio, connector::Trustpay, @@ -988,7 +972,6 @@ default_imp_for_pre_processing_steps!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Iatapay, connector::Itaubank, @@ -1014,7 +997,6 @@ default_imp_for_pre_processing_steps!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Wellsfargo, connector::Wellsfargopayout, @@ -1059,7 +1041,6 @@ default_imp_for_post_processing_steps!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Iatapay, connector::Itaubank, @@ -1083,7 +1064,6 @@ default_imp_for_post_processing_steps!( connector::Rapyd, connector::Riskified, connector::Signifyd, - connector::Square, connector::Threedsecureio, connector::Wellsfargo, connector::Wellsfargopayout, @@ -1218,7 +1198,6 @@ default_imp_for_payouts_create!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1247,7 +1226,6 @@ default_imp_for_payouts_create!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1301,7 +1279,6 @@ default_imp_for_payouts_retrieve!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1332,7 +1309,6 @@ default_imp_for_payouts_retrieve!( connector::Riskified, connector::Signifyd, connector::Stripe, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1389,7 +1365,6 @@ default_imp_for_payouts_eligibility!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1419,7 +1394,6 @@ default_imp_for_payouts_eligibility!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -1471,7 +1445,6 @@ default_imp_for_payouts_fulfill!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1499,7 +1472,6 @@ default_imp_for_payouts_fulfill!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1552,7 +1524,6 @@ default_imp_for_payouts_cancel!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1582,7 +1553,6 @@ default_imp_for_payouts_cancel!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1636,7 +1606,6 @@ default_imp_for_payouts_quote!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1666,7 +1635,6 @@ default_imp_for_payouts_quote!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -1721,7 +1689,6 @@ default_imp_for_payouts_recipient!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Forte, connector::Globalpay, connector::Gocardless, @@ -1751,7 +1718,6 @@ default_imp_for_payouts_recipient!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1808,7 +1774,6 @@ default_imp_for_payouts_recipient_account!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1839,7 +1804,6 @@ default_imp_for_payouts_recipient_account!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Shift4, connector::Threedsecureio, connector::Trustpay, @@ -1893,7 +1857,6 @@ default_imp_for_approve!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -1924,7 +1887,6 @@ default_imp_for_approve!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -1979,7 +1941,6 @@ default_imp_for_reject!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2010,7 +1971,6 @@ default_imp_for_reject!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2155,7 +2115,6 @@ default_imp_for_frm_sale!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2184,7 +2143,6 @@ default_imp_for_frm_sale!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2241,7 +2199,6 @@ default_imp_for_frm_checkout!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2270,7 +2227,6 @@ default_imp_for_frm_checkout!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2327,7 +2283,6 @@ default_imp_for_frm_transaction!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2356,7 +2311,6 @@ default_imp_for_frm_transaction!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2413,7 +2367,6 @@ default_imp_for_frm_fulfillment!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2442,7 +2395,6 @@ default_imp_for_frm_fulfillment!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2499,7 +2451,6 @@ default_imp_for_frm_record_return!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2528,7 +2479,6 @@ default_imp_for_frm_record_return!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2582,7 +2532,6 @@ default_imp_for_incremental_authorization!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2613,7 +2562,6 @@ default_imp_for_incremental_authorization!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2664,7 +2612,6 @@ default_imp_for_revoking_mandates!( connector::Braintree, connector::Checkout, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2694,7 +2641,6 @@ default_imp_for_revoking_mandates!( connector::Razorpay, connector::Riskified, connector::Signifyd, - connector::Square, connector::Stripe, connector::Shift4, connector::Threedsecureio, @@ -2906,7 +2852,6 @@ default_imp_for_authorize_session_token!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -2988,7 +2933,6 @@ default_imp_for_calculate_tax!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -3018,7 +2962,6 @@ default_imp_for_calculate_tax!( connector::Rapyd, connector::Razorpay, connector::Riskified, - connector::Square, connector::Signifyd, connector::Stripe, connector::Shift4, @@ -3072,7 +3015,6 @@ default_imp_for_session_update!( connector::Checkout, connector::Cybersource, connector::Datatrans, - connector::Dlocal, connector::Ebanx, connector::Forte, connector::Globalpay, @@ -3102,7 +3044,6 @@ default_imp_for_session_update!( connector::Rapyd, connector::Razorpay, connector::Riskified, - connector::Square, connector::Signifyd, connector::Stripe, connector::Shift4,
2024-09-30T08:36:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Move conector Dlocal and Square from router to hyperswitch_connector crate ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? 1. Create Merchant Account ``` curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1727684785", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "https://www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://google.com/success", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" }, "primary_business_details": [ { "country": "US", "business": "food" } ] }' ``` 2. Create API Key ``` curl --location 'http://localhost:8080/api_keys/merchant_1727684450' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2038-01-19T03:14:08.000Z" }' ``` 3. Create Payment Connector for Dlocal ``` curl --location 'http://localhost:8080/account/merchant_1727684450/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "dlocal", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "_____", "key1": "_____", "api_secret" : "_____" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245", "brand_id": "001", "destination_account_number": "5001000001223369" }, "business_country": "US", "business_label": "food" }' ``` 4. Payment Create ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ______' \ --data-raw '{ "amount": 60000, "currency": "BRL", "confirm": true, "capture_method": "automatic", "capture_on": "2024-09-10T10:11:12Z", "amount_to_capture": 60000, "customer_id": "jsdhfgbds", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "debit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "02", "card_exp_year": "37", "card_holder_name": "joseph Doe", "card_cvc": "999" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BR", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "dlocal" } }' ``` 5. Response ``` { "payment_id": "pay_2cRAibQolK8jdZr1Teai", "merchant_id": "merchant_1727684450", "status": "succeeded", "amount": 60000, "net_amount": 60000, "amount_capturable": 0, "amount_received": 60000, "connector": "dlocal", "client_secret": "pay_2cRAibQolK8jdZr1Teai_secret_tINYaNt6LoYfuq2wD2Am", "created": "2024-09-30T08:20:54.759Z", "currency": "BRL", "customer_id": "jsdhfgbds", "customer": { "id": "jsdhfgbds", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "02", "card_exp_year": "37", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BR", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "jsdhfgbds", "created_at": 1727684454, "expires": 1727688054, "secret": "epk_ed5899814cc94112940d95f020cdb9aa" }, "manual_retry_allowed": false, "connector_transaction_id": "T-413100-f19a6e86-e95d-4e9e-bb5c-e27371ae8aa0", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_2cRAibQolK8jdZr1Teai_1", "payment_link": null, "profile_id": "pro_9mhY0ulaJuedDbQRGBDi", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_x0MV7McpNzabX1vANWza", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-30T08:35:54.759Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-30T08:20:56.357Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
dcec2a2bff082b606cc3376e9451d53ed6ecdf04
juspay/hyperswitch
juspay__hyperswitch-6139
Bug: [REFACTOR]: [RISKIFIED] Add amount conversion framework to Riskified ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://support.riskified.com/hc/en-us/articles/360012160393-API-Integration-Guide) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs index 0f8ebb46134..7d9feec717a 100644 --- a/crates/router/src/connector/riskified.rs +++ b/crates/router/src/connector/riskified.rs @@ -1,8 +1,10 @@ pub mod transformers; -use std::fmt::Debug; #[cfg(feature = "frm")] use base64::Engine; +use common_utils::types::{ + AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, +}; #[cfg(feature = "frm")] use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; #[cfg(feature = "frm")] @@ -14,6 +16,7 @@ use ring::hmac; #[cfg(feature = "frm")] use transformers as riskified; +use super::utils::convert_amount; #[cfg(feature = "frm")] use super::utils::{self as connector_utils, FrmTransactionRouterDataRequest}; use crate::{ @@ -35,10 +38,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Riskified; +#[derive(Clone)] +pub struct Riskified { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} impl Riskified { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } + #[cfg(feature = "frm")] pub fn generate_authorization_signature( &self, @@ -173,7 +184,17 @@ impl req: &frm_types::FrmCheckoutRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let req_obj = riskified::RiskifiedPaymentsCheckoutRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.amount), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + )?; + let req_data = riskified::RiskifiedRouterData::from((amount, req)); + let req_obj = riskified::RiskifiedPaymentsCheckoutRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } @@ -293,7 +314,17 @@ impl Ok(RequestContent::Json(Box::new(req_obj))) } _ => { - let req_obj = riskified::TransactionSuccessRequest::try_from(req)?; + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.amount), + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + )?; + let req_data = riskified::RiskifiedRouterData::from((amount, req)); + let req_obj = riskified::TransactionSuccessRequest::try_from(&req_data)?; Ok(RequestContent::Json(Box::new(req_obj))) } } diff --git a/crates/router/src/connector/riskified/transformers/api.rs b/crates/router/src/connector/riskified/transformers/api.rs index d2d38855daf..bbeb045f692 100644 --- a/crates/router/src/connector/riskified/transformers/api.rs +++ b/crates/router/src/connector/riskified/transformers/api.rs @@ -1,5 +1,10 @@ use api_models::payments::AdditionalPaymentData; -use common_utils::{ext_traits::ValueExt, id_type, pii::Email}; +use common_utils::{ + ext_traits::ValueExt, + id_type, + pii::Email, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, +}; use error_stack::{self, ResultExt}; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -7,17 +12,37 @@ use time::PrimitiveDateTime; use crate::{ connector::utils::{ - AddressDetailsData, FraudCheckCheckoutRequest, FraudCheckTransactionRequest, RouterData, + convert_amount, AddressDetailsData, FraudCheckCheckoutRequest, + FraudCheckTransactionRequest, RouterData, }, core::{errors, fraud_check::types as core_types}, types::{ - self, api, api::Fulfillment, fraud_check as frm_types, storage::enums as storage_enums, + self, + api::{self, Fulfillment}, + fraud_check as frm_types, + storage::enums as storage_enums, ResponseId, ResponseRouterData, }, }; type Error = error_stack::Report<errors::ConnectorError>; +pub struct RiskifiedRouterData<T> { + pub amount: StringMajorUnit, + pub router_data: T, + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} + +impl<T> From<(StringMajorUnit, T)> for RiskifiedRouterData<T> { + fn from((amount, router_data): (StringMajorUnit, T)) -> Self { + Self { + amount, + router_data, + amount_converter: &StringMajorUnitForConnector, + } + } +} + #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct RiskifiedPaymentsCheckoutRequest { order: CheckoutRequest, @@ -35,7 +60,7 @@ pub struct CheckoutRequest { updated_at: PrimitiveDateTime, gateway: Option<String>, browser_ip: Option<std::net::IpAddr>, - total_price: i64, + total_price: StringMajorUnit, total_discounts: i64, cart_token: String, referring_site: String, @@ -60,13 +85,13 @@ pub struct PaymentDetails { #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct ShippingLines { - price: i64, + price: StringMajorUnit, title: Option<String>, } #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct DiscountCodes { - amount: i64, + amount: StringMajorUnit, code: Option<String>, } @@ -110,7 +135,7 @@ pub struct OrderAddress { #[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)] pub struct LineItem { - price: i64, + price: StringMajorUnit, quantity: i32, title: String, product_type: Option<api_models::payments::ProductType>, @@ -132,9 +157,14 @@ pub struct RiskifiedMetadata { shipping_lines: Vec<ShippingLines>, } -impl TryFrom<&frm_types::FrmCheckoutRouterData> for RiskifiedPaymentsCheckoutRequest { +impl TryFrom<&RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>> + for RiskifiedPaymentsCheckoutRequest +{ type Error = Error; - fn try_from(payment_data: &frm_types::FrmCheckoutRouterData) -> Result<Self, Self::Error> { + fn try_from( + payment: &RiskifiedRouterData<&frm_types::FrmCheckoutRouterData>, + ) -> Result<Self, Self::Error> { + let payment_data = payment.router_data.clone(); let metadata: RiskifiedMetadata = payment_data .frm_metadata .clone() @@ -148,6 +178,33 @@ impl TryFrom<&frm_types::FrmCheckoutRouterData> for RiskifiedPaymentsCheckoutReq let billing_address = payment_data.get_billing()?; let shipping_address = payment_data.get_shipping_address_with_phone_number()?; let address = payment_data.get_billing_address()?; + let line_items = payment_data + .request + .get_order_details()? + .iter() + .map(|order_detail| { + let price = convert_amount( + payment.amount_converter, + order_detail.amount, + payment_data.request.currency.ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { + field_name: "currency", + } + })?, + )?; + + Ok(LineItem { + price, + quantity: i32::from(order_detail.quantity), + title: order_detail.product_name.clone(), + product_type: order_detail.product_type.clone(), + requires_shipping: order_detail.requires_shipping, + product_id: order_detail.product_id.clone(), + category: order_detail.category.clone(), + brand: order_detail.brand.clone(), + }) + }) + .collect::<Result<Vec<_>, Self::Error>>()?; Ok(Self { order: CheckoutRequest { @@ -156,23 +213,9 @@ impl TryFrom<&frm_types::FrmCheckoutRouterData> for RiskifiedPaymentsCheckoutReq created_at: common_utils::date_time::now(), updated_at: common_utils::date_time::now(), gateway: payment_data.request.gateway.clone(), - total_price: payment_data.request.amount, + total_price: payment.amount.clone(), cart_token: payment_data.attempt_id.clone(), - line_items: payment_data - .request - .get_order_details()? - .iter() - .map(|order_detail| LineItem { - price: order_detail.amount.get_amount_as_i64(), // This should be changed to MinorUnit when we implement amount conversion for this connector. Additionally, the function get_amount_as_i64() should be avoided in the future. - quantity: i32::from(order_detail.quantity), - title: order_detail.product_name.clone(), - product_type: order_detail.product_type.clone(), - requires_shipping: order_detail.requires_shipping, - product_id: order_detail.product_id.clone(), - category: order_detail.category.clone(), - brand: order_detail.brand.clone(), - }) - .collect::<Vec<_>>(), + line_items, source: Source::DesktopWeb, billing_address: OrderAddress::try_from(billing_address).ok(), shipping_address: OrderAddress::try_from(shipping_address).ok(), @@ -411,7 +454,7 @@ pub struct SuccessfulTransactionData { pub struct TransactionDecisionData { external_status: TransactionStatus, reason: Option<String>, - amount: i64, + amount: StringMajorUnit, currency: storage_enums::Currency, #[serde(with = "common_utils::custom_serde::iso8601")] decided_at: PrimitiveDateTime, @@ -429,16 +472,21 @@ pub enum TransactionStatus { Approved, } -impl TryFrom<&frm_types::FrmTransactionRouterData> for TransactionSuccessRequest { +impl TryFrom<&RiskifiedRouterData<&frm_types::FrmTransactionRouterData>> + for TransactionSuccessRequest +{ type Error = Error; - fn try_from(item: &frm_types::FrmTransactionRouterData) -> Result<Self, Self::Error> { + fn try_from( + item_data: &RiskifiedRouterData<&frm_types::FrmTransactionRouterData>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data.clone(); Ok(Self { order: SuccessfulTransactionData { id: item.attempt_id.clone(), decision: TransactionDecisionData { external_status: TransactionStatus::Approved, reason: None, - amount: item.request.amount, + amount: item_data.amount.clone(), currency: item.request.get_currency()?, decided_at: common_utils::date_time::now(), payment_details: [TransactionPaymentDetails { diff --git a/crates/router/src/types/api/fraud_check.rs b/crates/router/src/types/api/fraud_check.rs index 2d1a42092f4..213aef9cf03 100644 --- a/crates/router/src/types/api/fraud_check.rs +++ b/crates/router/src/types/api/fraud_check.rs @@ -51,7 +51,7 @@ impl FraudCheckConnectorData { Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd))) } enums::FrmConnectors::Riskified => { - Ok(ConnectorEnum::Old(Box::new(&connector::Riskified))) + Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new()))) } } }
2024-10-17T18:02:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR does amount conversion changes for Riskified Connector and it accepts the amount in MinorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes https://github.com/juspay/hyperswitch/issues/6139 ## Test Case 1. Create an FRM payment with Riskified ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_zDKkW8FG9RWqLNhMLVekbZbKOO1AYL8AEOQMKBQx0e0MbbmvKbGF32hdEnyA4JuS' \ --data-raw '{ "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1000, "customer_id": "StripeCustomer2", "email": "guest@example.com", "name": "Bob Smith", "phone": "999999999", "phone_country_code": "+91", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "IN", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "31 Sherwood Gardens", "line3": "31 Sherwood Gardens", "city": "London", "state": "Manchester", "zip": "E14 9wn", "country": "GB", "first_name": "Bob", "last_name": "Smith" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "frm_metadata": { "vendor_name": "srujan", "shipping_lines": [ { "price": 240, "title": "customer" } ] }, "order_details": [ { "product_name": "gillete creme", "quantity": 2, "amount": 600 }, { "product_name": "gillete razor", "quantity": 1, "amount": 300 } ] }' ``` Response ``` { "payment_id": "pay_p2PnkzcC76EiUfkMHoS3", "merchant_id": "merchant_1732534203", "status": "succeeded", "amount": 1000, "net_amount": 1000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 1000, "connector": "stripe", "client_secret": "pay_p2PnkzcC76EiUfkMHoS3_secret_aJ2PoxDPJ177jxjuLJtI", "created": "2024-11-25T12:18:24.319Z", "currency": "USD", "customer_id": "StripeCustomer2", "customer": { "id": "StripeCustomer2", "name": "Bob Smith", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+91" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": null, "payment_checks": { "cvc_check": "pass", "address_line1_check": "pass", "address_postal_code_check": "pass" }, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "London", "country": "GB", "line1": "1467", "line2": "31 Sherwood Gardens", "line3": "31 Sherwood Gardens", "zip": "E14 9wn", "state": "Manchester", "first_name": "Bob", "last_name": "Smith" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "IN", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "brand": null, "amount": 600, "category": null, "quantity": 2, "product_id": null, "product_name": "gillete creme", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "requires_shipping": null }, { "brand": null, "amount": 300, "category": null, "quantity": 1, "product_id": null, "product_name": "gillete razor", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "requires_shipping": null } ], "email": "guest@example.com", "name": "Bob Smith", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer2", "created_at": 1732537104, "expires": 1732540704, "secret": "epk_af52a2410328468da0efcceab4721688" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3QP1FGD5R7gDAGff0hjO4CcX", "frm_message": { "frm_name": "riskified", "frm_transaction_id": "pay_p2PnkzcC76EiUfkMHoS3_1", "frm_transaction_type": "pre_frm", "frm_status": "legit", "frm_score": null, "frm_reason": "Reviewed and approved by Riskified", "frm_error": null }, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3QP1FGD5R7gDAGff0hjO4CcX", "payment_link": null, "profile_id": "pro_zRAcxSJqv3OTKIPGkuxI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_TSlADmpiVd230wMhKj67", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-25T12:33:24.319Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-25T12:18:27.847Z", "charges": null, "frm_metadata": { "vendor_name": "srujan", "shipping_lines": [ { "price": 240, "title": "customer" } ] }, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
cd6265887adf7c17136e9fb608e97e6dd535e360
juspay/hyperswitch
juspay__hyperswitch-6122
Bug: [REFACTOR]: [SHIFT4] Add amount conversion framework to Shift4 ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://dev.shift4.com/docs/api#cards) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 895487db3ba..08c23bc5710 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -1,8 +1,10 @@ pub mod transformers; -use std::fmt::Debug; - -use common_utils::{ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{ + ext_traits::ByteSliceExt, + request::RequestContent, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; use diesel_models::enums; use error_stack::{report, ResultExt}; use transformers as shift4; @@ -27,8 +29,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Shift4; +#[derive(Clone)] +pub struct Shift4 { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Shift4 { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Shift4 where @@ -206,7 +218,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = shift4::Shift4PaymentsRequest::try_from(req)?; + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?; + let connector_req = shift4::Shift4PaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -470,7 +488,21 @@ impl req: &types::PaymentsPreProcessingRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = shift4::Shift4PaymentsRequest::try_from(req)?; + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount.ok_or_else(|| { + errors::ConnectorError::MissingRequiredField { + field_name: "minor_amount", + } + })?, + req.request + .currency + .ok_or_else(|| errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?, + )?; + let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?; + let connector_req = shift4::Shift4PaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -559,7 +591,13 @@ impl req: &types::PaymentsCompleteAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = shift4::Shift4PaymentsRequest::try_from(req)?; + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?; + let connector_req = shift4::Shift4PaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -641,7 +679,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = shift4::Shift4RefundRequest::try_from(req)?; + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + let connector_router_data = shift4::Shift4RouterData::try_from((amount, req))?; + let connector_req = shift4::Shift4RefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 2210ab0a361..3b768151115 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -1,6 +1,6 @@ use api_models::payments; use cards::CardNumber; -use common_utils::pii::SecretSerdeValue; +use common_utils::{pii::SecretSerdeValue, types::MinorUnit}; use error_stack::ResultExt; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -23,11 +23,25 @@ trait Shift4AuthorizePreprocessingCommon { fn get_router_return_url(&self) -> Option<String>; fn get_email_optional(&self) -> Option<pii::Email>; fn get_complete_authorize_url(&self) -> Option<String>; - fn get_amount_required(&self) -> Result<i64, Error>; fn get_currency_required(&self) -> Result<diesel_models::enums::Currency, Error>; fn get_payment_method_data_required(&self) -> Result<domain::PaymentMethodData, Error>; } +pub struct Shift4RouterData<T> { + pub amount: MinorUnit, + pub router_data: T, +} + +impl<T> TryFrom<(MinorUnit, T)> for Shift4RouterData<T> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data: item, + }) + } +} + impl Shift4AuthorizePreprocessingCommon for types::PaymentsAuthorizeData { fn get_email_optional(&self) -> Option<pii::Email> { self.email.clone() @@ -37,10 +51,6 @@ impl Shift4AuthorizePreprocessingCommon for types::PaymentsAuthorizeData { self.complete_authorize_url.clone() } - fn get_amount_required(&self) -> Result<i64, error_stack::Report<errors::ConnectorError>> { - Ok(self.amount) - } - fn get_currency_required( &self, ) -> Result<diesel_models::enums::Currency, error_stack::Report<errors::ConnectorError>> { @@ -70,10 +80,6 @@ impl Shift4AuthorizePreprocessingCommon for types::PaymentsPreProcessingData { self.complete_authorize_url.clone() } - fn get_amount_required(&self) -> Result<i64, Error> { - self.get_amount() - } - fn get_currency_required(&self) -> Result<diesel_models::enums::Currency, Error> { self.get_currency() } @@ -95,7 +101,7 @@ impl Shift4AuthorizePreprocessingCommon for types::PaymentsPreProcessingData { } #[derive(Debug, Serialize)] pub struct Shift4PaymentsRequest { - amount: String, + amount: MinorUnit, currency: enums::Currency, captured: bool, #[serde(flatten)] @@ -195,19 +201,19 @@ pub enum CardPayment { CardToken(Secret<String>), } -impl<T, Req> TryFrom<&types::RouterData<T, Req, types::PaymentsResponseData>> +impl<T, Req> TryFrom<&Shift4RouterData<&types::RouterData<T, Req, types::PaymentsResponseData>>> for Shift4PaymentsRequest where Req: Shift4AuthorizePreprocessingCommon, { type Error = Error; fn try_from( - item: &types::RouterData<T, Req, types::PaymentsResponseData>, + item: &Shift4RouterData<&types::RouterData<T, Req, types::PaymentsResponseData>>, ) -> Result<Self, Self::Error> { - let submit_for_settlement = item.request.is_automatic_capture()?; - let amount = item.request.get_amount_required()?.to_string(); - let currency = item.request.get_currency_required()?; - let payment_method = Shift4PaymentMethod::try_from(item)?; + let submit_for_settlement = item.router_data.request.is_automatic_capture()?; + let amount = item.amount.to_owned(); + let currency = item.router_data.request.get_currency_required()?; + let payment_method = Shift4PaymentMethod::try_from(item.router_data)?; Ok(Self { amount, currency, @@ -437,27 +443,33 @@ where } } -impl<T> TryFrom<&types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>> - for Shift4PaymentsRequest +impl<T> + TryFrom< + &Shift4RouterData< + &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>, + >, + > for Shift4PaymentsRequest { type Error = Error; fn try_from( - item: &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>, + item: &Shift4RouterData< + &types::RouterData<T, types::CompleteAuthorizeData, types::PaymentsResponseData>, + >, ) -> Result<Self, Self::Error> { - match &item.request.payment_method_data { + match &item.router_data.request.payment_method_data { Some(domain::PaymentMethodData::Card(_)) => { let card_token: Shift4CardToken = - to_connector_meta(item.request.connector_meta.clone())?; + to_connector_meta(item.router_data.request.connector_meta.clone())?; Ok(Self { - amount: item.request.amount.to_string(), - currency: item.request.currency, + amount: item.amount.to_owned(), + currency: item.router_data.request.currency, payment_method: Shift4PaymentMethod::CardsNon3DSRequest(Box::new( CardsNon3DSRequest { card: CardPayment::CardToken(card_token.id), - description: item.description.clone(), + description: item.router_data.description.clone(), }, )), - captured: item.request.is_auto_capture()?, + captured: item.router_data.request.is_auto_capture()?, }) } Some(domain::PaymentMethodData::Wallet(_)) @@ -687,7 +699,7 @@ pub struct Token { #[derive(Default, Debug, Deserialize, Serialize)] pub struct ThreeDSecureInfo { - pub amount: i64, + pub amount: MinorUnit, pub currency: String, pub enrolled: bool, #[serde(rename = "liabilityShift")] @@ -814,15 +826,17 @@ impl<T, F> #[serde(rename_all = "camelCase")] pub struct Shift4RefundRequest { charge_id: String, - amount: i64, + amount: MinorUnit, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for Shift4RefundRequest { +impl<F> TryFrom<&Shift4RouterData<&types::RefundsRouterData<F>>> for Shift4RefundRequest { type Error = Error; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from( + item: &Shift4RouterData<&types::RefundsRouterData<F>>, + ) -> Result<Self, Self::Error> { Ok(Self { - charge_id: item.request.connector_transaction_id.clone(), - amount: item.request.refund_amount, + charge_id: item.router_data.request.connector_transaction_id.clone(), + amount: item.amount.to_owned(), }) } } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 5300e86afdb..18283834cf0 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -473,7 +473,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new()))) } enums::Connector::Rapyd => Ok(ConnectorEnum::Old(Box::new(&connector::Rapyd))), - enums::Connector::Shift4 => Ok(ConnectorEnum::Old(Box::new(&connector::Shift4))), + enums::Connector::Shift4 => { + Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) + } enums::Connector::Square => Ok(ConnectorEnum::Old(Box::new(&connector::Square))), enums::Connector::Stax => Ok(ConnectorEnum::Old(Box::new(&connector::Stax))), enums::Connector::Stripe => { diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs index fdaa1ebedef..ce10c9dad1a 100644 --- a/crates/router/tests/connectors/shift4.rs +++ b/crates/router/tests/connectors/shift4.rs @@ -15,7 +15,7 @@ impl utils::Connector for Shift4Test { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Shift4; utils::construct_connector_data_old( - Box::new(&Shift4), + Box::new(Shift4::new()), types::Connector::Shift4, types::api::GetToken::Connector, None,
2024-10-07T11:52:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [X] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds amount conversion framework to Shift4, for sending to connector. Resolves #6122 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3d1a3cdc8f942a3dca2e6a200bf9200366bd62f1
juspay/hyperswitch
juspay__hyperswitch-6116
Bug: [FEATURE] Update worldpay connector's integration # Storing long connector transaction IDs (\>128 characters) ## Aim This issue describes the approach for efficiently storing long connector transaction IDs in HyperSwitch application. ## Context HyperSwitch is integrated with multiple connectors, these underlying connectors generate their own resource IDs which are stored in HyperSwitch DB for future references and / or debugging. For payments, this is stored in payment\_attempt table \- `connector_transaction_id` For refunds, this is stored in refunds table \- `connector_refund_id` For captures, this is stored in captures table \- `connector_capture_id` Both these columns are of size 128 characters in length, giving ample amount of space for storing these resource identifiers. Some connectors \- like Worldpay, use a different approach for their resource identifiers. Worldpay uses an encrypted token as its resource identifier whose length usually exceeds 450 characters. HyperSwitch cannot keep increasing the length of these two columns for storing IDs with such large lengths due to performance impacts on both read and write, specifically during webhooks flows as `connector_transaction_id` is an indexed column. ## Solution Includes a bug fix and basically migrates the API endpoints to consume the v7 endpoints. Bug fix -`entity` is a param in their API spec for specifying the merchant's account. The solution requires making changes in two places \- 1. Convert `connector_transaction_id` to a typed enum with two variants in the application 1. `ConnectorTxnId` 2. `HashedConnectorData` 2. Introduce a new column per table for storing such large resource identifiers. ### Pre-requisites - Add a new column `connector_transaction_data` ### Storing large IDs - If input string length \> 128 characters, store this data in `connector_transaction_data` - Create a one-way hash of this data and store it in `connector_transaction_id` with a prefix `hs_hash_` ### Consuming large IDs - If input string length \> 128 characters, create a hash and query using the hashed value - Deserialize `connector_transaction_id` into a typed variant \- either `ConnectorTxnId` or `HashedConnectorData` based on the prefix (`hs_hash_`) - If it’s `HashedConnectorData`, use `connector_transaction_data` as resource ID ## Example Let’s say we want to extend storage of such IDs to payment attempts table 1. Add a new column in the said table \- `connector_transaction_data` 2. While receiving these IDs (assuming length \>128), store in `connector_transaction_data` 3. Create a one-way hash and store in `connector_transaction_id` 4. While querying using these IDs (webhooks flow), create a hash and query using the hashed value 5. Use `connector_transaction_data` instead of `connector_transaction_id` in application and application responses ## Notes - Never expose the hashed `connector_transaction_id’s` outside the system, i.e. in API responses or webhook responses - Deserialize into `HashedConnectorData` only when the `connector_transaction_id` is prefixed with `hs_hash_` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index e16a206b118..5d6d4049dea 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -6018,6 +6018,7 @@ "description": "The three letter ISO currency code in uppercase. Eg: 'USD' for the United States Dollar.", "enum": [ "AED", + "AFN", "ALL", "AMD", "ANG", @@ -6037,10 +6038,12 @@ "BOB", "BRL", "BSD", + "BTN", "BWP", "BYN", "BZD", "CAD", + "CDF", "CHF", "CLP", "CNY", @@ -6054,6 +6057,7 @@ "DOP", "DZD", "EGP", + "ERN", "ETB", "EUR", "FJD", @@ -6075,6 +6079,8 @@ "ILS", "INR", "IQD", + "IRR", + "ISK", "JMD", "JOD", "JPY", @@ -6082,6 +6088,7 @@ "KGS", "KHR", "KMF", + "KPW", "KRW", "KWD", "KYD", @@ -6128,6 +6135,7 @@ "SAR", "SBD", "SCR", + "SDG", "SEK", "SGD", "SHP", @@ -6138,8 +6146,11 @@ "SSP", "STN", "SVC", + "SYP", "SZL", "THB", + "TJS", + "TMT", "TND", "TOP", "TRY", @@ -6161,7 +6172,8 @@ "XPF", "YER", "ZAR", - "ZMW" + "ZMW", + "ZWL" ] }, "CustomerAcceptance": { diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 4f742a61698..dafc6048154 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -323,8 +323,10 @@ upi_collect = {country = "IN", currency = "INR"} open_banking_pis = {currency = "EUR,GBP"} [pm_filters.worldpay] -apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" -google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" +debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" } +apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" } [pm_filters.zen] boleto = { country = "BR", currency = "BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index c25b70d6ba0..caf8c030568 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -336,8 +336,10 @@ upi_collect = {country = "IN", currency = "INR"} open_banking_pis = {currency = "EUR,GBP"} [pm_filters.worldpay] -apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" -google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" +debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" } +apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" } [pm_filters.zen] boleto = { country = "BR", currency = "BRL" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 28f5a4e0575..6cc1193ab55 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -340,6 +340,8 @@ upi_collect = {country = "IN", currency = "INR"} open_banking_pis = {currency = "EUR,GBP"} [pm_filters.worldpay] +debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SAR,RSD,SCR,SLL,SG,ST,SBD,SOS,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,TMT,AED,UG,UA,US,UZ,VU,VE,VN,YER,CNY,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SAR,RSD,SCR,SLL,SG,ST,SBD,SOS,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,TMT,AED,UG,UA,US,UZ,VU,VE,VN,YER,CNY,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" google_pay.country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" diff --git a/config/development.toml b/config/development.toml index 0153c6ef102..4c2f1cf718e 100644 --- a/config/development.toml +++ b/config/development.toml @@ -518,6 +518,8 @@ google_pay = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } paypal = { currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD" } [pm_filters.worldpay] +debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" } apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 5ffe5df138f..d55e722b3e0 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -441,6 +441,12 @@ credit = { currency = "USD" } debit = { currency = "USD" } ach = { currency = "USD" } +[pm_filters.worldpay] +debit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +credit = { country = "AF,DZ,AW,AU,AZ,BS,BH,BD,BB,BZ,BM,BT,BO,BA,BW,BR,BN,BG,BI,KH,CA,CV,KY,CL,CO,KM,CD,CR,CZ,DK,DJ,ST,DO,EC,EG,SV,ER,ET,FK,FJ,GM,GE,GH,GI,GT,GN,GY,HT,HN,HK,HU,IS,IN,ID,IR,IQ,IE,IL,IT,JM,JP,JO,KZ,KE,KW,LA,LB,LS,LR,LY,LT,MO,MK,MG,MW,MY,MV,MR,MU,MX,MD,MN,MA,MZ,MM,NA,NZ,NI,NG,KP,NO,AR,PK,PG,PY,PE,UY,PH,PL,GB,QA,OM,RO,RU,RW,WS,SG,ST,ZA,KR,LK,SH,SD,SR,SZ,SE,CH,SY,TW,TJ,TZ,TH,TT,TN,TR,UG,UA,US,UZ,VU,VE,VN,ZM,ZW", currency = "AFN,DZD,ANG,AWG,AUD,AZN,BSD,BHD,BDT,BBD,BZD,BMD,BTN,BOB,BAM,BWP,BRL,BND,BGN,BIF,KHR,CAD,CVE,KYD,XOF,XAF,XPF,CLP,COP,KMF,CDF,CRC,EUR,CZK,DKK,DJF,DOP,XCD,EGP,SVC,ERN,ETB,EUR,FKP,FJD,GMD,GEL,GHS,GIP,GTQ,GNF,GYD,HTG,HNL,HKD,HUF,ISK,INR,IDR,IRR,IQD,ILS,JMD,JPY,JOD,KZT,KES,KWD,LAK,LBP,LSL,LRD,LYD,MOP,MKD,MGA,MWK,MYR,MVR,MRU,MUR,MXN,MDL,MNT,MAD,MZN,MMK,NAD,NPR,NZD,NIO,NGN,KPW,NOK,ARS,PKR,PAB,PGK,PYG,PEN,UYU,PHP,PLN,GBP,QAR,OMR,RON,RUB,RWF,WST,SAR,RSD,SCR,SLL,SGD,STN,SBD,SOS,ZAR,KRW,LKR,SHP,SDG,SRD,SZL,SEK,CHF,SYP,TWD,TJS,TZS,THB,TOP,TTD,TND,TRY,TMT,AED,UGX,UAH,USD,UZS,VUV,VND,YER,CNY,ZMW,ZWL" } +google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" } +apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US" } + [bank_config.online_banking_fpx] adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" fiuu.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_of_china,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank" diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 0a87e6c19aa..8306deeb258 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -558,6 +558,7 @@ pub enum CallConnectorAction { #[router_derive::diesel_enum(storage_type = "db_enum")] pub enum Currency { AED, + AFN, ALL, AMD, ANG, @@ -577,10 +578,12 @@ pub enum Currency { BOB, BRL, BSD, + BTN, BWP, BYN, BZD, CAD, + CDF, CHF, CLP, CNY, @@ -594,6 +597,7 @@ pub enum Currency { DOP, DZD, EGP, + ERN, ETB, EUR, FJD, @@ -615,6 +619,8 @@ pub enum Currency { ILS, INR, IQD, + IRR, + ISK, JMD, JOD, JPY, @@ -622,6 +628,7 @@ pub enum Currency { KGS, KHR, KMF, + KPW, KRW, KWD, KYD, @@ -668,6 +675,7 @@ pub enum Currency { SAR, SBD, SCR, + SDG, SEK, SGD, SHP, @@ -678,8 +686,11 @@ pub enum Currency { SSP, STN, SVC, + SYP, SZL, THB, + TJS, + TMT, TND, TOP, TRY, @@ -703,6 +714,7 @@ pub enum Currency { YER, ZAR, ZMW, + ZWL, } impl Currency { @@ -756,6 +768,7 @@ impl Currency { pub fn iso_4217(&self) -> &'static str { match *self { Self::AED => "784", + Self::AFN => "971", Self::ALL => "008", Self::AMD => "051", Self::ANG => "532", @@ -775,10 +788,12 @@ impl Currency { Self::BOB => "068", Self::BRL => "986", Self::BSD => "044", + Self::BTN => "064", Self::BWP => "072", Self::BYN => "933", Self::BZD => "084", Self::CAD => "124", + Self::CDF => "976", Self::CHF => "756", Self::CLP => "152", Self::COP => "170", @@ -791,6 +806,7 @@ impl Currency { Self::DOP => "214", Self::DZD => "012", Self::EGP => "818", + Self::ERN => "232", Self::ETB => "230", Self::EUR => "978", Self::FJD => "242", @@ -812,6 +828,8 @@ impl Currency { Self::ILS => "376", Self::INR => "356", Self::IQD => "368", + Self::IRR => "364", + Self::ISK => "352", Self::JMD => "388", Self::JOD => "400", Self::JPY => "392", @@ -819,6 +837,7 @@ impl Currency { Self::KGS => "417", Self::KHR => "116", Self::KMF => "174", + Self::KPW => "408", Self::KRW => "410", Self::KWD => "414", Self::KYD => "136", @@ -866,6 +885,7 @@ impl Currency { Self::SAR => "682", Self::SBD => "090", Self::SCR => "690", + Self::SDG => "938", Self::SEK => "752", Self::SGD => "702", Self::SHP => "654", @@ -876,8 +896,11 @@ impl Currency { Self::SSP => "728", Self::STN => "930", Self::SVC => "222", + Self::SYP => "760", Self::SZL => "748", Self::THB => "764", + Self::TJS => "972", + Self::TMT => "934", Self::TND => "788", Self::TOP => "776", Self::TRY => "949", @@ -900,6 +923,7 @@ impl Currency { Self::YER => "886", Self::ZAR => "710", Self::ZMW => "967", + Self::ZWL => "932", } } @@ -909,6 +933,7 @@ impl Currency { | Self::CLP | Self::DJF | Self::GNF + | Self::IRR | Self::JPY | Self::KMF | Self::KRW @@ -922,6 +947,7 @@ impl Currency { | Self::XOF | Self::XPF => true, Self::AED + | Self::AFN | Self::ALL | Self::AMD | Self::ANG @@ -940,10 +966,12 @@ impl Currency { | Self::BOB | Self::BRL | Self::BSD + | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD + | Self::CDF | Self::CHF | Self::CNY | Self::COP @@ -955,6 +983,7 @@ impl Currency { | Self::DOP | Self::DZD | Self::EGP + | Self::ERN | Self::ETB | Self::EUR | Self::FJD @@ -975,11 +1004,13 @@ impl Currency { | Self::ILS | Self::INR | Self::IQD + | Self::ISK | Self::JMD | Self::JOD | Self::KES | Self::KGS | Self::KHR + | Self::KPW | Self::KWD | Self::KYD | Self::KZT @@ -1022,6 +1053,7 @@ impl Currency { | Self::SAR | Self::SBD | Self::SCR + | Self::SDG | Self::SEK | Self::SGD | Self::SHP @@ -1032,8 +1064,11 @@ impl Currency { | Self::SSP | Self::STN | Self::SVC + | Self::SYP | Self::SZL | Self::THB + | Self::TJS + | Self::TMT | Self::TND | Self::TOP | Self::TRY @@ -1049,7 +1084,8 @@ impl Currency { | Self::XCD | Self::YER | Self::ZAR - | Self::ZMW => false, + | Self::ZMW + | Self::ZWL => false, } } @@ -1059,6 +1095,7 @@ impl Currency { true } Self::AED + | Self::AFN | Self::ALL | Self::AMD | Self::AOA @@ -1077,10 +1114,12 @@ impl Currency { | Self::BOB | Self::BRL | Self::BSD + | Self::BTN | Self::BWP | Self::BYN | Self::BZD | Self::CAD + | Self::CDF | Self::CHF | Self::CLP | Self::CNY @@ -1094,6 +1133,7 @@ impl Currency { | Self::DOP | Self::DZD | Self::EGP + | Self::ERN | Self::ETB | Self::EUR | Self::FJD @@ -1114,12 +1154,15 @@ impl Currency { | Self::IDR | Self::ILS | Self::INR + | Self::IRR + | Self::ISK | Self::JMD | Self::JPY | Self::KES | Self::KGS | Self::KHR | Self::KMF + | Self::KPW | Self::KRW | Self::KYD | Self::KZT @@ -1163,6 +1206,7 @@ impl Currency { | Self::SAR | Self::SBD | Self::SCR + | Self::SDG | Self::SEK | Self::SGD | Self::SHP @@ -1173,8 +1217,11 @@ impl Currency { | Self::SSP | Self::STN | Self::SVC + | Self::SYP | Self::SZL | Self::THB + | Self::TJS + | Self::TMT | Self::TOP | Self::TRY | Self::TTD @@ -1195,7 +1242,8 @@ impl Currency { | Self::XOF | Self::YER | Self::ZAR - | Self::ZMW => false, + | Self::ZMW + | Self::ZWL => false, } } diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 00ffb614bb0..21e5866aea0 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -154,3 +154,7 @@ pub const MAX_DESCRIPTION_LENGTH: u16 = 255; pub const MAX_STATEMENT_DESCRIPTOR_LENGTH: u16 = 22; /// Payout flow identifier used for performing GSM operations pub const PAYOUT_FLOW_STR: &str = "payout_flow"; + +/// The number of bytes allocated for the hashed connector transaction ID. +/// Total number of characters equals CONNECTOR_TRANSACTION_ID_HASH_BYTES times 2. +pub const CONNECTOR_TRANSACTION_ID_HASH_BYTES: usize = 25; diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 0cad88bfd4f..855dd179b31 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1247,3 +1247,129 @@ where self.0.to_sql(out) } } + +/// Domain type for connector_transaction_id +/// Maximum length for connector's transaction_id can be 128 characters in HS DB. +/// In case connector's use an identifier whose length exceeds 128 characters, +/// the hash value of such identifiers will be stored as connector_transaction_id. +/// The actual connector's identifier will be stored in a separate column - +/// connector_transaction_data or something with a similar name. +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)] +#[diesel(sql_type = sql_types::Text)] +pub enum ConnectorTransactionId { + /// Actual transaction identifier + TxnId(String), + /// Hashed value of the transaction identifier + HashedData(String), +} + +impl ConnectorTransactionId { + /// Implementation for retrieving the inner identifier + pub fn get_id(&self) -> &String { + match self { + Self::TxnId(id) | Self::HashedData(id) => id, + } + } + + /// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and connector_transaction_data + pub fn form_id_and_data(src: String) -> (Self, Option<String>) { + let txn_id = Self::from(src.clone()); + match txn_id { + Self::TxnId(_) => (txn_id, None), + Self::HashedData(_) => (txn_id, Some(src)), + } + } + + /// Implementation for retrieving + pub fn get_txn_id<'a>( + &'a self, + txn_data: Option<&'a String>, + ) -> Result<&'a String, error_stack::Report<ValidationError>> { + match (self, txn_data) { + (Self::TxnId(id), _) => Ok(id), + (Self::HashedData(_), Some(id)) => Ok(id), + (Self::HashedData(id), None) => Err(report!(ValidationError::InvalidValue { + message: "connector_transaction_data is empty for HashedData variant".to_string(), + }) + .attach_printable(format!( + "connector_transaction_data is empty for connector_transaction_id {}", + id + ))), + } + } +} + +impl From<String> for ConnectorTransactionId { + fn from(src: String) -> Self { + // ID already hashed + if src.starts_with("hs_hash_") { + Self::HashedData(src) + // Hash connector's transaction ID + } else if src.len() > 128 { + let mut hasher = blake3::Hasher::new(); + let mut output = [0u8; consts::CONNECTOR_TRANSACTION_ID_HASH_BYTES]; + hasher.update(src.as_bytes()); + hasher.finalize_xof().fill(&mut output); + let hash = hex::encode(output); + Self::HashedData(format!("hs_hash_{}", hash)) + // Default + } else { + Self::TxnId(src) + } + } +} + +impl<DB> Queryable<sql_types::Text, DB> for ConnectorTransactionId +where + DB: Backend, + Self: FromSql<sql_types::Text, DB>, +{ + type Row = Self; + + fn build(row: Self::Row) -> deserialize::Result<Self> { + Ok(row) + } +} + +impl<DB> FromSql<sql_types::Text, DB> for ConnectorTransactionId +where + DB: Backend, + String: FromSql<sql_types::Text, DB>, +{ + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { + let val = String::from_sql(bytes)?; + Ok(Self::from(val)) + } +} + +impl<DB> ToSql<sql_types::Text, DB> for ConnectorTransactionId +where + DB: Backend, + String: ToSql<sql_types::Text, DB>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { + match self { + Self::HashedData(id) | Self::TxnId(id) => id.to_sql(out), + } + } +} + +/// Trait for fetching actual or hashed transaction IDs +pub trait ConnectorTransactionIdTrait { + /// Returns an optional connector transaction ID + fn get_optional_connector_transaction_id(&self) -> Option<&String> { + None + } + /// Returns a connector transaction ID + fn get_connector_transaction_id(&self) -> &String { + self.get_optional_connector_transaction_id() + .unwrap_or_else(|| { + static EMPTY_STRING: String = String::new(); + &EMPTY_STRING + }) + } + /// Returns an optional connector refund ID + fn get_optional_connector_refund_id(&self) -> Option<&String> { + self.get_optional_connector_transaction_id() + } +} diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index f4523cf6171..322186d0e42 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -3410,9 +3410,10 @@ merchant_secret="Source verification key" payment_method_type = "google_pay" [[worldpay.wallet]] payment_method_type = "apple_pay" -[worldpay.connector_auth.BodyKey] +[worldpay.connector_auth.SignatureKey] api_key="Username" key1="Password" +api_secret="Merchant Identifier" [worldpay.connector_webhook_details] merchant_secret="Source verification key" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index e0d83ff57f5..20faae246e5 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -2469,9 +2469,10 @@ merchant_secret="Source verification key" payment_method_type = "google_pay" [[worldpay.wallet]] payment_method_type = "apple_pay" -[worldpay.connector_auth.BodyKey] +[worldpay.connector_auth.SignatureKey] api_key="Username" key1="Password" +api_secret="Merchant Identifier" [[worldpay.metadata.apple_pay]] name="certificate" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 80a3af60c49..e7618315b7a 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -3400,9 +3400,10 @@ merchant_secret="Source verification key" payment_method_type = "google_pay" [[worldpay.wallet]] payment_method_type = "apple_pay" -[worldpay.connector_auth.BodyKey] +[worldpay.connector_auth.SignatureKey] api_key="Username" key1="Password" +api_secret="Merchant Identifier" [worldpay.connector_webhook_details] merchant_secret="Source verification key" diff --git a/crates/currency_conversion/src/types.rs b/crates/currency_conversion/src/types.rs index a84520dca0a..2001495b2db 100644 --- a/crates/currency_conversion/src/types.rs +++ b/crates/currency_conversion/src/types.rs @@ -78,6 +78,7 @@ impl ExchangeRates { pub fn currency_match(currency: Currency) -> &'static iso::Currency { match currency { Currency::AED => iso::AED, + Currency::AFN => iso::AFN, Currency::ALL => iso::ALL, Currency::AMD => iso::AMD, Currency::ANG => iso::ANG, @@ -97,10 +98,12 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::BOB => iso::BOB, Currency::BRL => iso::BRL, Currency::BSD => iso::BSD, + Currency::BTN => iso::BTN, Currency::BWP => iso::BWP, Currency::BYN => iso::BYN, Currency::BZD => iso::BZD, Currency::CAD => iso::CAD, + Currency::CDF => iso::CDF, Currency::CHF => iso::CHF, Currency::CLP => iso::CLP, Currency::CNY => iso::CNY, @@ -114,6 +117,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::DOP => iso::DOP, Currency::DZD => iso::DZD, Currency::EGP => iso::EGP, + Currency::ERN => iso::ERN, Currency::ETB => iso::ETB, Currency::EUR => iso::EUR, Currency::FJD => iso::FJD, @@ -135,6 +139,8 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::ILS => iso::ILS, Currency::INR => iso::INR, Currency::IQD => iso::IQD, + Currency::IRR => iso::IRR, + Currency::ISK => iso::ISK, Currency::JMD => iso::JMD, Currency::JOD => iso::JOD, Currency::JPY => iso::JPY, @@ -142,6 +148,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::KGS => iso::KGS, Currency::KHR => iso::KHR, Currency::KMF => iso::KMF, + Currency::KPW => iso::KPW, Currency::KRW => iso::KRW, Currency::KWD => iso::KWD, Currency::KYD => iso::KYD, @@ -188,6 +195,7 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::SAR => iso::SAR, Currency::SBD => iso::SBD, Currency::SCR => iso::SCR, + Currency::SDG => iso::SDG, Currency::SEK => iso::SEK, Currency::SGD => iso::SGD, Currency::SHP => iso::SHP, @@ -198,9 +206,12 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::SSP => iso::SSP, Currency::STN => iso::STN, Currency::SVC => iso::SVC, + Currency::SYP => iso::SYP, Currency::SZL => iso::SZL, Currency::THB => iso::THB, + Currency::TJS => iso::TJS, Currency::TND => iso::TND, + Currency::TMT => iso::TMT, Currency::TOP => iso::TOP, Currency::TTD => iso::TTD, Currency::TRY => iso::TRY, @@ -222,5 +233,6 @@ pub fn currency_match(currency: Currency) -> &'static iso::Currency { Currency::YER => iso::YER, Currency::ZAR => iso::ZAR, Currency::ZMW => iso::ZMW, + Currency::ZWL => iso::ZWL, } } diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs index 0b0b86222e2..d6272c34060 100644 --- a/crates/diesel_models/src/capture.rs +++ b/crates/diesel_models/src/capture.rs @@ -1,4 +1,4 @@ -use common_utils::types::MinorUnit; +use common_utils::types::{ConnectorTransactionId, MinorUnit}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -6,7 +6,7 @@ use time::PrimitiveDateTime; use crate::{enums as storage_enums, schema::captures}; #[derive( - Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, Hash, + Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] #[diesel(table_name = captures, primary_key(capture_id), check_for_backend(diesel::pg::Pg))] pub struct Capture { @@ -26,10 +26,11 @@ pub struct Capture { #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub authorized_attempt_id: String, - pub connector_capture_id: Option<String>, + pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, // reference to the capture at connector side pub connector_response_reference_id: Option<String>, + pub connector_capture_data: Option<String>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] @@ -51,17 +52,19 @@ pub struct CaptureNew { #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, pub authorized_attempt_id: String, - pub connector_capture_id: Option<String>, + pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, pub connector_response_reference_id: Option<String>, + pub connector_capture_data: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum CaptureUpdate { ResponseUpdate { status: storage_enums::CaptureStatus, - connector_capture_id: Option<String>, + connector_capture_id: Option<ConnectorTransactionId>, connector_response_reference_id: Option<String>, + connector_capture_data: Option<String>, }, ErrorUpdate { status: storage_enums::CaptureStatus, @@ -79,8 +82,9 @@ pub struct CaptureUpdateInternal { pub error_code: Option<String>, pub error_reason: Option<String>, pub modified_at: Option<PrimitiveDateTime>, - pub connector_capture_id: Option<String>, + pub connector_capture_id: Option<ConnectorTransactionId>, pub connector_response_reference_id: Option<String>, + pub connector_capture_data: Option<String>, } impl CaptureUpdate { @@ -93,6 +97,7 @@ impl CaptureUpdate { modified_at: _, connector_capture_id, connector_response_reference_id, + connector_capture_data, } = self.into(); Capture { status: status.unwrap_or(source.status), @@ -103,6 +108,7 @@ impl CaptureUpdate { connector_capture_id: connector_capture_id.or(source.connector_capture_id), connector_response_reference_id: connector_response_reference_id .or(source.connector_response_reference_id), + connector_capture_data: connector_capture_data.or(source.connector_capture_data), ..source } } @@ -116,11 +122,13 @@ impl From<CaptureUpdate> for CaptureUpdateInternal { status, connector_capture_id: connector_transaction_id, connector_response_reference_id, + connector_capture_data, } => Self { status: Some(status), connector_capture_id: connector_transaction_id, modified_at: now, connector_response_reference_id, + connector_capture_data, ..Self::default() }, CaptureUpdate::ErrorUpdate { diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 20551c2754b..277061c78aa 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -1,4 +1,7 @@ -use common_utils::{id_type, pii, types::MinorUnit}; +use common_utils::{ + id_type, pii, + types::{ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit}, +}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -63,12 +66,13 @@ pub struct PaymentAttempt { 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 connector_payment_id: Option<ConnectorTransactionId>, 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 connector_payment_data: Option<String>, pub id: String, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, @@ -94,7 +98,7 @@ pub struct PaymentAttempt { 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 connector_transaction_id: Option<ConnectorTransactionId>, pub capture_method: Option<storage_enums::CaptureMethod>, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_on: Option<PrimitiveDateTime>, @@ -148,6 +152,47 @@ pub struct PaymentAttempt { pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + pub connector_transaction_data: Option<String>, +} + +#[cfg(feature = "v1")] +impl ConnectorTransactionIdTrait for PaymentAttempt { + fn get_optional_connector_transaction_id(&self) -> Option<&String> { + match self + .connector_transaction_id + .as_ref() + .map(|txn_id| txn_id.get_txn_id(self.connector_transaction_data.as_ref())) + .transpose() + { + Ok(txn_id) => txn_id, + + // In case hashed data is missing from DB, use the hashed ID as connector transaction ID + Err(_) => self + .connector_transaction_id + .as_ref() + .map(|txn_id| txn_id.get_id()), + } + } +} + +#[cfg(feature = "v2")] +impl ConnectorTransactionIdTrait for PaymentAttempt { + fn get_optional_connector_transaction_id(&self) -> Option<&String> { + match self + .connector_payment_id + .as_ref() + .map(|txn_id| txn_id.get_txn_id(self.connector_payment_data.as_ref())) + .transpose() + { + Ok(txn_id) => txn_id, + + // In case hashed data is missing from DB, use the hashed ID as connector payment ID + Err(_) => self + .connector_payment_id + .as_ref() + .map(|txn_id| txn_id.get_id()), + } + } } #[derive(Clone, Debug, Eq, PartialEq, Queryable, Serialize, Deserialize)] @@ -711,6 +756,7 @@ pub struct PaymentAttemptUpdateInternal { client_version: Option<String>, customer_acceptance: Option<pii::SecretSerdeValue>, card_network: Option<String>, + connector_payment_data: Option<String>, } #[cfg(feature = "v1")] @@ -721,7 +767,7 @@ pub struct PaymentAttemptUpdateInternal { pub net_amount: Option<MinorUnit>, pub currency: Option<storage_enums::Currency>, pub status: Option<storage_enums::AttemptStatus>, - pub connector_transaction_id: Option<String>, + pub connector_transaction_id: Option<ConnectorTransactionId>, pub amount_to_capture: Option<MinorUnit>, pub connector: Option<Option<String>>, pub authentication_type: Option<storage_enums::AuthenticationType>, @@ -766,6 +812,7 @@ pub struct PaymentAttemptUpdateInternal { pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + pub connector_transaction_data: Option<String>, } #[cfg(feature = "v2")] @@ -954,6 +1001,7 @@ impl PaymentAttemptUpdate { card_network, shipping_cost, order_tax_amount, + connector_transaction_data, } = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source); PaymentAttempt { amount: amount.unwrap_or(source.amount), @@ -1009,6 +1057,8 @@ impl PaymentAttemptUpdate { card_network: card_network.or(source.card_network), shipping_cost: shipping_cost.or(source.shipping_cost), order_tax_amount: order_tax_amount.or(source.order_tax_amount), + connector_transaction_data: connector_transaction_data + .or(source.connector_transaction_data), ..source } } @@ -2003,6 +2053,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::AuthenticationTypeUpdate { authentication_type, @@ -2057,6 +2108,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::ConfirmUpdate { amount, @@ -2141,6 +2193,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost, order_tax_amount, + connector_transaction_data: None, }, PaymentAttemptUpdate::VoidUpdate { status, @@ -2196,6 +2249,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::RejectUpdate { status, @@ -2252,6 +2306,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::BlocklistUpdate { status, @@ -2308,6 +2363,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::PaymentMethodDetailsUpdate { payment_method_id, @@ -2362,6 +2418,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::ResponseUpdate { status, @@ -2384,57 +2441,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { 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, - }, + } => { + let (connector_transaction_id, connector_transaction_data) = + connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + 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, + connector_transaction_data, + 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, @@ -2448,57 +2513,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { 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, - }, + } => { + let (connector_transaction_id, connector_transaction_data) = + connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + 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, + connector_transaction_data, + 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(), @@ -2549,6 +2622,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::UpdateTrackers { payment_token, @@ -2609,6 +2683,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::UnresolvedResponseUpdate { status, @@ -2620,57 +2695,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { 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, - }, + } => { + let (connector_transaction_id, connector_transaction_data) = + connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + 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, + connector_transaction_data, + 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, @@ -2679,57 +2762,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { 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, - }, + } => { + let (connector_transaction_id, connector_transaction_data) = + connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + 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, + connector_transaction_data, + 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, @@ -2784,6 +2875,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::AmountToCaptureUpdate { status, @@ -2839,6 +2931,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::ConnectorResponse { authentication_data, @@ -2847,57 +2940,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { 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, - }, + } => { + let (connector_transaction_id, connector_transaction_data) = + connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + Self { + authentication_data, + encoded_data, + connector_transaction_id, + connector: connector.map(Some), + modified_at: common_utils::date_time::now(), + updated_by, + charge_id, + connector_transaction_data, + 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, @@ -2951,6 +3052,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::AuthenticationUpdate { status, @@ -3008,6 +3110,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, PaymentAttemptUpdate::ManualUpdate { status, @@ -3018,57 +3121,65 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { 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, - }, + } => { + let (connector_transaction_id, connector_transaction_data) = + connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + 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), + connector_transaction_id, + connector_transaction_data, + amount: None, + net_amount: None, + currency: 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, + 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, + } + } PaymentAttemptUpdate::PostSessionTokensUpdate { updated_by, connector_metadata, @@ -3122,6 +3233,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, + connector_transaction_data: None, }, } } diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs index e194dc9f64c..7a32e410961 100644 --- a/crates/diesel_models/src/query/capture.rs +++ b/crates/diesel_models/src/query/capture.rs @@ -1,3 +1,4 @@ +use common_utils::types::ConnectorTransactionIdTrait; use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; @@ -67,3 +68,22 @@ impl Capture { .await } } + +impl ConnectorTransactionIdTrait for Capture { + fn get_optional_connector_transaction_id(&self) -> Option<&String> { + match self + .connector_capture_id + .as_ref() + .map(|capture_id| capture_id.get_txn_id(self.connector_capture_data.as_ref())) + .transpose() + { + Ok(capture_id) => capture_id, + + // In case hashed data is missing from DB, use the hashed ID as connector transaction ID + Err(_) => self + .connector_capture_id + .as_ref() + .map(|txn_id| txn_id.get_id()), + } + } +} diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index 42b0ffa620c..9e850bc9f1f 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -1,6 +1,6 @@ use common_utils::{ pii, - types::{ChargeRefunds, MinorUnit}, + types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit}, }; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; @@ -25,9 +25,9 @@ pub struct Refund { pub refund_id: String, //merchant_reference id pub payment_id: common_utils::id_type::PaymentId, pub merchant_id: common_utils::id_type::MerchantId, - pub connector_transaction_id: String, + pub connector_transaction_id: ConnectorTransactionId, pub connector: String, - pub connector_refund_id: Option<String>, + pub connector_refund_id: Option<ConnectorTransactionId>, pub external_reference_id: Option<String>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, @@ -51,6 +51,8 @@ pub struct Refund { pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, + pub connector_refund_data: Option<String>, + pub connector_transaction_data: Option<String>, } #[derive( @@ -71,9 +73,9 @@ pub struct RefundNew { pub merchant_id: common_utils::id_type::MerchantId, pub internal_reference_id: String, pub external_reference_id: Option<String>, - pub connector_transaction_id: String, + pub connector_transaction_id: ConnectorTransactionId, pub connector: String, - pub connector_refund_id: Option<String>, + pub connector_refund_id: Option<ConnectorTransactionId>, pub refund_type: storage_enums::RefundType, pub total_amount: MinorUnit, pub currency: storage_enums::Currency, @@ -94,17 +96,20 @@ pub struct RefundNew { pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub charges: Option<ChargeRefunds>, pub organization_id: common_utils::id_type::OrganizationId, + pub connector_refund_data: Option<String>, + pub connector_transaction_data: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum RefundUpdate { Update { - connector_refund_id: String, + connector_refund_id: ConnectorTransactionId, refund_status: storage_enums::RefundStatus, sent_to_gateway: bool, refund_error_message: Option<String>, refund_arn: String, updated_by: String, + connector_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, @@ -112,17 +117,19 @@ pub enum RefundUpdate { updated_by: String, }, StatusUpdate { - connector_refund_id: Option<String>, + connector_refund_id: Option<ConnectorTransactionId>, sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, + connector_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, refund_error_message: Option<String>, refund_error_code: Option<String>, updated_by: String, - connector_refund_id: Option<String>, + connector_refund_id: Option<ConnectorTransactionId>, + connector_refund_data: Option<String>, }, ManualUpdate { refund_status: Option<storage_enums::RefundStatus>, @@ -135,7 +142,7 @@ pub enum RefundUpdate { #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = refund)] pub struct RefundUpdateInternal { - connector_refund_id: Option<String>, + connector_refund_id: Option<ConnectorTransactionId>, refund_status: Option<storage_enums::RefundStatus>, sent_to_gateway: Option<bool>, refund_error_message: Option<String>, @@ -145,6 +152,7 @@ pub struct RefundUpdateInternal { refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, + connector_refund_data: Option<String>, } impl RefundUpdateInternal { @@ -160,6 +168,7 @@ impl RefundUpdateInternal { refund_error_code: self.refund_error_code, updated_by: self.updated_by, modified_at: self.modified_at, + connector_refund_data: self.connector_refund_data, ..source } } @@ -175,6 +184,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_arn, updated_by, + connector_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), @@ -182,6 +192,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_arn: Some(refund_arn), updated_by, + connector_refund_data, metadata: None, refund_reason: None, refund_error_code: None, @@ -202,17 +213,20 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), + connector_refund_data: None, }, RefundUpdate::StatusUpdate { connector_refund_id, sent_to_gateway, refund_status, updated_by, + connector_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, + connector_refund_data, refund_error_message: None, refund_arn: None, metadata: None, @@ -226,12 +240,14 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_code, updated_by, connector_refund_id, + connector_refund_data, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, + connector_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, @@ -254,6 +270,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), + connector_refund_data: None, }, } } @@ -272,6 +289,7 @@ impl RefundUpdate { refund_error_code, updated_by, modified_at: _, + connector_refund_data, } = self.into(); Refund { connector_refund_id: connector_refund_id.or(source.connector_refund_id), @@ -284,6 +302,7 @@ impl RefundUpdate { refund_reason: refund_reason.or(source.refund_reason), updated_by, modified_at: common_utils::date_time::now(), + connector_refund_data: connector_refund_data.or(source.connector_refund_data), ..source } } @@ -292,9 +311,10 @@ impl RefundUpdate { #[derive(Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct RefundCoreWorkflow { pub refund_internal_reference_id: String, - pub connector_transaction_id: String, + pub connector_transaction_id: ConnectorTransactionId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: common_utils::id_type::PaymentId, + pub connector_transaction_data: Option<String>, } impl common_utils::events::ApiEventMetric for Refund { @@ -306,6 +326,37 @@ impl common_utils::events::ApiEventMetric for Refund { } } +impl ConnectorTransactionIdTrait for Refund { + fn get_optional_connector_refund_id(&self) -> Option<&String> { + match self + .connector_refund_id + .as_ref() + .map(|refund_id| refund_id.get_txn_id(self.connector_refund_data.as_ref())) + .transpose() + { + Ok(refund_id) => refund_id, + + // In case hashed data is missing from DB, use the hashed ID as connector transaction ID + Err(_) => self + .connector_refund_id + .as_ref() + .map(|txn_id| txn_id.get_id()), + } + } + + fn get_connector_transaction_id(&self) -> &String { + match self + .connector_transaction_id + .get_txn_id(self.connector_transaction_data.as_ref()) + { + Ok(txn_id) => txn_id, + + // In case hashed data is missing from DB, use the hashed ID as connector transaction ID + Err(_) => self.connector_transaction_id.get_id(), + } + } +} + mod tests { #[test] fn test_backwards_compatibility() { @@ -336,7 +387,8 @@ mod tests { "profile_id": null, "updated_by": "admin", "merchant_connector_id": null, - "charges": null + "charges": null, + "connector_transaction_data": null }"#; let deserialized = serde_json::from_str::<super::Refund>(serialized_refund); diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index a9e0b54260c..5cd2abd3599 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -248,6 +248,8 @@ diesel::table! { capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, + #[max_length = 512] + connector_capture_data -> Nullable<Varchar>, } } @@ -846,6 +848,8 @@ diesel::table! { card_network -> Nullable<Varchar>, shipping_cost -> Nullable<Int8>, order_tax_amount -> Nullable<Int8>, + #[max_length = 512] + connector_transaction_data -> Nullable<Varchar>, } } @@ -1183,6 +1187,10 @@ diesel::table! { charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, + #[max_length = 512] + connector_refund_data -> Nullable<Varchar>, + #[max_length = 512] + connector_transaction_data -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 53f568f18c4..99a4453bba2 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -255,6 +255,8 @@ diesel::table! { capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, + #[max_length = 512] + connector_capture_data -> Nullable<Varchar>, } } @@ -813,6 +815,8 @@ diesel::table! { #[max_length = 128] external_reference_id -> Nullable<Varchar>, tax_on_surcharge -> Nullable<Int8>, + #[max_length = 512] + connector_payment_data -> Nullable<Varchar>, #[max_length = 64] id -> Varchar, shipping_cost -> Nullable<Int8>, @@ -1130,6 +1134,10 @@ diesel::table! { charges -> Nullable<Jsonb>, #[max_length = 32] organization_id -> Varchar, + #[max_length = 512] + connector_refund_data -> Nullable<Varchar>, + #[max_length = 512] + connector_transaction_data -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index a354e4a02ab..db30d02bd7c 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -2,7 +2,7 @@ use common_enums::{ AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod, PaymentMethodType, }; -use common_utils::types::MinorUnit; +use common_utils::types::{ConnectorTransactionId, MinorUnit}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -179,7 +179,7 @@ pub struct PaymentAttemptBatchNew { pub mandate_details: Option<MandateDataType>, pub error_reason: Option<String>, pub connector_response_reference_id: Option<String>, - pub connector_transaction_id: Option<String>, + pub connector_transaction_id: Option<ConnectorTransactionId>, pub multiple_capture_count: Option<i16>, pub amount_capturable: MinorUnit, pub updated_by: String, @@ -203,6 +203,7 @@ pub struct PaymentAttemptBatchNew { pub organization_id: common_utils::id_type::OrganizationId, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + pub connector_transaction_data: Option<String>, } #[cfg(feature = "v1")] diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 5aba0616143..42216b9f78f 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -6,7 +6,7 @@ use common_utils::{ id_type, pii, types::{ keymanager::{self, KeyManagerState}, - MinorUnit, + ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit, }, }; use diesel_models::{ @@ -1212,6 +1212,11 @@ impl behaviour::Conversion for PaymentAttempt { .and_then(|card| card.get("card_network")) .and_then(|network| network.as_str()) .map(|network| network.to_string()); + let (connector_transaction_id, connector_transaction_data) = self + .connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); Ok(DieselPaymentAttempt { payment_id: self.payment_id, merchant_id: self.merchant_id, @@ -1227,7 +1232,7 @@ impl behaviour::Conversion for PaymentAttempt { tax_amount: self.net_amount.get_tax_on_surcharge(), payment_method_id: self.payment_method_id, payment_method: self.payment_method, - connector_transaction_id: self.connector_transaction_id, + connector_transaction_id, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, @@ -1274,6 +1279,7 @@ impl behaviour::Conversion for PaymentAttempt { profile_id: self.profile_id, organization_id: self.organization_id, card_network, + connector_transaction_data, order_tax_amount: self.net_amount.get_order_tax_amount(), shipping_cost: self.net_amount.get_shipping_cost(), }) @@ -1289,6 +1295,9 @@ impl behaviour::Conversion for PaymentAttempt { Self: Sized, { async { + let connector_transaction_id = storage_model + .get_optional_connector_transaction_id() + .cloned(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, @@ -1308,7 +1317,7 @@ impl behaviour::Conversion for PaymentAttempt { offer_amount: storage_model.offer_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, - connector_transaction_id: storage_model.connector_transaction_id, + connector_transaction_id, capture_method: storage_model.capture_method, capture_on: storage_model.capture_on, confirm: storage_model.confirm, @@ -1511,6 +1520,11 @@ impl behaviour::Conversion for PaymentAttempt { connector, } = self; + let (connector_payment_id, connector_payment_data) = connector_payment_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); + Ok(DieselPaymentAttempt { payment_id, merchant_id, @@ -1566,6 +1580,7 @@ impl behaviour::Conversion for PaymentAttempt { authentication_applied, external_reference_id, connector, + connector_payment_data, }) } @@ -1579,6 +1594,9 @@ impl behaviour::Conversion for PaymentAttempt { Self: Sized, { async { + let connector_payment_id = storage_model + .get_optional_connector_transaction_id() + .cloned(); Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { payment_id: storage_model.payment_id, merchant_id: storage_model.merchant_id, @@ -1590,7 +1608,7 @@ impl behaviour::Conversion for PaymentAttempt { surcharge_amount: storage_model.surcharge_amount, payment_method_id: storage_model.payment_method_id, payment_method_type: storage_model.payment_method_type_v2, - connector_payment_id: storage_model.connector_payment_id, + connector_payment_id, confirm: storage_model.confirm, authentication_type: storage_model.authentication_type, created_at: storage_model.created_at, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index d599a2caa74..39047f7015a 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -118,6 +118,7 @@ pub struct PaymentsCaptureData { pub browser_info: Option<BrowserInformation>, pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. + pub capture_method: Option<storage_enums::CaptureMethod>, // New amount for amount frame work pub minor_payment_amount: MinorUnit, diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 1a340aa91d3..3aaeb0586d6 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -334,6 +334,7 @@ impl IntoDirValue for api_enums::Currency { fn into_dir_value(self) -> Result<dir::DirValue, KgraphError> { match self { Self::AED => Ok(dirval!(PaymentCurrency = AED)), + Self::AFN => Ok(dirval!(PaymentCurrency = AFN)), Self::ALL => Ok(dirval!(PaymentCurrency = ALL)), Self::AMD => Ok(dirval!(PaymentCurrency = AMD)), Self::ANG => Ok(dirval!(PaymentCurrency = ANG)), @@ -353,10 +354,12 @@ impl IntoDirValue for api_enums::Currency { Self::BOB => Ok(dirval!(PaymentCurrency = BOB)), Self::BRL => Ok(dirval!(PaymentCurrency = BRL)), Self::BSD => Ok(dirval!(PaymentCurrency = BSD)), + Self::BTN => Ok(dirval!(PaymentCurrency = BTN)), Self::BWP => Ok(dirval!(PaymentCurrency = BWP)), Self::BYN => Ok(dirval!(PaymentCurrency = BYN)), Self::BZD => Ok(dirval!(PaymentCurrency = BZD)), Self::CAD => Ok(dirval!(PaymentCurrency = CAD)), + Self::CDF => Ok(dirval!(PaymentCurrency = CDF)), Self::CHF => Ok(dirval!(PaymentCurrency = CHF)), Self::CLP => Ok(dirval!(PaymentCurrency = CLP)), Self::CNY => Ok(dirval!(PaymentCurrency = CNY)), @@ -370,6 +373,7 @@ impl IntoDirValue for api_enums::Currency { Self::DOP => Ok(dirval!(PaymentCurrency = DOP)), Self::DZD => Ok(dirval!(PaymentCurrency = DZD)), Self::EGP => Ok(dirval!(PaymentCurrency = EGP)), + Self::ERN => Ok(dirval!(PaymentCurrency = ERN)), Self::ETB => Ok(dirval!(PaymentCurrency = ETB)), Self::EUR => Ok(dirval!(PaymentCurrency = EUR)), Self::FJD => Ok(dirval!(PaymentCurrency = FJD)), @@ -391,6 +395,8 @@ impl IntoDirValue for api_enums::Currency { Self::ILS => Ok(dirval!(PaymentCurrency = ILS)), Self::INR => Ok(dirval!(PaymentCurrency = INR)), Self::IQD => Ok(dirval!(PaymentCurrency = IQD)), + Self::IRR => Ok(dirval!(PaymentCurrency = IRR)), + Self::ISK => Ok(dirval!(PaymentCurrency = ISK)), Self::JMD => Ok(dirval!(PaymentCurrency = JMD)), Self::JOD => Ok(dirval!(PaymentCurrency = JOD)), Self::JPY => Ok(dirval!(PaymentCurrency = JPY)), @@ -398,6 +404,7 @@ impl IntoDirValue for api_enums::Currency { Self::KGS => Ok(dirval!(PaymentCurrency = KGS)), Self::KHR => Ok(dirval!(PaymentCurrency = KHR)), Self::KMF => Ok(dirval!(PaymentCurrency = KMF)), + Self::KPW => Ok(dirval!(PaymentCurrency = KPW)), Self::KRW => Ok(dirval!(PaymentCurrency = KRW)), Self::KWD => Ok(dirval!(PaymentCurrency = KWD)), Self::KYD => Ok(dirval!(PaymentCurrency = KYD)), @@ -444,6 +451,7 @@ impl IntoDirValue for api_enums::Currency { Self::SAR => Ok(dirval!(PaymentCurrency = SAR)), Self::SBD => Ok(dirval!(PaymentCurrency = SBD)), Self::SCR => Ok(dirval!(PaymentCurrency = SCR)), + Self::SDG => Ok(dirval!(PaymentCurrency = SDG)), Self::SEK => Ok(dirval!(PaymentCurrency = SEK)), Self::SGD => Ok(dirval!(PaymentCurrency = SGD)), Self::SHP => Ok(dirval!(PaymentCurrency = SHP)), @@ -454,8 +462,11 @@ impl IntoDirValue for api_enums::Currency { Self::SSP => Ok(dirval!(PaymentCurrency = SSP)), Self::STN => Ok(dirval!(PaymentCurrency = STN)), Self::SVC => Ok(dirval!(PaymentCurrency = SVC)), + Self::SYP => Ok(dirval!(PaymentCurrency = SYP)), Self::SZL => Ok(dirval!(PaymentCurrency = SZL)), Self::THB => Ok(dirval!(PaymentCurrency = THB)), + Self::TJS => Ok(dirval!(PaymentCurrency = TJS)), + Self::TMT => Ok(dirval!(PaymentCurrency = TMT)), Self::TND => Ok(dirval!(PaymentCurrency = TND)), Self::TOP => Ok(dirval!(PaymentCurrency = TOP)), Self::TRY => Ok(dirval!(PaymentCurrency = TRY)), @@ -478,6 +489,7 @@ impl IntoDirValue for api_enums::Currency { Self::YER => Ok(dirval!(PaymentCurrency = YER)), Self::ZAR => Ok(dirval!(PaymentCurrency = ZAR)), Self::ZMW => Ok(dirval!(PaymentCurrency = ZMW)), + Self::ZWL => Ok(dirval!(PaymentCurrency = ZWL)), } } } diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 33c9393cede..b5469f12c16 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -2,9 +2,12 @@ mod requests; mod response; pub mod transformers; -use std::fmt::Debug; - -use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; +use common_utils::{ + crypto, + ext_traits::ByteSliceExt, + request::RequestContent, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, +}; use diesel_models::enums; use error_stack::ResultExt; use transformers as worldpay; @@ -30,8 +33,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Worldpay; +#[derive(Clone)] +pub struct Worldpay { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Worldpay { + pub const fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpay where @@ -42,10 +55,16 @@ where req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let mut headers = vec![( - headers::CONTENT_TYPE.to_string(), - self.get_content_type().to_string().into(), - )]; + let mut headers = vec![ + ( + headers::ACCEPT.to_string(), + self.get_content_type().to_string().into(), + ), + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + ), + ]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; headers.append(&mut api_key); Ok(headers) @@ -62,7 +81,7 @@ impl ConnectorCommon for Worldpay { } fn common_get_content_type(&self) -> &'static str { - "application/vnd.worldpay.payments-v6+json" + "application/vnd.worldpay.payments-v7+json" } fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { @@ -86,10 +105,13 @@ impl ConnectorCommon for Worldpay { res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { - let response: WorldpayErrorResponse = res - .response - .parse_struct("WorldpayErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response = if !res.response.is_empty() { + res.response + .parse_struct("WorldpayErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)? + } else { + WorldpayErrorResponse::default(res.status_code) + }; event_builder.map(|i| i.set_error_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -183,9 +205,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( - "{}payments/settlements/{}", + "{}payments/authorizations/cancellations/{connector_payment_id}", self.base_url(connectors), - connector_payment_id )) } @@ -328,8 +349,22 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); + let attempt_status = data.status; + let worldpay_status = response.last_event; + let status = match (attempt_status, worldpay_status.clone()) { + ( + enums::AttemptStatus::Authorizing + | enums::AttemptStatus::Authorized + | enums::AttemptStatus::CaptureInitiated + | enums::AttemptStatus::Pending + | enums::AttemptStatus::VoidInitiated, + EventType::Authorized, + ) => attempt_status, + _ => enums::AttemptStatus::from(&worldpay_status), + }; + Ok(types::PaymentsSyncRouterData { - status: enums::AttemptStatus::from(response.last_event), + status, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: data.request.connector_transaction_id.clone(), redirection_data: None, @@ -361,6 +396,33 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme self.common_get_content_type() } + fn get_url( + &self, + req: &types::PaymentsCaptureRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let connector_payment_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}payments/settlements/partials/{}", + self.base_url(connectors), + connector_payment_id + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsCaptureRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount_to_capture = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + let connector_req = WorldpayPartialRequest::try_from((req, amount_to_capture))?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + fn build_request( &self, req: &types::PaymentsCaptureRouterData, @@ -374,6 +436,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) + .set_body(types::PaymentsCaptureType::get_request_body( + self, req, connectors, + )?) .build(), )) } @@ -393,7 +458,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(types::PaymentsCaptureRouterData { - status: enums::AttemptStatus::Charged, + status: enums::AttemptStatus::Pending, response: Ok(types::PaymentsResponseData::TransactionResponse { resource_id: types::ResponseId::foreign_try_from(response.links)?, redirection_data: None, @@ -411,19 +476,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } - fn get_url( - &self, - req: &types::PaymentsCaptureRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - let connector_payment_id = req.request.connector_transaction_id.clone(); - Ok(format!( - "{}payments/settlements/{}", - self.base_url(connectors), - connector_payment_id - )) - } - fn get_error_response( &self, res: Response, @@ -463,7 +515,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( - "{}payments/authorizations", + "{}cardPayments/customerInitiatedTransactions", self.base_url(connectors) )) } @@ -476,10 +528,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P let connector_router_data = worldpay::WorldpayRouterData::try_from(( &self.get_currency_unit(), req.request.currency, - req.request.amount, + req.request.minor_amount, req, ))?; - let connector_req = WorldpayPaymentsRequest::try_from(&connector_router_data)?; + let auth = worldpay::WorldpayAuthType::try_from(&req.connector_auth_type) + .change_context(errors::ConnectorError::FailedToObtainAuthType)?; + let connector_req = + WorldpayPaymentsRequest::try_from((&connector_router_data, &auth.entity_id))?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -560,7 +615,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundExecuteRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = WorldpayRefundRequest::try_from(req)?; + let amount_to_refund = connector_utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + let connector_req = WorldpayPartialRequest::try_from((req, amount_to_refund))?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -613,7 +673,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon Ok(types::RefundExecuteRouterData { response: Ok(types::RefundsResponseData { connector_refund_id: ResponseIdStr::try_from(response.links)?.id, - refund_status: enums::RefundStatus::Success, + refund_status: enums::RefundStatus::Pending, }), ..data.clone() }) @@ -766,19 +826,20 @@ impl api::IncomingWebhook for Worldpay { .parse_struct("WorldpayWebhookEventType") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match body.event_details.event_type { - EventType::SentForSettlement | EventType::Charged => { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + EventType::Authorized => { + Ok(api::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess) } - EventType::Error | EventType::Expired => { + EventType::SentForSettlement => Ok(api::IncomingWebhookEvent::PaymentIntentProcessing), + EventType::Settled => Ok(api::IncomingWebhookEvent::PaymentIntentSuccess), + EventType::Error | EventType::Expired | EventType::SettlementFailed => { Ok(api::IncomingWebhookEvent::PaymentIntentFailure) } EventType::Unknown - | EventType::Authorized + | EventType::SentForAuthorization | EventType::Cancelled | EventType::Refused | EventType::Refunded | EventType::SentForRefund - | EventType::CaptureFailed | EventType::RefundFailed => Ok(api::IncomingWebhookEvent::EventNotSupported), } } diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs index 5fb5d75d940..301ae64946d 100644 --- a/crates/router/src/connector/worldpay/requests.rs +++ b/crates/router/src/connector/worldpay/requests.rs @@ -4,29 +4,28 @@ use serde::{Deserialize, Serialize}; #[serde(rename_all = "camelCase")] pub struct BillingAddress { #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option<String>, + pub address1: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub address2: Option<Secret<String>>, - pub postal_code: Secret<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub address3: Option<Secret<String>>, - pub country_code: common_enums::CountryAlpha2, #[serde(skip_serializing_if = "Option::is_none")] - pub address1: Option<Secret<String>>, + pub city: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option<Secret<String>>, + pub postal_code: Secret<String>, + pub country_code: common_enums::CountryAlpha2, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayPaymentsRequest { - #[serde(skip_serializing_if = "Option::is_none")] - pub channel: Option<Channel>, + pub transaction_reference: String, + pub merchant: Merchant, pub instruction: Instruction, + pub channel: Channel, #[serde(skip_serializing_if = "Option::is_none")] pub customer: Option<Customer>, - pub merchant: Merchant, - pub transaction_reference: String, } #[derive( @@ -35,6 +34,7 @@ pub struct WorldpayPaymentsRequest { #[serde(rename_all = "camelCase")] pub enum Channel { #[default] + Ecom, Moto, } @@ -101,11 +101,18 @@ pub struct NetworkToken { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Instruction { - #[serde(skip_serializing_if = "Option::is_none")] - pub debt_repayment: Option<bool>, - pub value: PaymentValue, + pub request_auto_settlement: RequestAutoSettlement, pub narrative: InstructionNarrative, + pub value: PaymentValue, pub payment_instrument: PaymentInstrument, + #[serde(skip_serializing_if = "Option::is_none")] + pub debt_repayment: Option<bool>, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RequestAutoSettlement { + pub enabled: bool, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] @@ -143,16 +150,15 @@ pub enum PaymentType { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardPayment { - #[serde(skip_serializing_if = "Option::is_none")] - pub billing_address: Option<BillingAddress>, - #[serde(skip_serializing_if = "Option::is_none")] - pub card_holder_name: Option<Secret<String>>, - pub card_expiry_date: CardExpiryDate, - #[serde(skip_serializing_if = "Option::is_none")] - pub cvc: Option<Secret<String>>, #[serde(rename = "type")] pub payment_type: PaymentType, pub card_number: cards::CardNumber, + pub expiry_date: ExpiryDate, + #[serde(skip_serializing_if = "Option::is_none")] + pub card_holder_name: Option<Secret<String>>, + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_address: Option<BillingAddress>, + pub cvc: Secret<String>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] @@ -174,7 +180,7 @@ pub struct WalletPayment { } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] -pub struct CardExpiryDate { +pub struct ExpiryDate { pub month: Secret<i8>, pub year: Secret<i32>, } @@ -182,13 +188,13 @@ pub struct CardExpiryDate { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct PaymentValue { pub amount: i64, - pub currency: String, + pub currency: api_models::enums::Currency, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Merchant { - pub entity: String, + pub entity: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub mcc: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] @@ -220,7 +226,7 @@ pub struct SubMerchant { } #[derive(Default, Debug, Serialize)] -pub struct WorldpayRefundRequest { +pub struct WorldpayPartialRequest { pub value: PaymentValue, pub reference: String, } diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs index 14ccbc1fac8..dbd596e2e20 100644 --- a/crates/router/src/connector/worldpay/response.rs +++ b/crates/router/src/connector/worldpay/response.rs @@ -1,33 +1,43 @@ use masking::Secret; use serde::{Deserialize, Serialize}; +use super::requests::*; use crate::{core::errors, types, types::transformers::ForeignTryFrom}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayPaymentsResponse { + pub outcome: Option<PaymentOutcome>, + /// Any risk factors which have been identified for the authorization. This section will not appear if no risks are identified. #[serde(skip_serializing_if = "Option::is_none")] - pub exemption: Option<Exemption>, + pub risk_factors: Option<Vec<RiskFactorsInner>>, #[serde(skip_serializing_if = "Option::is_none")] pub issuer: Option<Issuer>, - pub outcome: Option<Outcome>, #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option<String>, + pub scheme: Option<PaymentsResponseScheme>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_instrument: Option<PaymentsResPaymentInstrument>, - /// Any risk factors which have been identified for the authorization. This section will not appear if no risks are identified. - #[serde(skip_serializing_if = "Option::is_none")] - pub risk_factors: Option<Vec<RiskFactorsInner>>, - #[serde(skip_serializing_if = "Option::is_none")] - pub scheme: Option<PaymentsResponseScheme>, #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] pub links: Option<PaymentLinks>, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub enum Outcome { +pub enum PaymentOutcome { + #[serde(alias = "authorized", alias = "Authorized")] Authorized, Refused, + #[serde(alias = "Sent for Settlement")] + SentForSettlement, + #[serde(alias = "Sent for Refund")] + SentForRefund, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum RefundOutcome { + #[serde(alias = "Sent for Refund")] + SentForRefund, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -41,31 +51,57 @@ pub struct WorldpayEventResponse { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum EventType { + SentForAuthorization, + #[serde(alias = "Authorized")] Authorized, + #[serde(alias = "Sent for Settlement")] + SentForSettlement, + Settled, + SettlementFailed, Cancelled, - Charged, - SentForRefund, - RefundFailed, - Refused, - Refunded, Error, - SentForSettlement, Expired, - CaptureFailed, + Refused, + #[serde(alias = "Sent for Refund")] + SentForRefund, + Refunded, + RefundFailed, #[serde(other)] Unknown, } -#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] -pub struct Exemption { - pub result: String, - pub reason: String, -} - #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct PaymentLinks { - #[serde(rename = "payments:events", skip_serializing_if = "Option::is_none")] + #[serde( + rename = "cardPayments:events", + skip_serializing_if = "Option::is_none" + )] pub events: Option<PaymentLink>, + #[serde( + rename = "cardPayments:settle", + skip_serializing_if = "Option::is_none" + )] + pub settle_event: Option<PaymentLink>, + #[serde( + rename = "cardPayments:partialSettle", + skip_serializing_if = "Option::is_none" + )] + pub partial_settle_event: Option<PaymentLink>, + #[serde( + rename = "cardPayments:refund", + skip_serializing_if = "Option::is_none" + )] + pub refund_event: Option<PaymentLink>, + #[serde( + rename = "cardPayments:partialRefund", + skip_serializing_if = "Option::is_none" + )] + pub partial_refund_event: Option<PaymentLink>, + #[serde( + rename = "cardPayments:reverse", + skip_serializing_if = "Option::is_none" + )] + pub reverse_event: Option<PaymentLink>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] @@ -116,12 +152,6 @@ impl ForeignTryFrom<Option<PaymentLinks>> for types::ResponseId { } } -impl Exemption { - pub fn new(result: String, reason: String) -> Self { - Self { result, reason } - } -} - #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Issuer { @@ -137,103 +167,32 @@ impl Issuer { } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] pub struct PaymentsResPaymentInstrument { #[serde(rename = "type", skip_serializing_if = "Option::is_none")] - pub risk_type: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub card: Option<PaymentInstrumentCard>, -} - -impl PaymentsResPaymentInstrument { - pub fn new() -> Self { - Self { - risk_type: None, - card: None, - } - } -} - -#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PaymentInstrumentCard { - #[serde(skip_serializing_if = "Option::is_none")] - pub number: Option<PaymentInstrumentCardNumber>, - #[serde(skip_serializing_if = "Option::is_none")] - pub issuer: Option<PaymentInstrumentCardIssuer>, - #[serde(skip_serializing_if = "Option::is_none")] - pub payment_account_reference: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub country_code: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] + pub payment_instrument_type: Option<String>, + pub card_bin: Option<String>, + pub last_four: Option<String>, + pub category: Option<String>, + pub expiry_date: Option<ExpiryDate>, + pub card_brand: Option<String>, pub funding_type: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub brand: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub expiry_date: Option<PaymentInstrumentCardExpiryDate>, + pub issuer_name: Option<String>, + pub payment_account_reference: Option<String>, } -impl PaymentInstrumentCard { +impl PaymentsResPaymentInstrument { pub fn new() -> Self { Self { - number: None, - issuer: None, - payment_account_reference: None, - country_code: None, - funding_type: None, - brand: None, + payment_instrument_type: None, + card_bin: None, + last_four: None, + category: None, expiry_date: None, - } - } -} - -#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PaymentInstrumentCardExpiryDate { - #[serde(skip_serializing_if = "Option::is_none")] - pub month: Option<Secret<i32>>, - #[serde(skip_serializing_if = "Option::is_none")] - pub year: Option<Secret<i32>>, -} - -impl PaymentInstrumentCardExpiryDate { - pub fn new() -> Self { - Self { - month: None, - year: None, - } - } -} - -#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PaymentInstrumentCardIssuer { - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<String>, -} - -impl PaymentInstrumentCardIssuer { - pub fn new() -> Self { - Self { name: None } - } -} - -#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct PaymentInstrumentCardNumber { - #[serde(skip_serializing_if = "Option::is_none")] - pub bin: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub last4_digits: Option<String>, - #[serde(skip_serializing_if = "Option::is_none")] - pub dpan: Option<String>, -} - -impl PaymentInstrumentCardNumber { - pub fn new() -> Self { - Self { - bin: None, - last4_digits: None, - dpan: None, + card_brand: None, + funding_type: None, + issuer_name: None, + payment_account_reference: None, } } } @@ -282,15 +241,12 @@ pub enum Detail { #[derive( Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] +#[serde(rename_all = "camelCase")] pub enum Risk { #[default] - #[serde(rename = "not_checked")] NotChecked, - #[serde(rename = "not_matched")] NotMatched, - #[serde(rename = "not_supplied")] NotSupplied, - #[serde(rename = "verificationFailed")] VerificationFailed, } @@ -305,7 +261,7 @@ impl PaymentsResponseScheme { } } -#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct WorldpayErrorResponse { pub error_name: String, @@ -313,6 +269,23 @@ pub struct WorldpayErrorResponse { pub validation_errors: Option<serde_json::Value>, } +impl WorldpayErrorResponse { + pub fn default(status_code: u16) -> Self { + match status_code { + code @ 404 => Self { + error_name: format!("{} Not found", code), + message: "Resource not found".to_string(), + validation_errors: None, + }, + code => Self { + error_name: code.to_string(), + message: "Unknown error".to_string(), + validation_errors: None, + }, + } + } +} + #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayWebhookTransactionId { diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index dca6f82adc1..c5398b83a86 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -1,6 +1,9 @@ +use api_models::payments::Address; use base64::Engine; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, ext_traits::OptionExt, types::MinorUnit}; use diesel_models::enums; +use error_stack::ResultExt; +use hyperswitch_connectors::utils::RouterData; use masking::{PeekInterface, Secret}; use serde::Serialize; @@ -23,36 +26,61 @@ impl<T> TryFrom<( &types::api::CurrencyUnit, types::storage::enums::Currency, - i64, + MinorUnit, T, )> for WorldpayRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (_currency_unit, _currency, amount, item): ( + (_currency_unit, _currency, minor_amount, item): ( &types::api::CurrencyUnit, types::storage::enums::Currency, - i64, + MinorUnit, T, ), ) -> Result<Self, Self::Error> { Ok(Self { - amount, + amount: minor_amount.get_amount_as_i64(), router_data: item, }) } } fn fetch_payment_instrument( payment_method: domain::PaymentMethodData, + billing_address: Option<&Address>, ) -> CustomResult<PaymentInstrument, errors::ConnectorError> { match payment_method { domain::PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment { - card_expiry_date: CardExpiryDate { + payment_type: PaymentType::Card, + expiry_date: ExpiryDate { month: utils::CardData::get_expiry_month_as_i8(&card)?, year: utils::CardData::get_expiry_year_as_i32(&card)?, }, card_number: card.card_number, - ..CardPayment::default() + cvc: card.card_cvc, + card_holder_name: card.nick_name, + billing_address: if let Some(address) = + billing_address.and_then(|addr| addr.address.clone()) + { + Some(BillingAddress { + address1: address.line1, + address2: address.line2, + address3: address.line3, + city: address.city, + state: address.state, + postal_code: address.zip.get_required_value("zip").change_context( + errors::ConnectorError::MissingRequiredField { field_name: "zip" }, + )?, + country_code: address + .country + .get_required_value("country_code") + .change_context(errors::ConnectorError::MissingRequiredField { + field_name: "country_code", + })?, + }) + } else { + None + }, })), domain::PaymentMethodData::Wallet(wallet) => match wallet { domain::WalletData::GooglePay(data) => { @@ -122,7 +150,7 @@ fn fetch_payment_instrument( } impl - TryFrom< + TryFrom<( &WorldpayRouterData< &types::RouterData< types::api::payments::Authorize, @@ -130,24 +158,33 @@ impl PaymentsResponseData, >, >, - > for WorldpayPaymentsRequest + &Secret<String>, + )> for WorldpayPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: &WorldpayRouterData< - &types::RouterData< - types::api::payments::Authorize, - PaymentsAuthorizeData, - PaymentsResponseData, + req: ( + &WorldpayRouterData< + &types::RouterData< + types::api::payments::Authorize, + PaymentsAuthorizeData, + PaymentsResponseData, + >, >, - >, + &Secret<String>, + ), ) -> Result<Self, Self::Error> { + let (item, entity_id) = req; Ok(Self { instruction: Instruction { + request_auto_settlement: RequestAutoSettlement { + enabled: item.router_data.request.capture_method + == Some(enums::CaptureMethod::Automatic), + }, value: PaymentValue { amount: item.amount, - currency: item.router_data.request.currency.to_string(), + currency: item.router_data.request.currency, }, narrative: InstructionNarrative { line1: item @@ -159,19 +196,16 @@ impl }, payment_instrument: fetch_payment_instrument( item.router_data.request.payment_method_data.clone(), + item.router_data.get_optional_billing(), )?, debt_repayment: None, }, merchant: Merchant { - entity: item - .router_data - .connector_request_reference_id - .clone() - .replace('_', "-"), + entity: entity_id.clone(), ..Default::default() }, transaction_reference: item.router_data.connector_request_reference_id.clone(), - channel: None, + channel: Channel::Ecom, customer: None, }) } @@ -179,17 +213,32 @@ impl pub struct WorldpayAuthType { pub(super) api_key: Secret<String>, + pub(super) entity_id: Secret<String>, } impl TryFrom<&types::ConnectorAuthType> for WorldpayAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { + // TODO: Remove this later, kept purely for backwards compatibility types::ConnectorAuthType::BodyKey { api_key, key1 } => { let auth_key = format!("{}:{}", key1.peek(), api_key.peek()); let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); Ok(Self { api_key: Secret::new(auth_header), + entity_id: Secret::new("default".to_string()), + }) + } + types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => { + let auth_key = format!("{}:{}", key1.peek(), api_key.peek()); + let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key)); + Ok(Self { + api_key: Secret::new(auth_header), + entity_id: api_secret.clone(), }) } _ => Err(errors::ConnectorError::FailedToObtainAuthType)?, @@ -197,22 +246,25 @@ impl TryFrom<&types::ConnectorAuthType> for WorldpayAuthType { } } -impl From<Outcome> for enums::AttemptStatus { - fn from(item: Outcome) -> Self { +impl From<PaymentOutcome> for enums::AttemptStatus { + fn from(item: PaymentOutcome) -> Self { match item { - Outcome::Authorized => Self::Authorized, - Outcome::Refused => Self::Failure, + PaymentOutcome::Authorized => Self::Authorized, + PaymentOutcome::Refused => Self::Failure, + PaymentOutcome::SentForSettlement => Self::CaptureInitiated, + PaymentOutcome::SentForRefund => Self::AutoRefunded, } } } -impl From<EventType> for enums::AttemptStatus { - fn from(value: EventType) -> Self { +impl From<&EventType> for enums::AttemptStatus { + fn from(value: &EventType) -> Self { match value { + EventType::SentForAuthorization => Self::Authorizing, + EventType::SentForSettlement => Self::CaptureInitiated, + EventType::Settled => Self::Charged, EventType::Authorized => Self::Authorized, - EventType::CaptureFailed => Self::CaptureFailed, - EventType::Refused => Self::Failure, - EventType::Charged | EventType::SentForSettlement => Self::Charged, + EventType::Refused | EventType::SettlementFailed => Self::Failure, EventType::Cancelled | EventType::SentForRefund | EventType::RefundFailed @@ -227,17 +279,17 @@ impl From<EventType> for enums::AttemptStatus { impl From<EventType> for enums::RefundStatus { fn from(value: EventType) -> Self { match value { - EventType::Refunded => Self::Success, + EventType::Refunded | EventType::SentForRefund => Self::Success, EventType::RefundFailed => Self::Failure, EventType::Authorized | EventType::Cancelled - | EventType::Charged - | EventType::SentForRefund + | EventType::Settled | EventType::Refused | EventType::Error | EventType::SentForSettlement + | EventType::SentForAuthorization + | EventType::SettlementFailed | EventType::Expired - | EventType::CaptureFailed | EventType::Unknown => Self::Pending, } } @@ -273,14 +325,29 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>> } } -impl<F> TryFrom<&types::RefundsRouterData<F>> for WorldpayRefundRequest { +impl TryFrom<(&types::PaymentsCaptureRouterData, MinorUnit)> for WorldpayPartialRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(req: (&types::PaymentsCaptureRouterData, MinorUnit)) -> Result<Self, Self::Error> { + let (item, amount) = req; + Ok(Self { + reference: item.payment_id.clone().replace("_", "-"), + value: PaymentValue { + amount: amount.get_amount_as_i64(), + currency: item.request.currency, + }, + }) + } +} + +impl<F> TryFrom<(&types::RefundsRouterData<F>, MinorUnit)> for WorldpayPartialRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(req: (&types::RefundsRouterData<F>, MinorUnit)) -> Result<Self, Self::Error> { + let (item, amount) = req; Ok(Self { - reference: item.request.connector_transaction_id.clone(), + reference: item.request.refund_id.clone().replace("_", "-"), value: PaymentValue { - amount: item.request.refund_amount, - currency: item.request.currency.to_string(), + amount: amount.get_amount_as_i64(), + currency: item.request.currency, }, }) } diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs index 6b25be73185..68db6423e06 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -106,7 +106,10 @@ impl payment_method, error_code: self.payment_attempt.error_code.clone(), error_message: self.payment_attempt.error_message.clone(), - connector_transaction_id: self.payment_attempt.connector_transaction_id.clone(), + connector_transaction_id: self + .payment_attempt + .get_connector_payment_id() + .map(ToString::to_string), connector: self.payment_attempt.connector.clone(), }, // self.order_details response: Ok(FraudCheckResponseData::TransactionResponse { diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 2257c42f446..0ea78e1ce14 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -6,7 +6,7 @@ use async_trait::async_trait; use common_enums::{AuthorizationStatus, SessionUpdateStatus}; use common_utils::{ ext_traits::{AsyncExt, Encode}, - types::{keymanager::KeyManagerState, MinorUnit}, + types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit}, }; use error_stack::{report, ResultExt}; use futures::FutureExt; @@ -1400,6 +1400,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( } => { let connector_transaction_id = match pre_processing_id.to_owned() { types::PreprocessingResponseId::PreProcessingId(_) => None, + types::PreprocessingResponseId::ConnectorTransactionId( connector_txn_id, ) => Some(connector_txn_id), @@ -1446,8 +1447,8 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( ); let connector_transaction_id = match resource_id { types::ResponseId::NoResponseId => None, - types::ResponseId::ConnectorTransactionId(id) - | types::ResponseId::EncodedData(id) => Some(id), + types::ResponseId::ConnectorTransactionId(ref id) + | types::ResponseId::EncodedData(ref id) => Some(id), }; let encoded_data = payment_data.payment_attempt.encoded_data.clone(); @@ -1496,12 +1497,23 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( .multiple_capture_data { Some(multiple_capture_data) => { + let (connector_capture_id, connector_capture_data) = + match resource_id { + types::ResponseId::NoResponseId => (None, None), + types::ResponseId::ConnectorTransactionId(id) + | types::ResponseId::EncodedData(id) => { + let (txn_id, txn_data) = + ConnectorTransactionId::form_id_and_data(id); + (Some(txn_id), txn_data) + } + }; let capture_update = storage::CaptureUpdate::ResponseUpdate { status: enums::CaptureStatus::foreign_try_from( router_data.status, )?, - connector_capture_id: connector_transaction_id.clone(), + connector_capture_id: connector_capture_id.clone(), connector_response_reference_id, + connector_capture_data: connector_capture_data.clone(), }; let capture_update_list = vec![( multiple_capture_data.get_latest_capture().clone(), @@ -1519,7 +1531,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( Some(storage::PaymentAttemptUpdate::ResponseUpdate { status: updated_attempt_status, connector: None, - connector_transaction_id: connector_transaction_id.clone(), + connector_transaction_id: connector_transaction_id.cloned(), authentication_type: auth_update, amount_capturable: router_data .request @@ -1872,7 +1884,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( &add_attributes([ ( "connector", - payment_data.payment_attempt.connector.unwrap_or_default(), + payment_data + .payment_attempt + .connector + .clone() + .unwrap_or_default(), ), ( "merchant_id", @@ -1886,12 +1902,15 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( ); Err(error_stack::Report::new( errors::ApiErrorResponse::IntegrityCheckFailed { + connector_transaction_id: payment_data + .payment_attempt + .get_connector_payment_id() + .map(ToString::to_string), reason: payment_data .payment_attempt .error_message .unwrap_or_default(), field_names: err.field_names, - connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, }, )) } @@ -2015,7 +2034,7 @@ fn response_to_capture_update( let mut unmapped_captures = vec![]; for (connector_capture_id, capture_sync_response) in response_list { let capture = - multiple_capture_data.get_capture_by_connector_capture_id(connector_capture_id); + multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id); if let Some(capture) = capture { capture_update_list.push(( capture.clone(), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 72e6c6b9979..8ad39ffc894 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -9,7 +9,7 @@ use common_utils::{ consts::X_HS_LATENCY, fp_utils, pii::Email, - types::{AmountConvertor, MinorUnit, StringMajorUnitForConnector}, + types::{self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnitForConnector}, }; use diesel_models::ephemeral_key; use error_stack::{report, ResultExt}; @@ -204,8 +204,8 @@ where let resource_id = match payment_data .payment_attempt - .connector_transaction_id - .clone() + .get_connector_payment_id() + .map(ToString::to_string) { Some(id) => types::ResponseId::ConnectorTransactionId(id), None => types::ResponseId::NoResponseId, @@ -1163,6 +1163,10 @@ where }) }); + let connector_transaction_id = payment_attempt + .get_connector_payment_id() + .map(ToString::to_string); + let payments_response = api::PaymentsResponse { payment_id: payment_intent.payment_id, merchant_id: payment_intent.merchant_id, @@ -1231,7 +1235,7 @@ where connector_request_reference_id_config, &merchant_id, ), - connector_transaction_id: payment_attempt.connector_transaction_id, + connector_transaction_id, frm_message, metadata: payment_intent.metadata, connector_metadata: payment_intent.connector_metadata, @@ -1396,6 +1400,7 @@ pub fn wait_screen_next_steps_check( #[cfg(feature = "v1")] impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse { fn foreign_from((pi, pa): (storage::PaymentIntent, storage::PaymentAttempt)) -> Self { + let connector_transaction_id = pa.get_connector_payment_id().map(ToString::to_string); Self { payment_id: pi.payment_id, merchant_id: pi.merchant_id, @@ -1418,7 +1423,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay setup_future_usage: pi.setup_future_usage, capture_method: pa.capture_method, authentication_type: pa.authentication_type, - connector_transaction_id: pa.connector_transaction_id, + connector_transaction_id, attempt_count: pi.attempt_count, profile_id: pi.profile_id, merchant_connector_id: pa.merchant_connector_id, @@ -1983,6 +1988,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureD })?; let amount = payment_data.payment_attempt.get_total_amount(); Ok(Self { + capture_method: payment_data.get_capture_method(), amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module minor_amount_to_capture: amount_to_capture, currency: payment_data.currency, @@ -2321,14 +2327,21 @@ impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { connector_response_reference_id, .. } => { - let connector_capture_id = match resource_id { - types::ResponseId::ConnectorTransactionId(id) => Some(id), - types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => None, + let (connector_capture_id, connector_capture_data) = match resource_id { + types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => { + (None, None) + } + types::ResponseId::ConnectorTransactionId(id) => { + let (txn_id, txn_data) = + common_utils_type::ConnectorTransactionId::form_id_and_data(id); + (Some(txn_id), txn_data) + } }; Ok(Self::ResponseUpdate { status: enums::CaptureStatus::foreign_try_from(status)?, connector_capture_id, connector_response_reference_id, + connector_capture_data, }) } types::CaptureSyncResponse::Error { @@ -2395,7 +2408,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz browser_info, email: payment_data.email, payment_method_data: payment_data.payment_method_data.map(From::from), - connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, + connector_transaction_id: payment_data + .payment_attempt + .get_connector_payment_id() + .map(ToString::to_string), redirect_response, connector_meta: payment_data.payment_attempt.connector_metadata, complete_authorize_url, @@ -2494,7 +2510,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProce complete_authorize_url, browser_info, surcharge_details: payment_data.surcharge_details, - connector_transaction_id: payment_data.payment_attempt.connector_transaction_id, + connector_transaction_id: payment_data + .payment_attempt + .get_connector_payment_id() + .map(ToString::to_string), redirect_response: None, mandate_id: payment_data.mandate_id, related_transaction_id: None, diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index 3034b74db45..1a7e2047678 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -4,7 +4,7 @@ use api_models::payment_methods::SurchargeDetailsResponse; use common_utils::{ errors::CustomResult, ext_traits::{Encode, OptionExt}, - types as common_types, + types::{self as common_types, ConnectorTransactionIdTrait}, }; use error_stack::ResultExt; use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt; @@ -162,11 +162,13 @@ impl MultipleCaptureData { } pub fn get_capture_by_connector_capture_id( &self, - connector_capture_id: String, + connector_capture_id: &String, ) -> Option<&storage::Capture> { self.all_captures .iter() - .find(|(_, capture)| capture.connector_capture_id == Some(connector_capture_id.clone())) + .find(|(_, capture)| { + capture.get_optional_connector_transaction_id() == Some(connector_capture_id) + }) .map(|(_, capture)| capture) } pub fn get_latest_capture(&self) -> &storage::Capture { @@ -176,14 +178,14 @@ impl MultipleCaptureData { let pending_connector_capture_ids = self .get_pending_captures() .into_iter() - .filter_map(|capture| capture.connector_capture_id.clone()) + .filter_map(|capture| capture.get_optional_connector_transaction_id().cloned()) .collect(); pending_connector_capture_ids } pub fn get_pending_captures_without_connector_capture_id(&self) -> Vec<&storage::Capture> { self.get_pending_captures() .into_iter() - .filter(|capture| capture.connector_capture_id.is_none()) + .filter(|capture| capture.get_optional_connector_transaction_id().is_none()) .collect() } } diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index cf0374fe826..86211770e0d 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use api_models::admin::MerchantConnectorInfo; use common_utils::{ ext_traits::{AsyncExt, ValueExt}, - types::MinorUnit, + types::{ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit}, }; use diesel_models::process_tracker::business_status; use error_stack::{report, ResultExt}; @@ -235,6 +235,7 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some("NOT_IMPLEMENTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, + connector_refund_data: None, }) } errors::ConnectorError::NotSupported { message, connector } => { @@ -246,6 +247,7 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some("NOT_SUPPORTED".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: None, + connector_refund_data: None, }) } _ => None, @@ -287,12 +289,18 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some(err.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, + connector_refund_data: None, }, Ok(response) => { // match on connector integrity checks match router_data_res.integrity_check.clone() { Err(err) => { - let refund_connector_transaction_id = err.connector_transaction_id; + let (refund_connector_transaction_id, connector_refund_data) = + err.connector_transaction_id.map_or((None, None), |txn_id| { + let (refund_id, refund_data) = + ConnectorTransactionId::form_id_and_data(txn_id); + (Some(refund_id), refund_data) + }); metrics::INTEGRITY_CHECK_FAILED.add( &metrics::CONTEXT, 1, @@ -313,6 +321,7 @@ pub async fn trigger_refund_to_gateway( refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, + connector_refund_data, } } Ok(()) => { @@ -323,13 +332,16 @@ pub async fn trigger_refund_to_gateway( &add_attributes([("connector", connector.connector_name.to_string())]), ) } + let (connector_refund_id, connector_refund_data) = + ConnectorTransactionId::form_id_and_data(response.connector_refund_id); storage::RefundUpdate::Update { - connector_refund_id: response.connector_refund_id, + connector_refund_id, refund_status: response.refund_status, sent_to_gateway: true, refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), + connector_refund_data, } } } @@ -424,7 +436,7 @@ pub async fn refund_retrieve_core( let payment_attempt = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( - &refund.connector_transaction_id, + refund.get_connector_transaction_id(), payment_id, merchant_id, merchant_account.storage_scheme, @@ -591,6 +603,7 @@ pub async fn sync_refund_with_gateway( refund_error_code: Some(error_message.code), updated_by: storage_scheme.to_string(), connector_refund_id: None, + connector_refund_data: None, } } Ok(response) => match router_data_res.integrity_check.clone() { @@ -606,7 +619,13 @@ pub async fn sync_refund_with_gateway( ), ]), ); - let refund_connector_transaction_id = err.connector_transaction_id; + let (refund_connector_transaction_id, connector_refund_data) = err + .connector_transaction_id + .map_or((None, None), |refund_id| { + let (refund_id, refund_data) = + ConnectorTransactionId::form_id_and_data(refund_id); + (Some(refund_id), refund_data) + }); storage::RefundUpdate::ErrorUpdate { refund_status: Some(enums::RefundStatus::ManualReview), refund_error_message: Some(format!( @@ -616,16 +635,22 @@ pub async fn sync_refund_with_gateway( refund_error_code: Some("IE".to_string()), updated_by: storage_scheme.to_string(), connector_refund_id: refund_connector_transaction_id, + connector_refund_data, + } + } + Ok(()) => { + let (connector_refund_id, connector_refund_data) = + ConnectorTransactionId::form_id_and_data(response.connector_refund_id); + storage::RefundUpdate::Update { + connector_refund_id, + refund_status: response.refund_status, + sent_to_gateway: true, + refund_error_message: None, + refund_arn: "".to_string(), + updated_by: storage_scheme.to_string(), + connector_refund_data, } } - Ok(()) => storage::RefundUpdate::Update { - connector_refund_id: response.connector_refund_id, - refund_status: response.refund_status, - sent_to_gateway: true, - refund_error_message: None, - refund_arn: "".to_string(), - updated_by: storage_scheme.to_string(), - }, }, }; @@ -752,7 +777,7 @@ pub async fn validate_and_create_refund( .attach_printable("invalid merchant_id in request")) })?; - let connecter_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| { + let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| { report!(errors::ApiErrorResponse::InternalServerError) .attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.") })?; @@ -760,7 +785,7 @@ pub async fn validate_and_create_refund( let all_refunds = db .find_refund_by_merchant_id_connector_transaction_id( merchant_account.get_id(), - &connecter_transaction_id, + &connector_transaction_id, merchant_account.storage_scheme, ) .await @@ -800,13 +825,15 @@ pub async fn validate_and_create_refund( .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("No connector populated in payment attempt")?; + let (connector_transaction_id, connector_transaction_data) = + ConnectorTransactionId::form_id_and_data(connector_transaction_id); let refund_create_req = storage::RefundNew { refund_id: refund_id.to_string(), internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"), external_reference_id: Some(refund_id.clone()), payment_id: req.payment_id, merchant_id: merchant_account.get_id().clone(), - connector_transaction_id: connecter_transaction_id.to_string(), + connector_transaction_id, connector, refund_type: req.refund_type.unwrap_or_default().foreign_into(), total_amount: payment_attempt.get_total_amount(), @@ -827,6 +854,8 @@ pub async fn validate_and_create_refund( refund_arn: None, updated_by: Default::default(), organization_id: merchant_account.organization_id.clone(), + connector_refund_data: None, + connector_transaction_data, }; let refund = match db @@ -1402,7 +1431,7 @@ pub async fn trigger_refund_execute_workflow( let payment_attempt = db .find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id( - &refund.connector_transaction_id, + refund.get_connector_transaction_id(), &refund_core.payment_id, &refund.merchant_id, merchant_account.storage_scheme, @@ -1506,6 +1535,7 @@ pub fn refund_to_refund_core_workflow_model( connector_transaction_id: refund.connector_transaction_id.clone(), merchant_id: refund.merchant_id.clone(), payment_id: refund.payment_id.clone(), + connector_transaction_data: refund.connector_transaction_data.clone(), } } diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index ae8b7c15a73..a6a9c36bfda 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -12,7 +12,7 @@ use common_utils::{crypto::Encryptable, pii::Email}; use common_utils::{ errors::CustomResult, ext_traits::AsyncExt, - types::{keymanager::KeyManagerState, MinorUnit}, + types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -325,6 +325,8 @@ pub async fn construct_refund_router_data<'a, F>( field_name: "browser_info", })?; + let connector_refund_id = refund.get_optional_connector_refund_id().cloned(); + let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), @@ -349,7 +351,7 @@ pub async fn construct_refund_router_data<'a, F>( minor_amount_captured: payment_intent.amount_captured, request: types::RefundsData { refund_id: refund.refund_id.clone(), - connector_transaction_id: refund.connector_transaction_id.clone(), + connector_transaction_id: refund.get_connector_transaction_id().clone(), refund_amount: refund.refund_amount.get_amount_as_i64(), minor_refund_amount: refund.refund_amount, currency, @@ -358,14 +360,14 @@ pub async fn construct_refund_router_data<'a, F>( webhook_url, connector_metadata: payment_attempt.connector_metadata.clone(), reason: refund.refund_reason.clone(), - connector_refund_id: refund.connector_refund_id.clone(), + connector_refund_id: connector_refund_id.clone(), browser_info, charges, integrity_object: None, }, response: Ok(types::RefundsResponseData { - connector_refund_id: refund.connector_refund_id.clone().unwrap_or_default(), + connector_refund_id: connector_refund_id.unwrap_or_default(), refund_status: refund.refund_status, }), access_token: None, diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index af531984a19..3942c395665 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -814,6 +814,7 @@ async fn refunds_incoming_webhook_flow( .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) .attach_printable("failed refund status mapping from event type")?, updated_by: merchant_account.storage_scheme.to_string(), + connector_refund_data: None, }; db.update_refund( refund.to_owned(), diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index 335110248ab..3a8750feff9 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -391,11 +391,11 @@ mod storage { let field = format!("add_{}", address_id); Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Address>::HGet(&field), key, - ) + )) .await? .try_into_hget() }, @@ -502,14 +502,14 @@ mod storage { }, }; - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<storage_types::Address>( (&field, redis_value), redis_entry, ), key, - ) + )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() @@ -601,7 +601,7 @@ mod storage { }, }; - match kv_wrapper::<diesel_models::Address, _, _>( + match Box::pin(kv_wrapper::<diesel_models::Address, _, _>( self, KvOperation::HSetNx::<diesel_models::Address>( &field, @@ -609,7 +609,7 @@ mod storage { redis_entry, ), key, - ) + )) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs index 16b18a873d3..cbc27f918d4 100644 --- a/crates/router/src/db/capture.rs +++ b/crates/router/src/db/capture.rs @@ -198,6 +198,7 @@ impl CaptureInterface for MockDb { capture_sequence: capture.capture_sequence, connector_capture_id: capture.connector_capture_id, connector_response_reference_id: capture.connector_response_reference_id, + connector_capture_data: capture.connector_capture_data, }; captures.push(capture.clone()); Ok(capture) diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index 9cd044f69eb..5020c238e4a 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -219,11 +219,11 @@ mod storage { Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, - ) + )) .await? .try_into_hget() .map(Some) @@ -293,11 +293,11 @@ mod storage { Box::pin(db_utils::try_redis_get_else_try_database_get( // check for ValueNotFound async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, - ) + )) .await? .try_into_hget() .map(Some) @@ -453,14 +453,14 @@ mod storage { }, }; - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<diesel_models::Customer>( (&field, redis_value), redis_entry, ), key, - ) + )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() @@ -584,11 +584,11 @@ mod storage { let field = format!("cust_{}", customer_id.get_string_repr()); Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Customer>::HGet(&field), key, - ) + )) .await? .try_into_hget() }, @@ -773,7 +773,7 @@ mod storage { }; let storage_customer = new_customer.into(); - match kv_wrapper::<diesel_models::Customer, _, _>( + match Box::pin(kv_wrapper::<diesel_models::Customer, _, _>( self, KvOperation::HSetNx::<diesel_models::Customer>( &field, @@ -781,7 +781,7 @@ mod storage { redis_entry, ), key, - ) + )) .await .change_context(errors::StorageError::KVError)? .try_into_hsetnx() diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index 40e5f88614d..95733805b43 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -114,11 +114,11 @@ mod storage { Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&field), key, - ) + )) .await? .try_into_hget() }, @@ -172,11 +172,11 @@ mod storage { Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<diesel_models::Mandate>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -281,14 +281,14 @@ mod storage { }, }; - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<diesel_models::Mandate>::Hset( (&field, redis_value), redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() @@ -369,7 +369,7 @@ mod storage { .await?; } - match kv_wrapper::<diesel_models::Mandate, _, _>( + match Box::pin(kv_wrapper::<diesel_models::Mandate, _, _>( self, KvOperation::<diesel_models::Mandate>::HSetNx( &field, @@ -377,7 +377,7 @@ mod storage { redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index 6e052076799..e75fb940a35 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -210,13 +210,13 @@ mod storage { Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<storage_types::PaymentMethod>::HGet( &lookup.sk_id, ), key, - ) + )) .await? .try_into_hget() }, @@ -348,13 +348,13 @@ mod storage { Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<storage_types::PaymentMethod>::HGet( &lookup.sk_id, ), key, - ) + )) .await? .try_into_hget() }, @@ -500,7 +500,7 @@ mod storage { }, }; - match kv_wrapper::<diesel_models::PaymentMethod, _, _>( + match Box::pin(kv_wrapper::<diesel_models::PaymentMethod, _, _>( self, KvOperation::<diesel_models::PaymentMethod>::HSetNx( &field, @@ -508,7 +508,7 @@ mod storage { redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() @@ -597,14 +597,14 @@ mod storage { }, }; - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<diesel_models::PaymentMethod>::Hset( (&field, redis_value), redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() @@ -743,11 +743,11 @@ mod storage { let pattern = "payment_method_id_*"; let redis_fut = async { - let kv_result = kv_wrapper::<storage_types::PaymentMethod, _, _>( + let kv_result = Box::pin(kv_wrapper::<storage_types::PaymentMethod, _, _>( self, KvOperation::<storage_types::PaymentMethod>::Scan(pattern), key, - ) + )) .await? .try_into_scan(); kv_result.map(|payment_methods| { diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index cf092ad410e..41cb3cef5c6 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; #[cfg(feature = "olap")] -use common_utils::types::MinorUnit; +use common_utils::types::{ConnectorTransactionIdTrait, MinorUnit}; use diesel_models::{errors::DatabaseError, refund::RefundUpdateInternal}; use hyperswitch_domain_models::refunds; @@ -298,7 +298,9 @@ mod storage { #[cfg(feature = "kv_store")] mod storage { - use common_utils::{ext_traits::Encode, fallback_reverse_lookup_not_found}; + use common_utils::{ + ext_traits::Encode, fallback_reverse_lookup_not_found, types::ConnectorTransactionIdTrait, + }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::refunds; use redis_interface::HsetnxReply; @@ -359,11 +361,11 @@ mod storage { }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -432,6 +434,8 @@ mod storage { merchant_connector_id: new.merchant_connector_id.clone(), charges: new.charges.clone(), organization_id: new.organization_id.clone(), + connector_refund_data: new.connector_refund_data.clone(), + connector_transaction_data: new.connector_transaction_data.clone(), }; let field = format!( @@ -470,7 +474,8 @@ mod storage { updated_by: storage_scheme.to_string(), }, ]; - if let Some(connector_refund_id) = created_refund.to_owned().connector_refund_id + if let Some(connector_refund_id) = + created_refund.to_owned().get_optional_connector_refund_id() { reverse_lookups.push(storage_types::ReverseLookupNew { sk_id: field.clone(), @@ -491,7 +496,7 @@ mod storage { futures::future::try_join_all(rev_look).await?; - match kv_wrapper::<storage_types::Refund, _, _>( + match Box::pin(kv_wrapper::<storage_types::Refund, _, _>( self, KvOperation::<storage_types::Refund>::HSetNx( &field, @@ -499,7 +504,7 @@ mod storage { redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() @@ -560,11 +565,11 @@ mod storage { Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::Scan(&pattern), key, - ) + )) .await? .try_into_scan() }, @@ -619,14 +624,14 @@ mod storage { }, }; - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<storage_types::Refund>( (&field, redis_value), redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() @@ -672,11 +677,11 @@ mod storage { }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -730,11 +735,11 @@ mod storage { }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -777,11 +782,11 @@ mod storage { }; Box::pin(db_utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<storage_types::Refund>::Scan("pa_*_ref_*"), key, - ) + )) .await? .try_into_scan() }, @@ -921,6 +926,8 @@ impl RefundInterface for MockDb { merchant_connector_id: new.merchant_connector_id, charges: new.charges, organization_id: new.organization_id, + connector_refund_data: new.connector_refund_data, + connector_transaction_data: new.connector_transaction_data, }; refunds.push(refund.clone()); Ok(refund) @@ -937,7 +944,7 @@ impl RefundInterface for MockDb { .iter() .take_while(|refund| { refund.merchant_id == *merchant_id - && refund.connector_transaction_id == connector_transaction_id + && refund.get_connector_transaction_id() == connector_transaction_id }) .cloned() .collect::<Vec<_>>()) @@ -995,7 +1002,10 @@ impl RefundInterface for MockDb { .iter() .find(|refund| { refund.merchant_id == *merchant_id - && refund.connector_refund_id == Some(connector_refund_id.to_string()) + && refund + .get_optional_connector_refund_id() + .map(|refund_id| refund_id.as_str()) + == Some(connector_refund_id) && refund.connector == connector }) .cloned() diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rs index d51ed5ed385..06bd84675b1 100644 --- a/crates/router/src/db/reverse_lookup.rs +++ b/crates/router/src/db/reverse_lookup.rs @@ -120,7 +120,7 @@ mod storage { }, }; - match kv_wrapper::<ReverseLookup, _, _>( + match Box::pin(kv_wrapper::<ReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { @@ -129,7 +129,7 @@ mod storage { &created_rev_lookup.lookup_id ), }, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() @@ -168,13 +168,13 @@ mod storage { enums::MerchantStorageScheme::PostgresOnly => database_call().await, enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<ReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, - ) + )) .await? .try_into_get() }; diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index c4fb4a43dd0..7eff6f881ba 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -1,4 +1,7 @@ -use common_utils::{id_type, types::MinorUnit}; +use common_utils::{ + id_type, + types::{ConnectorTransactionIdTrait, MinorUnit}, +}; use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; @@ -39,9 +42,9 @@ impl<'a> KafkaRefund<'a> { refund_id: &refund.refund_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, - connector_transaction_id: &refund.connector_transaction_id, + connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, - connector_refund_id: refund.connector_refund_id.as_ref(), + connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index f2150020c97..8f9f77878a1 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -1,4 +1,7 @@ -use common_utils::{id_type, types::MinorUnit}; +use common_utils::{ + id_type, + types::{ConnectorTransactionIdTrait, MinorUnit}, +}; use diesel_models::{enums as storage_enums, refund::Refund}; use time::OffsetDateTime; @@ -40,9 +43,9 @@ impl<'a> KafkaRefundEvent<'a> { refund_id: &refund.refund_id, payment_id: &refund.payment_id, merchant_id: &refund.merchant_id, - connector_transaction_id: &refund.connector_transaction_id, + connector_transaction_id: refund.get_connector_transaction_id(), connector: &refund.connector, - connector_refund_id: refund.connector_refund_id.as_ref(), + connector_refund_id: refund.get_optional_connector_refund_id(), external_reference_id: refund.external_reference_id.as_ref(), refund_type: &refund.refund_type, total_amount: &refund.total_amount, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e115558995d..37387a01da3 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -482,7 +482,7 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(&connector::Worldline))) } enums::Connector::Worldpay => { - Ok(ConnectorEnum::Old(Box::new(&connector::Worldpay))) + Ok(ConnectorEnum::Old(Box::new(connector::Worldpay::new()))) } enums::Connector::Mifinity => { Ok(ConnectorEnum::Old(Box::new(connector::Mifinity::new()))) diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 88d9b433ecb..40335d5f2ab 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -63,6 +63,7 @@ impl PaymentAttemptExt for PaymentAttempt { capture_sequence, connector_capture_id: None, connector_response_reference_id: None, + connector_capture_data: None, }) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 4d753b59bc7..2146ab34271 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -10,6 +10,7 @@ use common_utils::{ ext_traits::{Encode, StringExt, ValueExt}, fp_utils::when, pii, + types::ConnectorTransactionIdTrait, }; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; @@ -1292,6 +1293,9 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount> #[cfg(feature = "v1")] impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { fn foreign_from(payment_attempt: storage::PaymentAttempt) -> Self { + let connector_transaction_id = payment_attempt + .get_connector_payment_id() + .map(ToString::to_string); Self { attempt_id: payment_attempt.attempt_id, status: payment_attempt.status, @@ -1300,7 +1304,7 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { connector: payment_attempt.connector, error_message: payment_attempt.error_reason, payment_method: payment_attempt.payment_method, - connector_transaction_id: payment_attempt.connector_transaction_id, + connector_transaction_id, capture_method: payment_attempt.capture_method, authentication_type: payment_attempt.authentication_type, created_at: payment_attempt.created_at, @@ -1323,6 +1327,7 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { impl ForeignFrom<storage::Capture> for payments::CaptureResponse { fn foreign_from(capture: storage::Capture) -> Self { + let connector_capture_id = capture.get_optional_connector_transaction_id().cloned(); Self { capture_id: capture.capture_id, status: capture.status, @@ -1330,7 +1335,7 @@ impl ForeignFrom<storage::Capture> for payments::CaptureResponse { currency: capture.currency, connector: capture.connector, authorized_attempt_id: capture.authorized_attempt_id, - connector_capture_id: capture.connector_capture_id, + connector_capture_id, capture_sequence: capture.capture_sequence, error_message: capture.error_message, error_code: capture.error_code, diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 1f7d75fba83..122989a82cf 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -2,7 +2,10 @@ use api_models::{ enums::Connector::{DummyConnector4, DummyConnector7}, user::sample_data::SampleDataRequest, }; -use common_utils::{id_type, types::MinorUnit}; +use common_utils::{ + id_type, + types::{ConnectorTransactionId, MinorUnit}, +}; use diesel_models::{user::sample_data::PaymentAttemptBatchNew, RefundNew}; use error_stack::ResultExt; use hyperswitch_domain_models::payments::PaymentIntent; @@ -253,10 +256,12 @@ pub async fn generate_sample_data( tax_details: None, skip_external_tax_calculation: None, }; + let (connector_transaction_id, connector_transaction_data) = + ConnectorTransactionId::form_id_and_data(attempt_id.clone()); let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), payment_id: payment_id.clone(), - connector_transaction_id: Some(attempt_id.clone()), + connector_transaction_id: Some(connector_transaction_id), merchant_id: merchant_id.clone(), status: match is_failed_payment { true => common_enums::AttemptStatus::Failure, @@ -333,18 +338,21 @@ pub async fn generate_sample_data( organization_id: org_id.clone(), shipping_cost: None, order_tax_amount: None, + connector_transaction_data, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { refunds_count += 1; + let (connector_transaction_id, connector_transaction_data) = + ConnectorTransactionId::form_id_and_data(attempt_id.clone()); Some(RefundNew { refund_id: common_utils::generate_id_with_default_len("test"), internal_reference_id: common_utils::generate_id_with_default_len("test"), external_reference_id: None, payment_id: payment_id.clone(), - attempt_id: attempt_id.clone(), + attempt_id, merchant_id: merchant_id.clone(), - connector_transaction_id: attempt_id.clone(), + connector_transaction_id, connector_refund_id: None, description: Some("This is a sample refund".to_string()), created_at, @@ -369,6 +377,8 @@ pub async fn generate_sample_data( merchant_connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, organization_id: org_id.clone(), + connector_refund_data: None, + connector_transaction_data, }) } else { None diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index f61770a5bde..2b20ed4cf16 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -30,6 +30,7 @@ api_key = "Bearer MyApiKey" [worldpay] api_key = "api_key" key1 = "key1" +api_secret = "Merchant Identifier" [payu] api_key = "Bearer MyApiKey" diff --git a/crates/router/tests/connectors/worldpay.rs b/crates/router/tests/connectors/worldpay.rs index d4f6e167ff8..451aa398eb7 100644 --- a/crates/router/tests/connectors/worldpay.rs +++ b/crates/router/tests/connectors/worldpay.rs @@ -20,7 +20,7 @@ impl utils::Connector for Worldpay { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Worldpay; utils::construct_connector_data_old( - Box::new(&Worldpay), + Box::new(Worldpay::new()), types::Connector::Worldpay, types::api::GetToken::Connector, None, diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs index 943ef1f36f7..54377e45267 100644 --- a/crates/storage_impl/src/lookup.rs +++ b/crates/storage_impl/src/lookup.rs @@ -97,13 +97,13 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> { }, }; - match kv_wrapper::<DieselReverseLookup, _, _>( + match Box::pin(kv_wrapper::<DieselReverseLookup, _, _>( self, KvOperation::SetNx(&created_rev_lookup, redis_entry), PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{}", &created_rev_lookup.lookup_id), }, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&created_rev_lookup.lookup_id))? .try_into_setnx() @@ -140,13 +140,13 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> { storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await, storage_enums::MerchantStorageScheme::RedisKv => { let redis_fut = async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<DieselReverseLookup>::Get, PartitionKey::CombinationKey { combination: &format!("reverse_lookup_{id}"), }, - ) + )) .await? .try_into_get() }; diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 9053b7561ad..231f72bd731 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1,6 +1,10 @@ #[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; -use common_utils::{errors::CustomResult, fallback_reverse_lookup_not_found}; +use common_utils::{ + errors::CustomResult, + fallback_reverse_lookup_not_found, + types::{ConnectorTransactionId, ConnectorTransactionIdTrait}, +}; use diesel_models::{ enums::{ MandateAmountData as DieselMandateAmountData, MandateDataType as DieselMandateType, @@ -556,7 +560,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; - match kv_wrapper::<PaymentAttempt, _, _>( + match Box::pin(kv_wrapper::<PaymentAttempt, _, _>( self, KvOperation::HSetNx( &field, @@ -564,7 +568,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() @@ -628,7 +632,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } MerchantStorageScheme::RedisKv => { let key_str = key.to_string(); - let old_connector_transaction_id = &this.connector_transaction_id; + let old_connector_transaction_id = &this.get_connector_payment_id(); let old_preprocessing_id = &this.preprocessing_step_id; let updated_attempt = PaymentAttempt::from_storage_model( payment_attempt @@ -653,7 +657,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { match ( old_connector_transaction_id, - &updated_attempt.connector_transaction_id, + &updated_attempt.get_connector_payment_id(), ) { (None, Some(connector_transaction_id)) => { add_connector_txn_id_to_reverse_lookup( @@ -661,7 +665,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), - connector_transaction_id.as_str(), + connector_transaction_id, storage_scheme, ) .await?; @@ -673,7 +677,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { key_str.as_str(), &this.merchant_id, updated_attempt.attempt_id.as_str(), - connector_transaction_id.as_str(), + connector_transaction_id, storage_scheme, ) .await?; @@ -710,11 +714,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { (_, _) => {} } - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::Hset::<DieselPaymentAttempt>((&field, redis_value), redis_entry), key, - ) + )) .await .change_context(errors::StorageError::KVError)? .try_into_hset() @@ -798,7 +802,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { Box::pin(try_redis_get_else_try_database_get( async { - kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key).await?.try_into_hget() + Box::pin(kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key)).await?.try_into_hget() }, || 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}, )) @@ -839,11 +843,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let pattern = "pa_*"; let redis_fut = async { - let kv_result = kv_wrapper::<PaymentAttempt, _, _>( + let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>( self, KvOperation::<DieselPaymentAttempt>::Scan(pattern), key, - ) + )) .await? .try_into_scan(); kv_result.and_then(|mut payment_attempts| { @@ -898,11 +902,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let pattern = "pa_*"; let redis_fut = async { - let kv_result = kv_wrapper::<PaymentAttempt, _, _>( + let kv_result = Box::pin(kv_wrapper::<PaymentAttempt, _, _>( self, KvOperation::<DieselPaymentAttempt>::Scan(pattern), key, - ) + )) .await? .try_into_scan(); kv_result.and_then(|mut payment_attempts| { @@ -974,11 +978,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { }; Box::pin(try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -1031,9 +1035,13 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { let field = format!("pa_{attempt_id}"); Box::pin(try_redis_get_else_try_database_get( async { - kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::HGet(&field), key) - .await? - .try_into_hget() + Box::pin(kv_wrapper( + self, + KvOperation::<DieselPaymentAttempt>::HGet(&field), + key, + )) + .await? + .try_into_hget() }, || async { self.router_store @@ -1094,11 +1102,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { }; Box::pin(try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -1183,11 +1191,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { Box::pin(try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<DieselPaymentAttempt>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -1237,9 +1245,13 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { }; Box::pin(try_redis_get_else_try_database_get( async { - kv_wrapper(self, KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), key) - .await? - .try_into_scan() + Box::pin(kv_wrapper( + self, + KvOperation::<DieselPaymentAttempt>::Scan("pa_*"), + key, + )) + .await? + .try_into_scan() }, || async { self.router_store @@ -1367,6 +1379,11 @@ impl DataModelExt for PaymentAttempt { type StorageModel = DieselPaymentAttempt; fn to_storage_model(self) -> Self::StorageModel { + let (connector_transaction_id, connector_transaction_data) = self + .connector_transaction_id + .map(ConnectorTransactionId::form_id_and_data) + .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) + .unwrap_or((None, None)); DieselPaymentAttempt { payment_id: self.payment_id, merchant_id: self.merchant_id, @@ -1383,7 +1400,7 @@ impl DataModelExt for PaymentAttempt { tax_amount: self.net_amount.get_tax_on_surcharge(), payment_method_id: self.payment_method_id, payment_method: self.payment_method, - connector_transaction_id: self.connector_transaction_id, + connector_transaction_id, capture_method: self.capture_method, capture_on: self.capture_on, confirm: self.confirm, @@ -1437,12 +1454,16 @@ impl DataModelExt for PaymentAttempt { customer_acceptance: self.customer_acceptance, organization_id: self.organization_id, profile_id: self.profile_id, + connector_transaction_data, shipping_cost: self.net_amount.get_shipping_cost(), order_tax_amount: self.net_amount.get_order_tax_amount(), } } fn from_storage_model(storage_model: Self::StorageModel) -> Self { + let connector_transaction_id = storage_model + .get_optional_connector_transaction_id() + .cloned(); Self { net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new( storage_model.amount, @@ -1462,7 +1483,7 @@ impl DataModelExt for PaymentAttempt { offer_amount: storage_model.offer_amount, payment_method_id: storage_model.payment_method_id, payment_method: storage_model.payment_method, - connector_transaction_id: storage_model.connector_transaction_id, + connector_transaction_id, capture_method: storage_model.capture_method, capture_on: storage_model.capture_on, confirm: storage_model.confirm, diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index f5c3deeb18c..8ca63e79037 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -113,7 +113,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { .await .change_context(StorageError::EncryptionError)?; - match kv_wrapper::<DieselPaymentIntent, _, _>( + match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HSetNx( &field, @@ -121,7 +121,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() @@ -228,11 +228,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { }, }; - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() @@ -316,11 +316,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { let field = payment_id.get_hash_key_for_kv_store(); Box::pin(utils::try_redis_get_else_try_database_get( async { - kv_wrapper::<DieselPaymentIntent, _, _>( + Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>( self, KvOperation::<DieselPaymentIntent>::HGet(&field), key, - ) + )) .await? .try_into_hget() }, diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs index 33d73f99e5f..81d06a1cbd5 100644 --- a/crates/storage_impl/src/payouts/payout_attempt.rs +++ b/crates/storage_impl/src/payouts/payout_attempt.rs @@ -115,7 +115,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { self.insert_reverse_lookup(reverse_lookup, storage_scheme) .await?; - match kv_wrapper::<DieselPayoutAttempt, _, _>( + match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>( self, KvOperation::<DieselPayoutAttempt>::HSetNx( &field, @@ -123,7 +123,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() @@ -227,11 +227,11 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { _ => {} } - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPayoutAttempt>::Hset((&field, redis_value), redis_entry), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() @@ -284,11 +284,11 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { }; Box::pin(utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, @@ -345,11 +345,11 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { }; Box::pin(utils::try_redis_get_else_try_database_get( async { - kv_wrapper( + Box::pin(kv_wrapper( self, KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id), key, - ) + )) .await? .try_into_hget() }, diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index 2a49b01458f..9a94743da3f 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -134,7 +134,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { }, }; - match kv_wrapper::<DieselPayouts, _, _>( + match Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HSetNx( &field, @@ -142,7 +142,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { redis_entry, ), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hsetnx() @@ -208,11 +208,11 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { }, }; - kv_wrapper::<(), _, _>( + Box::pin(kv_wrapper::<(), _, _>( self, KvOperation::<DieselPayouts>::Hset((&field, redis_value), redis_entry), key, - ) + )) .await .map_err(|err| err.to_redis_failed_response(&key_str))? .try_into_hset() @@ -255,11 +255,11 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { let field = format!("po_{payout_id}"); Box::pin(utils::try_redis_get_else_try_database_get( async { - kv_wrapper::<DieselPayouts, _, _>( + Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HGet(&field), key, - ) + )) .await? .try_into_hget() }, @@ -312,11 +312,11 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { let field = format!("po_{payout_id}"); Box::pin(utils::try_redis_get_else_try_database_get( async { - kv_wrapper::<DieselPayouts, _, _>( + Box::pin(kv_wrapper::<DieselPayouts, _, _>( self, KvOperation::<DieselPayouts>::HGet(&field), key, - ) + )) .await? .try_into_hget() .map(Some) diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 74b1526fe8e..2fde935b670 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -312,8 +312,12 @@ where Op::Find => MerchantStorageScheme::RedisKv, Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly, Op::Update(partition_key, field, Some(_updated_by)) => { - match kv_wrapper::<D, _, _>(store, KvOperation::<D>::HGet(field), partition_key) - .await + match Box::pin(kv_wrapper::<D, _, _>( + store, + KvOperation::<D>::HGet(field), + partition_key, + )) + .await { Ok(_) => { metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(&metrics::CONTEXT, 1, &[]); diff --git a/crates/test_utils/tests/sample_auth.toml b/crates/test_utils/tests/sample_auth.toml index 08b24817c24..c7ec4f12c54 100644 --- a/crates/test_utils/tests/sample_auth.toml +++ b/crates/test_utils/tests/sample_auth.toml @@ -30,6 +30,7 @@ api_key = "Bearer MyApiKey" [worldpay] api_key = "api_key" key1 = "key1" +api_secret = "Merchant Identifier" [payu] api_key = "Bearer MyApiKey" diff --git a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js index ea7b4f09fd7..c2d1b7483c1 100644 --- a/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js +++ b/cypress-tests-v2/cypress/e2e/configs/Payment/Commons.js @@ -1069,7 +1069,7 @@ export const connectorDetails = { status: 400, body: { error: - "Json deserialize error: unknown variant `United`, expected one of `AED`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BWP`, `BYN`, `BZD`, `CAD`, `CHF`, `CLP`, `CNY`, `COP`, `CRC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STN`, `SVC`, `SZL`, `THB`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`", + "Json deserialize error: unknown variant `United`, expected one of `AED`, `AFN`, `ALL`, `AMD`, `ANG`, `AOA`, `ARS`, `AUD`, `AWG`, `AZN`, `BAM`, `BBD`, `BDT`, `BGN`, `BHD`, `BIF`, `BMD`, `BND`, `BOB`, `BRL`, `BSD`, `BTN`, `BWP`, `BYN`, `BZD`, `CAD`, `CDF`, `CHF`, `CLP`, `CNY`, `COP`, `CRC`, `CUP`, `CVE`, `CZK`, `DJF`, `DKK`, `DOP`, `DZD`, `EGP`, `ERN`, `ETB`, `EUR`, `FJD`, `FKP`, `GBP`, `GEL`, `GHS`, `GIP`, `GMD`, `GNF`, `GTQ`, `GYD`, `HKD`, `HNL`, `HRK`, `HTG`, `HUF`, `IDR`, `ILS`, `INR`, `IQD`, `IRR`, `ISK`, `JMD`, `JOD`, `JPY`, `KES`, `KGS`, `KHR`, `KMF`, `KPW`, `KRW`, `KWD`, `KYD`, `KZT`, `LAK`, `LBP`, `LKR`, `LRD`, `LSL`, `LYD`, `MAD`, `MDL`, `MGA`, `MKD`, `MMK`, `MNT`, `MOP`, `MRU`, `MUR`, `MVR`, `MWK`, `MXN`, `MYR`, `MZN`, `NAD`, `NGN`, `NIO`, `NOK`, `NPR`, `NZD`, `OMR`, `PAB`, `PEN`, `PGK`, `PHP`, `PKR`, `PLN`, `PYG`, `QAR`, `RON`, `RSD`, `RUB`, `RWF`, `SAR`, `SBD`, `SCR`, `SDG`, `SEK`, `SGD`, `SHP`, `SLE`, `SLL`, `SOS`, `SRD`, `SSP`, `STN`, `SVC`, `SYP`, `SZL`, `THB`, `TJS`, `TMT`, `TND`, `TOP`, `TRY`, `TTD`, `TWD`, `TZS`, `UAH`, `UGX`, `USD`, `UYU`, `UZS`, `VES`, `VND`, `VUV`, `WST`, `XAF`, `XCD`, `XOF`, `XPF`, `YER`, `ZAR`, `ZMW`, `ZWL`", }, }, }, diff --git a/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/down.sql b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/down.sql new file mode 100644 index 00000000000..8008535f877 --- /dev/null +++ b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/down.sql @@ -0,0 +1,11 @@ +ALTER TABLE payment_attempt +DROP COLUMN IF EXISTS connector_transaction_data; + +ALTER TABLE refund +DROP COLUMN IF EXISTS connector_refund_data; + +ALTER TABLE refund +DROP COLUMN IF EXISTS connector_transaction_data; + +ALTER TABLE captures +DROP COLUMN IF EXISTS connector_capture_data; \ No newline at end of file diff --git a/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/up.sql b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/up.sql new file mode 100644 index 00000000000..adab6dd3edf --- /dev/null +++ b/migrations/2024-09-25-113851_increase_connector_transaction_id_length_in_payment_and_refund/up.sql @@ -0,0 +1,11 @@ +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS connector_transaction_data VARCHAR(512); + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS connector_refund_data VARCHAR(512); + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS connector_transaction_data VARCHAR(512); + +ALTER TABLE captures +ADD COLUMN IF NOT EXISTS connector_capture_data VARCHAR(512); \ No newline at end of file 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 cfc769e70e1..519bef65cbb 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 @@ -38,4 +38,5 @@ ALTER TABLE payment_attempt DROP COLUMN payment_method_type_v2, DROP COLUMN routing_result, DROP COLUMN authentication_applied, DROP COLUMN external_reference_id, - DROP COLUMN tax_on_surcharge; + DROP COLUMN tax_on_surcharge, + DROP COLUMN connector_payment_data; 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 520bbdf6e7e..136bc550811 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 @@ -41,4 +41,5 @@ ADD COLUMN payment_method_type_v2 VARCHAR, ADD COLUMN routing_result JSONB, ADD COLUMN authentication_applied "AuthenticationType", ADD COLUMN external_reference_id VARCHAR(128), - ADD COLUMN tax_on_surcharge BIGINT; + ADD COLUMN tax_on_surcharge BIGINT, + ADD COLUMN connector_payment_data VARCHAR(512); diff --git a/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql b/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql similarity index 98% rename from v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql rename to v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql index 65e90b126fb..2cdb0296033 100644 --- a/v2_migrations/2024-08-28-081847_drop_v1_columns/down.sql +++ b/v2_migrations/2024-10-08-081847_drop_v1_columns/down.sql @@ -76,6 +76,7 @@ ADD COLUMN IF NOT EXISTS attempt_id VARCHAR(64) NOT NULL, ADD COLUMN offer_amount bigint, ADD COLUMN payment_method VARCHAR, ADD COLUMN connector_transaction_id VARCHAR(64), + ADD COLUMN connector_transaction_data VARCHAR(512), ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), diff --git a/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql b/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql similarity index 98% rename from v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql rename to v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql index 55b0b19d0b4..48ae811bf34 100644 --- a/v2_migrations/2024-08-28-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2024-10-08-081847_drop_v1_columns/up.sql @@ -74,6 +74,7 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN offer_amount, DROP COLUMN payment_method, DROP COLUMN connector_transaction_id, + DROP COLUMN connector_transaction_data, DROP COLUMN capture_method, DROP COLUMN capture_on, DROP COLUMN mandate_id,
2024-09-26T10:48:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Described in #6116 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Strengthens worldpay connector's integration. ## How did you test it? Things to test 1. No 3DS payment using auto capture 2. No 3DS payment using manual capture (full amount captures) 3. Refunds 4. Payments Sync 5. Backwards compatibility Notes - Refunds cannot be tested as WP relies only on webhooks to update the status to settled (succeeded in HS). Webhook URLs are configured asynchronously by reaching out to them - For manually updating the status to succeeded state and testing refunds, RSA key pairs can be created and webhook updates can be sent manually by configuring the MCA during creation (attach manually created private key in `merchant_secret` during MCA creation for WP) - For WP's webhook body, refer this - https://developer.worldpay.com/products/access/events/signature <details> <summary>1. Create and capture</summary> cURL curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \ --data-raw '{ "amount": 30, "currency": "USD", "confirm": true, "capture_method": "automatic", "amount_to_capture": 30, "customer_id": "default_cust", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "debit", "connector": [ "worldpay" ], "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "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": "127.0.0.1" } }' Response { "payment_id": "pay_NZqQvZ8fcOPBh9G8DGYL", "merchant_id": "merchant_1727351469", "status": "processing", "amount": 30, "net_amount": 30, "amount_capturable": 0, "amount_received": null, "connector": "worldpay", "client_secret": "pay_NZqQvZ8fcOPBh9G8DGYL_secret_pS12cS9WGzDVePcuToPS", "created": "2024-09-26T11:56:54.387Z", "currency": "USD", "customer_id": "default_cust", "customer": { "id": "default_cust", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "default_cust", "created_at": 1727351814, "expires": 1727355414, "secret": "epk_acfbbc3281c148dd987b6132993fea2d" }, "manual_retry_allowed": false, "connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLnb6ueU9CbFGwfx591hAsgQIRSoXyZaKoMjxP1EcfaiTUMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83h2J9B9mwlKgm3S:taO:ZbBw8gpCy5HM2WoIeZ0:XaCCrRM9QKRvbI4hUfmMTrs3ETMXutYDlb4dag7xGA2Qa4Ttn9WFEcXNtvDKZy5OJFs3A==", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_UANp3p6unZQH3GOhADuU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-26T12:11:54.387Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-26T11:56:55.183Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } </details> <details> <summary>2. Create a payment using manual capture</summary> cURL curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \ --data-raw '{ "amount": 30, "currency": "USD", "confirm": true, "capture_method": "manual", "amount_to_capture": 30, "customer_id": "default_cust", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "debit", "connector": [ "worldpay" ], "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "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": "127.0.0.1" } }' Response { "payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq", "merchant_id": "merchant_1727351469", "status": "requires_capture", "amount": 30, "net_amount": 30, "amount_capturable": 30, "amount_received": null, "connector": "worldpay", "client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG", "created": "2024-09-26T12:13:39.556Z", "currency": "USD", "customer_id": "default_cust", "customer": { "id": "default_cust", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "default_cust", "created_at": 1727352819, "expires": 1727356419, "secret": "epk_6524fd56e9334269b3da878638480886" }, "manual_retry_allowed": false, "connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_UANp3p6unZQH3GOhADuU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-26T12:28:39.555Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-26T12:13:40.443Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } cURL (capture) curl --location 'http://localhost:8080/payments/pay_CqvpsM1Aj2IEuOvZvrsq/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jGgKDnT9zDIpkNIbAU44DdT8uzauyY5huxSuQbqmgsvMmiTVnYVY6kNRE1xZtrnC' \ --data '{}' Response { "payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq", "merchant_id": "merchant_1727351469", "status": "succeeded", "amount": 30, "net_amount": 30, "amount_capturable": 0, "amount_received": 30, "connector": "worldpay", "client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG", "created": "2024-09-26T12:13:39.556Z", "currency": "USD", "customer_id": "default_cust", "customer": { "id": "default_cust", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_UANp3p6unZQH3GOhADuU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-26T12:28:39.555Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-26T12:14:26.304Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } </details> <details> <summary>3. Full amount refunds</summary> cURL curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' \ --data '{ "payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq", "amount": 30, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' Response { "refund_id": "ref_GX50lP3TOZ5LEBgkCt3o", "payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq", "amount": 30, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "created_at": "2024-09-26T12:17:08.162Z", "updated_at": "2024-09-26T12:17:09.220Z", "connector": "worldpay", "profile_id": "pro_UANp3p6unZQH3GOhADuU", "merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466", "charges": null } </details> <details> <summary>4. Retrieve payment</summary> cURL curl --location 'http://localhost:8080/payments/pay_CqvpsM1Aj2IEuOvZvrsq?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_hQVsbuQEJOsMxgS1XyrwdxU1vAi4WsMp2r5Ywh9238jRnvJamzRXpeJVimSfE4oN' Response { "payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq", "merchant_id": "merchant_1727351469", "status": "succeeded", "amount": 30, "net_amount": 30, "amount_capturable": 0, "amount_received": 30, "connector": "worldpay", "client_secret": "pay_CqvpsM1Aj2IEuOvZvrsq_secret_ZsHjmwNUQxz7qENlWKRG", "created": "2024-09-26T12:13:39.556Z", "currency": "USD", "customer_id": "default_cust", "customer": { "id": "default_cust", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": [ { "refund_id": "ref_GX50lP3TOZ5LEBgkCt3o", "payment_id": "pay_CqvpsM1Aj2IEuOvZvrsq", "amount": 30, "currency": "USD", "status": "succeeded", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "created_at": "2024-09-26T12:17:08.162Z", "updated_at": "2024-09-26T12:17:09.220Z", "connector": "worldpay", "profile_id": "pro_UANp3p6unZQH3GOhADuU", "merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466", "charges": null } ], "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "debit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLIfNhwuN4ZodT3laQe9WH8oRdkrhkT0SqvHaO8Zdn9+:UMYEzVJGIlCiYSGGWYG0a6076ZdnXFUQXCzmyoO5fYnojCGT5jnSkpzJvYFEyy2NCnMzk2C7iamI1tOIdYFfYCvERwWWTa+80d:aJmIlSKgn3O0PHAq2Xi+sNlchm83i2AtgthuD6sD4iuhj0IAQHfRrDquis0nMGnyeSQ0:qu7E2oMvn7cMnoWOTWCv9o84KnJGlExG1RNLYMTWnQ3VTJDVBhcAjNaDWUTFEl:Kfxw==", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_UANp3p6unZQH3GOhADuU", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AaZU41n7q7gnrpacJ466", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-26T12:28:39.555Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-26T12:14:26.304Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } </details> <details> <summary>5. Backwards compatibility</summary> 1. Create a new txn in existing application cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_1ty6UhSj8fnfhCQCpepIQXI3x22TPuzM5kWasidjCtlc0Am2ZaNRzfwU94hyXMjB' \ --data-raw '{"amount":100,"currency":"USD","confirm":true,"capture_method":"automatic","amount_to_capture":100,"customer_id":"default_cust","email":"guest@example.com","name":"John Doe","phone":"999999999","phone_country_code":"+1","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://google.com","payment_method":"card","payment_method_type":"debit","billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"CA","zip":"94122","country":"US","first_name":"John","last_name":"Doe"}},"connector":["stripe"],"payment_method_data":{"card":{"card_number":"4242424242424242","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"joseph Doe","card_cvc":"123"}},"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"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":"127.0.0.1"}}' Response {"payment_id":"pay_lzpTmYZBcWkTipqMfYaR","merchant_id":"merchant_1729081398","status":"succeeded","amount":100,"net_amount":100,"amount_capturable":0,"amount_received":100,"connector":"stripe","client_secret":"pay_lzpTmYZBcWkTipqMfYaR_secret_2YrHIhNliM3Qr1BhFHGz","created":"2024-10-16T12:25:02.294Z","currency":"USD","customer_id":"default_cust","customer":{"id":"default_cust","name":"John Doe","email":"guest@example.com","phone":"999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":null,"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null,"payment_checks":{"cvc_check":"pass","address_line1_check":"pass","address_postal_code_check":"pass"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"order_details":null,"email":"guest@example.com","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":{"customer_id":"default_cust","created_at":1729081502,"expires":1729085102,"secret":"epk_eb2cedad9dd440f2871464e3b6255f2e"},"manual_retry_allowed":false,"connector_transaction_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","payment_link":null,"profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-16T12:40:02.294Z","fingerprint":null,"browser_info":{"language":"nl-NL","time_zone":0,"ip_address":"127.0.0.1","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","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-16T12:25:03.819Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} 2. Fetch the same payment in new application cURL curl --location --request GET 'http://localhost:8080/payments/pay_lzpTmYZBcWkTipqMfYaR?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_G3dnuM0z1Jjij7fFSo8pGC02QrgBgDB3wulB18mtqGiVkWnAq0vyoaCsQSXxbBrt' Response {"payment_id":"pay_lzpTmYZBcWkTipqMfYaR","merchant_id":"merchant_1729081398","status":"succeeded","amount":100,"net_amount":100,"amount_capturable":0,"amount_received":100,"connector":"stripe","client_secret":"pay_lzpTmYZBcWkTipqMfYaR_secret_2YrHIhNliM3Qr1BhFHGz","created":"2024-10-16T12:25:02.294Z","currency":"USD","customer_id":"default_cust","customer":{"id":"default_cust","name":"John Doe","email":"guest@example.com","phone":"999999999","phone_country_code":"+1"},"description":"Its my first payment request","refunds":[{"refund_id":"ref_fxU4gvgDk3oPteI1wy4P","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:14.725Z","updated_at":"2024-10-16T12:25:18.559Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null},{"refund_id":"ref_oHm62P61wXjq7sx7vskd","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:11.356Z","updated_at":"2024-10-16T12:25:12.371Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null},{"refund_id":"ref_xSdJ24sgZQf4qDyDpUfj","payment_id":"pay_lzpTmYZBcWkTipqMfYaR","amount":30,"currency":"USD","status":"succeeded","reason":"Customer returned product","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"error_message":null,"error_code":null,"created_at":"2024-10-16T12:25:13.069Z","updated_at":"2024-10-16T12:25:14.019Z","connector":"stripe","profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","charges":null}],"disputes":null,"mandate_id":null,"mandate_data":null,"setup_future_usage":null,"off_session":null,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"4242","card_type":null,"card_network":null,"card_issuer":null,"card_issuing_country":null,"card_isin":"424242","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":null,"payment_checks":{"cvc_check":"pass","address_line1_check":"pass","address_postal_code_check":"pass"},"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":{"address":{"city":"San Fransico","country":"US","line1":"1467","line2":"Harrison Street","line3":"Harrison Street","zip":"94122","state":"CA","first_name":"John","last_name":"Doe"},"phone":null,"email":null},"order_details":null,"email":"guest@example.com","name":"John Doe","phone":"999999999","return_url":"https://google.com/","authentication_type":"no_three_ds","statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","next_action":null,"cancellation_reason":null,"error_code":null,"error_message":null,"unified_code":null,"unified_message":null,"payment_experience":null,"payment_method_type":"debit","connector_label":null,"business_country":null,"business_label":"default","business_sub_label":null,"allowed_payment_method_types":null,"ephemeral_key":null,"manual_retry_allowed":false,"connector_transaction_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"pi_3QAWHiD5R7gDAGff0IAM68qV","payment_link":null,"profile_id":"pro_bP0BEYSUdhJT7cdrdqY3","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_vnDKcmsknIH8byKxlY0q","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2024-10-16T12:40:02.294Z","fingerprint":null,"browser_info":{"language":"nl-NL","time_zone":0,"ip_address":"127.0.0.1","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","color_depth":24,"java_enabled":true,"screen_width":1536,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":723,"java_script_enabled":true},"payment_method_id":null,"payment_method_status":null,"updated":"2024-10-16T12:25:03.819Z","charges":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
39d89f23b6ae85c4f91a52bb0d970277b43237d8
juspay/hyperswitch
juspay__hyperswitch-6115
Bug: fix: env added for hyperswitch-web Added env for hyperswitch-web
diff --git a/docker-compose.yml b/docker-compose.yml index ef6ff17b5e9..f766ff91053 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -162,6 +162,7 @@ services: - SELF_SERVER_URL=http://localhost:5252 - SDK_ENV=local - ENV_LOGGING_URL=http://localhost:3103 + - ENV_BACKEND_URL=http://localhost:8080 labels: logs: "promtail"
2024-09-26T12:12:55Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description In docker for hyperswitch-web we were facing that it's always pointing to beta.hyperswitch.io as `ENV_BACKEND_URL` was not getting passed. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Via checking HyperLoader.js file at 9050 port. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
8049993320e0c103d72dcae0497928ba622d7b59
juspay/hyperswitch
juspay__hyperswitch-6111
Bug: [FEATURE] Extend the BatchSampleDataInterface Trait for Disputes ### Feature Description The issue is sub part of issue: #5991 We currently have a feature for generating sample data, which includes batch insertion of payments and refunds. The feature inserts payments and refunds in batches using the BatchSampleDataInterface trait. We need to extend this functionality to support batch insertion and deletion of disputes as well. Steps to Implement Batch Support for Disputes **Extend the BatchSampleDataInterface Trait** We need to extend the existing BatchSampleDataInterface to include methods for batch insertion and deletion of disputes. These methods will be similar to the ones already implemented for PaymentIntent, PaymentAttempt, and Refund. **New Methods for Disputes:** `insert_disputes_batch_for_sample_data`: This method will handle batch insertion of disputes. `delete_disputes_for_sample_data`: This method will handle (batch) deletion of disputes. ### Possible Implementation Add Functions for Dispute Insert and Delete in `BatchSampleDataInterface` - File: `crates/router/src/db/user/sample_data.rs` - Extend the existing BatchSampleDataInterface to include the methods for inserting and deleting disputes. Complete these interface functions for Store, Mock Db and Kafka like we did for other functions. Write Batch Insert and Delete Queries for Disputes - File: `crates/diesel_model/src/query/user/sample_data.rs` - Define the queries (using diesel) to handle batch insertion and deletion of disputes, similar to how they are handled for payments and refunds. To test we can hard code some dummy dispute and try inserting using the function we made in core. We can check Db and see the logs for the query that is getting printed. Steps for Testing Dispute Batch Insertion and Deletion - To verify the batch insertion and deletion of disputes using the functions implemented in the BatchSampleDataInterface, we can perform a simple test by hardcoding some dummy dispute data. - Once we have the dummy dispute data, we can use the `generate_sample_data_for_user` method from the core function to insert the disputes into the database. This should invoke the appropriate batch insertion logic. (Or we can make an api to test the behaviour when the function is invoked) Curl to invoke this core function: ``` curl --location 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` The JWT token we can get from signup and then skipping the 2FA: ``` curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "JohnTest@test.com", "password": "Test@321" }' ``` This will give an intermediate token in response, we need to use this token to skip 2FA ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer Intermediatetoken' ``` This will give us JWT Token that we can use to hit the sample_data api Curl to delete sample data (The core function for sample dispute delete can be used to our advantage): ``` curl --location --request DELETE 'http://localhost:8080/user/sample_data' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ }' ``` - We can check Database Logs and Printed Queries whether the appropriate queries are getting printed - We can also manually check DB Note: Omit the Code for Testing part in the PR raised, have only Insert and Delete logic related to the DB, include the relevant logs and screenshots after test. The Sample disputes generation part, we will be handling in the separate PR. (#6117 ) ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs index b5400f570a3..27e674f7d7b 100644 --- a/crates/diesel_models/src/query/user/sample_data.rs +++ b/crates/diesel_models/src/query/user/sample_data.rs @@ -12,9 +12,11 @@ use crate::schema_v2::{ payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl, }; use crate::{ - errors, schema::refund::dsl as refund_dsl, user::sample_data::PaymentAttemptBatchNew, - PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, RefundNew, - StorageResult, + errors, + schema::{dispute::dsl as dispute_dsl, refund::dsl as refund_dsl}, + user::sample_data::PaymentAttemptBatchNew, + Dispute, DisputeNew, PaymentAttempt, PaymentIntent, PaymentIntentNew, PgPooledConn, Refund, + RefundNew, StorageResult, }; pub async fn insert_payment_intents( @@ -61,6 +63,21 @@ pub async fn insert_refunds( .attach_printable("Error while inserting refunds") } +pub async fn insert_disputes( + conn: &PgPooledConn, + batch: Vec<DisputeNew>, +) -> StorageResult<Vec<Dispute>> { + let query = diesel::insert_into(<Dispute>::table()).values(batch); + + logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); + + query + .get_results_async(conn) + .await + .change_context(errors::DatabaseError::Others) + .attach_printable("Error while inserting disputes") +} + #[cfg(feature = "v1")] pub async fn delete_payment_intents( conn: &PgPooledConn, @@ -165,3 +182,29 @@ pub async fn delete_refunds( _ => Ok(result), }) } + +pub async fn delete_disputes( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, +) -> StorageResult<Vec<Dispute>> { + let query = diesel::delete(<Dispute>::table()) + .filter(dispute_dsl::merchant_id.eq(merchant_id.to_owned())) + .filter(dispute_dsl::dispute_id.like("test_%")); + + logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string()); + + query + .get_results_async(conn) + .await + .change_context(errors::DatabaseError::Others) + .attach_printable("Error while deleting disputes") + .and_then(|result| match result.len() { + n if n > 0 => { + logger::debug!("{n} records deleted"); + Ok(result) + } + 0 => Err(error_stack::report!(errors::DatabaseError::NotFound) + .attach_printable("No records deleted")), + _ => Ok(result), + }) +} diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 9f237c226b6..6e9daeedc59 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3239,6 +3239,26 @@ impl BatchSampleDataInterface for KafkaStore { Ok(refunds_list) } + #[cfg(feature = "v1")] + async fn insert_disputes_batch_for_sample_data( + &self, + batch: Vec<diesel_models::DisputeNew>, + ) -> CustomResult<Vec<diesel_models::Dispute>, hyperswitch_domain_models::errors::StorageError> + { + let disputes_list = self + .diesel_store + .insert_disputes_batch_for_sample_data(batch) + .await?; + + for dispute in disputes_list.iter() { + let _ = self + .kafka_producer + .log_dispute(dispute, None, self.tenant_id.clone()) + .await; + } + Ok(disputes_list) + } + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, @@ -3306,6 +3326,27 @@ impl BatchSampleDataInterface for KafkaStore { Ok(refunds_list) } + + #[cfg(feature = "v1")] + async fn delete_disputes_for_sample_data( + &self, + merchant_id: &id_type::MerchantId, + ) -> CustomResult<Vec<diesel_models::Dispute>, hyperswitch_domain_models::errors::StorageError> + { + let disputes_list = self + .diesel_store + .delete_disputes_for_sample_data(merchant_id) + .await?; + + for dispute in disputes_list.iter() { + let _ = self + .kafka_producer + .log_dispute_delete(dispute, self.tenant_id.clone()) + .await; + } + + Ok(disputes_list) + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs index 709ff4a358a..3add7b744d0 100644 --- a/crates/router/src/db/user/sample_data.rs +++ b/crates/router/src/db/user/sample_data.rs @@ -1,5 +1,6 @@ use common_utils::types::keymanager::KeyManagerState; use diesel_models::{ + dispute::{Dispute, DisputeNew}, errors::DatabaseError, query::user::sample_data as sample_data_queries, refund::{Refund, RefundNew}, @@ -39,6 +40,12 @@ pub trait BatchSampleDataInterface { batch: Vec<RefundNew>, ) -> CustomResult<Vec<Refund>, StorageError>; + #[cfg(feature = "v1")] + async fn insert_disputes_batch_for_sample_data( + &self, + batch: Vec<DisputeNew>, + ) -> CustomResult<Vec<Dispute>, StorageError>; + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, @@ -58,6 +65,12 @@ pub trait BatchSampleDataInterface { &self, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Vec<Refund>, StorageError>; + + #[cfg(feature = "v1")] + async fn delete_disputes_for_sample_data( + &self, + merchant_id: &common_utils::id_type::MerchantId, + ) -> CustomResult<Vec<Dispute>, StorageError>; } #[async_trait::async_trait] @@ -127,6 +140,19 @@ impl BatchSampleDataInterface for Store { .map_err(diesel_error_to_data_error) } + #[cfg(feature = "v1")] + async fn insert_disputes_batch_for_sample_data( + &self, + batch: Vec<DisputeNew>, + ) -> CustomResult<Vec<Dispute>, StorageError> { + let conn = pg_connection_write(self) + .await + .change_context(StorageError::DatabaseConnectionError)?; + sample_data_queries::insert_disputes(&conn, batch) + .await + .map_err(diesel_error_to_data_error) + } + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, @@ -184,6 +210,19 @@ impl BatchSampleDataInterface for Store { .await .map_err(diesel_error_to_data_error) } + + #[cfg(feature = "v1")] + async fn delete_disputes_for_sample_data( + &self, + merchant_id: &common_utils::id_type::MerchantId, + ) -> CustomResult<Vec<Dispute>, StorageError> { + let conn = pg_connection_write(self) + .await + .change_context(StorageError::DatabaseConnectionError)?; + sample_data_queries::delete_disputes(&conn, merchant_id) + .await + .map_err(diesel_error_to_data_error) + } } #[async_trait::async_trait] @@ -214,6 +253,14 @@ impl BatchSampleDataInterface for storage_impl::MockDb { Err(StorageError::MockDbError)? } + #[cfg(feature = "v1")] + async fn insert_disputes_batch_for_sample_data( + &self, + _batch: Vec<DisputeNew>, + ) -> CustomResult<Vec<Dispute>, StorageError> { + Err(StorageError::MockDbError)? + } + #[cfg(feature = "v1")] async fn delete_payment_intents_for_sample_data( &self, @@ -239,6 +286,14 @@ impl BatchSampleDataInterface for storage_impl::MockDb { ) -> CustomResult<Vec<Refund>, StorageError> { Err(StorageError::MockDbError)? } + + #[cfg(feature = "v1")] + async fn delete_disputes_for_sample_data( + &self, + _merchant_id: &common_utils::id_type::MerchantId, + ) -> CustomResult<Vec<Dispute>, StorageError> { + Err(StorageError::MockDbError)? + } } // TODO: This error conversion is re-used from storage_impl and is not DRY when it should be diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 4fd692e1166..51ae9456ecc 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -582,6 +582,21 @@ impl KafkaProducer { .attach_printable_lazy(|| format!("Failed to add consolidated dispute event {dispute:?}")) } + pub async fn log_dispute_delete( + &self, + delete_old_dispute: &Dispute, + tenant_id: TenantID, + ) -> MQResult<()> { + self.log_event(&KafkaEvent::old( + &KafkaDispute::from_storage(delete_old_dispute), + tenant_id.clone(), + self.ckh_database_name.clone(), + )) + .attach_printable_lazy(|| { + format!("Failed to add negative dispute event {delete_old_dispute:?}") + }) + } + #[cfg(feature = "payouts")] pub async fn log_payout( &self,
2024-10-11T13:39:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> I've extended the interface for `BatchSampleDataInterface` to with `insert_disputes_batch_for_sample_data` and `delete_disputes_for_sample_data`, and added implementation to all structs implementing this trait. I've also modified `generate_sample_data` function in `utils/user/sample_data.rs` to generate dispute data, and `delete_sample_data_for_user` function in `core/user/sample_data.rs` to delete the generated dispute data. The overall result is the `/user/sample_data` endpoint now supports dispute data generation and deletion. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> resolve #6111 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual test is done, screenshots are provided in the comment section of this issue: https://github.com/juspay/hyperswitch/issues/6111 ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible (I did not find where to add unit tests for this issue)
53e82c3faef3ee629a38180e3882a2920332a9a8
juspay/hyperswitch
juspay__hyperswitch-6097
Bug: [REFACTOR]: [TSYS] Add amount conversion framework to Tsys ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://developers.tsys.com/api/product?key=Authentication+Platform) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/hyperswitch_connectors/src/connectors/tsys.rs b/crates/hyperswitch_connectors/src/connectors/tsys.rs index ec53a99316f..25b47981def 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys.rs @@ -1,12 +1,11 @@ pub mod transformers; -use std::fmt::Debug; - use common_enums::enums; 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::{ @@ -41,10 +40,18 @@ use hyperswitch_interfaces::{ use transformers as tsys; use crate::{constants::headers, types::ResponseRouterData, utils}; +#[derive(Clone)] +pub struct Tsys { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} -#[derive(Debug, Clone)] -pub struct Tsys; - +impl Tsys { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} impl api::Payment for Tsys {} impl api::PaymentSession for Tsys {} impl api::ConnectorAccessToken for Tsys {} @@ -156,7 +163,14 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = tsys::TsysPaymentsRequest::try_from(req)?; + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + let connector_router_data = tsys::TsysRouterData::from((amount, req)); + let connector_req: transformers::TsysPaymentsRequest = + tsys::TsysPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -316,7 +330,13 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = tsys::TsysPaymentsCaptureRequest::try_from(req)?; + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + let connector_router_data = tsys::TsysRouterData::from((amount, req)); + let connector_req = tsys::TsysPaymentsCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -473,7 +493,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tsys { req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = tsys::TsysRefundRequest::try_from(req)?; + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + let connector_router_data = tsys::TsysRouterData::from((amount, req)); + + let connector_req = tsys::TsysRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index e97cf228729..0e47edf294c 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -1,4 +1,5 @@ use common_enums::enums; +use common_utils::types::StringMinorUnit; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, @@ -7,13 +8,26 @@ use hyperswitch_domain_models::{ router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - self, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, - RefundSyncRouterData, RefundsRouterData, + self, PaymentsCancelRouterData, PaymentsSyncRouterData, RefundSyncRouterData, + RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; +pub struct TsysRouterData<T> { + pub amount: StringMinorUnit, + pub router_data: T, +} + +impl<T> From<(StringMinorUnit, T)> for TsysRouterData<T> { + fn from((amount, router_data): (StringMinorUnit, T)) -> Self { + Self { + amount, + router_data, + } + } +} use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, @@ -33,7 +47,7 @@ pub struct TsysPaymentAuthSaleRequest { device_id: Secret<String>, transaction_key: Secret<String>, card_data_source: String, - transaction_amount: String, + transaction_amount: StringMinorUnit, currency_code: enums::Currency, card_number: cards::CardNumber, expiration_date: Secret<String>, @@ -46,9 +60,12 @@ pub struct TsysPaymentAuthSaleRequest { order_number: String, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { +impl TryFrom<&TsysRouterData<&types::PaymentsAuthorizeRouterData>> for TsysPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + fn try_from( + item_data: &TsysRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data.clone(); match item.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => { let connector_auth: TsysAuthType = @@ -57,7 +74,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for TsysPaymentsRequest { device_id: connector_auth.device_id, transaction_key: connector_auth.transaction_key, card_data_source: "INTERNET".to_string(), - transaction_amount: item.request.amount.to_string(), + transaction_amount: item_data.amount.clone(), currency_code: item.request.currency, card_number: ccard.card_number.clone(), expiration_date: ccard @@ -430,7 +447,7 @@ pub struct TsysCaptureRequest { #[serde(rename = "deviceID")] device_id: Secret<String>, transaction_key: Secret<String>, - transaction_amount: String, + transaction_amount: StringMinorUnit, #[serde(rename = "transactionID")] transaction_id: String, #[serde(rename = "developerID")] @@ -444,16 +461,19 @@ pub struct TsysPaymentsCaptureRequest { capture: TsysCaptureRequest, } -impl TryFrom<&PaymentsCaptureRouterData> for TsysPaymentsCaptureRequest { +impl TryFrom<&TsysRouterData<&types::PaymentsCaptureRouterData>> for TsysPaymentsCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &PaymentsCaptureRouterData) -> Result<Self, Self::Error> { + fn try_from( + item_data: &TsysRouterData<&types::PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { + let item = item_data.router_data.clone(); let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?; let capture = TsysCaptureRequest { device_id: connector_auth.device_id, transaction_key: connector_auth.transaction_key, transaction_id: item.request.connector_transaction_id.clone(), developer_id: connector_auth.developer_id, - transaction_amount: item.request.amount_to_capture.to_string(), + transaction_amount: item_data.amount.clone(), }; Ok(Self { capture }) } @@ -466,7 +486,7 @@ pub struct TsysReturnRequest { #[serde(rename = "deviceID")] device_id: Secret<String>, transaction_key: Secret<String>, - transaction_amount: String, + transaction_amount: StringMinorUnit, #[serde(rename = "transactionID")] transaction_id: String, } @@ -478,14 +498,15 @@ pub struct TsysRefundRequest { return_request: TsysReturnRequest, } -impl<F> TryFrom<&RefundsRouterData<F>> for TsysRefundRequest { +impl<F> TryFrom<&TsysRouterData<&RefundsRouterData<F>>> for TsysRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item_data: &TsysRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let item = item_data.router_data; let connector_auth: TsysAuthType = TsysAuthType::try_from(&item.connector_auth_type)?; let return_request = TsysReturnRequest { device_id: connector_auth.device_id, transaction_key: connector_auth.transaction_key, - transaction_amount: item.request.refund_amount.to_string(), + transaction_amount: item_data.amount.clone(), transaction_id: item.request.connector_transaction_id.clone(), }; Ok(Self { return_request }) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 5300e86afdb..8c953939831 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -508,7 +508,7 @@ impl ConnectorData { enums::Connector::Trustpay => { Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new()))) } - enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(&connector::Tsys))), + enums::Connector::Tsys => Ok(ConnectorEnum::Old(Box::new(connector::Tsys::new()))), enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), enums::Connector::Wellsfargo => { diff --git a/crates/router/tests/connectors/tsys.rs b/crates/router/tests/connectors/tsys.rs index 4cda0b479b2..6a4843ac2cd 100644 --- a/crates/router/tests/connectors/tsys.rs +++ b/crates/router/tests/connectors/tsys.rs @@ -16,7 +16,7 @@ impl utils::Connector for TsysTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Tsys; utils::construct_connector_data_old( - Box::new(&Tsys), + Box::new(Tsys::new()), types::Connector::Tsys, types::api::GetToken::Connector, None,
2024-10-09T22:18:50Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description added `StringMajorUnit` for amount conversion ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #6097 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3d1a3cdc8f942a3dca2e6a200bf9200366bd62f1
juspay/hyperswitch
juspay__hyperswitch-6094
Bug: [FIX] keymanager config if disabled
diff --git a/config/development.toml b/config/development.toml index 6e56d5bb14d..a607dd94a16 100644 --- a/config/development.toml +++ b/config/development.toml @@ -13,7 +13,7 @@ use_xray_generator = false bg_metrics_collection_interval_in_secs = 15 [key_manager] -url = "http://localhost:5000" +enabled = false # TODO: Update database credentials before running application [master_database] diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs index abcb7aa87f7..078f1f3fcd8 100644 --- a/crates/common_utils/src/types/keymanager.rs +++ b/crates/common_utils/src/types/keymanager.rs @@ -25,7 +25,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct KeyManagerState { - pub enabled: Option<bool>, + pub enabled: bool, pub url: String, pub client_idle_timeout: Option<u64>, #[cfg(feature = "km_forward_x_request_id")] diff --git a/crates/hyperswitch_domain_models/src/type_encryption.rs b/crates/hyperswitch_domain_models/src/type_encryption.rs index 0ff37b0bc29..983528dee98 100644 --- a/crates/hyperswitch_domain_models/src/type_encryption.rs +++ b/crates/hyperswitch_domain_models/src/type_encryption.rs @@ -101,7 +101,7 @@ mod encrypt { fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool { #[cfg(feature = "encryption_service")] { - _state.enabled.unwrap_or_default() + _state.enabled } #[cfg(not(feature = "encryption_service"))] { diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 5719e111759..86bcb687b11 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -12461,16 +12461,3 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> { ), ]) } - -impl Default for super::settings::KeyManagerConfig { - fn default() -> Self { - Self { - enabled: None, - url: String::from("localhost:5000"), - #[cfg(feature = "keymanager_mtls")] - ca: String::default().into(), - #[cfg(feature = "keymanager_mtls")] - cert: String::default().into(), - } - } -} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 8c893b88319..5a204f8508c 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -232,14 +232,22 @@ impl SecretsHandler for settings::KeyManagerConfig { let keyconfig = value.get_inner(); #[cfg(feature = "keymanager_mtls")] - let ca = _secret_management_client - .get_secret(keyconfig.ca.clone()) - .await?; + let ca = if keyconfig.enabled { + _secret_management_client + .get_secret(keyconfig.ca.clone()) + .await? + } else { + keyconfig.ca.clone() + }; #[cfg(feature = "keymanager_mtls")] - let cert = _secret_management_client - .get_secret(keyconfig.cert.clone()) - .await?; + let cert = if keyconfig.enabled { + _secret_management_client + .get_secret(keyconfig.cert.clone()) + .await? + } else { + keyconfig.ca.clone() + }; Ok(value.transition_state(|keyconfig| Self { #[cfg(feature = "keymanager_mtls")] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 675b8c44e2a..de45252dbf3 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -213,9 +213,10 @@ pub struct KvConfig { pub soft_kill: Option<bool>, } -#[derive(Debug, Deserialize, Clone)] +#[derive(Debug, Deserialize, Clone, Default)] +#[serde(default)] pub struct KeyManagerConfig { - pub enabled: Option<bool>, + pub enabled: bool, pub url: String, #[cfg(feature = "keymanager_mtls")] pub cert: Secret<String>, @@ -859,6 +860,8 @@ impl Settings<SecuredSecret> { .map(|x| x.get_inner().validate()) .transpose()?; + self.key_manager.get_inner().validate()?; + Ok(()) } } diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 67db7b1266c..62b5c08a198 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -222,3 +222,25 @@ impl super::settings::NetworkTokenizationService { }) } } + +impl super::settings::KeyManagerConfig { + pub fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::fp_utils::when; + + #[cfg(feature = "keymanager_mtls")] + when( + self.enabled && (self.ca.is_default_or_empty() || self.cert.is_default_or_empty()), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "Invalid CA or Certificate for Keymanager.".into(), + )) + }, + )?; + + when(self.enabled && self.url.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "Invalid URL for Keymanager".into(), + )) + }) + } +}
2024-09-26T07:16:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> This fixes unnecessary failure when url and cert for the keymanager is not provided in the config but keymanager is disabled. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> If the keymanager is disabled in the config, there's no reason to provide `url` and `cert` for keymanager since they won't be used. This PR adds a check which checks if keymanager is enabled and only fail for these configs missing if keymanager is enabled ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This cannot be tested on any environment ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code
962b9978d651e3cc9185b2f6f849c7f255868077
juspay/hyperswitch
juspay__hyperswitch-6092
Bug: [REFACTOR]: [MOLLIE] Add amount conversion framework to Mollie ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.mollie.com/reference/create-payment) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/hyperswitch_connectors/src/connectors/mollie.rs b/crates/hyperswitch_connectors/src/connectors/mollie.rs index 5066fb422fa..010ae90c56f 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie.rs @@ -1,12 +1,11 @@ pub mod transformers; -use std::fmt::Debug; - use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -43,10 +42,20 @@ use masking::{Mask, PeekInterface}; use transformers as mollie; // use self::mollie::{webhook_headers, VoltWebhookBodyEventType}; -use crate::{constants::headers, types::ResponseRouterData}; +use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount}; + +#[derive(Clone)] +pub struct Mollie { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} -#[derive(Debug, Clone)] -pub struct Mollie; +impl Mollie { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } +} impl api::Payment for Mollie {} impl api::PaymentSession for Mollie {} @@ -254,12 +263,13 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = mollie::MollieRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + + let router_obj = mollie::MollieRouterData::from((amount, req)); let connector_req = mollie::MolliePaymentsRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -448,12 +458,13 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Mollie req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = mollie::MollieRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + + let router_obj = mollie::MollieRouterData::from((amount, req)); let connector_req = mollie::MollieRefundRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs index a12434a460a..dc5f64bee18 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs @@ -1,6 +1,6 @@ use cards::CardNumber; use common_enums::enums; -use common_utils::{pii::Email, request::Method}; +use common_utils::{pii::Email, request::Method, types::StringMajorUnit}; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, BankRedirectData, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, PaymentMethodToken, RouterData}, @@ -8,7 +8,7 @@ use hyperswitch_domain_models::{ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; -use hyperswitch_interfaces::{api, errors}; +use hyperswitch_interfaces::errors; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use url::Url; @@ -17,7 +17,7 @@ use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, unimplemented_payment_method, utils::{ - self, AddressDetailsData, BrowserInformationData, CardData as CardDataUtil, + AddressDetailsData, BrowserInformationData, CardData as CardDataUtil, PaymentMethodTokenizationRequestData, PaymentsAuthorizeRequestData, RouterData as _, }, }; @@ -26,26 +26,16 @@ type Error = error_stack::Report<errors::ConnectorError>; #[derive(Debug, Serialize)] pub struct MollieRouterData<T> { - pub amount: String, + pub amount: StringMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for MollieRouterData<T> { - type Error = error_stack::Report<errors::ConnectorError>; - - fn try_from( - (currency_unit, currency, amount, router_data): ( - &api::CurrencyUnit, - enums::Currency, - i64, - T, - ), - ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; - Ok(Self { +impl<T> From<(StringMajorUnit, T)> for MollieRouterData<T> { + fn from((amount, router_data): (StringMajorUnit, T)) -> Self { + Self { amount, router_data, - }) + } } } @@ -68,7 +58,7 @@ pub struct MolliePaymentsRequest { #[derive(Default, Debug, Serialize, Deserialize)] pub struct Amount { currency: enums::Currency, - value: String, + value: StringMajorUnit, } #[derive(Debug, Serialize)] diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e115558995d..ba2d6999f2b 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -434,7 +434,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new()))) } enums::Connector::Klarna => Ok(ConnectorEnum::Old(Box::new(&connector::Klarna))), - enums::Connector::Mollie => Ok(ConnectorEnum::Old(Box::new(&connector::Mollie))), + enums::Connector::Mollie => { + Ok(ConnectorEnum::Old(Box::new(connector::Mollie::new()))) + } enums::Connector::Nexixpay => { Ok(ConnectorEnum::Old(Box::new(connector::Nexixpay::new()))) } diff --git a/crates/router/tests/connectors/mollie.rs b/crates/router/tests/connectors/mollie.rs index 7017363cad0..d59bc78226d 100644 --- a/crates/router/tests/connectors/mollie.rs +++ b/crates/router/tests/connectors/mollie.rs @@ -13,7 +13,7 @@ impl utils::Connector for MollieTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Mollie; utils::construct_connector_data_old( - Box::new(&Mollie), + Box::new(Mollie::new()), types::Connector::Mollie, types::api::GetToken::Connector, None,
2024-10-09T18:52:03Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> This PR do amount conversion changes for Mollie Connector and it accepts the amount in StringMajorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes https://github.com/juspay/hyperswitch/issues/6092 ## Test Cases 1. Create Merchant Account ``` curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "merchant_1729161609", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "primary_business_details": [ { "country": "US", "business": "default" }, { "country": "GB", "business": "payouts" } ], "merchant_details": { "primary_contact_person": "John Test", "primary_email": "JohnTest@test.com", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "JohnTest2@test.com", "secondary_phone": "cillum do dolor id", "website": "www.example.com", "about_business": "Online Retail with a wide selection of organic products for North America", "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "return_url": "https://duck.com", "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "sub_merchants_enabled": false, "metadata": { "city": "NY", "unit": "245" } }' ``` 2. Create API key ``` curl --location 'http://localhost:8080/api_keys/merchant_1729160602' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:__' \ --data '{ "name": "API Key 1", "description": null, "expiration": "2045-09-23T01:02:03.000Z" }' ``` 3. Create MCA for Mollie connector ``` curl --location 'http://localhost:8080/account/merchant_1729160602/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "mollie", "connector_account_details":{ "auth_type":"HeaderKey", "api_key":"_____________" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "afterpay_clearpay", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method" : "bank_transfer", "payment_method_types":[ { "payment_method_type":"sepa", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "przelewy24", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "bancontact_card", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "eps", "payment_experience": "redirect_to_url", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "city": "NY", "unit": "245" }, "business_country": "US", "business_label": "default" }' ``` 4. Create a Payment of Przelewy24 via Mollie ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ____' \ --data-raw '{ "amount": 6540, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "bank_redirect", "payment_method_type": "przelewy24", "payment_method_data": { "bank_redirect": { "przelewy24": { } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "BE", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "profile_id": "pro_xA9ALBzKrljCM1SCCV26" }' ``` Response ``` { "payment_id": "pay_bEvdBi9AeDtAMvrSZi2J", "merchant_id": "merchant_1729160602", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "amount_capturable": 6540, "amount_received": null, "connector": "mollie", "client_secret": "pay_bEvdBi9AeDtAMvrSZi2J_secret_iv9QnUtPYFZbjeV0P7iW", "created": "2024-10-17T10:25:07.604Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_redirect", "payment_method_data": { "bank_redirect": { "type": "BankRedirectResponse", "bank_name": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "BE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "BE", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_bEvdBi9AeDtAMvrSZi2J/merchant_1729160602/pay_bEvdBi9AeDtAMvrSZi2J_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "przelewy24", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1729160707, "expires": 1729164307, "secret": "epk_7d82e37938e54484ab6baf8d22109af3" }, "manual_retry_allowed": null, "connector_transaction_id": "tr_fZzrHzunjU", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "tr_fZzrHzunjU", "payment_link": null, "profile_id": "pro_xA9ALBzKrljCM1SCCV26", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_WVDHef0DfuinnrZPKggd", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-17T10:40:07.604Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-17T10:25:09.587Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
edd099886da9c46800a646fe809796a08eb78c99
juspay/hyperswitch
juspay__hyperswitch-6086
Bug: feat(analytics): add card network feature Add a filter in payment analytics for the card network column
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index e0235c67bed..149c77212a0 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -280,7 +280,10 @@ impl HealthCheck for OpenSearchClient { if health.status != OpenSearchHealthStatus::Red { Ok(()) } else { - Err(QueryExecutionError::DatabaseError.into()) + Err::<(), error_stack::Report<QueryExecutionError>>( + QueryExecutionError::DatabaseError.into(), + ) + .attach_printable_lazy(|| format!("Opensearch cluster health is red: {health:?}")) } } } diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index dca42b6802e..f41e1719450 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -296,6 +296,7 @@ pub async fn get_filters( PaymentDimensions::ClientSource => fil.client_source, PaymentDimensions::ClientVersion => fil.client_version, PaymentDimensions::ProfileId => fil.profile_id, + PaymentDimensions::CardNetwork => fil.card_network, }) .collect::<Vec<String>>(); res.query_data.push(FilterValue { diff --git a/crates/analytics/src/payments/filters.rs b/crates/analytics/src/payments/filters.rs index 8e62c77a81f..094fd574169 100644 --- a/crates/analytics/src/payments/filters.rs +++ b/crates/analytics/src/payments/filters.rs @@ -59,4 +59,5 @@ pub struct PaymentFilterRow { pub client_source: Option<String>, pub client_version: Option<String>, pub profile_id: Option<String>, + pub card_network: Option<String>, } diff --git a/crates/analytics/src/payments/types.rs b/crates/analytics/src/payments/types.rs index f5139a9ea2b..b7984a19ea3 100644 --- a/crates/analytics/src/payments/types.rs +++ b/crates/analytics/src/payments/types.rs @@ -65,6 +65,25 @@ where .add_filter_in_range_clause(PaymentDimensions::ProfileId, &self.profile_id) .attach_printable("Error adding profile id filter")?; } + if !self.card_network.is_empty() { + let card_networks: Vec<String> = self + .card_network + .iter() + .flat_map(|cn| { + [ + format!("\"{cn}\""), + cn.to_string(), + format!("\"{cn}\"").to_uppercase(), + ] + }) + .collect(); + builder + .add_filter_in_range_clause( + PaymentDimensions::CardNetwork, + card_networks.as_slice(), + ) + .attach_printable("Error adding card network filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 76a5f5a0918..e9395439209 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -489,6 +489,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { currency, status, @@ -499,6 +503,7 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { client_source, client_version, profile_id, + card_network, }) } } diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index 40ff4bf2607..c474d47ee63 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -7,7 +7,8 @@ use common_utils::id_type; use super::{NameDescription, TimeRange}; use crate::enums::{ - AttemptStatus, AuthenticationType, Connector, Currency, PaymentMethod, PaymentMethodType, + AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod, + PaymentMethodType, }; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] @@ -29,6 +30,8 @@ pub struct PaymentFilters { #[serde(default)] pub client_version: Vec<String>, #[serde(default)] + pub card_network: Vec<CardNetwork>, + #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, } @@ -64,6 +67,7 @@ pub enum PaymentDimensions { ClientSource, ClientVersion, ProfileId, + CardNetwork, } #[derive(
2024-09-25T20:51:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add card network analytics filter in payment analytics ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> <img width="431" alt="image" src="https://github.com/user-attachments/assets/d209f786-a967-4245-a780-e9539a5c7469"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
9a605afe372a0602127090da59e35ac9ca7396e1
juspay/hyperswitch
juspay__hyperswitch-6112
Bug: refactor(users): Deprecate non-profile level user APIs - Currently there are few APIs in Backend which are not at profile level. For example - Switch merchant. - We have to remove those APIs. - If there is any v2 counter part for those APIs, v1 APIs should be modified so that they will work the same way as v1.
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 9b100a7321e..bb61a025180 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -12,25 +12,16 @@ use crate::user::{ }, AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, - CreateUserAuthenticationMethodRequest, DashboardEntryResponse, ForgotPasswordRequest, - GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, - GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, GetUserRoleDetailsResponseV2, - InviteUserRequest, ListUsersResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, - RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, - SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, - TokenResponse, TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, - UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, - VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, + CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest, + GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, + GetUserRoleDetailsResponseV2, InviteUserRequest, ReInviteUserRequest, RecoveryCodes, + ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, + SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest, + SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse, + UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, + UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; -impl ApiEventMetric for DashboardEntryResponse { - fn get_api_event_type(&self) -> Option<ApiEventsType> { - Some(ApiEventsType::User { - user_id: self.user_id.clone(), - }) - } -} - #[cfg(feature = "recon")] impl ApiEventMetric for VerifyTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { @@ -55,7 +46,6 @@ common_utils::impl_api_event_type!( SwitchProfileRequest, CreateInternalUserRequest, UserMerchantCreate, - ListUsersResponse, AuthorizeResponse, ConnectAccountRequest, ForgotPasswordRequest, @@ -69,7 +59,6 @@ common_utils::impl_api_event_type!( UpdateUserAccountDetailsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, - GetUserRoleDetailsResponse, GetUserRoleDetailsResponseV2, TokenResponse, TwoFactorAuthStatusResponse, diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index eb09abd471c..a2c76ecc394 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -3,26 +3,21 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest, - ListRolesResponse, RoleInfoResponseNew, RoleInfoWithGroupsResponse, - RoleInfoWithPermissionsResponse, UpdateRoleRequest, + RoleInfoResponseNew, RoleInfoWithGroupsResponse, UpdateRoleRequest, }, - AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, - ListUsersInEntityRequest, MerchantSelectRequest, UpdateUserRoleRequest, + AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest, + UpdateUserRoleRequest, }; common_utils::impl_api_event_type!( Miscellaneous, ( - RoleInfoWithPermissionsResponse, GetRoleRequest, AuthorizationInfoResponse, UpdateUserRoleRequest, - MerchantSelectRequest, - AcceptInvitationRequest, DeleteUserRoleRequest, CreateRoleRequest, UpdateRoleRequest, - ListRolesResponse, ListRolesAtEntityLevelRequest, RoleInfoResponseNew, RoleInfoWithGroupsResponse, diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 7b22387b3c3..d66f9f3bc03 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -1,6 +1,6 @@ use std::fmt::Debug; -use common_enums::{EntityType, PermissionGroup, RoleScope, TokenPurpose}; +use common_enums::{EntityType, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; @@ -25,19 +25,6 @@ pub struct SignUpRequest { pub password: Secret<String>, } -#[derive(serde::Serialize, Debug, Clone)] -pub struct DashboardEntryResponse { - pub token: Secret<String>, - pub merchant_id: id_type::MerchantId, - pub name: Secret<String>, - pub email: pii::Email, - pub verification_days_left: Option<i64>, - pub user_role: String, - //this field is added for audit/debug reasons - #[serde(skip_serializing)] - pub user_id: String, -} - pub type SignInRequest = SignUpRequest; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] @@ -131,20 +118,6 @@ pub struct UserMerchantCreate { pub company_name: String, } -#[derive(Debug, serde::Serialize)] -pub struct ListUsersResponse(pub Vec<UserDetails>); - -#[derive(Debug, serde::Serialize)] -pub struct UserDetails { - pub email: pii::Email, - pub name: Secret<String>, - pub role_id: String, - pub role_name: String, - pub status: UserStatus, - #[serde(with = "common_utils::custom_serde::iso8601")] - pub last_modified_at: time::PrimitiveDateTime, -} - #[derive(serde::Serialize, Debug, Clone)] pub struct GetUserDetailsResponse { pub merchant_id: id_type::MerchantId, @@ -167,19 +140,6 @@ pub struct GetUserRoleDetailsRequest { pub email: pii::Email, } -#[derive(Debug, serde::Serialize)] -pub struct GetUserRoleDetailsResponse { - pub email: pii::Email, - pub name: Secret<String>, - pub role_id: String, - pub role_name: String, - pub status: UserStatus, - #[serde(with = "common_utils::custom_serde::iso8601")] - pub last_modified_at: time::PrimitiveDateTime, - pub groups: Vec<PermissionGroup>, - pub role_scope: RoleScope, -} - #[derive(Debug, serde::Serialize)] pub struct GetUserRoleDetailsResponseV2 { pub role_id: String, @@ -207,16 +167,6 @@ pub struct SendVerifyEmailRequest { pub email: pii::Email, } -#[derive(Debug, serde::Serialize)] -pub struct UserMerchantAccount { - pub merchant_id: id_type::MerchantId, - pub merchant_name: OptionalEncryptableName, - pub is_active: bool, - pub role_id: String, - pub role_name: String, - pub org_id: id_type::OrganizationId, -} - #[cfg(feature = "recon")] #[derive(serde::Serialize, Debug)] pub struct VerifyTokenResponse { diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index f2743d6a311..ab32651e729 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -54,42 +54,17 @@ pub enum ParentGroup { Recon, } -#[derive(Debug, serde::Serialize)] -pub enum PermissionModule { - Payments, - Refunds, - MerchantAccount, - Connectors, - Routing, - Analytics, - Mandates, - Customer, - Disputes, - ThreeDsDecisionManager, - SurchargeDecisionManager, - AccountCreate, - Payouts, - Recon, -} - #[derive(Debug, serde::Serialize)] pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>); #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum AuthorizationInfo { - Module(ModuleInfo), Group(GroupInfo), GroupWithTag(ParentInfo), } -#[derive(Debug, serde::Serialize)] -pub struct ModuleInfo { - pub module: PermissionModule, - pub description: &'static str, - pub permissions: Vec<PermissionInfo>, -} - +// TODO: To be deprecated #[derive(Debug, serde::Serialize)] pub struct GroupInfo { pub group: PermissionGroup, @@ -122,16 +97,6 @@ pub enum UserStatus { InvitationSent, } -#[derive(Debug, serde::Deserialize, serde::Serialize)] -pub struct MerchantSelectRequest { - pub merchant_ids: Vec<common_utils::id_type::MerchantId>, -} - -#[derive(Debug, serde::Deserialize, serde::Serialize)] -pub struct AcceptInvitationRequest { - pub merchant_ids: Vec<common_utils::id_type::MerchantId>, -} - #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct DeleteUserRoleRequest { pub email: pii::Email, diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index be467421e65..885ec455e4c 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -1,8 +1,6 @@ pub use common_enums::PermissionGroup; use common_enums::{EntityType, RoleScope}; -use super::Permission; - #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateRoleRequest { pub role_name: String, @@ -16,17 +14,6 @@ pub struct UpdateRoleRequest { pub role_name: Option<String>, } -#[derive(Debug, serde::Serialize)] -pub struct ListRolesResponse(pub Vec<RoleInfoWithGroupsResponse>); - -#[derive(Debug, serde::Serialize)] -pub struct RoleInfoWithPermissionsResponse { - pub role_id: String, - pub permissions: Vec<Permission>, - pub role_name: String, - pub role_scope: RoleScope, -} - #[derive(Debug, serde::Serialize)] pub struct RoleInfoWithGroupsResponse { pub role_id: String, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index f36ecc18116..9f865c1071e 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1135,121 +1135,6 @@ pub async fn create_internal_user( Ok(ApplicationResponse::StatusOk) } -pub async fn switch_merchant_id( - state: SessionState, - request: user_api::SwitchMerchantRequest, - user_from_token: auth::UserFromToken, -) -> UserResponse<user_api::DashboardEntryResponse> { - if user_from_token.merchant_id == request.merchant_id { - return Err(UserErrors::InvalidRoleOperationWithMessage( - "User switching to same merchant_id".to_string(), - ) - .into()); - } - - let user = user_from_token.get_user_from_db(&state).await?; - let key_manager_state = &(&state).into(); - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( - &state, - &user_from_token.role_id, - &user_from_token.merchant_id, - &user_from_token.org_id, - ) - .await - .to_not_found_response(UserErrors::InternalServerError)?; - - let (token, role_id) = if role_info.is_internal() { - let key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &request.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(UserErrors::MerchantIdNotFound) - } else { - e.change_context(UserErrors::InternalServerError) - } - })?; - - let org_id = state - .store - .find_merchant_account_by_merchant_id( - key_manager_state, - &request.merchant_id, - &key_store, - ) - .await - .map_err(|e| { - if e.current_context().is_db_not_found() { - e.change_context(UserErrors::MerchantIdNotFound) - } else { - e.change_context(UserErrors::InternalServerError) - } - })? - .organization_id; - - let token = utils::user::generate_jwt_auth_token_with_attributes_without_profile( - &state, - user_from_token.user_id, - request.merchant_id.clone(), - org_id.clone(), - user_from_token.role_id.clone(), - ) - .await?; - - (token, user_from_token.role_id) - } else { - let user_roles = state - .store - .list_user_roles_by_user_id_and_version(&user_from_token.user_id, UserRoleVersion::V1) - .await - .change_context(UserErrors::InternalServerError)?; - - let active_user_roles = user_roles - .into_iter() - .filter(|role| role.status == UserStatus::Active) - .collect::<Vec<_>>(); - - let user_role = active_user_roles - .iter() - .find_map(|role| { - let Some(ref merchant_id) = role.merchant_id else { - return Some(Err(report!(UserErrors::InternalServerError))); - }; - if merchant_id == &request.merchant_id { - Some(Ok(role)) - } else { - None - } - }) - .transpose()? - .ok_or(report!(UserErrors::InvalidRoleOperation)) - .attach_printable("User doesn't have access to switch")?; - - let token = - utils::user::generate_jwt_auth_token_without_profile(&state, &user, user_role).await?; - utils::user_role::set_role_permissions_in_cache_by_user_role(&state, user_role).await; - - (token, user_role.role_id.clone()) - }; - - let response = user_api::DashboardEntryResponse { - token: token.clone(), - name: user.get_name(), - email: user.get_email(), - user_id: user.get_user_id().to_string(), - verification_days_left: None, - user_role: role_id, - merchant_id: request.merchant_id, - }; - - auth::cookies::set_cookie_response(response, token) -} - pub async fn create_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, @@ -1282,142 +1167,6 @@ pub async fn create_merchant_account( Ok(ApplicationResponse::StatusOk) } -pub async fn list_merchants_for_user( - state: SessionState, - user_from_token: auth::UserIdFromAuth, -) -> UserResponse<Vec<user_api::UserMerchantAccount>> { - let user_roles = state - .store - .list_user_roles_by_user_id_and_version( - user_from_token.user_id.as_str(), - UserRoleVersion::V1, - ) - .await - .change_context(UserErrors::InternalServerError)?; - - let merchant_accounts_map = state - .store - .list_multiple_merchant_accounts( - &(&state).into(), - user_roles - .iter() - .map(|role| { - role.merchant_id - .clone() - .ok_or(UserErrors::InternalServerError) - }) - .collect::<Result<Vec<_>, _>>()?, - ) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account)) - .collect::<HashMap<_, _>>(); - - let roles_map = futures::future::try_join_all(user_roles.iter().map(|user_role| async { - let Some(merchant_id) = &user_role.merchant_id else { - return Err(report!(UserErrors::InternalServerError)) - .attach_printable("merchant_id not found for user_role"); - }; - let Some(org_id) = &user_role.org_id else { - return Err(report!(UserErrors::InternalServerError) - .attach_printable("org_id not found in user_role")); - }; - roles::RoleInfo::from_role_id_in_merchant_scope( - &state, - &user_role.role_id, - merchant_id, - org_id, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Unable to find role info for user role") - })) - .await? - .into_iter() - .map(|role_info| (role_info.get_role_id().to_owned(), role_info)) - .collect::<HashMap<_, _>>(); - - Ok(ApplicationResponse::Json( - user_roles - .into_iter() - .map(|user_role| { - let Some(merchant_id) = &user_role.merchant_id else { - return Err(report!(UserErrors::InternalServerError)) - .attach_printable("merchant_id not found for user_role"); - }; - let Some(org_id) = &user_role.org_id else { - return Err(report!(UserErrors::InternalServerError) - .attach_printable("org_id not found in user_role")); - }; - let merchant_account = merchant_accounts_map - .get(merchant_id) - .ok_or(UserErrors::InternalServerError) - .attach_printable("Merchant account for user role doesn't exist")?; - - let role_info = roles_map - .get(&user_role.role_id) - .ok_or(UserErrors::InternalServerError) - .attach_printable("Role info for user role doesn't exist")?; - - Ok(user_api::UserMerchantAccount { - merchant_id: merchant_id.to_owned(), - merchant_name: merchant_account.merchant_name.clone(), - is_active: user_role.status == UserStatus::Active, - role_id: user_role.role_id, - role_name: role_info.get_role_name().to_string(), - org_id: org_id.to_owned(), - }) - }) - .collect::<Result<Vec<_>, _>>()?, - )) -} - -pub async fn get_user_details_in_merchant_account( - state: SessionState, - user_from_token: auth::UserFromToken, - request: user_api::GetUserRoleDetailsRequest, - _req_state: ReqState, -) -> UserResponse<user_api::GetUserRoleDetailsResponse> { - let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?) - .await - .to_not_found_response(UserErrors::InvalidRoleOperation)?; - - let required_user_role = state - .store - .find_user_role_by_user_id_merchant_id( - required_user.get_user_id(), - &user_from_token.merchant_id, - UserRoleVersion::V1, - ) - .await - .to_not_found_response(UserErrors::InvalidRoleOperation) - .attach_printable("User not found in the merchant account")?; - - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( - &state, - &required_user_role.role_id, - &user_from_token.merchant_id, - &user_from_token.org_id, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("User role exists but the corresponding role doesn't")?; - - Ok(ApplicationResponse::Json( - user_api::GetUserRoleDetailsResponse { - email: required_user.get_email(), - name: required_user.get_name(), - role_id: role_info.get_role_id().to_string(), - role_name: role_info.get_role_name().to_string(), - status: required_user_role.status.foreign_into(), - last_modified_at: required_user_role.last_modified, - groups: role_info.get_permission_groups().to_vec(), - role_scope: role_info.get_scope(), - }, - )) -} - pub async fn list_user_roles_details( state: SessionState, user_from_token: auth::UserFromToken, @@ -1670,80 +1419,6 @@ pub async fn list_user_roles_details( Ok(ApplicationResponse::Json(role_details_list)) } -pub async fn list_users_for_merchant_account( - state: SessionState, - user_from_token: auth::UserFromToken, -) -> UserResponse<user_api::ListUsersResponse> { - let user_roles: HashMap<String, _> = state - .store - .list_user_roles_by_merchant_id(&user_from_token.merchant_id, UserRoleVersion::V1) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("No user roles for given merchant_id")? - .into_iter() - .map(|role| (role.user_id.clone(), role)) - .collect(); - - let user_ids = user_roles.keys().cloned().collect::<Vec<_>>(); - - let users = state - .global_store - .find_users_by_user_ids(user_ids) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("No users for given merchant_id")?; - - let users_and_user_roles: Vec<_> = users - .into_iter() - .filter_map(|user| { - user_roles - .get(&user.user_id) - .map(|role| (user.clone(), role.clone())) - }) - .collect(); - - let users_user_roles_and_roles = - futures::future::try_join_all(users_and_user_roles.into_iter().map( - |(user, user_role)| async { - roles::RoleInfo::from_role_id_in_merchant_scope( - &state, - &user_role.role_id.clone(), - user_role - .merchant_id - .as_ref() - .ok_or(UserErrors::InternalServerError)?, - user_role - .org_id - .as_ref() - .ok_or(UserErrors::InternalServerError)?, - ) - .await - .map(|role_info| (user, user_role, role_info)) - .to_not_found_response(UserErrors::InternalServerError) - }, - )) - .await?; - - let user_details_vec = users_user_roles_and_roles - .into_iter() - .map(|(user, user_role, role_info)| { - let user = domain::UserFromStorage::from(user); - user_api::UserDetails { - email: user.get_email(), - name: user.get_name(), - role_id: user_role.role_id.clone(), - role_name: role_info.get_role_name().to_string(), - status: user_role.status.foreign_into(), - last_modified_at: user_role.last_modified, - } - }) - .collect(); - - Ok(ApplicationResponse::Json(user_api::ListUsersResponse( - user_details_vec, - ))) -} - #[cfg(feature = "email")] pub async fn verify_email_token_only_flow( state: SessionState, diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index b841f88eca1..ad37176358b 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -26,6 +26,7 @@ pub mod role; use common_enums::{EntityType, PermissionGroup}; use strum::IntoEnumIterator; +// TODO: To be deprecated pub async fn get_authorization_info_with_groups( _state: SessionState, ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { @@ -38,6 +39,7 @@ pub async fn get_authorization_info_with_groups( ), )) } + pub async fn get_authorization_info_with_group_tag( ) -> UserResponse<user_role_api::AuthorizationInfoResponse> { static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| { @@ -253,49 +255,6 @@ pub async fn update_user_role( Ok(ApplicationResponse::StatusOk) } -pub async fn accept_invitation( - state: SessionState, - user_token: auth::UserFromToken, - req: user_role_api::AcceptInvitationRequest, -) -> UserResponse<()> { - let merchant_accounts = state - .store - .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids) - .await - .change_context(UserErrors::InternalServerError)?; - let update_result = - futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async { - let (update_v1_result, update_v2_result) = - utils::user_role::update_v1_and_v2_user_roles_in_db( - &state, - user_token.user_id.as_str(), - &merchant_account.organization_id, - merchant_account.get_id(), - None, - UserRoleUpdate::UpdateStatus { - status: UserStatus::Active, - modified_by: user_token.user_id.clone(), - }, - ) - .await; - - if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) - || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) - { - Err(report!(UserErrors::InternalServerError)) - } else { - Ok(()) - } - })) - .await; - - if update_result.is_empty() || update_result.iter().all(Result::is_err) { - return Err(UserErrors::MerchantIdNotFound.into()); - } - - Ok(ApplicationResponse::StatusOk) -} - pub async fn accept_invitations_v2( state: SessionState, user_from_token: auth::UserFromToken, @@ -348,67 +307,6 @@ pub async fn accept_invitations_v2( Ok(ApplicationResponse::StatusOk) } -pub async fn merchant_select_token_only_flow( - state: SessionState, - user_token: auth::UserFromSinglePurposeToken, - req: user_role_api::MerchantSelectRequest, -) -> UserResponse<user_api::TokenResponse> { - let merchant_accounts = state - .store - .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids) - .await - .change_context(UserErrors::InternalServerError)?; - - let update_result = - futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async { - let (update_v1_result, update_v2_result) = - utils::user_role::update_v1_and_v2_user_roles_in_db( - &state, - user_token.user_id.as_str(), - &merchant_account.organization_id, - merchant_account.get_id(), - None, - UserRoleUpdate::UpdateStatus { - status: UserStatus::Active, - modified_by: user_token.user_id.clone(), - }, - ) - .await; - - if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found()) - || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found()) - { - Err(report!(UserErrors::InternalServerError)) - } else { - Ok(()) - } - })) - .await; - - if update_result.is_empty() || update_result.iter().all(Result::is_err) { - return Err(UserErrors::MerchantIdNotFound.into()); - } - - let user_from_db: domain::UserFromStorage = state - .global_store - .find_user_by_id(user_token.user_id.as_str()) - .await - .change_context(UserErrors::InternalServerError)? - .into(); - - let current_flow = - domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?; - let next_flow = current_flow.next(user_from_db.clone(), &state).await?; - - let token = next_flow.get_token(&state).await?; - - let response = user_api::TokenResponse { - token: token.clone(), - token_type: next_flow.get_flow().into(), - }; - auth::cookies::set_cookie_response(response, token) -} - pub async fn accept_invitations_pre_auth( state: SessionState, user_token: auth::UserFromSinglePurposeToken, @@ -644,20 +542,23 @@ pub async fn delete_user_role( } // Check if user has any more role associations - let user_roles_v2 = state + let remaining_roles = state .store - .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V2) - .await - .change_context(UserErrors::InternalServerError)?; - - let user_roles_v1 = state - .store - .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V1) + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: user_from_db.get_user_id(), + org_id: None, + merchant_id: None, + profile_id: None, + entity_id: None, + version: None, + status: None, + limit: None, + }) .await .change_context(UserErrors::InternalServerError)?; // If user has no more role associated with him then deleting user - if user_roles_v2.is_empty() && user_roles_v1.is_empty() { + if remaining_roles.is_empty() { state .global_store .delete_user_by_user_id(user_from_db.get_user_id()) diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index d5d655b4a89..b5b5cab421f 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -83,45 +83,6 @@ pub async fn create_role( )) } -pub async fn list_invitable_roles_with_groups( - state: SessionState, - user_from_token: UserFromToken, -) -> UserResponse<role_api::ListRolesResponse> { - let predefined_roles_map = PREDEFINED_ROLES - .iter() - .filter(|(_, role_info)| role_info.is_invitable()) - .map( - |(role_id, role_info)| role_api::RoleInfoWithGroupsResponse { - groups: role_info.get_permission_groups().to_vec(), - role_id: role_id.to_string(), - role_name: role_info.get_role_name().to_string(), - role_scope: role_info.get_scope(), - }, - ); - - let custom_roles_map = state - .store - .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .filter_map(|role| { - let role_info = roles::RoleInfo::from(role); - role_info - .is_invitable() - .then_some(role_api::RoleInfoWithGroupsResponse { - groups: role_info.get_permission_groups().to_vec(), - role_id: role_info.get_role_id().to_string(), - role_name: role_info.get_role_name().to_string(), - role_scope: role_info.get_scope(), - }) - }); - - Ok(ApplicationResponse::Json(role_api::ListRolesResponse( - predefined_roles_map.chain(custom_roles_map).collect(), - ))) -} - pub async fn get_role_with_groups( state: SessionState, user_from_token: UserFromToken, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index d14de8c2330..f6cbdd5bbc6 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3037,37 +3037,6 @@ impl UserRoleInterface for KafkaStore { self.diesel_store.insert_user_role(user_role).await } - async fn find_user_role_by_user_id( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<user_storage::UserRole, errors::StorageError> { - self.diesel_store - .find_user_role_by_user_id(user_id, version) - .await - } - - async fn find_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<user_storage::UserRole, errors::StorageError> { - self.diesel_store - .find_user_role_by_user_id_merchant_id(user_id, merchant_id, version) - .await - } - - async fn list_user_roles_by_user_id_and_version( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { - self.diesel_store - .list_user_roles_by_user_id_and_version(user_id, version) - .await - } - async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, @@ -3127,16 +3096,6 @@ impl UserRoleInterface for KafkaStore { .await } - async fn list_user_roles_by_merchant_id( - &self, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> { - self.diesel_store - .list_user_roles_by_merchant_id(merchant_id, version) - .await - } - async fn list_user_roles_by_user_id<'a>( &self, payload: ListUserRolesByUserIdPayload<'a>, diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index d511010e6b5..9a5c7149b68 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -54,31 +54,6 @@ pub trait UserRoleInterface { user_role: InsertUserRolePayload, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; - async fn find_user_role_by_user_id( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError>; - - async fn find_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError>; - - async fn list_user_roles_by_user_id_and_version( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; - - async fn list_user_roles_by_merchant_id( - &self, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; - async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, @@ -132,59 +107,6 @@ impl UserRoleInterface for Store { .map_err(|error| report!(errors::StorageError::from(error))) } - #[instrument(skip_all)] - async fn find_user_role_by_user_id( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::UserRole::find_by_user_id(&conn, user_id.to_owned(), version) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn find_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::UserRole::find_by_user_id_merchant_id( - &conn, - user_id.to_owned(), - merchant_id.to_owned(), - version, - ) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - async fn list_user_roles_by_user_id_and_version( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::UserRole::list_by_user_id(&conn, user_id.to_owned(), version) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - - #[instrument(skip_all)] - async fn list_user_roles_by_merchant_id( - &self, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; - storage::UserRole::list_by_merchant_id(&conn, merchant_id.to_owned(), version) - .await - .map_err(|error| report!(errors::StorageError::from(error))) - } - #[instrument(skip_all)] async fn find_user_role_by_user_id_and_lineage( &self, @@ -335,96 +257,6 @@ impl UserRoleInterface for MockDb { .collect::<Result<Vec<_>, _>>() } - async fn find_user_role_by_user_id( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError> { - let user_roles = self.user_roles.lock().await; - user_roles - .iter() - .find(|user_role| user_role.user_id == user_id && user_role.version == version) - .cloned() - .ok_or( - errors::StorageError::ValueNotFound(format!( - "No user role available for user_id = {user_id}" - )) - .into(), - ) - } - - async fn find_user_role_by_user_id_merchant_id( - &self, - user_id: &str, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<storage::UserRole, errors::StorageError> { - let user_roles = self.user_roles.lock().await; - - for user_role in user_roles.iter() { - let Some(user_role_merchant_id) = &user_role.merchant_id else { - continue; - }; - if user_role.user_id == user_id - && user_role_merchant_id == merchant_id - && user_role.version == version - { - return Ok(user_role.clone()); - } - } - - Err(errors::StorageError::ValueNotFound(format!( - "No user role available for user_id = {} and merchant_id = {}", - user_id, - merchant_id.get_string_repr() - )) - .into()) - } - - async fn list_user_roles_by_user_id_and_version( - &self, - user_id: &str, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { - let user_roles = self.user_roles.lock().await; - - Ok(user_roles - .iter() - .cloned() - .filter_map(|ele| { - if ele.user_id == user_id && ele.version == version { - return Some(ele); - } - None - }) - .collect()) - } - - async fn list_user_roles_by_merchant_id( - &self, - merchant_id: &id_type::MerchantId, - version: enums::UserRoleVersion, - ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { - let user_roles = self.user_roles.lock().await; - - let filtered_roles: Vec<_> = user_roles - .iter() - .filter_map(|role| { - if let Some(role_merchant_id) = &role.merchant_id { - if role_merchant_id == merchant_id && role.version == version { - Some(role.clone()) - } else { - None - } - } else { - None - } - }) - .collect(); - - Ok(filtered_roles) - } - async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index d5f73921a9d..f7ea8cf3649 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1791,26 +1791,11 @@ impl User { .service( web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)), ) - .service( - web::resource("/switch_merchant").route(web::post().to(user::switch_merchant_id)), - ) .service( web::resource("/create_merchant") .route(web::post().to(user::user_merchant_account_create)), ) - // TODO: Remove this endpoint once migration to /merchants/list is done - .service( - web::resource("/switch/list").route(web::get().to(user::list_merchants_for_user)), - ) - .service( - web::resource("/merchants/list") - .route(web::get().to(user::list_merchants_for_user)), - ) - // The route is utilized to select an invitation from a list of merchants in an intermediate state - .service( - web::resource("/merchants_select/list") - .route(web::get().to(user::list_merchants_for_user)), - ) + // TODO: To be deprecated .service( web::resource("/permission_info") .route(web::get().to(user_role::get_authorization_info)), @@ -1952,12 +1937,13 @@ impl User { // User management route = route.service( web::scope("/user") - .service(web::resource("").route(web::get().to(user::get_user_role_details))) + .service(web::resource("").route(web::post().to(user::list_user_roles_details))) + // TODO: To be deprecated .service(web::resource("/v2").route(web::post().to(user::list_user_roles_details))) .service( - web::resource("/list") - .route(web::get().to(user::list_users_for_merchant_account)), + web::resource("/list").route(web::get().to(user_role::list_users_in_lineage)), ) + // TODO: To be deprecated .service( web::resource("/v2/list") .route(web::get().to(user_role::list_users_in_lineage)), @@ -1970,8 +1956,11 @@ impl User { web::scope("/invite/accept") .service( web::resource("") - .route(web::post().to(user_role::merchant_select)) - .route(web::put().to(user_role::accept_invitation)), + .route(web::post().to(user_role::accept_invitations_v2)), + ) + .service( + web::resource("/pre_auth") + .route(web::post().to(user_role::accept_invitations_pre_auth)), ) .service( web::scope("/v2") @@ -1996,36 +1985,38 @@ impl User { ); // Role information - route = route.service( - web::scope("/role") - .service( - web::resource("") - .route(web::get().to(user_role::get_role_from_token)) - .route(web::post().to(user_role::create_role)), - ) - .service( - web::resource("/v2/list").route(web::get().to(user_role::list_roles_with_info)), - ) - .service( - web::scope("/list") - .service(web::resource("").route(web::get().to(user_role::list_all_roles))) - .service( - web::resource("/invite").route( + route = + route.service( + web::scope("/role") + .service( + web::resource("") + .route(web::get().to(user_role::get_role_from_token)) + .route(web::post().to(user_role::create_role)), + ) + // TODO: To be deprecated + .service( + web::resource("/v2/list") + .route(web::get().to(user_role::list_roles_with_info)), + ) + .service( + web::scope("/list") + .service( + web::resource("") + .route(web::get().to(user_role::list_roles_with_info)), + ) + .service(web::resource("/invite").route( web::get().to(user_role::list_invitable_roles_at_entity_level), - ), - ) - .service( - web::resource("/update").route( + )) + .service(web::resource("/update").route( web::get().to(user_role::list_updatable_roles_at_entity_level), - ), - ), - ) - .service( - web::resource("/{role_id}") - .route(web::get().to(user_role::get_role)) - .route(web::put().to(user_role::update_role)), - ), - ); + )), + ) + .service( + web::resource("/{role_id}") + .route(web::get().to(user_role::get_role)) + .route(web::put().to(user_role::update_role)), + ), + ); #[cfg(feature = "dummy_connector")] { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 482bc40c49f..18211b7fbb0 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -219,16 +219,13 @@ impl From<Flow> for ApiIdentifier { | Flow::VerifyPaymentConnector | Flow::InternalUserSignup | Flow::SwitchOrg - | Flow::SwitchMerchant | Flow::SwitchMerchantV2 | Flow::SwitchProfile | Flow::UserMerchantAccountCreate | Flow::GenerateSampleData | Flow::DeleteSampleData - | Flow::UserMerchantAccountList | Flow::GetUserDetails | Flow::GetUserRoleDetails - | Flow::ListUsersForMerchantAccount | Flow::ForgotPassword | Flow::ResetPassword | Flow::RotatePassword @@ -259,8 +256,7 @@ impl From<Flow> for ApiIdentifier { | Flow::ListInvitationsForUser | Flow::AuthSelect => Self::User, - Flow::ListRoles - | Flow::ListRolesV2 + Flow::ListRolesV2 | Flow::ListInvitableRolesAtEntityLevel | Flow::ListUpdatableRolesAtEntityLevel | Flow::GetRole @@ -268,9 +264,7 @@ impl From<Flow> for ApiIdentifier { | Flow::UpdateUserRole | Flow::GetAuthorizationInfo | Flow::GetRolesInfo - | Flow::AcceptInvitation | Flow::AcceptInvitationsV2 - | Flow::MerchantSelect | Flow::AcceptInvitationsPreAuth | Flow::DeleteUserRole | Flow::CreateRole diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index b1fbd2bb6df..4ed2280c6a3 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -228,24 +228,6 @@ pub async fn internal_user_signup( .await } -pub async fn switch_merchant_id( - state: web::Data<AppState>, - http_req: HttpRequest, - json_payload: web::Json<user_api::SwitchMerchantRequest>, -) -> HttpResponse { - let flow = Flow::SwitchMerchant; - Box::pin(api::server_wrap( - flow, - state.clone(), - &http_req, - json_payload.into_inner(), - |state, user, req, _| user_core::switch_merchant_id(state, req, user), - &auth::DashboardNoPermissionAuth, - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn user_merchant_account_create( state: web::Data<AppState>, req: HttpRequest, @@ -316,41 +298,6 @@ pub async fn delete_sample_data( .await } -pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { - let flow = Flow::UserMerchantAccountList; - Box::pin(api::server_wrap( - flow, - state, - &req, - (), - |state, user, _, _| user_core::list_merchants_for_user(state, user), - &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::AcceptInvite), - api_locking::LockAction::NotApplicable, - )) - .await -} - -pub async fn get_user_role_details( - state: web::Data<AppState>, - req: HttpRequest, - payload: web::Query<user_api::GetUserRoleDetailsRequest>, -) -> HttpResponse { - let flow = Flow::GetUserDetails; - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - payload.into_inner(), - user_core::get_user_details_in_merchant_account, - &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, - }, - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn list_user_roles_details( state: web::Data<AppState>, req: HttpRequest, @@ -372,26 +319,6 @@ pub async fn list_user_roles_details( .await } -pub async fn list_users_for_merchant_account( - state: web::Data<AppState>, - req: HttpRequest, -) -> HttpResponse { - let flow = Flow::ListUsersForMerchantAccount; - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - (), - |state, user, _, _| user_core::list_users_for_merchant_account(state, user), - &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, - }, - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn rotate_password( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 922e7612b14..777cbe1fd95 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -16,6 +16,7 @@ use crate::{ }, }; +// TODO: To be deprecated pub async fn get_authorization_info( state: web::Data<AppState>, http_req: HttpRequest, @@ -76,25 +77,6 @@ pub async fn create_role( .await } -pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { - let flow = Flow::ListRoles; - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - (), - |state, user, _, _| async move { - role_core::list_invitable_roles_with_groups(state, user).await - }, - &auth::JWTAuth { - permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, - }, - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn get_role( state: web::Data<AppState>, req: HttpRequest, @@ -167,25 +149,6 @@ pub async fn update_user_role( .await } -pub async fn accept_invitation( - state: web::Data<AppState>, - req: HttpRequest, - json_payload: web::Json<user_role_api::AcceptInvitationRequest>, -) -> HttpResponse { - let flow = Flow::AcceptInvitation; - let payload = json_payload.into_inner(); - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - payload, - |state, user, req_body, _| user_role_core::accept_invitation(state, user, req_body), - &auth::DashboardNoPermissionAuth, - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn accept_invitations_v2( state: web::Data<AppState>, req: HttpRequest, @@ -205,27 +168,6 @@ pub async fn accept_invitations_v2( .await } -pub async fn merchant_select( - state: web::Data<AppState>, - req: HttpRequest, - json_payload: web::Json<user_role_api::MerchantSelectRequest>, -) -> HttpResponse { - let flow = Flow::MerchantSelect; - let payload = json_payload.into_inner(); - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - payload, - |state, user, req_body, _| async move { - user_role_core::merchant_select_token_only_flow(state, user, req_body).await - }, - &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite), - api_locking::LockAction::NotApplicable, - )) - .await -} - pub async fn accept_invitations_pre_auth( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index 822035c7925..7cfde3efeea 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -1,21 +1,17 @@ use api_models::user_role::{GroupInfo, ParentGroup, PermissionInfo}; use common_enums::PermissionGroup; -use strum::{EnumIter, IntoEnumIterator}; +use strum::IntoEnumIterator; use super::{permission_groups::get_permissions_vec, permissions::Permission}; -pub fn get_module_authorization_info() -> Vec<ModuleInfo> { - PermissionModule::iter() - .map(|module| ModuleInfo::new(&module)) - .collect() -} - +// TODO: To be deprecated pub fn get_group_authorization_info() -> Vec<GroupInfo> { PermissionGroup::iter() .map(get_group_info_from_permission_group) .collect() } +// TODO: To be deprecated pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<PermissionInfo> { permissions .iter() @@ -26,169 +22,7 @@ pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<P .collect() } -// TODO: Deprecate once groups are stable -#[derive(PartialEq, EnumIter, Clone)] -pub enum PermissionModule { - Payments, - Refunds, - MerchantAccount, - Connectors, - Routing, - Analytics, - Mandates, - Customer, - Disputes, - ThreeDsDecisionManager, - SurchargeDecisionManager, - AccountCreate, - Payouts, - Recon, -} - -impl PermissionModule { - pub fn get_module_description(&self) -> &'static str { - match self { - Self::Payments => "Everything related to payments - like creating and viewing payment related information are within this module", - Self::Refunds => "Refunds module encompasses everything related to refunds - like creating and viewing payment related information", - Self::MerchantAccount => "Accounts module permissions allow the user to view and update account details, configure webhooks and much more", - Self::Connectors => "All connector related actions - like configuring new connectors, viewing and updating connector configuration lies with this module", - Self::Routing => "All actions related to new, active, and past routing stacks take place here", - Self::Analytics => "Permission to view and analyse the data relating to payments, refunds, sdk etc.", - Self::Mandates => "Everything related to mandates - like creating and viewing mandate related information are within this module", - Self::Customer => "Everything related to customers - like creating and viewing customer related information are within this module", - Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module", - Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant", - Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant", - Self::AccountCreate => "Create new account within your organization", - Self::Payouts => "Everything related to payouts - like creating and viewing payout related information are within this module", - Self::Recon => "Everything related to recon - raise requests for activating recon and generate recon auth tokens", - } - } -} - -// TODO: Deprecate once groups are stable -pub struct ModuleInfo { - pub module: PermissionModule, - pub description: &'static str, - pub permissions: Vec<PermissionInfo>, -} - -impl ModuleInfo { - pub fn new(module: &PermissionModule) -> Self { - let module_name = module.clone(); - let description = module.get_module_description(); - - match module { - PermissionModule::Payments => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::PaymentRead, - Permission::PaymentWrite, - ]), - }, - PermissionModule::Refunds => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::RefundRead, - Permission::RefundWrite, - ]), - }, - PermissionModule::MerchantAccount => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::MerchantAccountRead, - Permission::MerchantAccountWrite, - ]), - }, - PermissionModule::Connectors => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::MerchantConnectorAccountRead, - Permission::MerchantConnectorAccountWrite, - ]), - }, - PermissionModule::Routing => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::RoutingRead, - Permission::RoutingWrite, - ]), - }, - PermissionModule::Analytics => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[Permission::Analytics]), - }, - PermissionModule::Mandates => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::MandateRead, - Permission::MandateWrite, - ]), - }, - PermissionModule::Customer => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::CustomerRead, - Permission::CustomerWrite, - ]), - }, - PermissionModule::Disputes => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::DisputeRead, - Permission::DisputeWrite, - ]), - }, - PermissionModule::ThreeDsDecisionManager => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::ThreeDsDecisionManagerRead, - Permission::ThreeDsDecisionManagerWrite, - ]), - }, - - PermissionModule::SurchargeDecisionManager => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::SurchargeDecisionManagerRead, - Permission::SurchargeDecisionManagerWrite, - ]), - }, - PermissionModule::AccountCreate => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::MerchantAccountCreate, - ]), - }, - PermissionModule::Payouts => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[ - Permission::PayoutRead, - Permission::PayoutWrite, - ]), - }, - PermissionModule::Recon => Self { - module: module_name, - description, - permissions: get_permission_info_from_permissions(&[Permission::ReconAdmin]), - }, - } - } -} - +// TODO: To be deprecated fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo { let description = get_group_description(group); GroupInfo { @@ -198,6 +32,7 @@ fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo { } } +// TODO: To be deprecated fn get_group_description(group: PermissionGroup) -> &'static str { match group { PermissionGroup::OperationsView => { @@ -250,10 +85,10 @@ pub fn get_parent_group_description(group: ParentGroup) -> &'static str { ParentGroup::Operations => "Payments, Refunds, Payouts, Mandates, Disputes and Customers", ParentGroup::Connectors => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager", ParentGroup::Workflows => "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager", - ParentGroup::Analytics => "View Analytics", + ParentGroup::Analytics => "View Analytics", ParentGroup::Users => "Manage and invite Users to the Team", - ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc", - ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", - ParentGroup::Recon => "View and manage reconciliation reports", + ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc", + ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", + ParentGroup::Recon => "View and manage reconciliation reports", } } diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 19d682aeef1..6361b82afb4 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -32,7 +32,7 @@ use crate::{ }, db::{user_role::InsertUserRolePayload, GlobalStorageInterface}, routes::SessionState, - services::{self, authentication::UserFromToken, authorization::info}, + services::{self, authentication::UserFromToken}, types::transformers::ForeignFrom, utils::user::password, }; @@ -1019,37 +1019,6 @@ impl UserFromStorage { } } -impl From<info::ModuleInfo> for user_role_api::ModuleInfo { - fn from(value: info::ModuleInfo) -> Self { - Self { - module: value.module.into(), - description: value.description, - permissions: value.permissions.into_iter().map(Into::into).collect(), - } - } -} - -impl From<info::PermissionModule> for user_role_api::PermissionModule { - fn from(value: info::PermissionModule) -> Self { - match value { - info::PermissionModule::Payments => Self::Payments, - info::PermissionModule::Refunds => Self::Refunds, - info::PermissionModule::MerchantAccount => Self::MerchantAccount, - info::PermissionModule::Connectors => Self::Connectors, - info::PermissionModule::Routing => Self::Routing, - info::PermissionModule::Analytics => Self::Analytics, - info::PermissionModule::Mandates => Self::Mandates, - info::PermissionModule::Customer => Self::Customer, - info::PermissionModule::Disputes => Self::Disputes, - info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager, - info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager, - info::PermissionModule::AccountCreate => Self::AccountCreate, - info::PermissionModule::Payouts => Self::Payouts, - info::PermissionModule::Recon => Self::Recon, - } - } -} - impl ForeignFrom<UserStatus> for user_role_api::UserStatus { fn foreign_from(value: UserStatus) -> Self { match value { diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 22edf6768c8..8975519fd97 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -5,8 +5,7 @@ use common_enums::UserAuthType; use common_utils::{ encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier, }; -use diesel_models::user_role::UserRole; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; @@ -86,45 +85,6 @@ impl UserFromToken { } } -pub async fn generate_jwt_auth_token_without_profile( - state: &SessionState, - user: &UserFromStorage, - user_role: &UserRole, -) -> UserResult<Secret<String>> { - let token = AuthToken::new_token( - user.get_user_id().to_string(), - user_role - .merchant_id - .as_ref() - .ok_or(report!(UserErrors::InternalServerError)) - .attach_printable("merchant_id not found for user_role")? - .clone(), - user_role.role_id.clone(), - &state.conf, - user_role - .org_id - .as_ref() - .ok_or(report!(UserErrors::InternalServerError)) - .attach_printable("org_id not found for user_role")? - .clone(), - None, - ) - .await?; - Ok(Secret::new(token)) -} - -pub async fn generate_jwt_auth_token_with_attributes_without_profile( - state: &SessionState, - user_id: String, - merchant_id: id_type::MerchantId, - org_id: id_type::OrganizationId, - role_id: String, -) -> UserResult<Secret<String>> { - let token = - AuthToken::new_token(user_id, merchant_id, role_id, &state.conf, org_id, None).await?; - Ok(Secret::new(token)) -} - pub async fn generate_jwt_auth_token_with_attributes( state: &SessionState, user_id: String, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 603c5cc91c1..2bae094fd96 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -364,8 +364,6 @@ pub enum Flow { InternalUserSignup, /// Switch org SwitchOrg, - /// Switch merchant - SwitchMerchant, /// Switch merchant v2 SwitchMerchantV2, /// Switch profile @@ -374,8 +372,6 @@ pub enum Flow { GetAuthorizationInfo, /// Get Roles info GetRolesInfo, - /// List roles - ListRoles, /// List roles v2 ListRolesV2, /// List invitable roles at entity level @@ -394,14 +390,10 @@ pub enum Flow { GenerateSampleData, /// Delete Sample Data DeleteSampleData, - /// List merchant accounts for user - UserMerchantAccountList, /// Get details of a user GetUserDetails, /// Get details of a user role in a merchant account GetUserRoleDetails, - /// List users for merchant account - ListUsersForMerchantAccount, /// PaymentMethodAuth Link token create PmAuthLinkTokenCreate, /// PaymentMethodAuth Exchange token create @@ -434,12 +426,8 @@ pub enum Flow { VerifyEmailRequest, /// Update user account details UpdateUserAccountDetails, - /// Accept user invitation using merchant_ids - AcceptInvitation, /// Accept user invitation using entities AcceptInvitationsV2, - /// Select merchant from invitations - MerchantSelect, /// Accept user invitation using entities before user login AcceptInvitationsPreAuth, /// Initiate external authentication for a payment
2024-09-26T12:17:17Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Deletions - `/user/switch_merchant` - `/user/switch/list` - `/user/merchants/list` - `/user/merchant_select/list` Modifications - `/user/user` will work same as `/user/user/v2` - `/user/user/list` will work same as `/user/user/v2/list` - `/user/user/invite/accept` will work same as `/user/user/invite/accept/v2` - `/user/user/invite/accept/pre_auth` will work same as `/user/user/invite/accept/v2/pre_auth` - `/user/role/list` will work same as `/user/role/v2/list` ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes [#6112](https://github.com/juspay/hyperswitch/issues/6112). ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> All the below APIs with throw 404. - `/user/switch_merchant` - `/user/switch/list` - `/user/merchants/list` - `/user/merchant_select/list` All the below APIs with behave differently. - `/user/user` will work same as `/user/user/v2` - `/user/user/list` will work same as `/user/user/v2/list` - `/user/user/invite/accept` will work same as `/user/user/invite/accept/v2` - `/user/user/invite/accept/pre_auth` will work same as `/user/user/invite/accept/v2/pre_auth` - `/user/role/list` will work same as `/user/role/v2/list` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
67d6d2247bb53dc25831d65305269ba6889c99de
juspay/hyperswitch
juspay__hyperswitch-6129
Bug: [CYPRESS]: Verify Time Range Filters in "Payment operations" page. --- ### **Title**: Verify Time Range Filters in "Payment operations" page. --- ### **Description**: This task is to write and execute automated test cases for various UI elements and functionalities on the "Payment Operations" page. The tests should validate that key UI elements are present and that core functionalities operate as expected. ### **Objective**: Ensure that the "Payment Operations" page displays all key elements and that interactions like searching, filtering, and report generation work as intended. The task will include multiple test cases covering these areas. ### **Pre-requisites:** [Create a dummy connector](https://github.com/juspay/hyperswitch/issues/6125) [Use the SDK to process a payment](https://github.com/juspay/hyperswitch/issues/6124) --- ### **Test Cases**: #### **Test Case 1: Verify Time Range Filters** - **Pre-requisites**: Make a payment. - **Steps**: 1. Login to the application. 2. Navigate to the "Payment Operations" page. 3. Verify the default time range is "Last 30 Days." 4. Click on the time range dropdown and select various options: "Last 30 Mins," "Last 1 Hour," "Last 2 Hours," etc. - **Expected Results**: - For each selected time range, verify the payments are displayed accordingly. - "Customize columns" button visibility should be checked based on the presence of payments. #### **Test Case 2: Verify "Custom Range" in Time Range Filters** - **Pre-requisites**: Make a payment. - **Steps**: 1. Login to the application. 2. Navigate to the "Payment Operations" page. 3. Select "Custom Range" in the time range dropdown. 4. Select a custom date range and click "Apply." - **Expected Results**: - Payments within the selected range should be displayed. - The selected time range should be displayed when the dropdown is minimized. --- ### **Acceptance Criteria**: 1. All test cases should pass with the expected results. 2. Each test case must verify the required functionality or UI element. 3. The tests should be included in the regression suite and executed in the CI/CD pipeline. --- ### **Submission Process**: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). - For this issue, please submit a PR on juspay/hyperswitch-control-center repo, and link it to the issue. Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ---
2023-07-08T11:58:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR updates the schedule for the auto release workflow to run every Tuesday, Wednesday and Thursday. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> We mostly won't be making any releases on Mondays and Fridays, so yeah. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> N/A ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
f56f9d643451b9a7ff961b21fc6ec0eefac0ebdf
juspay/hyperswitch
juspay__hyperswitch-6131
Bug: [CYPRESS]: Verify Columns in "Payment operations" page. --- ### **Title**: Verify Columns in "Payment operations" page. --- ### **Description**: This task is to write and execute automated test cases for various UI elements and functionalities on the "Payment Operations" page. The tests should validate that key UI elements are present and that core functionalities operate as expected. ### **Objective**: Ensure that the "Payment Operations" page displays all key elements and that interactions like searching, filtering, and report generation work as intended. The task will include multiple test cases covering these areas. ### **Pre-requisites:** [Create a dummy connector](https://github.com/juspay/hyperswitch/issues/6125) [Use the SDK to process a payment](https://github.com/juspay/hyperswitch/issues/6124) --- ### **Test Cases**: #### **Test Case 1: Customize Columns in Payments Table** - **Pre-requisites**: Make a payment. - **Steps**: 1. Login to the application. 2. Navigate to the "Payment Operations" page. 3. Click on the "Customize Columns" button. 4. Verify that the following column names are present: - Merchant Order Reference Id - Metadata - Payment Status - Payment Method Type - Payment Method - Payment ID - Customer Email - Description - Created - Connector Transaction ID - Connector - Amount - AmountCapturable - Authentication Type - Profile Id - Capture Method - Client Secret - Currency - Customer ID - Merchant ID - Setup Future Usage - Attempt count 5. Select all columns. 6. Click on "22 Columns selected." 7. Click on the "Customize Columns" button. 8. Unselect all optional columns: - AmountCapturable - Authentication Type - Profile Id - Capture Method - Client Secret - Currency - Customer ID - Merchant ID - Setup Future Usage - Attempt count 9. Click on "12 Columns selected." - **Expected Results**: - All selected columns should be present and visible in the payments table. - Only the selected columns should be visible after unselecting optional columns. #### **Test Case 2: Search Columns in "Customize Columns" List** - **Pre-requisites**: User is logged in. - **Steps**: 1. Navigate to the "Payment Operations" page. 2. Click on the "Customize Columns" button. 3. Verify that the search bar has the placeholder "Search in 22 options." 4. Search for any available column names such as "Merchant," "Profile," "Payments." - **Expected Results**: - Resulting column names should contain the search string. #### **Test Case 3: Search Invalid Columns in "Customize Columns" List** - **Pre-requisites**: User is logged in. - **Steps**: 1. Navigate to the "Payment Operations" page. 2. Click on the "Customize Columns" button. 3. Verify that the search bar has the placeholder "Search in 22 options." 4. Search for invalid column names such as "abacd," "something," "createdAt." - **Expected Results**: - "No matching records found" text should be shown. - Clicking on the "X" button should clear the search text and display all column names. --- ### **Acceptance Criteria**: 1. All test cases should pass with the expected results. 2. Each test case must verify the required functionality or UI element. 3. The tests should be included in the regression suite and executed in the CI/CD pipeline. --- ### **Submission Process**: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). - For this issue, submit a PR on https://github.com/juspay/hyperswitch-control-center repo, and link to the issue. Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ---
2023-07-10T09:17:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> - Also push to public docker repositories for all release tags ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
b428298030b3c04a249f175b51b7904ab96e2ce7
juspay/hyperswitch
juspay__hyperswitch-6090
Bug: restructure `Samsung Pay` connector wallet details We need to restructure the Samsung Pay session token data stored in the connector wallet details as going forward we will add support for samsung pay payments with hyperswitch credentials. Then the samsung pay payment can be done using either merchant's credentials or hyperswitch's credentials. If it is merchant's credentials, it needs to be provided in the time of the merchant connector account creation. But when it comes to hyperswitch's credentials flow, merchant will provide only merchant specific business information (like merchant name that should be displayed to customer during the payment and merchant's business country). Whereas the private key or the required Samsung Pay certificates for the decryption will reside in the application env. ``` "connector_wallets_details": { "samsung_pay": { "merchant_credentials": { "service_id": "samsung pay service id", "merchant_display_name": "merchant name", "merchant_business_country": "IN", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } } ``` ``` "connector_wallets_details": { "samsung_pay": { "application_credentials": { "merchant_display_name": "merchant name", "merchant_business_country": "IN", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } } ```
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 456bb8e43a3..9d606dacb9f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4908,20 +4908,37 @@ pub struct GpaySessionTokenData { pub data: GpayMetaData, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +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. + ApplicationCredentials(SamsungPayApplicationCredentials), + MerchantCredentials(SamsungPayMerchantCredentials), +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] - pub data: SamsungPayMetadata, + pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -pub struct SamsungPayMetadata { +pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SamsungPayApplicationCredentials { + pub merchant_display_name: String, + pub merchant_business_country: api_enums::CountryAlpha2, + pub allowed_brands: Vec<String>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 5bd81897dd8..ee657bc3949 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -502,7 +502,7 @@ fn create_samsung_pay_session_token( router_data: &types::PaymentsSessionRouterData, header_payload: api_models::payments::HeaderPayload, ) -> RouterResult<types::PaymentsSessionRouterData> { - let samsung_pay_wallet_details = router_data + let samsung_pay_session_token_data = router_data .connector_wallets_details .clone() .parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData") @@ -527,18 +527,30 @@ fn create_samsung_pay_session_token( .get_required_value("samsung pay domain") .attach_printable("Failed to get domain for samsung pay session call")?; + let samsung_pay_wallet_details = match samsung_pay_session_token_data.data { + payment_types::SamsungPayCombinedMetadata::MerchantCredentials( + samsung_pay_merchant_credentials, + ) => samsung_pay_merchant_credentials, + payment_types::SamsungPayCombinedMetadata::ApplicationCredentials( + _samsung_pay_application_credentials, + ) => Err(errors::ApiErrorResponse::NotSupported { + message: "Samsung Pay decryption flow with application credentials is not implemented" + .to_owned(), + })?, + }; + Ok(types::PaymentsSessionRouterData { response: Ok(types::PaymentsResponseData::SessionResponse { session_token: payment_types::SessionToken::SamsungPay(Box::new( payment_types::SamsungPaySessionTokenResponse { version: "2".to_string(), - service_id: samsung_pay_wallet_details.data.service_id, + service_id: samsung_pay_wallet_details.service_id, order_number: router_data.payment_id.clone(), merchant_payment_information: payment_types::SamsungPayMerchantPaymentInformation { - name: samsung_pay_wallet_details.data.merchant_display_name, + name: samsung_pay_wallet_details.merchant_display_name, url: merchant_domain, - country_code: samsung_pay_wallet_details.data.merchant_business_country, + country_code: samsung_pay_wallet_details.merchant_business_country, }, amount: payment_types::SamsungPayAmountDetails { amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly, @@ -546,7 +558,7 @@ fn create_samsung_pay_session_token( total_amount: samsung_pay_amount, }, protocol: payment_types::SamsungPayProtocolType::Protocol3ds, - allowed_brands: samsung_pay_wallet_details.data.allowed_brands, + allowed_brands: samsung_pay_wallet_details.allowed_brands, }, )), }),
2024-09-26T06:27:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> We need to restructure the Samsung Pay session token data stored in the connector wallet details as going forward we will add support for samsung pay payments with hyperswitch credentials. Then the samsung pay payment can be done using either merchant's credentials or hyperswitch's credentials. If it is merchant's credentials, it needs to be provided in the time of the merchant connector account creation. But when it comes to hyperswitch's credentials flow, merchant will provide only merchant specific business information (like merchant name that should be displayed to customer during the payment and merchant's business country). Whereas the private key or the required Samsung Pay certificates for the decryption will reside in the application env. ``` "connector_wallets_details": { "samsung_pay": { "merchant_credentials": { "service_id": "samsung pay service id", "merchant_display_name": "merchant name", "merchant_business_country": "IN", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } } ``` ``` "connector_wallets_details": { "samsung_pay": { "application_credentials": { "merchant_display_name": "Hyperswitch", "merchant_business_country": "IN", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } } }, ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` { "connector_type": "payment_processor", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_secret": "api_secret", "key1": "key1", "api_key": "api_key" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "invoke_sdk_client", "payment_method_type": "klarna" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "klarna" } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "Discover", "DinersClub" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "samsung_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_wallets_details": { "samsung_pay": { "application_credentials": { "service_id": "49400558c67f4a97b3925f", "merchant_display_name": "Hyperswitch", "merchant_business_country": "IN", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } } }, "connector_webhook_details": { "merchant_secret": "merchant_secret" } } ``` -> create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:' \ --data '{ "amount": 100000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1727248481" }' ``` ``` { "payment_id": "pay_wySk2SloqGsTbSB8ficv", "merchant_id": "merchant_1727343230", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_wySk2SloqGsTbSB8ficv_secret_LDsqsymJeHNbX6X6tGW6", "created": "2024-09-26T13:33:39.781Z", "currency": "USD", "customer_id": "cu_1727248481", "customer": { "id": "cu_1727248481", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1727248481", "created_at": 1727357619, "expires": 1727361219, "secret": "epk_780a72fc4a0d48338eeb3f029191723e" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_xEdgnpJ0oxDZrkzS02MR", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-26T13:48:39.780Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-26T13:33:39.842Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key:' \ --data '{ "payment_id": "pay_GEoTU1wJGcWqs0vQ9TLD", "wallets": [], "client_secret": "pay_GEoTU1wJGcWqs0vQ9TLD_secret_HIh790VwGvLS2aTVfIAN" }' ``` ``` { "payment_id": "pay_GEoTU1wJGcWqs0vQ9TLD", "client_secret": "pay_GEoTU1wJGcWqs0vQ9TLD_secret_HIh790VwGvLS2aTVfIAN", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay_GEoTU1wJGcWqs0vQ9TLD", "merchant": { "name": "Hyperswitch", "url": "sdk-test-app.netlify.app", "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
962b9978d651e3cc9185b2f6f849c7f255868077
juspay/hyperswitch
juspay__hyperswitch-6024
Bug: [REFACTOR]: [WELLSFARGO] Add amount conversion framework to Wellsfargo ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://developer.wellsfargo.com/guides/user-guides/open-banking-europe-api-integration/obei#step-1-%E2%80%93-request-payment-initiation) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 0cad88bfd4f..1c0ca722f29 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -580,6 +580,10 @@ impl StringMajorUnit { .ok_or(ParsingError::DecimalToI64ConversionFailure)?; Ok(MinorUnit::new(amount_i64)) } + /// forms a new StringMajorUnit default unit i.e zero + pub fn zero() -> Self { + Self("0".to_string()) + } /// Get string amount from struct to be removed in future pub fn get_amount_as_string(&self) -> String { diff --git a/crates/router/src/connector/wellsfargo.rs b/crates/router/src/connector/wellsfargo.rs index f5cdb6431b3..a63007f0a27 100644 --- a/crates/router/src/connector/wellsfargo.rs +++ b/crates/router/src/connector/wellsfargo.rs @@ -1,9 +1,10 @@ pub mod transformers; -use std::fmt::Debug; - use base64::Engine; -use common_utils::request::RequestContent; +use common_utils::{ + request::RequestContent, + types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector}, +}; use diesel_models::enums; use error_stack::{report, Report, ResultExt}; use masking::{ExposeInterface, PeekInterface}; @@ -12,6 +13,7 @@ use time::OffsetDateTime; use transformers as wellsfargo; use url::Url; +use super::utils::convert_amount; use crate::{ configs::settings, connector::{ @@ -35,10 +37,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Wellsfargo; +#[derive(Clone)] +pub struct Wellsfargo { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} impl Wellsfargo { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } + pub fn generate_digest(&self, payload: &[u8]) -> String { let payload_digest = digest::digest(&digest::SHA256, payload); consts::BASE64_ENGINE.encode(payload_digest) @@ -600,12 +610,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = wellsfargo::WellsfargoRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.amount_to_capture), req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + + let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); + let connector_req = wellsfargo::WellsfargoPaymentsCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -792,12 +804,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = wellsfargo::WellsfargoRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.amount), req.request.currency, - req.request.amount, - req, - ))?; + )?; + + let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_req = wellsfargo::WellsfargoPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -915,20 +928,21 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = wellsfargo::WellsfargoRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.amount.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "Amount", + }, + )?), req.request .currency .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "Currency", })?, - req.request - .amount - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "Amount", - })?, - req, - ))?; + )?; + + let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_req = wellsfargo::WellsfargoVoidRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1040,12 +1054,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundExecuteRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = wellsfargo::WellsfargoRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.refund_amount), req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + + let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_req = wellsfargo::WellsfargoRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -1204,12 +1219,13 @@ impl req: &types::PaymentsIncrementalAuthorizationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = wellsfargo::WellsfargoRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + MinorUnit::new(req.request.additional_amount), req.request.currency, - req.request.additional_amount, - req, - ))?; + )?; + + let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req)); let connector_request = wellsfargo::WellsfargoPaymentsIncrementalAuthorizationRequest::try_from( &connector_router_data, diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index ee34c26d670..b5adaf9545b 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -1,7 +1,10 @@ use api_models::payments; use base64::Engine; use common_enums::FutureUsage; -use common_utils::{pii, types::SemanticVersion}; +use common_utils::{ + pii, + types::{SemanticVersion, StringMajorUnit}, +}; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -26,21 +29,16 @@ use crate::{ #[derive(Debug, Serialize)] pub struct WellsfargoRouterData<T> { - pub amount: String, + pub amount: StringMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for WellsfargoRouterData<T> { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (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)?; - Ok(Self { +impl<T> From<(StringMajorUnit, T)> for WellsfargoRouterData<T> { + fn from((amount, router_data): (StringMajorUnit, T)) -> Self { + Self { amount, - router_data: item, - }) + router_data, + } } } @@ -61,7 +59,7 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest { let order_information = OrderInformationWithBill { amount_details: Amount { - total_amount: "0".to_string(), + total_amount: StringMajorUnit::zero(), currency: item.request.currency, }, bill_to: Some(bill_to), @@ -471,14 +469,14 @@ pub struct OrderInformation { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Amount { - total_amount: String, + total_amount: StringMajorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdditionalAmount { - additional_amount: String, + additional_amount: StringMajorUnit, currency: String, } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index e115558995d..851cda7143c 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -510,7 +510,7 @@ impl ConnectorData { enums::Connector::Volt => Ok(ConnectorEnum::Old(Box::new(connector::Volt::new()))), enums::Connector::Wellsfargo => { - Ok(ConnectorEnum::Old(Box::new(&connector::Wellsfargo))) + Ok(ConnectorEnum::Old(Box::new(connector::Wellsfargo::new()))) } // enums::Connector::Wellsfargopayout => { diff --git a/crates/router/tests/connectors/wellsfargo.rs b/crates/router/tests/connectors/wellsfargo.rs index 4425c077377..cab82c59ac8 100644 --- a/crates/router/tests/connectors/wellsfargo.rs +++ b/crates/router/tests/connectors/wellsfargo.rs @@ -11,7 +11,7 @@ impl utils::Connector for WellsfargoTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Wellsfargo; utils::construct_connector_data_old( - Box::new(&Wellsfargo), + Box::new(Wellsfargo::new()), types::Connector::Wellsfargo, api::GetToken::Connector, None,
2024-10-13T18:46:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> This PR do amount conversion changes for Wellsfargo Connector and it accepts the amount in StringMajorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes https://github.com/juspay/hyperswitch/issues/6024 ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
19a8474d8731ed7149b541f02ad237e30c4c9f24
juspay/hyperswitch
juspay__hyperswitch-6019
Bug: [REFACTOR]: [HELCIM] Add amount conversion framework to Helcim ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://devdocs.helcim.com/docs/payment-api) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [ ] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [ ] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv.rs b/crates/hyperswitch_connectors/src/connectors/fiserv.rs index e80c57454a0..50eebb99518 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv.rs @@ -1,13 +1,12 @@ pub mod transformers; -use std::fmt::Debug; - use base64::Engine; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -44,12 +43,23 @@ use time::OffsetDateTime; use transformers as fiserv; use uuid::Uuid; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{construct_not_implemented_error_report, convert_amount}, +}; -#[derive(Debug, Clone)] -pub struct Fiserv; +#[derive(Clone)] +pub struct Fiserv { + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} impl Fiserv { + pub fn new() -> &'static Self { + &Self { + amount_converter: &FloatMajorUnitForConnector, + } + } pub fn generate_authorization_signature( &self, auth: fiserv::FiservAuthType, @@ -194,7 +204,7 @@ impl ConnectorValidation for Fiserv { | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), + construct_not_implemented_error_report(capture_method, self.id()), ), } } @@ -421,12 +431,12 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = fiserv::FiservRouterData::try_from(( - &self.get_currency_unit(), + let amount_to_capture = convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + let router_obj = fiserv::FiservRouterData::try_from((amount_to_capture, req))?; let connector_req = fiserv::FiservCaptureRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -530,12 +540,12 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = fiserv::FiservRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let router_obj = fiserv::FiservRouterData::try_from((amount, req))?; let connector_req = fiserv::FiservPaymentsRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -624,12 +634,12 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiserv req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = fiserv::FiservRouterData::try_from(( - &self.get_currency_unit(), + let refund_amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let router_obj = fiserv::FiservRouterData::try_from((refund_amount, req))?; let connector_req = fiserv::FiservRefundRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs index d6e2cd54db7..8f9a15e49c2 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs @@ -1,5 +1,5 @@ use common_enums::enums; -use common_utils::{ext_traits::ValueExt, pii}; +use common_utils::{ext_traits::ValueExt, pii, types::FloatMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, @@ -9,7 +9,7 @@ use hyperswitch_domain_models::{ router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; -use hyperswitch_interfaces::{api, errors}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -23,22 +23,14 @@ use crate::{ #[derive(Debug, Serialize)] pub struct FiservRouterData<T> { - pub amount: String, + pub amount: FloatMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for FiservRouterData<T> { +impl<T> TryFrom<(FloatMajorUnit, T)> for FiservRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, router_data): ( - &api::CurrencyUnit, - enums::Currency, - i64, - T, - ), - ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + fn try_from((amount, router_data): (FloatMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data, @@ -89,8 +81,7 @@ pub struct GooglePayToken { #[derive(Default, Debug, Serialize)] pub struct Amount { - #[serde(serialize_with = "utils::str_to_f32")] - total: String, + total: FloatMajorUnit, currency: String, } @@ -143,7 +134,7 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP ) -> Result<Self, Self::Error> { let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?; let amount = Amount { - total: item.amount.clone(), + total: item.amount, currency: item.router_data.request.currency.to_string(), }; let transaction_details = TransactionDetails { @@ -484,7 +475,7 @@ impl TryFrom<&FiservRouterData<&types::PaymentsCaptureRouterData>> for FiservCap })?; Ok(Self { amount: Amount { - total: item.amount.clone(), + total: item.amount, currency: item.router_data.request.currency.to_string(), }, transaction_details: TransactionDetails { @@ -579,7 +570,7 @@ impl<F> TryFrom<&FiservRouterData<&types::RefundsRouterData<F>>> for FiservRefun })?; Ok(Self { amount: Amount { - total: item.amount.clone(), + total: item.amount, currency: item.router_data.request.currency.to_string(), }, merchant_details: MerchantDetails { diff --git a/crates/hyperswitch_connectors/src/connectors/helcim.rs b/crates/hyperswitch_connectors/src/connectors/helcim.rs index 844eab7825f..79b950063c3 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim.rs @@ -1,5 +1,4 @@ pub mod transformers; -use std::fmt::Debug; use api_models::webhooks::IncomingWebhookEvent; use common_enums::enums; @@ -7,6 +6,7 @@ use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -49,11 +49,21 @@ use transformers as helcim; use crate::{ constants::headers, types::ResponseRouterData, - utils::{to_connector_meta, PaymentsAuthorizeRequestData}, + utils::{convert_amount, to_connector_meta, PaymentsAuthorizeRequestData}, }; -#[derive(Debug, Clone)] -pub struct Helcim; +#[derive(Clone)] +pub struct Helcim { + amount_convertor: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} + +impl Helcim { + pub fn new() -> &'static Self { + &Self { + amount_convertor: &FloatMajorUnitForConnector, + } + } +} impl api::Payment for Helcim {} impl api::PaymentSession for Helcim {} @@ -305,13 +315,13 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = helcim::HelcimRouterData::try_from(( - &self.get_currency_unit(), + let connector_router_data = convert_amount( + self.amount_convertor, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; - let connector_req = helcim::HelcimPaymentsRequest::try_from(&connector_router_data)?; + )?; + let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?; + let connector_req = helcim::HelcimPaymentsRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -484,13 +494,13 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = helcim::HelcimRouterData::try_from(( - &self.get_currency_unit(), + let connector_router_data = convert_amount( + self.amount_convertor, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; - let connector_req = helcim::HelcimCaptureRequest::try_from(&connector_router_data)?; + )?; + let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?; + let connector_req = helcim::HelcimCaptureRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -651,13 +661,13 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Helcim req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = helcim::HelcimRouterData::try_from(( - &self.get_currency_unit(), + let connector_router_data = convert_amount( + self.amount_convertor, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; - let connector_req = helcim::HelcimRefundRequest::try_from(&connector_router_data)?; + )?; + let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?; + let connector_req = helcim::HelcimRefundRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs index 0a5453a49d0..d890bd88ac3 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs @@ -1,5 +1,8 @@ use common_enums::enums; -use common_utils::pii::{Email, IpAddress}; +use common_utils::{ + pii::{Email, IpAddress}, + types::FloatMajorUnit, +}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{Card, PaymentMethodData}, @@ -15,10 +18,7 @@ use hyperswitch_domain_models::{ RefundsRouterData, SetupMandateRouterData, }, }; -use hyperswitch_interfaces::{ - api::{self}, - errors, -}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -33,16 +33,13 @@ use crate::{ #[derive(Debug, Serialize)] pub struct HelcimRouterData<T> { - pub amount: f64, + pub amount: FloatMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for HelcimRouterData<T> { +impl<T> TryFrom<(FloatMajorUnit, T)> for HelcimRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), - ) -> Result<Self, Self::Error> { - let amount = crate::utils::get_amount_as_f64(currency_unit, amount, currency)?; + fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, @@ -77,7 +74,7 @@ pub struct HelcimVerifyRequest { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct HelcimPaymentsRequest { - amount: f64, + amount: FloatMajorUnit, currency: enums::Currency, ip_address: Secret<String, IpAddress>, card_data: HelcimCard, @@ -115,8 +112,8 @@ pub struct HelcimInvoice { pub struct HelcimLineItems { description: String, quantity: u8, - price: f64, - total: f64, + price: FloatMajorUnit, + total: FloatMajorUnit, } #[derive(Debug, Serialize)] @@ -514,7 +511,7 @@ impl<F> #[serde(rename_all = "camelCase")] pub struct HelcimCaptureRequest { pre_auth_transaction_id: u64, - amount: f64, + amount: FloatMajorUnit, ip_address: Secret<String, IpAddress>, #[serde(skip_serializing_if = "Option::is_none")] ecommerce: Option<bool>, @@ -637,7 +634,7 @@ impl<F> #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct HelcimRefundRequest { - amount: f64, + amount: FloatMajorUnit, original_transaction_id: u64, ip_address: Secret<String, IpAddress>, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index ce40e373462..fd26e459539 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -57,7 +57,6 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use regex::Regex; use router_env::logger; -use serde::Serializer; use serde_json::Value; use time::PrimitiveDateTime; @@ -344,16 +343,6 @@ pub(crate) fn construct_not_implemented_error_report( .into() } -pub(crate) fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error> -where - S: Serializer, -{ - let float_value = value.parse::<f64>().map_err(|_| { - serde::ser::Error::custom("Invalid string, cannot be converted to float value") - })?; - serializer.serialize_f64(float_value) -} - pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method"; pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 99d577c657b..3247395ad7e 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -432,7 +432,9 @@ impl ConnectorData { enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } - enums::Connector::Fiserv => Ok(ConnectorEnum::Old(Box::new(&connector::Fiserv))), + enums::Connector::Fiserv => { + Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) + } enums::Connector::Fiservemea => { Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new()))) } @@ -453,7 +455,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(&connector::Gocardless))) } // enums::Connector::Hipay => Ok(ConnectorEnum::Old(Box::new(connector::Hipay))), - enums::Connector::Helcim => Ok(ConnectorEnum::Old(Box::new(&connector::Helcim))), + enums::Connector::Helcim => { + Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new()))) + } enums::Connector::Iatapay => { Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new()))) } diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 7f13de31004..78235278ed9 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -16,7 +16,7 @@ impl utils::Connector for FiservTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Fiserv; utils::construct_connector_data_old( - Box::new(&Fiserv), + Box::new(Fiserv::new()), types::Connector::Fiserv, types::api::GetToken::Connector, None, diff --git a/crates/router/tests/connectors/helcim.rs b/crates/router/tests/connectors/helcim.rs index 761b07736ce..5b02e2f8431 100644 --- a/crates/router/tests/connectors/helcim.rs +++ b/crates/router/tests/connectors/helcim.rs @@ -11,7 +11,7 @@ impl utils::Connector for HelcimTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Helcim; utils::construct_connector_data_old( - Box::new(&Helcim), + Box::new(Helcim::new()), types::Connector::Helcim, types::api::GetToken::Connector, None,
2025-02-21T08:52:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> added **FloatMajorUnit** for amount conversion for **Fiserv** added **FloatMajorUnit** for amount conversion for **Helcim** ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> fixes #6256 and #6019 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested through postman: - Create a MCA for **fiserv**: - Create a Payment with **fiserv**: request: ``` { "amount": 10000, "currency": "USD", "amount_to_capture": 10000, "confirm": true, "profile_id": {{profile_id}}, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4147463011110083", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6540, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "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" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, //Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find more in the doc. "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 } ``` response: - The payment should be succeeded ``` { "payment_id": "pay_9mnPycKv5V2w9aNCHyO8", "merchant_id": "merchant_1740127595", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "fiserv", "client_secret": "pay_9mnPycKv5V2w9aNCHyO8_secret_X4CTRqm4Ldyx6L7s2OPa", "created": "2025-02-21T08:46:50.624Z", "currency": "USD", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0083", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "414746", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "order_details": [ { "brand": null, "amount": 6540, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "customer@gmail.com", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1740127610, "expires": 1740131210, "secret": "epk_a6328125a3ad471d88ef13493272c1cc" }, "manual_retry_allowed": false, "connector_transaction_id": "6f2fdeb7a1884bc0957c0f977644c30c", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "CHG015117c1ffa76779d655a830730d7add1a", "payment_link": null, "profile_id": "pro_IxmWaGQVX320n30wDNuM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_o2Tw2yV2oWr4vEC5b22q", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-21T09:01:50.623Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-21T08:46:54.326Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` using curl : <img width="614" alt="Screenshot 2025-03-11 at 10 48 50 PM" src="https://github.com/user-attachments/assets/da58c0b9-6dbf-4bab-94d3-37817eac3479" /> <img width="1496" alt="Screenshot 2025-03-11 at 10 51 03 PM" src="https://github.com/user-attachments/assets/e2f6e5f6-40d6-4253-ac82-9ea6da361eac" /> - Create a MCA for **helcim**: - Create a Payment with **helcim**: ``` { "amount": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 100, "customer_id": "helcim", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5413330089099130", "card_exp_month": "01", "card_exp_year": "28", "card_holder_name": "joseph Doe", "card_cvc": "100" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-US", "screen_height": 1080, "screen_width": 1920, "time_zone": 123, "ip_address": "192.168.1.1", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "os_type": "Windows", "os_version": "10", "device_model": "Desktop" }, "order_details": [{ "product_name":"something", "quantity": 4, "amount" : 400 }] } ``` response: - The payment should be succeeded ``` { "payment_id": "pay_TORNbtguEZUEleC3kYt5", "merchant_id": "merchant_1740386925", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "helcim", "client_secret": "pay_TORNbtguEZUEleC3kYt5_secret_PLV79VNxPEreoif4WfRh", "created": "2025-02-24T08:49:05.760Z", "currency": "USD", "customer_id": "helcim", "customer": { "id": "helcim", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "9130", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "541333", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "28", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "brand": null, "amount": 400, "category": null, "quantity": 4, "tax_rate": null, "product_id": null, "product_name": "something", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "helcim", "created_at": 1740386945, "expires": 1740390545, "secret": "epk_79d58a8d4ee84ef7bd0e66d4ffa2d471" }, "manual_retry_allowed": false, "connector_transaction_id": "32476974", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_TORNbtguEZUEleC3kYt5_1", "payment_link": null, "profile_id": "pro_1daddCjtZeUez131YwqB", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_b16Kuzg7hY5sPy9NgQUV", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-24T09:04:05.759Z", "fingerprint": null, "browser_info": { "os_type": "Windows", "language": "en-US", "time_zone": 123, "ip_address": "192.168.1.1", "os_version": "10", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "color_depth": 24, "device_model": "Desktop", "java_enabled": true, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-24T08:49:09.053Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` using curl : <img width="1168" alt="Screenshot 2025-03-11 at 11 09 50 PM" src="https://github.com/user-attachments/assets/48ee3269-56fe-45ce-85ac-8a57a72b0640" /> <img width="1496" alt="Screenshot 2025-03-11 at 11 10 41 PM" src="https://github.com/user-attachments/assets/860742b5-d26b-4c4d-91dd-325a39ee5082" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
24aa00341f907e7b77df9348f62d1416cc098691
juspay/hyperswitch
juspay__hyperswitch-6130
Bug: [CYPRESS]: Verify Search in "Payment operations" page. --- ### **Title**: Verify Search in "Payment operations" page. --- ### **Description**: This task is to write and execute automated test cases for various UI elements and functionalities on the "Payment Operations" page. The tests should validate that key UI elements are present and that core functionalities operate as expected. ### **Objective**: Ensure that the "Payment Operations" page displays all key elements and that interactions like searching, filtering, and report generation work as intended. The task will include multiple test cases covering these areas. ### **Pre-requisites:** [Create a dummy connector](https://github.com/juspay/hyperswitch/issues/6125) [Use the SDK to process a payment](https://github.com/juspay/hyperswitch/issues/6124) --- ### **Test Cases**: #### **Test Case 1: Search for Payment Using Existing Payment ID** - **Pre-requisites**: Make a payment. - **Steps**: 1. Login to the application. 2. Navigate to the "Payment Operations" page. 3. Enter an existing payment ID into the search bar. - **Test Data**: {{payment_id}} - **Expected Results**: - Payments table should contain one row with valid payment details. #### **Test Case 2: Search for Payment Using Invalid Payment ID** - **Pre-requisites**: User is logged in. - **Steps**: 1. Navigate to the "Payment Operations" page. 2. Enter an invalid payment ID or string into the search bar. - **Test Data**: "abacd," "something," "createdAt" - **Expected Results**: - "There are no payments as of now" text should be displayed. - "Customize columns" button should not be present. --- ### **Acceptance Criteria**: 1. All test cases should pass with the expected results. 2. Each test case must verify the required functionality or UI element. 3. The tests should be included in the regression suite and executed in the CI/CD pipeline. --- ### **Submission Process**: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). - For this issue, please submit a PR on juspay/hyperswitch-control-center repo, and link it to the issue. Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ---
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 4e8710e031c..f1c7e8396da 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -10,7 +10,6 @@ license.workspace = true [features] default = ["payouts"] errors = ["dep:actix-web", "dep:reqwest"] -multiple_mca = [] dummy_connector = ["common_enums/dummy_connector"] detailed_errors = [] payouts = [] diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index ec68111dd0e..a3a6643056b 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -76,11 +76,6 @@ pub struct MerchantAccountCreate { pub locker_id: Option<String>, ///Default business details for connector routing - #[cfg(feature = "multiple_mca")] - #[schema(value_type = PrimaryBusinessDetails)] - pub primary_business_details: Vec<PrimaryBusinessDetails>, - - #[cfg(not(feature = "multiple_mca"))] #[schema(value_type = Option<PrimaryBusinessDetails>)] pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, @@ -603,21 +598,10 @@ pub struct MerchantConnectorCreate { ]))] pub frm_configs: Option<FrmConfigs>, - /// Business Country of the connector - #[cfg(feature = "multiple_mca")] #[schema(value_type = CountryAlpha2, example = "US")] pub business_country: api_enums::CountryAlpha2, - #[cfg(not(feature = "multiple_mca"))] - #[schema(value_type = Option<CountryAlpha2>, example = "US")] - pub business_country: Option<api_enums::CountryAlpha2>, - - ///Business Type of the merchant - #[schema(example = "travel")] - #[cfg(feature = "multiple_mca")] pub business_label: String, - #[cfg(not(feature = "multiple_mca"))] - pub business_label: Option<String>, /// Business Sub label of the merchant #[schema(example = "chase")] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index cccaaca5cb6..45091f0f61f 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -22,7 +22,6 @@ kv_store = [] accounts_cache = [] openapi = ["olap", "oltp", "payouts"] vergen = ["router_env/vergen"] -multiple_mca = ["api_models/multiple_mca"] dummy_connector = ["api_models/dummy_connector"] external_access_dc = ["dummy_connector"] detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 6db72e93f45..ebe22a49da0 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -38,31 +38,6 @@ pub fn create_merchant_publishable_key() -> String { ) } -fn get_primary_business_details( - request: &api::MerchantAccountCreate, -) -> Vec<PrimaryBusinessDetails> { - // In this case, business details is not optional, it will always be passed - #[cfg(feature = "multiple_mca")] - { - request.primary_business_details.to_owned() - } - - // In this case, business details will be optional, if it is not passed, then create the - // default value - #[cfg(not(feature = "multiple_mca"))] - { - request - .primary_business_details - .to_owned() - .unwrap_or_else(|| { - vec![PrimaryBusinessDetails { - country: enums::CountryAlpha2::US, - business: "default".to_string(), - }] - }) - } -} - pub async fn create_merchant_account( db: &dyn StorageInterface, req: api::MerchantAccountCreate, @@ -76,7 +51,7 @@ pub async fn create_merchant_account( let publishable_key = Some(create_merchant_publishable_key()); let primary_business_details = utils::Encode::<Vec<PrimaryBusinessDetails>>::encode_to_value( - &get_primary_business_details(&req), + &req.primary_business_details.unwrap_or_default(), ) .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "primary_business_details", @@ -383,27 +358,6 @@ async fn validate_merchant_id<S: Into<String>>( .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound) } -fn get_business_details_wrapper( - request: &api::MerchantConnectorCreate, - _merchant_account: &domain::MerchantAccount, -) -> RouterResult<(enums::CountryAlpha2, String)> { - #[cfg(feature = "multiple_mca")] - { - // The fields are mandatory - Ok((request.business_country, request.business_label.to_owned())) - } - - #[cfg(not(feature = "multiple_mca"))] - { - // If the value is not passed, then take it from Merchant account - helpers::get_business_details( - request.business_country, - request.business_label.as_ref(), - _merchant_account, - ) - } -} - fn validate_certificate_in_mca_metadata( connector_metadata: Secret<serde_json::Value>, ) -> RouterResult<()> { @@ -459,11 +413,15 @@ pub async fn create_payment_connector( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let (business_country, business_label) = get_business_details_wrapper(&req, &merchant_account)?; + helpers::validate_business_details( + req.business_country, + &req.business_label, + &merchant_account, + )?; let connector_label = helpers::get_connector_label( - business_country, - &business_label, + req.business_country, + &req.business_label, req.business_sub_label.as_ref(), &req.connector_name.to_string(), ); @@ -526,8 +484,8 @@ pub async fn create_payment_connector( metadata: req.metadata, frm_configs, connector_label: connector_label.clone(), - business_country, - business_label, + business_country: req.business_country, + business_label: req.business_label.clone(), business_sub_label: req.business_sub_label, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 66e9a305708..05a0f88ca0f 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1830,6 +1830,32 @@ pub fn get_connector_label( connector_label } +/// Check whether the business details are configured in the merchant account +pub fn validate_business_details( + business_country: api_enums::CountryAlpha2, + business_label: &String, + merchant_account: &domain::MerchantAccount, +) -> RouterResult<()> { + let primary_business_details = merchant_account + .primary_business_details + .clone() + .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to parse primary business details")?; + + primary_business_details + .iter() + .find(|business_details| { + &business_details.business == business_label + && business_details.country == business_country + }) + .ok_or(errors::ApiErrorResponse::PreconditionFailed { + message: "business_details are not configured in the merchant account".to_string(), + })?; + + Ok(()) +} + /// Do lazy parsing of primary business details /// If both country and label are passed, no need to parse business details from merchant_account /// If any one is missing, get it from merchant_account @@ -1840,42 +1866,29 @@ pub fn get_business_details( business_label: Option<&String>, merchant_account: &domain::MerchantAccount, ) -> RouterResult<(api_enums::CountryAlpha2, String)> { - let (business_country, business_label) = match business_country.zip(business_label) { - Some((business_country, business_label)) => { - (business_country.to_owned(), business_label.to_owned()) - } - None => { - // Parse the primary business details from merchant account - let primary_business_details: Vec<api_models::admin::PrimaryBusinessDetails> = - merchant_account - .primary_business_details - .clone() - .parse_value("PrimaryBusinessDetails") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to parse primary business details")?; + let primary_business_details = merchant_account + .primary_business_details + .clone() + .parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to parse primary business details")?; - if primary_business_details.len() == 1 { - let primary_business_details = primary_business_details.first().ok_or( - errors::ApiErrorResponse::MissingRequiredField { - field_name: "primary_business_details", - }, - )?; - ( - business_country.unwrap_or_else(|| primary_business_details.country.to_owned()), - business_label - .map(ToString::to_string) - .unwrap_or_else(|| primary_business_details.business.to_owned()), - ) - } else { - // If primary business details are not present or more than one - Err(report!(errors::ApiErrorResponse::MissingRequiredField { - field_name: "business_country, business_label" - }))? - } + match business_country.zip(business_label) { + Some((business_country, business_label)) => { + Ok((business_country.to_owned(), business_label.to_owned())) } - }; - - Ok((business_country, business_label)) + _ => match primary_business_details.first() { + Some(business_details) if primary_business_details.len() == 1 => Ok(( + business_country.unwrap_or_else(|| business_details.country.to_owned()), + business_label + .map(ToString::to_string) + .unwrap_or_else(|| business_details.business.to_owned()), + )), + _ => Err(report!(errors::ApiErrorResponse::MissingRequiredField { + field_name: "business_country, business_label" + })), + }, + } } #[inline] diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index e456f58a0e1..c3c2bae9896 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -586,11 +586,29 @@ impl PaymentCreate { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert order details to value")?; - let (business_country, business_label) = helpers::get_business_details( - request.business_country, - request.business_label.as_ref(), - merchant_account, - )?; + let (business_country, business_label) = + match (request.business_country, request.business_label.as_ref()) { + (Some(business_country), Some(business_label)) => { + helpers::validate_business_details( + business_country, + business_label, + merchant_account, + )?; + + Ok((business_country, business_label.clone())) + } + (None, Some(_)) => Err(errors::ApiErrorResponse::MissingRequiredField { + field_name: "business_country", + }), + (Some(_), None) => Err(errors::ApiErrorResponse::MissingRequiredField { + field_name: "business_label", + }), + (None, None) => Ok(helpers::get_business_details( + request.business_country, + request.business_label.as_ref(), + merchant_account, + )?), + }?; let allowed_payment_method_types = request .get_allowed_payment_method_types_as_value() diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 11ef305ffa3..2ba0b4a41c9 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5634,7 +5634,9 @@ "required": [ "connector_type", "connector_name", - "connector_label" + "connector_label", + "business_country", + "business_label" ], "properties": { "connector_type": { @@ -5730,16 +5732,10 @@ "nullable": true }, "business_country": { - "allOf": [ - { - "$ref": "#/components/schemas/CountryAlpha2" - } - ], - "nullable": true + "$ref": "#/components/schemas/CountryAlpha2" }, "business_label": { - "type": "string", - "nullable": true + "type": "string" }, "business_sub_label": { "type": "string",
2023-07-11T10:26:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Refactoring ## Description <!-- Describe your changes in detail --> This PR will remove the multiple mca feature. No fields will have default values in primary business details. - When creating merchant connector account, `business_label` and `business_country` are mandatory. A validation is added to ensure that the business details passed when creating connector account, are configured in the merchant account. - When creating the payment, if no business details (`business_country` and `business_label`) are passed then take it from the merchant account. If more than one business details are configured in the merchant account, then raise an error mentioning that business details are mandatory. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> - Create a merchant account, without primary business details - Create connector account without business details -> Error <img width="829" alt="Screenshot 2023-07-11 at 3 48 23 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/f5ac8294-b38b-48de-ab44-be5f7854aedc"> - Create connector account with business details -> Error <img width="785" alt="Screenshot 2023-07-11 at 3 47 56 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/76b8a6b3-f7cc-4148-9667-d5ed675a82c4"> - Create a payment without business data. <img width="718" alt="Screenshot 2023-07-11 at 3 50 58 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/977002fb-6f16-4a5e-903e-b25c4fabad6e"> - Create a payment with business data. <img width="829" alt="Screenshot 2023-07-11 at 3 51 43 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/ac3e03d2-5ee7-441a-994d-60c120cc7dcb"> - Create a merchant account with business data ( only one business detail ). - Create a payment without business data -> Take business data from merchant account. - Create a merchant account with business data ( two business details ). - Create a payment without business data. -> Error <img width="720" alt="Screenshot 2023-07-11 at 3 55 04 PM" src="https://github.com/juspay/hyperswitch/assets/48803246/7a864518-5dd0-4397-8557-194993999c4b"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
bad9b9482398bb624cb34ae7021837f7af6e8e00
juspay/hyperswitch
juspay__hyperswitch-6020
Bug: [REFACTOR]: [RAPYD] Add amount conversion framework to Rapyd ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.rapyd.net/en/create-refund.html) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index da10513b3d3..196eb4ce73d 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -1,11 +1,11 @@ pub mod transformers; -use std::fmt::Debug; use base64::Engine; use common_utils::{ date_time, ext_traits::{Encode, StringExt}, request::RequestContent, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use diesel_models::enums; use error_stack::{Report, ResultExt}; @@ -17,6 +17,7 @@ use transformers as rapyd; use super::utils as connector_utils; use crate::{ configs::settings, + connector::utils::convert_amount, consts, core::errors::{self, CustomResult}, events::connector_api_logs::ConnectorEvent, @@ -34,9 +35,17 @@ use crate::{ utils::{self, crypto, ByteSliceExt, BytesExt}, }; -#[derive(Debug, Clone)] -pub struct Rapyd; - +#[derive(Clone)] +pub struct Rapyd { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} +impl Rapyd { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl Rapyd { pub fn generate_signature( &self, @@ -198,12 +207,12 @@ impl req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = rapyd::RapydRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = rapyd::RapydRouterData::from((amount, req)); let connector_req = rapyd::RapydPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -528,12 +537,12 @@ impl req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = rapyd::RapydRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + let connector_router_data = rapyd::RapydRouterData::from((amount, req)); let connector_req = rapyd::CaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -668,12 +677,12 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref req: &types::RefundsRouterData<api::Execute>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = rapyd::RapydRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let connector_router_data = rapyd::RapydRouterData::from((amount, req)); let connector_req = rapyd::RapydRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 1246444ff31..b83ffcec412 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -1,3 +1,4 @@ +use common_utils::types::MinorUnit; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -15,25 +16,22 @@ use crate::{ #[derive(Debug, Serialize)] pub struct RapydRouterData<T> { - pub amount: i64, + pub amount: MinorUnit, pub router_data: 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): (&api::CurrencyUnit, enums::Currency, i64, T), - ) -> Result<Self, Self::Error> { - Ok(Self { +impl<T> From<(MinorUnit, T)> for RapydRouterData<T> { + fn from((amount, router_data): (MinorUnit, T)) -> Self { + Self { amount, - router_data: item, - }) + router_data, + } } } #[derive(Default, Debug, Serialize)] pub struct RapydPaymentsRequest { - pub amount: i64, + pub amount: MinorUnit, pub currency: enums::Currency, pub payment_method: PaymentMethod, pub payment_method_options: Option<PaymentMethodOptions>, @@ -302,7 +300,7 @@ pub struct DisputeResponseData { #[derive(Default, Debug, Serialize)] pub struct RapydRefundRequest { pub payment: String, - pub amount: Option<i64>, + pub amount: Option<MinorUnit>, pub currency: Option<enums::Currency>, } @@ -409,7 +407,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> #[derive(Debug, Serialize, Clone)] pub struct CaptureRequest { - amount: Option<i64>, + amount: Option<MinorUnit>, receipt_email: Option<Secret<String>>, statement_descriptor: Option<String>, } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index b85ae5bfab2..9c21340a7e9 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -471,7 +471,9 @@ impl ConnectorData { enums::Connector::Razorpay => { Ok(ConnectorEnum::Old(Box::new(connector::Razorpay::new()))) } - enums::Connector::Rapyd => Ok(ConnectorEnum::Old(Box::new(&connector::Rapyd))), + enums::Connector::Rapyd => { + Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new()))) + } enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) } diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs index fe6bc34cf18..ff083a37e59 100644 --- a/crates/router/tests/connectors/rapyd.rs +++ b/crates/router/tests/connectors/rapyd.rs @@ -16,7 +16,7 @@ impl utils::Connector for Rapyd { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Rapyd; utils::construct_connector_data_old( - Box::new(&Rapyd), + Box::new(Rapyd::new()), types::Connector::Rapyd, types::api::GetToken::Connector, None,
2024-10-23T13:43:06Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds amount conversion framework to rapyd. rapyd accepts amount in MinorUnit ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Amount conversion for rapyd Fixes #6020 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
cd6265887adf7c17136e9fb608e97e6dd535e360
juspay/hyperswitch
juspay__hyperswitch-6018
Bug: pass Samsung Pay `public_key_hash` in the confirm call The token received form Samsung Pay will be int the JWT format. The header of that will contain the `kid` which is the `public_key_hash`. This is needs to be passed to Cybersource in the confirm call.
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index f0b84fc93c1..810551e0cb7 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -130,6 +130,7 @@ impl ConnectorValidation for Adyen { } }, PaymentMethodType::Ach + | PaymentMethodType::SamsungPay | PaymentMethodType::Alma | PaymentMethodType::Bacs | PaymentMethodType::Givex @@ -222,7 +223,6 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::RedCompra | PaymentMethodType::RedPagos | PaymentMethodType::CryptoCurrency - | PaymentMethodType::SamsungPay | PaymentMethodType::Evoucher | PaymentMethodType::Cashapp | PaymentMethodType::UpiCollect diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 9c596f5575c..864f77b55dd 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -6,8 +6,13 @@ use api_models::{ }; use base64::Engine; use common_enums::FutureUsage; -use common_utils::{ext_traits::ValueExt, pii, types::SemanticVersion}; +use common_utils::{ + ext_traits::{OptionExt, ValueExt}, + pii, + types::SemanticVersion, +}; use error_stack::ResultExt; +use josekit::jwt::decode_header; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -457,6 +462,14 @@ pub struct SamsungPayPaymentInformation { tokenized_card: SamsungPayTokenizedCard, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SamsungPayFluidDataValue { + public_key_hash: Secret<String>, + version: String, + data: Secret<String>, +} + #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentInformation { @@ -1531,13 +1544,17 @@ impl let bill_to = build_bill_to(item.router_data.get_optional_billing(), email)?; let order_information = OrderInformationWithBill::from((item, Some(bill_to))); + let samsung_pay_fluid_data_value = + get_samsung_pay_fluid_data_value(&samsung_pay_data.payment_credential.token_data)?; + + let samsung_pay_fluid_data_str = serde_json::to_string(&samsung_pay_fluid_data_value) + .change_context(errors::ConnectorError::RequestEncodingFailed) + .attach_printable("Failed to serialize samsung pay fluid data")?; + let payment_information = PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation { fluid_data: FluidData { - value: Secret::from( - consts::BASE64_ENGINE - .encode(samsung_pay_data.payment_credential.token_data.data.peek()), - ), + value: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)), descriptor: Some( consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY), ), @@ -1571,6 +1588,28 @@ 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_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str()); + + let samsung_pay_fluid_data_value = SamsungPayFluidDataValue { + public_key_hash: Secret::new( + samsung_pay_kid_optional + .get_required_value("samsung pay public_key_hash") + .change_context(errors::ConnectorError::RequestEncodingFailed)? + .to_string(), + ), + version: samsung_pay_token_data.version.clone(), + data: Secret::new(consts::BASE64_ENGINE.encode(samsung_pay_token_data.data.peek())), + }; + Ok(samsung_pay_fluid_data_value) +} + impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> for CybersourcePaymentsRequest {
2024-09-25T05:31:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> The token received form Samsung Pay will be int the JWT format. The header of that will contain the `kid` which is the `public_key_hash`. This is needs to be passed to Cybersource in the confirm call. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test Samsung Pay flow -> Enable Samsung Pay payment method for the connector (Cybersource) ``` { "connector_type": "payment_processor", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_secret": "api_secret", "key1": "key1", "api_key": "api_key" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "invoke_sdk_client", "payment_method_type": "klarna" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "klarna" } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "Discover", "DinersClub" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "samsung_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_wallets_details": { "samsung_pay": { "service_id": "49400558c67f4a97b3925f", "merchant_display_name": "Hyperswitch", "merchant_business_country": "IN", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } }, "connector_webhook_details": { "merchant_secret": "merchant_secret" } } ``` -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \ --data '{ "amount": 100000, "currency": "INR", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1726743607" }' ``` ``` { "payment_id": "pay_9oXGqEDD6bQTYhbLvC40", "merchant_id": "merchant_1727087901", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P", "created": "2024-09-25T05:46:55.720Z", "currency": "USD", "customer_id": "cu_1727243216", "customer": { "id": "cu_1727243216", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1727243216", "created_at": 1727243215, "expires": 1727246815, "secret": "epk_af7b8c52b45e490bac3a87ec19188c46" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_avq4S1jpyTn6UkRb4hZc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-25T06:01:55.720Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-25T05:46:55.804Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Chrome' \ --header 'x-client-platform: web' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_3ccbd5ee07844da0a0f7f7b746c3465c' \ --data '{ "payment_id": "pay_9oXGqEDD6bQTYhbLvC40", "wallets": [], "client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P" }' ``` ``` { "payment_id": "pay_9oXGqEDD6bQTYhbLvC40", "client_secret": "pay_9oXGqEDD6bQTYhbLvC40_secret_oftRxCm8PcntUjgd7z4P", "session_token": [ { "wallet_name": "google_pay", "merchant_info": { "merchant_name": "Stripe" }, "shipping_address_required": false, "email_required": false, "shipping_address_parameters": { "phone_number_required": false }, "allowed_payment_methods": [ { "type": "CARD", "parameters": { "allowed_auth_methods": [ "PAN_ONLY", "CRYPTOGRAM_3DS" ], "allowed_card_networks": [ "AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA" ], "billing_address_required": false }, "tokenization_specification": { "type": "PAYMENT_GATEWAY", "parameters": { "gateway": "stripe", "stripe:version": "2018-10-31", "stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO" } } } ], "transaction_info": { "country_code": "US", "currency_code": "USD", "total_price_status": "Final", "total_price": "1000.00" }, "delayed_session_token": false, "connector": "cybersource", "sdk_next_action": { "next_action": "confirm" }, "secrets": null }, { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay_9oXGqEDD6bQTYhbLvC40", "merchant": { "name": "Hyperswitch", "url": "sdk-test-app.netlify.app", "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "1000.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout" }, "connector": "cybersource", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null } ] } ``` -> Confirm call ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_i7CIay3cWADIXr8SlfpZUYnlSri7K5xgVeUsaE31Lvms3KstLwTHVoOby02qzez9' \ --data-raw '{ "amount": 1, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 1, "customer_id": "custhype123", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "samsungpay@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "samsung_pay", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "samsung_pay": { "payment_credential": { "card_brand": "visa", "recurring_payment": false, "card_last4digits": "1661", "method": "3DS", "3_d_s": { "type": "S", "version": "100", "data": "eyJhbGciOiJSU0ExXzUiLCJraWQiOiJKdnI0ZlM1L0N0dmx6Ly95cGZYK2xkQ1p4dFBIUVBNUHg4SzI5Ty9lZm1JPSIsInR5cCI6IkpPU0UiLCJjaGFubmVsU2VjdXJpdHlDb250ZXh0IjoiUlNBX1BLSSIsImVuYyI6IkExMjhHQ00ifQ.PC27m6Zz5arTvQuQAVgUDl4fczWtG8lAQwybchbD6v7UYalTz0fIo45ZFHHmlol7Q087pbH_2KPfGAi2dc3i-Akao1I-e7sL5VO4W19MWtnfN1cF2RpMmHIlLuOrqNUcqJQ2WFqhXFpzr1C9hL47nWYc4tTScI2V4kdbERFxMIKpDIHH0SL1xGHl1v5l3oXeehY-sfMFEKpKqINHQs7mxZB0Cw9HLw6WvyJ2IBh-pgzEAvMSFrHpYI2TedKbVSafSDgmHfc6vLcfiHxNXenCiHYYRHEVqqu-MAJ1svfS31fZUCAv3NRLo4G886auZvc-XWaLrwTT-5EoaUsOo8BH6w.yQY3X4j_pVJ6o7Bu.ocIct0IUNZLaHhdbi3LVjWZ3bcy22_2vV-vD7JfwyPPIACGzrZmtdKSB6eEPdo7RGtWJQ2prmDYQsL3VUP9dKRnVGbpnGJsL5Cv5D4p9JX4iPrlgL5GeFNmhHsIFDNmVnepZ-swXhI1p4SzmTpwd16X8Hupt9lQXiTRPkerJHExCpqw3ZZCcTiV2sSm53wfeYOpXYZJ2DvIB51Hpsi1eHyI8F6dDqJ0h6XUBTZzy_5iLWVvuppS2.3RlqL07i3F_Zh_xzjTt_rA" } } } } } }' ``` ``` { "payment_id": "pay_R5DGXtaNE918aMsxrmmY", "merchant_id": "merchant_1727087901", "status": "succeeded", "amount": 1, "net_amount": 1, "amount_capturable": 0, "amount_received": 1, "connector": "cybersource", "client_secret": "pay_R5DGXtaNE918aMsxrmmY_secret_uYxRmMDDtbMNF0oJpFp5", "created": "2024-09-25T05:48:27.368Z", "currency": "USD", "customer_id": "custhype123", "customer": { "id": "custhype123", "name": "Joseph Doe", "email": "samsungpay@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "samsungpay@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "samsung_pay", "connector_label": "cybersource_US_default_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "custhype123", "created_at": 1727243307, "expires": 1727246907, "secret": "epk_26d63c60253046abb4e95d28c66addb5" }, "manual_retry_allowed": false, "connector_transaction_id": "7272433088196497503955", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_R5DGXtaNE918aMsxrmmY_1", "payment_link": null, "profile_id": "pro_avq4S1jpyTn6UkRb4hZc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_NMxxPseaV1nTfu7vHpR5", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-25T06:03:27.368Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-25T05:48:30.388Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2a10b09a2f7c6bcf0b9b7c23b5b88066e1d0f029
juspay/hyperswitch
juspay__hyperswitch-6028
Bug: [FEATURE] Implement Paze Wallet ### Feature Description Integrate paze wallet https://www.paze.com/ ### Possible Implementation Integrate paze wallet https://www.paze.com/ ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 388ccb79a66..44ac1d3e08d 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -5592,6 +5592,11 @@ "type": "object", "description": "This field contains the Samsung Pay certificates and credentials", "nullable": true + }, + "paze": { + "type": "object", + "description": "This field contains the Paze certificates and credentials", + "nullable": true } }, "additionalProperties": false @@ -12548,6 +12553,7 @@ "open_banking_uk", "pay_bright", "paypal", + "paze", "pix", "pay_safe_card", "przelewy24", @@ -17138,6 +17144,39 @@ } } }, + "PazeSessionTokenResponse": { + "type": "object", + "required": [ + "client_id", + "client_name", + "client_profile_id" + ], + "properties": { + "client_id": { + "type": "string", + "description": "Paze Client ID" + }, + "client_name": { + "type": "string", + "description": "Client Name to be displayed on the Paze screen" + }, + "client_profile_id": { + "type": "string", + "description": "Paze Client Profile ID" + } + } + }, + "PazeWalletData": { + "type": "object", + "required": [ + "complete_response" + ], + "properties": { + "complete_response": { + "type": "string" + } + } + }, "PhoneDetails": { "type": "object", "properties": { @@ -19377,6 +19416,27 @@ } ] }, + { + "allOf": [ + { + "$ref": "#/components/schemas/PazeSessionTokenResponse" + }, + { + "type": "object", + "required": [ + "wallet_name" + ], + "properties": { + "wallet_name": { + "type": "string", + "enum": [ + "paze" + ] + } + } + } + ] + }, { "type": "object", "required": [ @@ -20551,6 +20611,17 @@ } } }, + { + "type": "object", + "required": [ + "paze" + ], + "properties": { + "paze": { + "$ref": "#/components/schemas/PazeWalletData" + } + } + }, { "type": "object", "required": [ diff --git a/config/config.example.toml b/config/config.example.toml index 54f0d1a27a4..c0358d91a26 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -540,6 +540,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.stax] credit = { currency = "USD" } @@ -581,6 +582,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key 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 generated by RSA:2048 algorithm. Refer Hyperswitch Docs (https://docs.hyperswitch.io/hyperswitch-cloud/payment-methods-setup/wallets/apple-pay/ios-application/) to generate the private key +[paze_decrypt_keys] +paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365 +paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem + [applepay_merchant_configs] # Run below command to get common merchant identifier for applepay in shell # diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index db43cac979b..5dce5be9c96 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -29,6 +29,10 @@ apple_pay_ppc_key = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY" # Private key 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 generated by RSA:2048 algorithm. Refer Hyperswitch Docs (https://docs.hyperswitch.io/hyperswitch-cloud/payment-methods-setup/wallets/apple-pay/ios-application/) to generate the private key +[paze_decrypt_keys] +paze_private_key = "PAZE_PRIVATE_KEY" # Base 64 Encoded Private Key File cakey.pem generated for Paze -> Command to create private key: openssl req -newkey rsa:2048 -x509 -keyout cakey.pem -out cacert.pem -days 365 +paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" # PEM Passphrase used for generating Private Key File cakey.pem + [applepay_merchant_configs] common_merchant_identifier = "APPLE_PAY_COMMON_MERCHANT_IDENTIFIER" # Refer to config.example.toml to learn how you can generate this value merchant_cert = "APPLE_PAY_MERCHANT_CERTIFICATE" # Merchant Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Merchant Identity Certificate diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index dbb4161ec5d..4f742a61698 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -307,6 +307,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/deployments/production.toml b/config/deployments/production.toml index c100ccf46de..c25b70d6ba0 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -281,6 +281,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 89aea282764..28f5a4e0575 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -284,6 +284,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/config/development.toml b/config/development.toml index f0e26172514..0153c6ef102 100644 --- a/config/development.toml +++ b/config/development.toml @@ -453,6 +453,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } @@ -617,6 +618,10 @@ 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" +[paze_decrypt_keys] +paze_private_key = "PAZE_PRIVATE_KEY" +paze_private_key_passphrase = "PAZE_PRIVATE_KEY_PASSPHRASE" + [generic_link] [generic_link.payment_method_collect] sdk_url = "http://localhost:9050/HyperLoader.js" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 1b9ef294dc0..5ffe5df138f 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -420,6 +420,7 @@ debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } samsung_pay = { currency = "USD,GBP,EUR" } +paze = { currency = "USD" } [pm_filters.nexixpay] credit = { country = "AT,BE,CY,EE,FI,FR,DE,GR,IE,IT,LV,LT,LU,MT,NL,PT,SK,SI,ES,BG,HR,DK,GB,NO,PL,CZ,RO,SE,CH,HU", currency = "ARS,AUD,BHD,CAD,CLP,CNY,COP,HRK,CZK,DKK,HKD,HUF,INR,JPY,KZT,JOD,KRW,KWD,MYR,MXN,NGN,NOK,PHP,QAR,RUB,SAR,SGD,VND,ZAR,SEK,CHF,THB,AED,EGP,GBP,USD,TWD,BYN,RSD,AZN,RON,TRY,AOA,BGN,EUR,UAH,PLN,BRL" } diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 6e7f4f29d03..8f24bdf65bc 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1558,6 +1558,10 @@ pub struct ConnectorWalletDetails { #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub samsung_pay: Option<pii::SecretSerdeValue>, + /// This field contains the Paze certificates and credentials + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option<Object>)] + pub paze: Option<pii::SecretSerdeValue>, } /// 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." diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 9cafc37af54..a758d457858 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1930,6 +1930,7 @@ impl GetPaymentMethodType for WalletData { Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, + Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, @@ -2819,6 +2820,8 @@ pub enum WalletData { PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), + /// The wallet data for Paze + Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection @@ -2879,6 +2882,7 @@ impl GetAddressFromPaymentMethodData for WalletData { | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) + | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} @@ -2891,6 +2895,13 @@ impl GetAddressFromPaymentMethodData for WalletData { } } +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct PazeWalletData { + #[schema(value_type = String)] + pub complete_response: Secret<String>, +} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { @@ -4932,6 +4943,19 @@ pub struct GpaySessionTokenData { pub data: GpayMetaData, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PazeSessionTokenData { + #[serde(rename = "paze")] + pub data: PazeMetadata, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PazeMetadata { + pub client_id: String, + pub client_name: String, + pub client_profile_id: String, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { @@ -5138,10 +5162,23 @@ pub enum SessionToken { ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), + /// The session response structure for Paze + Paze(Box<PazeSessionTokenResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct PazeSessionTokenResponse { + /// Paze Client ID + pub client_id: String, + /// Client Name to be displayed on the Paze screen + pub client_name: String, + /// Paze Client Profile ID + pub client_profile_id: String, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 528f38ac61a..5ab05c9a688 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1593,6 +1593,7 @@ pub enum PaymentMethodType { OpenBankingUk, PayBright, Paypal, + Paze, Pix, PaySafeCard, Przelewy24, diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index db4162a8bb1..4fba749ef63 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1843,6 +1843,7 @@ impl From<PaymentMethodType> for PaymentMethod { PaymentMethodType::OnlineBankingThailand => Self::BankRedirect, PaymentMethodType::OnlineBankingPoland => Self::BankRedirect, PaymentMethodType::OnlineBankingSlovakia => Self::BankRedirect, + PaymentMethodType::Paze => Self::Wallet, PaymentMethodType::PermataBankTransfer => Self::BankTransfer, PaymentMethodType::Pix => Self::BankTransfer, PaymentMethodType::Pse => Self::BankTransfer, diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 68ade2909b4..88997691eb6 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -56,7 +56,10 @@ impl DashboardRequestPayload { | (Connector::Stripe, WeChatPay) => { Some(api_models::enums::PaymentExperience::DisplayQrCode) } - (_, GooglePay) | (_, ApplePay) | (_, PaymentMethodType::SamsungPay) => { + (_, GooglePay) + | (_, ApplePay) + | (_, PaymentMethodType::SamsungPay) + | (_, PaymentMethodType::Paze) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } _ => Some(api_models::enums::PaymentExperience::RedirectToUrl), diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs index 0d2f959c702..136cdf4d981 100644 --- a/crates/euclid/src/frontend/dir/enums.rs +++ b/crates/euclid/src/frontend/dir/enums.rs @@ -91,6 +91,7 @@ pub enum WalletType { Cashapp, Venmo, Mifinity, + Paze, } #[derive( diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs index 33d368e9696..da589ec3748 100644 --- a/crates/euclid/src/frontend/dir/lowering.rs +++ b/crates/euclid/src/frontend/dir/lowering.rs @@ -58,6 +58,7 @@ impl From<enums::WalletType> for global_enums::PaymentMethodType { enums::WalletType::Cashapp => Self::Cashapp, enums::WalletType::Venmo => Self::Venmo, enums::WalletType::Mifinity => Self::Mifinity, + enums::WalletType::Paze => Self::Paze, } } } diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs index 3e35bcd391c..de0b619b120 100644 --- a/crates/euclid/src/frontend/dir/transformers.rs +++ b/crates/euclid/src/frontend/dir/transformers.rs @@ -188,6 +188,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet global_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } + global_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), } } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index eab8d878f05..c4ca017cec7 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -366,6 +366,9 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { FiuuPaymentMethodData::try_from(decrypt_data) } + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Fiuu"))? + } } } WalletData::AliPayQr(_) @@ -384,6 +387,7 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) + | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} diff --git a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs index 4986e8d5f32..772f2af209e 100644 --- a/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/globepay/transformers.rs @@ -74,6 +74,7 @@ impl TryFrom<&GlobepayRouterData<&types::PaymentsAuthorizeRouterData>> for Globe | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) + | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} diff --git a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs index d0525921632..a12434a460a 100644 --- a/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/mollie/transformers.rs @@ -182,6 +182,9 @@ impl TryFrom<&MollieRouterData<&types::PaymentsAuthorizeRouterData>> for MollieP "Mollie" ))? } + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Mollie"))? + } }), }, ))) diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index 4e2b30a574b..ad09e7445d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -119,6 +119,7 @@ impl TryFrom<(&types::TokenizationRouterData, WalletData)> for SquareTokenReques | WalletData::MobilePayRedirect(_) | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) + | WalletData::Paze(_) | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} @@ -263,6 +264,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for SquarePaymentsRequest { PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Square"), )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Square"))? + } }, amount_money: SquarePaymentsAmountData { amount: item.request.amount, diff --git a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs index f7b2016a370..686178e9621 100644 --- a/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/stax/transformers.rs @@ -82,6 +82,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"), )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Stax"))? + } }, idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) @@ -99,6 +102,9 @@ impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPayme PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"), )?, + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Stax"))? + } }, idempotency_id: Some(item.router_data.connector_request_reference_id.clone()), }) diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 4c7c9adaf8e..66b8081b0f2 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1781,6 +1781,7 @@ pub enum PaymentMethodDataType { MobilePayRedirect, PaypalRedirect, PaypalSdk, + Paze, SamsungPay, TwintRedirect, VippsRedirect, @@ -1898,6 +1899,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType { hyperswitch_domain_models::payment_method_data::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, hyperswitch_domain_models::payment_method_data::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, hyperswitch_domain_models::payment_method_data::WalletData::PaypalSdk(_) => Self::PaypalSdk, + hyperswitch_domain_models::payment_method_data::WalletData::Paze(_) => Self::Paze, hyperswitch_domain_models::payment_method_data::WalletData::SamsungPay(_) => Self::SamsungPay, hyperswitch_domain_models::payment_method_data::WalletData::TwintRedirect {} => Self::TwintRedirect, hyperswitch_domain_models::payment_method_data::WalletData::VippsRedirect {} => Self::VippsRedirect, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 9f505f26712..3ccfabf021c 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -117,6 +117,7 @@ pub enum WalletData { MobilePayRedirect(Box<MobilePayRedirection>), PaypalRedirect(PaypalRedirection), PaypalSdk(PayPalWalletData), + Paze(PazeWalletData), SamsungPay(Box<SamsungPayWalletData>), TwintRedirect {}, VippsRedirect {}, @@ -134,6 +135,12 @@ pub struct MifinityData { pub language_preference: Option<String>, } +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct PazeWalletData { + pub complete_response: Secret<String>, +} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { @@ -689,6 +696,9 @@ impl From<api_models::payments::WalletData> for WalletData { token: paypal_sdk_data.token, }) } + api_models::payments::WalletData::Paze(paze_data) => { + Self::Paze(PazeWalletData::from(paze_data)) + } api_models::payments::WalletData::SamsungPay(samsung_pay_data) => { Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data))) } @@ -754,6 +764,14 @@ impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData { } } +impl From<api_models::payments::PazeWalletData> for PazeWalletData { + fn from(value: api_models::payments::PazeWalletData) -> Self { + Self { + complete_response: value.complete_response, + } + } +} + impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData { fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self { Self { @@ -1388,6 +1406,7 @@ impl GetPaymentMethodType for WalletData { Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, + Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index cd8ac85594e..b41b42eaa2d 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -220,6 +220,7 @@ pub struct AccessToken { pub enum PaymentMethodToken { Token(Secret<String>), ApplePayDecrypt(Box<ApplePayPredecryptData>), + PazeDecrypt(Box<PazeDecryptedData>), } #[derive(Debug, Clone, serde::Deserialize)] @@ -241,6 +242,69 @@ pub struct ApplePayCryptogramData { pub eci_indicator: Option<String>, } +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeDecryptedData { + pub client_id: Secret<String>, + pub profile_id: String, + pub token: PazeToken, + pub payment_card_network: common_enums::enums::CardNetwork, + pub dynamic_data: Vec<PazeDynamicData>, + pub billing_address: PazeAddress, + pub consumer: PazeConsumer, + pub eci: Option<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeToken { + pub payment_token: cards::CardNumber, + pub token_expiration_month: Secret<String>, + pub token_expiration_year: Secret<String>, + pub payment_account_reference: Secret<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeDynamicData { + pub dynamic_data_value: Option<Secret<String>>, + pub dynamic_data_type: Option<String>, + pub dynamic_data_expiration: Option<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeAddress { + pub name: Option<Secret<String>>, + pub line1: Option<Secret<String>>, + pub line2: Option<Secret<String>>, + pub line3: Option<Secret<String>>, + pub city: Option<Secret<String>>, + pub state: Option<Secret<String>>, + pub zip: Option<Secret<String>>, + pub country_code: Option<common_enums::enums::CountryAlpha2>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazeConsumer { + // This is consumer data not customer data. + pub first_name: Option<Secret<String>>, + pub last_name: Option<Secret<String>>, + pub full_name: Secret<String>, + pub email_address: common_utils::pii::Email, + pub mobile_number: Option<PazePhoneNumber>, + pub country_code: Option<common_enums::enums::CountryAlpha2>, + pub language_code: Option<String>, +} + +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PazePhoneNumber { + pub country_code: Secret<String>, + pub phone_number: Secret<String>, +} + #[derive(Debug, Default, Clone)] pub struct RecurringMandatePaymentData { pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 2ec0cbe8031..e897292d6ff 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -146,6 +146,7 @@ fn get_dir_value_payment_method( api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } + api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), } } diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs index 758a0dd3de0..1a340aa91d3 100644 --- a/crates/kgraph_utils/src/transformers.rs +++ b/crates/kgraph_utils/src/transformers.rs @@ -307,6 +307,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) { api_enums::PaymentMethodType::OpenBankingPIS => { Ok(dirval!(OpenBankingType = OpenBankingPIS)) } + api_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)), } } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index a76726eb8ac..24fbadc0a59 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -389,6 +389,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsCaptureRequest, api_models::payments::PaymentsSessionRequest, api_models::payments::PaymentsSessionResponse, + api_models::payments::PazeWalletData, api_models::payments::SessionToken, api_models::payments::ApplePaySessionResponse, api_models::payments::ThirdPartySdkSessionResponse, @@ -445,6 +446,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayRedirectData, api_models::payments::GooglePayThirdPartySdk, api_models::payments::GooglePaySessionResponse, + api_models::payments::PazeSessionTokenResponse, api_models::payments::SamsungPaySessionTokenResponse, api_models::payments::SamsungPayMerchantPaymentInformation, api_models::payments::SamsungPayAmountDetails, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 05a2c72ba94..bc44068030b 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -323,6 +323,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::PaymentsSessionResponse, api_models::payments::PaymentsCreateIntentRequest, api_models::payments::PaymentsCreateIntentResponse, + api_models::payments::PazeWalletData, api_models::payments::AmountDetails, api_models::payments::SessionToken, api_models::payments::ApplePaySessionResponse, @@ -358,6 +359,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayPaymentMethodInfo, api_models::payments::ApplePayWalletData, api_models::payments::ApplepayPaymentMethod, + api_models::payments::PazeSessionTokenResponse, api_models::payments::SamsungPaySessionTokenResponse, api_models::payments::SamsungPayMerchantPaymentInformation, api_models::payments::SamsungPayAmountDetails, diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 0f25477802c..dbdba189ed1 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -178,6 +178,27 @@ impl SecretsHandler for settings::ApplePayDecryptConfig { } } +#[async_trait::async_trait] +impl SecretsHandler for settings::PazeDecryptConfig { + async fn convert_to_raw_secret( + value: SecretStateContainer<Self, SecuredSecret>, + secret_management_client: &dyn SecretManagementInterface, + ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { + let paze_decrypt_keys = value.get_inner(); + + let (paze_private_key, paze_private_key_passphrase) = tokio::try_join!( + secret_management_client.get_secret(paze_decrypt_keys.paze_private_key.clone()), + secret_management_client + .get_secret(paze_decrypt_keys.paze_private_key_passphrase.clone()), + )?; + + Ok(value.transition_state(|_| Self { + paze_private_key, + paze_private_key_passphrase, + })) + } +} + #[async_trait::async_trait] impl SecretsHandler for settings::ApplepayMerchantConfigs { async fn convert_to_raw_secret( @@ -388,6 +409,17 @@ pub(crate) async fn fetch_raw_secrets( .await .expect("Failed to decrypt applepay decrypt configs"); + #[allow(clippy::expect_used)] + let paze_decrypt_keys = if let Some(paze_keys) = conf.paze_decrypt_keys { + Some( + settings::PazeDecryptConfig::convert_to_raw_secret(paze_keys, secret_management_client) + .await + .expect("Failed to decrypt paze decrypt configs"), + ) + } else { + None + }; + #[allow(clippy::expect_used)] let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret( conf.applepay_merchant_configs, @@ -479,6 +511,7 @@ pub(crate) async fn fetch_raw_secrets( #[cfg(feature = "payouts")] payouts: conf.payouts, applepay_decrypt_keys, + paze_decrypt_keys, multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors, applepay_merchant_configs, lock_settings: conf.lock_settings, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1124423714b..149ee2b8456 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -96,6 +96,7 @@ pub struct Settings<S: SecretState> { pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, + pub paze_decrypt_keys: Option<SecretStateContainer<PazeDecryptConfig, S>>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, @@ -723,6 +724,12 @@ pub struct ApplePayDecryptConfig { pub apple_pay_merchant_cert_key: Secret<String>, } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct PazeDecryptConfig { + pub paze_private_key: Secret<String>, + pub paze_private_key_passphrase: Secret<String>, +} + #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct LockerBasedRecipientConnectorList { @@ -864,6 +871,11 @@ impl Settings<SecuredSecret> { .map(|x| x.get_inner().validate()) .transpose()?; + self.paze_decrypt_keys + .as_ref() + .map(|x| x.get_inner().validate()) + .transpose()?; + self.key_manager.get_inner().validate()?; Ok(()) diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index f109fe3f773..7040998ccf0 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -236,6 +236,27 @@ impl super::settings::NetworkTokenizationService { } } +impl super::settings::PazeDecryptConfig { + pub fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::fp_utils::when; + + when(self.paze_private_key.is_default_or_empty(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "paze_private_key must not be empty".into(), + )) + })?; + + when( + self.paze_private_key_passphrase.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "paze_private_key_passphrase must not be empty".into(), + )) + }, + ) + } +} + impl super::settings::KeyManagerConfig { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 46f312b38f2..abd99fae18c 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -120,6 +120,7 @@ impl TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> for Pay | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect { .. } | domain::WalletData::VippsRedirect { .. } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 810551e0cb7..e5215022e94 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -218,6 +218,7 @@ impl ConnectorValidation for Adyen { | PaymentMethodType::Pse | PaymentMethodType::LocalBankTransfer | PaymentMethodType::Efecty + | PaymentMethodType::Paze | PaymentMethodType::PagoEfectivo | PaymentMethodType::PromptPay | PaymentMethodType::RedCompra diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 50ce6aea0f4..4cc392c57bc 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2149,6 +2149,7 @@ impl<'a> TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> | domain::WalletData::GooglePayRedirect(_) | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::WeChatPayQr(_) | domain::WalletData::CashappQr(_) | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented( diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 4d84f64534e..868a4767c31 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -254,6 +254,7 @@ fn get_wallet_details( | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 868409dafc7..e352d8b79bc 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -1747,6 +1747,7 @@ fn get_wallet_data( | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index b987a6717a1..ab6367eeb6e 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -297,6 +297,7 @@ impl TryFrom<&types::SetupMandateRouterData> for BankOfAmericaPaymentsRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -977,6 +978,9 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> "Bank Of America" ))? } + types::PaymentMethodToken::PazeDecrypt(_) => Err( + unimplemented_payment_method!("Paze", "Bank Of America"), + )?, }, None => { let email = item.router_data.request.get_email()?; @@ -1051,6 +1055,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -2328,6 +2333,9 @@ impl TryFrom<(&types::SetupMandateRouterData, domain::ApplePayWalletData)> "Manual", "Bank Of America" ))?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Bank Of America"))? + } }, None => PaymentInformation::from(&apple_pay_data), }; diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 6ebcdf0e765..b156aafb6ef 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -369,6 +369,7 @@ impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for Blues | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs index 5fd6b0e6a2e..a48e49a10cc 100644 --- a/crates/router/src/connector/boku/transformers.rs +++ b/crates/router/src/connector/boku/transformers.rs @@ -180,6 +180,7 @@ fn get_wallet_type(wallet_data: &domain::WalletData) -> Result<String, errors::C | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 05d8c1c559d..29f741d8bdc 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -1591,6 +1591,9 @@ impl types::PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Braintree"))? + } }, transaction: transaction_body, }, @@ -1689,6 +1692,9 @@ fn get_braintree_redirect_form( "Simplified", "Braintree" ))?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Braintree"))? + } }, bin: match card_details { domain::PaymentMethodData::Card(card_details) => { diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 223256155cf..2950fdb6bd1 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -106,6 +106,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -301,6 +302,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme types::PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Checkout"))? + } }, })), domain::WalletData::ApplePay(_) => { @@ -327,6 +331,9 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme }, ))) } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Checkout"))? + } } } domain::WalletData::AliPayQr(_) @@ -345,6 +352,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 38bb016ff25..8a6c3c075ff 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -176,6 +176,9 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { types::PaymentMethodToken::Token(_) => Err( unimplemented_payment_method!("Apple Pay", "Manual", "Cybersource"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Cybersource"))? + } }, None => ( PaymentInformation::ApplePayToken(Box::new( @@ -221,6 +224,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1322,6 +1326,92 @@ impl } } +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + Box<hyperswitch_domain_models::router_data::PazeDecryptedData>, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, paze_data): ( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + Box<hyperswitch_domain_models::router_data::PazeDecryptedData>, + ), + ) -> Result<Self, Self::Error> { + let email = item.router_data.request.get_email()?; + let (first_name, last_name) = match paze_data.billing_address.name { + Some(name) => { + let (first_name, last_name) = name + .peek() + .split_once(' ') + .map(|(first, last)| (first.to_string(), last.to_string())) + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "billing_address.name", + })?; + (Secret::from(first_name), Secret::from(last_name)) + } + None => ( + item.router_data.get_billing_first_name()?, + item.router_data.get_billing_last_name()?, + ), + }; + let bill_to = BillTo { + first_name: Some(first_name), + last_name: Some(last_name), + address1: paze_data.billing_address.line1, + locality: paze_data.billing_address.city.map(|city| city.expose()), + administrative_area: Some(Secret::from( + //Paze wallet is currently supported in US only + common_enums::UsStatesAbbreviation::foreign_try_from( + paze_data + .billing_address + .state + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "billing_address.state", + })? + .peek() + .to_owned(), + )? + .to_string(), + )), + postal_code: paze_data.billing_address.zip, + country: paze_data.billing_address.country_code, + email, + }; + let order_information = OrderInformationWithBill::from((item, Some(bill_to))); + + let payment_information = + PaymentInformation::NetworkToken(Box::new(NetworkTokenPaymentInformation { + tokenized_card: NetworkTokenizedCard { + number: paze_data.token.payment_token, + expiration_month: paze_data.token.token_expiration_month, + expiration_year: paze_data.token.token_expiration_year, + cryptogram: Some(paze_data.token.payment_account_reference), + transaction_type: "1".to_string(), + }, + })); + + let processing_information = ProcessingInformation::try_from((item, None, None))?; + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information: None, + merchant_defined_information, + }) + } +} + impl TryFrom<( &CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>, @@ -1645,6 +1735,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> "Cybersource" ))? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Cybersource"))? + } }, None => { let email = item @@ -1719,6 +1812,19 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> domain::WalletData::SamsungPay(samsung_pay_data) => { Self::try_from((item, samsung_pay_data)) } + domain::WalletData::Paze(_) => { + match item.router_data.payment_method_token.clone() { + Some(types::PaymentMethodToken::PazeDecrypt( + paze_decrypted_data, + )) => Self::try_from((item, paze_decrypted_data)), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message( + "Cybersource", + ), + ) + .into()), + } + } domain::WalletData::AliPayQr(_) | domain::WalletData::AliPayRedirect(_) | domain::WalletData::AliPayHkRedirect(_) diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index ff2f9d95026..4982aaf4d88 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -429,7 +429,8 @@ impl TryFrom<&types::SetupMandateRouterData> for GocardlessMandateRequest { let payment_method_token = item.get_payment_method_token()?; let customer_bank_account = match payment_method_token { types::PaymentMethodToken::Token(token) => Ok(token), - types::PaymentMethodToken::ApplePayDecrypt(_) => { + types::PaymentMethodToken::ApplePayDecrypt(_) + | types::PaymentMethodToken::PazeDecrypt(_) => { Err(errors::ConnectorError::NotImplemented( "Setup Mandate flow for selected payment method through Gocardless".to_string(), )) diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 0e6fab80584..2c3d3651284 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -598,6 +598,7 @@ impl | common_enums::PaymentMethodType::OpenBankingUk | common_enums::PaymentMethodType::PayBright | common_enums::PaymentMethodType::Paypal + | common_enums::PaymentMethodType::Paze | common_enums::PaymentMethodType::Pix | common_enums::PaymentMethodType::PaySafeCard | common_enums::PaymentMethodType::Przelewy24 diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs index 0af3826c877..92b6b45785d 100644 --- a/crates/router/src/connector/mifinity/transformers.rs +++ b/crates/router/src/connector/mifinity/transformers.rs @@ -169,6 +169,7 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index 547a38ad849..e0146bf2eda 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -493,6 +493,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -556,6 +557,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -714,6 +716,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 55b2fbe4176..5bf72133384 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -722,6 +722,7 @@ fn get_wallet_details( | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect { .. } | domain::WalletData::VippsRedirect { .. } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index 069a51ae52e..57b04cdca17 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -558,6 +558,7 @@ impl | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 5d987174273..99e04018632 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -326,6 +326,7 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index f280d3a42a2..d9728174f84 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -914,6 +914,7 @@ where | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index e0ab598d76d..b4aa66a1c49 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -403,6 +403,7 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -715,6 +716,9 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest { types::PaymentMethodToken::ApplePayDecrypt(_) => Err( unimplemented_payment_method!("Apple Pay", "Simplified", "Payme"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Payme"))? + } }; Ok(Self { buyer_email, diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 4f5ab133735..41fd533309e 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -490,6 +490,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index 13c0395cf9f..e206fe0e0ae 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -282,6 +282,7 @@ impl TryFrom<&domain::WalletData> for Shift4PaymentMethod { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index f9fd519241a..68bab815d65 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -737,6 +737,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { | enums::PaymentMethodType::MandiriVa | enums::PaymentMethodType::PermataBankTransfer | enums::PaymentMethodType::PaySafeCard + | enums::PaymentMethodType::Paze | enums::PaymentMethodType::Givex | enums::PaymentMethodType::Benefit | enums::PaymentMethodType::Knet @@ -1062,6 +1063,7 @@ impl ForeignTryFrom<&domain::WalletData> for Option<StripePaymentMethodType> { | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1478,6 +1480,7 @@ impl TryFrom<(&domain::WalletData, Option<types::PaymentMethodToken>)> for Strip | domain::WalletData::GooglePayThirdPartySdk(_) | domain::WalletData::MbWayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1809,6 +1812,9 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntent wallet_name: "Apple Pay".to_string(), })? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(crate::unimplemented_payment_method!("Paze", "Stripe"))? + } }; Some(StripePaymentMethodData::Wallet( StripeWallet::ApplepayPayment(ApplepayPayment { diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index c66e1f2f65c..31afb0adf11 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2638,6 +2638,7 @@ pub enum PaymentMethodDataType { MobilePayRedirect, PaypalRedirect, PaypalSdk, + Paze, SamsungPay, TwintRedirect, VippsRedirect, @@ -2755,6 +2756,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { domain::payments::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, domain::payments::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, domain::payments::WalletData::PaypalSdk(_) => Self::PaypalSdk, + domain::payments::WalletData::Paze(_) => Self::Paze, domain::payments::WalletData::SamsungPay(_) => Self::SamsungPay, domain::payments::WalletData::TwintRedirect {} => Self::TwintRedirect, domain::payments::WalletData::VippsRedirect {} => Self::VippsRedirect, diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index be3cf4a1cef..ee34c26d670 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -135,6 +135,9 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest { types::PaymentMethodToken::Token(_) => Err( unimplemented_payment_method!("Apple Pay", "Manual", "Wellsfargo"), )?, + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Wellsfargo"))? + } }, None => ( PaymentInformation::ApplePayToken(Box::new( @@ -180,6 +183,7 @@ impl TryFrom<&types::SetupMandateRouterData> for WellsfargoZeroMandateRequest { | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} @@ -1158,6 +1162,9 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>> "Wellsfargo" ))? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Wellsfargo"))? + } }, None => { let email = item.router_data.request.get_email()?; @@ -1242,6 +1249,7 @@ impl TryFrom<&WellsfargoRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index de82e11548c..467a1cba902 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -83,6 +83,7 @@ fn fetch_payment_instrument( | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index d2e8ce40283..2b2e7e889e2 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -486,6 +486,7 @@ impl | domain::WalletData::MbWayRedirect(_) | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalSdk(_) + | domain::WalletData::Paze(_) | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c56bfaca913..aa4ff406a2c 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -234,6 +234,16 @@ pub enum ApplePayDecryptionError { DerivingSharedSecretKeyFailed, } +#[derive(Debug, thiserror::Error)] +pub enum PazeDecryptionError { + #[error("Failed to base64 decode input data")] + Base64DecodingFailed, + #[error("Failed to decrypt input data")] + DecryptionFailed, + #[error("Certificate parsing failed")] + CertificateParsingFailed, +} + #[cfg(feature = "detailed_errors")] pub mod error_stack_parsing { diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 9f904116171..363d52cd8bf 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -34,13 +34,13 @@ use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; use error_stack::{report, ResultExt}; use events::EventInfo; use futures::future::join_all; -use helpers::ApplePayData; +use helpers::{decrypt_paze_token, ApplePayData}; #[cfg(feature = "v2")] use hyperswitch_domain_models::payments::PaymentIntentData; pub use hyperswitch_domain_models::{ mandates::{CustomerAcceptance, MandateData}, payment_address::PaymentAddress, - router_data::RouterData, + router_data::{PaymentMethodToken, RouterData}, router_request_types::CustomerDetails, }; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -1710,42 +1710,12 @@ where &call_connector_action, ); - // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay - // and the connector supports Apple Pay predecrypt - match &tokenization_action { - TokenizationAction::DecryptApplePayToken(payment_processing_details) - | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( - payment_processing_details, - ) => { - let apple_pay_data = match payment_data.get_payment_method_data() { - Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( - wallet_data, - ))) => Some( - ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone())) - .change_context(errors::ApiErrorResponse::InternalServerError)? - .decrypt( - &payment_processing_details.payment_processing_certificate, - &payment_processing_details.payment_processing_certificate_key, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?, - ), - _ => None, - }; - - let apple_pay_predecrypt = apple_pay_data - .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( - "ApplePayPredecryptData", - ) - .change_context(errors::ApiErrorResponse::InternalServerError)?; - - router_data.payment_method_token = Some( - hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt( - Box::new(apple_pay_predecrypt), - ), - ); - } - _ => (), + router_data.payment_method_token = if let Some(decrypted_token) = + add_decrypted_payment_method_token(tokenization_action.clone(), payment_data).await? + { + Some(decrypted_token) + } else { + router_data.payment_method_token }; let payment_method_token_response = router_data @@ -1853,6 +1823,83 @@ where Ok((router_data, merchant_connector_account)) } +pub async fn add_decrypted_payment_method_token<F, D>( + tokenization_action: TokenizationAction, + payment_data: &D, +) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> +where + F: Send + Clone + Sync, + D: OperationSessionGetters<F> + Send + Sync + Clone, +{ + // Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay + // and the connector supports Apple Pay predecrypt + match &tokenization_action { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) => { + let apple_pay_data = match payment_data.get_payment_method_data() { + Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay( + wallet_data, + ))) => Some( + ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data.clone())) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to parse apple pay token to json")? + .decrypt( + &payment_processing_details.payment_processing_certificate, + &payment_processing_details.payment_processing_certificate_key, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to decrypt apple pay token")?, + ), + _ => None, + }; + + let apple_pay_predecrypt = apple_pay_data + .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>( + "ApplePayPredecryptData", + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "failed to parse decrypted apple pay response to ApplePayPredecryptData", + )?; + + Ok(Some(PaymentMethodToken::ApplePayDecrypt(Box::new( + apple_pay_predecrypt, + )))) + } + TokenizationAction::DecryptPazeToken(payment_processing_details) => { + let paze_data = match payment_data.get_payment_method_data() { + Some(domain::PaymentMethodData::Wallet(domain::WalletData::Paze(wallet_data))) => { + Some( + decrypt_paze_token( + wallet_data.clone(), + payment_processing_details.paze_private_key.clone(), + payment_processing_details + .paze_private_key_passphrase + .clone(), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to decrypt paze token")?, + ) + } + _ => None, + }; + let paze_decrypted_data = paze_data + .parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>( + "PazeDecryptedData", + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to parse PazeDecryptedData")?; + Ok(Some(PaymentMethodToken::PazeDecrypt(Box::new( + paze_decrypted_data, + )))) + } + _ => Ok(None), + } +} + pub async fn get_merchant_bank_data_for_open_banking_connectors( merchant_connector_account: &helpers::MerchantConnectorAccountType, key_store: &domain::MerchantKeyStore, @@ -2642,59 +2689,87 @@ async fn decide_payment_method_tokenize_action( pm_parent_token: Option<&str>, is_connector_tokenization_enabled: bool, apple_pay_flow: Option<domain::ApplePayFlow>, + payment_method_type: Option<storage_enums::PaymentMethodType>, ) -> RouterResult<TokenizationAction> { - match pm_parent_token { - None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { - (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( - payment_processing_details, - ) - } - (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, - (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::DecryptApplePayToken(payment_processing_details) - } - (false, _) => TokenizationAction::TokenizeInRouter, - }), - Some(token) => { - let redis_conn = state - .store - .get_redis_conn() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to get redis connection")?; - - let key = format!( - "pm_token_{}_{}_{}", - token.to_owned(), - payment_method, - connector_name - ); + if let Some(storage_enums::PaymentMethodType::Paze) = payment_method_type { + // Paze generates a one time use network token which should not be tokenized in the connector or router. + match &state.conf.paze_decrypt_keys { + Some(paze_keys) => Ok(TokenizationAction::DecryptPazeToken( + PazePaymentProcessingDetails { + paze_private_key: paze_keys.get_inner().paze_private_key.clone(), + paze_private_key_passphrase: paze_keys + .get_inner() + .paze_private_key_passphrase + .clone(), + }, + )), + None => Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch Paze configs"), + } + } else { + match pm_parent_token { + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ) + } + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { + TokenizationAction::DecryptApplePayToken(payment_processing_details) + } + (false, _) => TokenizationAction::TokenizeInRouter, + }), + Some(token) => { + let redis_conn = state + .store + .get_redis_conn() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get redis connection")?; + + let key = format!( + "pm_token_{}_{}_{}", + token.to_owned(), + payment_method, + connector_name + ); - let connector_token_option = redis_conn - .get_key::<Option<String>>(&key) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to fetch the token from redis")?; + let connector_token_option = redis_conn + .get_key::<Option<String>>(&key) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch the token from redis")?; - match connector_token_option { - Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)), - None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { - (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( - payment_processing_details, - ) - } - (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, - (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => { - TokenizationAction::DecryptApplePayToken(payment_processing_details) + match connector_token_option { + Some(connector_token) => { + Ok(TokenizationAction::ConnectorToken(connector_token)) } - (false, _) => TokenizationAction::TokenizeInRouter, - }), + None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) { + ( + true, + Some(domain::ApplePayFlow::Simplified(payment_processing_details)), + ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( + payment_processing_details, + ), + (true, _) => TokenizationAction::TokenizeInConnectorAndRouter, + ( + false, + Some(domain::ApplePayFlow::Simplified(payment_processing_details)), + ) => TokenizationAction::DecryptApplePayToken(payment_processing_details), + (false, _) => TokenizationAction::TokenizeInRouter, + }), + } } } } } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +pub struct PazePaymentProcessingDetails { + pub paze_private_key: Secret<String>, + pub paze_private_key_passphrase: Secret<String>, +} + #[derive(Clone, Debug)] pub enum TokenizationAction { TokenizeInRouter, @@ -2704,6 +2779,7 @@ pub enum TokenizationAction { SkipConnectorTokenization, DecryptApplePayToken(payments_api::PaymentProcessingDetails), TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails), + DecryptPazeToken(PazePaymentProcessingDetails), } #[cfg(feature = "v2")] @@ -2791,6 +2867,7 @@ where payment_data.get_token(), is_connector_tokenization_enabled, apple_pay_flow, + *payment_method_type, ) .await?; @@ -2846,6 +2923,9 @@ where ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt( payment_processing_details, ), + TokenizationAction::DecryptPazeToken(paze_payment_processing_details) => { + TokenizationAction::DecryptPazeToken(paze_payment_processing_details) + } }; (payment_data.to_owned(), connector_tokenization_action) } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index ee657bc3949..1785eee87c5 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -498,6 +498,34 @@ async fn create_applepay_session_token( } } +fn create_paze_session_token( + router_data: &types::PaymentsSessionRouterData, + _header_payload: api_models::payments::HeaderPayload, +) -> RouterResult<types::PaymentsSessionRouterData> { + let paze_wallet_details = router_data + .connector_wallets_details + .clone() + .parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData") + .change_context(errors::ConnectorError::NoConnectorWalletDetails) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_wallets_details".to_string(), + expected_format: "paze_metadata_format".to_string(), + })?; + + Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::Paze(Box::new( + payment_types::PazeSessionTokenResponse { + client_id: paze_wallet_details.data.client_id, + client_name: paze_wallet_details.data.client_name, + client_profile_id: paze_wallet_details.data.client_profile_id, + }, + )), + }), + ..router_data.clone() + }) +} + fn create_samsung_pay_session_token( router_data: &types::PaymentsSessionRouterData, header_payload: api_models::payments::HeaderPayload, @@ -967,6 +995,7 @@ impl RouterDataSession for types::PaymentsSessionRouterData { api::GetToken::PaypalSdkMetadata => { create_paypal_sdk_session_token(state, self, connector, business_profile) } + api::GetToken::PazeMetadata => create_paze_session_token(self, header_payload), api::GetToken::Connector => { let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< api::Session, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index fbd1170ebad..a39b151bd27 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -30,7 +30,7 @@ use futures::future::Either; use hyperswitch_domain_models::payments::payment_intent::CustomerData; use hyperswitch_domain_models::{ mandates::MandateData, - payment_method_data::GetPaymentMethodType, + payment_method_data::{GetPaymentMethodType, PazeWalletData}, payments::{ payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, PaymentIntent, @@ -2545,6 +2545,7 @@ pub fn validate_payment_method_type_against_payment_method( | api_enums::PaymentMethodType::KakaoPay | api_enums::PaymentMethodType::Cashapp | api_enums::PaymentMethodType::Mifinity + | api_enums::PaymentMethodType::Paze ), api_enums::PaymentMethod::BankRedirect => matches!( payment_method_type, @@ -4624,6 +4625,9 @@ async fn get_and_merge_apple_pay_metadata( samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), + paze: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.paze.clone()), } } api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { @@ -4639,6 +4643,9 @@ async fn get_and_merge_apple_pay_metadata( samsung_pay: connector_wallets_details_optional .as_ref() .and_then(|d| d.samsung_pay.clone()), + paze: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.paze.clone()), } } }; @@ -4980,6 +4987,71 @@ impl ApplePayData { } } +pub fn decrypt_paze_token( + paze_wallet_data: PazeWalletData, + paze_private_key: masking::Secret<String>, + paze_private_key_passphrase: masking::Secret<String>, +) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> { + let decoded_paze_private_key = BASE64_ENGINE + .decode(paze_private_key.expose().as_bytes()) + .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; + let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase( + decoded_paze_private_key.as_slice(), + paze_private_key_passphrase.expose().as_bytes(), + ) + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; + let decrypted_private_key_pem = String::from_utf8( + decrypted_private_key + .private_key_to_pem() + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?, + ) + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; + let decrypter = jwe::RSA_OAEP_256 + .decrypter_from_pem(decrypted_private_key_pem) + .change_context(errors::PazeDecryptionError::CertificateParsingFailed)?; + + let paze_complete_response: Vec<&str> = paze_wallet_data + .complete_response + .peek() + .split('.') + .collect(); + let encrypted_jwe_key = paze_complete_response + .get(1) + .ok_or(errors::PazeDecryptionError::DecryptionFailed)? + .to_string(); + let decoded_jwe_key = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(encrypted_jwe_key) + .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; + let jws_body: JwsBody = serde_json::from_slice(&decoded_jwe_key) + .change_context(errors::PazeDecryptionError::DecryptionFailed)?; + + let (deserialized_payload, _deserialized_header) = + jwe::deserialize_compact(jws_body.secured_payload.peek(), &decrypter) + .change_context(errors::PazeDecryptionError::DecryptionFailed)?; + let encoded_secured_payload_element = String::from_utf8(deserialized_payload) + .change_context(errors::PazeDecryptionError::DecryptionFailed)? + .split('.') + .collect::<Vec<&str>>() + .get(1) + .ok_or(errors::PazeDecryptionError::DecryptionFailed)? + .to_string(); + let decoded_secured_payload_element = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(encoded_secured_payload_element) + .change_context(errors::PazeDecryptionError::Base64DecodingFailed)?; + let parsed_decrypted: serde_json::Value = + serde_json::from_slice(&decoded_secured_payload_element) + .change_context(errors::PazeDecryptionError::DecryptionFailed)?; + Ok(parsed_decrypted) +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct JwsBody { + pub payload_id: String, + pub session_id: String, + pub secured_payload: masking::Secret<String>, +} + pub fn get_key_params_for_surcharge_details( payment_method_data: &domain::PaymentMethodData, ) -> Option<( diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index cc8b839cc80..2e37d26cdec 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -492,6 +492,7 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken { api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata, api_models::enums::PaymentMethodType::SamsungPay => Self::SamsungPayMetadata, api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata, + api_models::enums::PaymentMethodType::Paze => Self::PazeMetadata, _ => Self::Connector, } } diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 6815d2dfc4f..ee75536e7c9 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -133,6 +133,11 @@ where message: "Apple Pay Decrypt token is not supported".to_string(), })? } + types::PaymentMethodToken::PazeDecrypt(_) => { + Err(errors::ApiErrorResponse::NotSupported { + message: "Paze Decrypt token is not supported".to_string(), + })? + } }; Some((connector_name, token)) } else { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index c2ed06d9bad..e115558995d 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -177,6 +177,7 @@ pub enum GetToken { SamsungPayMetadata, ApplePayMetadata, PaypalSdkMetadata, + PazeMetadata, Connector, } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index a75ef879daf..49d8d50442e 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -476,6 +476,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod { | api_enums::PaymentMethodType::Dana | api_enums::PaymentMethodType::MbWay | api_enums::PaymentMethodType::MobilePay + | api_enums::PaymentMethodType::Paze | api_enums::PaymentMethodType::SamsungPay | api_enums::PaymentMethodType::Twint | api_enums::PaymentMethodType::Vipps
2024-09-25T13:09:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> New wallet Paze is integrated in Hyperswitch with Cybserource as the supported payment processor. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/6028 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Paze Payments need to be tested via Cybersource: 1. Payments Connector - Create: Request: ``` curl --location 'http://localhost:8080/account/merchant_1727784802/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_secret": "Hidden", "api_key": "Hidden", "key1": "Hidden" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "card_networks": [ "Visa", "Mastercard" ], "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paze", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_wallets_details": { "paze": { "client_id": "Hidden", "client_name": "Hidden", "client_profile_id": "Hidden" } }, "connector_webhook_details": { "merchant_secret": "MyWebhookSecret" }, "metadata": { "city": "NY", "unit": "245" }, "business_country": "US", "business_label": "default" }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "cybersource", "connector_label": "cybersource_US_default_default", "merchant_connector_id": "mca_LaFobeWWU3nzVfEQnMid", "profile_id": "pro_3BNSt57cBpRKDJzhCxfA", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "********************************", "key1": "*************", "api_secret": "****************************************" }, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paze", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_webhook_details": { "merchant_secret": "MyWebhookSecret", "additional_secret": null }, "metadata": { "city": "NY", "unit": "245" }, "test_mode": true, "disabled": false, "frm_configs": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, "connector_wallets_details": { "paze": { "client_id": "Hidden", "client_name": "Hidden", "client_profile_id": "Hidden" } } } ``` 2. Sessions Call: Request: ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_1140ed2282ae444f83e6f632b93494c6' \ --data '{ "payment_id": "pay_pu2Qby7cIiVAwj83fN6i", "wallets": [], "client_secret": "pay_pu2Qby7cIiVAwj83fN6i_secret_CP7BwLCIUk5SEMsyWxvq" }' ``` Response: ``` { "payment_id": "pay_pu2Qby7cIiVAwj83fN6i", "client_secret": "pay_pu2Qby7cIiVAwj83fN6i_secret_CP7BwLCIUk5SEMsyWxvq", "session_token": [ { "wallet_name": "paze", "client_id": "Hidden", "client_name": "Hidden", "client_profile_id": "Hidden" } ] } ``` 3. Authorize Call: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_QgqEI16yUU6qP3jOiSA3j2jbMhRbGL9JWvfXEwtTJuNgRESEP3sT8ERvUr0zfQlw' \ --data-raw '{ "amount": 1234, "currency": "USD", "confirm": true, "customer_id": "customer123", "email": "guest@example.com", "payment_method": "wallet", "payment_method_type": "paze", "payment_method_data": { "wallet": { "paze": { "complete_response": "hidden" } } }, "billing": { "address": { "first_name": "joseph", "last_name": "Doe" } } }' ``` Response: ``` { "payment_id": "pay_zdsQ2IvNNzTzlXqRxcVf", "merchant_id": "merchant_1727784802", "status": "succeeded", "amount": 1234, "net_amount": 1234, "amount_capturable": 0, "amount_received": 1234, "connector": "cybersource", "client_secret": "pay_zdsQ2IvNNzTzlXqRxcVf_secret_7KXFE67dATn1TB5tystW", "created": "2024-10-02T19:01:05.077Z", "currency": "USD", "customer_id": "customer123", "customer": { "id": "customer123", "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "guest@example.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "paze", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1727895665, "expires": 1727899265, "secret": "epk_b224eba38d6043489989317e299307db" }, "manual_retry_allowed": false, "connector_transaction_id": "7278956668186980703954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_zdsQ2IvNNzTzlXqRxcVf_1", "payment_link": null, "profile_id": "pro_3BNSt57cBpRKDJzhCxfA", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_Y57pUeM64cR6N1yMkABh", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-02T19:16:05.076Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-02T19:01:08.367Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2bc21cfc5e3e6d8403bec82fde14cfd01536f406
juspay/hyperswitch
juspay__hyperswitch-6014
Bug: [BUG] Add reference to Sepa Bank Transfer Next Customer Actions Responses ### Bug Description Sepa bank transfer payment responses don't contain reference for the payment. A reference is very important unique id for the payment reconciliation by the connectors. e.g. Stripe does create a payment reference but Hyperswitch does not pass it down as part of **next action** in the **create-payment** api call. Check below for the detailed request and response structures. ### Expected Behavior The next action section of the response should display reference. ``` "next_action": { "type": "display_bank_transfer_information", "bank_transfer_steps_and_charges_details": { "sepa_bank_instructions": { "account_holder_name": "LOL GmbH", "bic": "SOGEDEFFXXX", "country": "DE", "iban": "DEXXXXXXXXXXXXXXXX6", "reference" : "HZDK38NZ88MC }, "receiver": { "amount_received": 0, "amount_charged": null, "amount_remaining": 60 } } } ``` ### Actual Behavior 1. Add a stripe connector to process sepa bank transfer payments ( customers pay to IBAN asynchronously) 2. Create a payment ``` curl --location 'https://sandbox.hyperswitch.io/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <apiKey>' \ --data-raw '{ "amount": 60, "authentication_type": "no_three_ds", "confirm": true, "currency": "EUR", "customer_id": "cus_2CMeBeWVAEo4CpobIIOW", "payment_method": "bank_transfer", "payment_method_type": "sepa", "payment_method_data": { "bank_transfer": { "sepa_bank_transfer" : { "billing_details" : { "email" : "gmail@rajanikanth.com", "name" : "Rajanikanth" }, "country" : "DE" } } } }' ``` The successful output : ```JSON { "payment_id": "pay_H38rD4DfWwKg6Omoi2j4", "merchant_id": "merchant_1713521192", "status": "requires_customer_action", "amount": 60, "net_amount": 60, "amount_capturable": 60, "amount_received": 0, "connector": "stripe", "client_secret": "pay_H38rD4DfWwKg6Omoi2j4_secret_hrWAvfkxn8BxCA60muqK", "created": "2024-04-22T13:40:07.848Z", "currency": "EUR", "customer_id": "cus_2CMeBeWVAEo4CpobIIOW", "customer": { "id": "cus_2CMeBeWVAEo4CpobIIOW", "name": "R. Rajanikanth", "email": "gmail@rajanikanth.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": {}, "billing": null }, "payment_token": "token_e6zWZTicyszgnSJOYfoD", "shipping": null, "billing": null, "order_details": null, "email": "gmail@rajanikanth.com", "name": "R. Rajanikanth", "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "display_bank_transfer_information", "bank_transfer_steps_and_charges_details": { "sepa_bank_instructions": { "account_holder_name": "LOL GmbH", "bic": "SOGEDEFFXXX", "country": "DE", "iban": "DE7XXXXXXXXX2713356" }, "receiver": { "amount_received": 0, "amount_charged": null, "amount_remaining": 60 } } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": null, "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cus_2CMeBeWVAEo4CpobIIOW", "created_at": 1713793207, "expires": 1713796807, "secret": "epk_af95122559b54d969745ec25d126fe76" }, "manual_retry_allowed": null, "connector_transaction_id": "pi_3P8N6KP6tL3tSvaR0C4oriJt", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3P8N6KP6tL3tSvaR0C4oriJt", "payment_link": null, "profile_id": "pro_47tvU9WWnp9JNx2Xm6TR", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_8CXOXTBeD2bS07s71M0R", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-04-22T13:55:07.848Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-04-22T13:40:08.953Z" } ``` 3. In above response, the reference in the next action is missing. ``` "next_action": { "type": "display_bank_transfer_information", "bank_transfer_steps_and_charges_details": { "sepa_bank_instructions": { "account_holder_name": "LOL GmbH", "bic": "SOGEDEFFXXX", "country": "DE", "iban": "DEXXXXXXXXXXX32713356" }, "receiver": { "amount_received": 0, "amount_charged": null, "amount_remaining": 60 } } } ``` 4. Although stripe creates a reference ``` Amount remaining : €0.60 EUR BIC : SOGEDEFFXXX IBAN : DE73977977789374832713356 Country: DE Account holder name: LOL GmbH Reference : HZDK38NZ88MC ``` 5. `StripeBankTransferDetails` in the code has reference but it is not passed down as the api response. ### Steps To Reproduce 1. Add a stripe connector to process sepa bank transfer payments ( customers pay to IBAN asynchronously) 2. Create a bank transfer payment. 3. Observe the successful response. ### Context For The Bug https://docs.stripe.com/api/payment_intents/object#payment_intent_object-next_action-display_bank_transfer_instructions-reference ### Environment sandbox hyperswitch ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? None
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index fb679970f3d..c554245b936 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -18325,7 +18325,8 @@ "account_holder_name", "bic", "country", - "iban" + "iban", + "reference" ], "properties": { "account_holder_name": { @@ -18342,6 +18343,10 @@ "iban": { "type": "string", "example": "123456789" + }, + "reference": { + "type": "string", + "example": "U2PVVSEV4V9Y" } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 23c3b219b65..cc6a9af5258 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3545,6 +3545,8 @@ pub struct SepaBankTransferInstructions { pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, + #[schema(value_type = String, example = "U2PVVSEV4V9Y")] + pub reference: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 2129ad327c2..1a25075ce21 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2475,7 +2475,16 @@ pub fn get_connector_metadata( let (sepa_bank_instructions, bacs_bank_instructions) = bank_instructions.map_or((None, None), |financial_address| { ( - financial_address.iban.to_owned(), + financial_address + .iban + .to_owned() + .map(|sepa_financial_details| SepaFinancialDetails { + account_holder_name: sepa_financial_details.account_holder_name, + bic: sepa_financial_details.bic, + country: sepa_financial_details.country, + iban: sepa_financial_details.iban, + reference: response.reference.to_owned(), + }), financial_address.sort_code.to_owned(), ) }); @@ -2880,6 +2889,7 @@ pub struct SepaFinancialDetails { pub bic: Secret<String>, pub country: Secret<String>, pub iban: Secret<String>, + pub reference: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
2024-10-03T13:51:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> 'reference' added in sepa_bank_instructions, for Stripe Sepa Bank Transfer ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/6014 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request ~~~ curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: <apiKey>' \ --data-raw '{ "amount": 60, "authentication_type": "no_three_ds", "confirm": true, "currency": "EUR", "customer_id": "StripeCustomer", "payment_method": "bank_transfer", "payment_method_type": "sepa", "payment_method_data": { "bank_transfer": { "sepa_bank_transfer" : { "billing_details" : { "email" : "gmail@rajanikanth.com", "name" : "Rajanikanth" }, "country" : "DE" } } } }' ~~~ The successful output : ~~~ { "payment_id": "pay_bLamnDrh3V3GefetEL3Tm", "merchant_id": "merchant_1727948661", "status": "requires_customer_action", "amount": 60, "net_amount": 60, "amount_capturable": 60, "amount_received": 0, "connector": "stripe", "client_secret": "pay_bLamnDrh3V3cefctEL3Tm_secret_QsqbBrkZn2pI7cerfer", "created": "2024-10-03T13:25:34.962Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "bank_transfer", "payment_method_data": { "bank_transfer": { "sepa": {} }, "billing": null }, "payment_token": "token_kwd45640isqRNJdwedwB", "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "display_bank_transfer_information", "bank_transfer_steps_and_charges_details": { "sepa_bank_instructions": { "account_holder_name": "ABCD France", "bic": "SOGEDEFFXXX", "country": "DE", "iban": "DE4039739XXXXXXXX89727", "reference": "8NXKXQARUC9X" }, "receiver": { "amount_received": 0, "amount_charged": null, "amount_remaining": 60 } } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1727961934, "expires": 1727965534, "secret": "epk_f8ad2600b91b47bcaa762322eaa6f5f3" }, "manual_retry_allowed": null, "connector_transaction_id": "pi_3Q5p2CEOxxxxxx0EG1g4Ou", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3Q5p2CEOxxxxxx0EG1g4Ou", "payment_link": null, "profile_id": "pro_TSOb6xQbAkCdcsTtYf6C", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_XjEZ8bwoCedxxxdE3u", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-03T13:40:34.962Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-03T13:25:36.680Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ~~~ ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
a3c2694943a985d27b5bc8b0371884d17a6ca34d
juspay/hyperswitch
juspay__hyperswitch-6009
Bug: [$100] Develop Email Template Design ### Please make sure to read this through the below Guidelines before attempting the problem statements [Contribution Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) [Bounty Program Guidelines](https://github.com/juspay/hyperswitch/wiki/Guidelines-for-Bounty-Program) [Terms of Contest](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) ## Context As part of automating the welcome email process for merchants signing up to our dashboard, we need to create a visually appealing, fully responsive email template based on the design provided in the Figma file. The template will serve as the welcome email for merchants, replacing the current manual process, and must align with our brand guidelines. #### **Requirements:** - Follow the design provided in the Figma file: [Figma Link](https://www.figma.com/design/lhmTvW2vuc2p5B4ZvsEOTw/Email-Tempalte-Design?node-id=0-1&t=OKWmXqVOsidKUk7y-1) - Utilize existing assets (images, logos, icons, etc.) found in the figma. - Ensure the template is fully responsive and compatible with major email clients (e.g., Gmail, Outlook, Apple Mail). - Include all the design elements such as header, body content, call-to-action button, and footer as outlined in the Figma file. - Write clean, maintainable, and well-documented code. #### **Acceptance Criteria:** - Email template developed according to the Figma design. - The template is responsive and displays correctly across major email clients. - The design aligns with the brand style guidelines. - Code is properly commented and documented. - A preview of the email template is provided. #### **Additional Notes:** If you have any questions regarding the design or assets, please drop a message in our Community Channels
2023-07-13T14:33:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes the command used to generate release notes in the release new version workflow. ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> The current command handles things much better and avoids trimming of changelog entries unnecessarily. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Locally. Trust me, it works. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
9112417caee51117c170af6096825c5b1b2bd0e0
juspay/hyperswitch
juspay__hyperswitch-6004
Bug: [BUG] [CORE] Payment method details are being none in Psync Response. ### Bug Description Payment method details are being none in Psync Response. ### Expected Behavior Payment method data should be populated in Psync response for all the payment methods, except for network token. ### Actual Behavior Payment method details are being none in Psync Response for all the payment methods. ### Steps To Reproduce Make a payment. Sync the response and check for payment method data ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. 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 --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 37e178dc7f3..d8c5f88dde9 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -784,36 +784,16 @@ where .map(ToString::to_string) .unwrap_or("".to_owned()); let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> = - match payment_data.get_payment_method_data(){ - Some(payment_method_data) => match payment_method_data{ - hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardRedirect(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::PayLater(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankDebit(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankTransfer(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::Crypto(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::MandatePayment | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::RealTimePayment(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::Voucher(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::GiftCard(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardToken(_) | - hyperswitch_domain_models::payment_method_data::PaymentMethodData::OpenBanking(_) => {payment_attempt - .payment_method_data - .clone() - .map(|data| data.parse_value("payment_method_data")) - .transpose() - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "payment_method_data", - })?}, - hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_) => None, - } - None => None - - }; + payment_attempt + .payment_method_data + .clone() + .and_then(|data| match data { + serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null + _ => Some(data.parse_value("AdditionalPaymentData")), + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?; let surcharge_details = payment_attempt
2024-09-24T08:35:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, in Psync response, payment_method_data is being none. Updated the Psync response with pm data. For network token pm data will be none, since we are not storing additional pm data in attempt. For other payment methods, it will continue to function as it did previously. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> payment curl - ```{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com/", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "routing": { "type": "single", "data": "stripe" } } ``` test cases - make a successful payment, pm data should be displayed in the response PaymentsCreate - <img width="702" alt="Screenshot 2024-09-24 at 1 54 01 PM" src="https://github.com/user-attachments/assets/cb4635ef-95c9-4127-aa67-25f1b372efd3"> PSync - <img width="710" alt="Screenshot 2024-09-24 at 1 54 16 PM" src="https://github.com/user-attachments/assets/1fb845e8-da1a-4257-af73-0cdce5171d56"> Save Card flow - <img width="763" alt="Screenshot 2024-09-24 at 1 54 30 PM" src="https://github.com/user-attachments/assets/2c2dde1c-f841-47b5-9d76-a4fcd48d5204"> payment create - wallet - googlepay <img width="994" alt="Screenshot 2024-09-24 at 5 26 55 PM" src="https://github.com/user-attachments/assets/5bb6671b-3758-4d06-8d01-1a344efff518"> sync response - wallet <img width="896" alt="Screenshot 2024-09-24 at 5 28 48 PM" src="https://github.com/user-attachments/assets/643f82c8-3915-4e7b-b807-ec63ec12435d"> confirm - network token <img width="752" alt="Screenshot 2024-09-24 at 5 31 01 PM" src="https://github.com/user-attachments/assets/156d2f2c-4728-445e-b046-58ae7790c1dc"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
8a9fed36fc7f01f54d9a2e725abf459fac857222
juspay/hyperswitch
juspay__hyperswitch-6012
Bug: fix: remove internal entity type We can remove type internal. TODO: - Being internal is the property of role and does not depend on entity type - We can remove logic for internal entity type and transfer it use role.is_internal() wherever it is being used in the code. - The mini logics like get entity type can be altered it won't take entity type internal to consideration. Once this is done, We need to migrate entity type internal in DB to Merchant.
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index a9ece7e9c02..d6f452a5a01 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3144,7 +3144,6 @@ pub enum ApiVersion { #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { - Internal = 3, Organization = 2, Merchant = 1, Profile = 0, diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index 29be4d62aef..71caa41deac 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -33,11 +33,6 @@ impl UserRole { let org_id = self.org_id.clone()?.get_string_repr().to_string(); Some((org_id, EntityType::Organization)) } - (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER) - | (enums::UserRoleVersion::V1, consts::ROLE_ID_INTERNAL_ADMIN) => { - let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string(); - Some((merchant_id, EntityType::Internal)) - } (enums::UserRoleVersion::V1, _) => { let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string(); Some((merchant_id, EntityType::Merchant)) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 4c797486970..f36ecc18116 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -650,7 +650,6 @@ async fn handle_existing_user_invitation( }; let _user_role = match role_info.get_entity_type() { - EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()), EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()), EntityType::Merchant => { user_role @@ -682,7 +681,6 @@ async fn handle_existing_user_invitation( { let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let entity = match role_info.get_entity_type() { - EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()), EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()), EntityType::Merchant => email_types::Entity { entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), @@ -769,7 +767,6 @@ async fn handle_new_user_invitation( }; let _user_role = match role_info.get_entity_type() { - EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()), EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()), EntityType::Merchant => { user_role @@ -805,7 +802,6 @@ async fn handle_new_user_invitation( let _ = req_state.clone(); let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; let entity = match role_info.get_entity_type() { - EntityType::Internal => return Err(UserErrors::InvalidRoleId.into()), EntityType::Organization => return Err(UserErrors::InvalidRoleId.into()), EntityType::Merchant => email_types::Entity { entity_id: user_from_token.merchant_id.get_string_repr().to_owned(), @@ -1089,15 +1085,13 @@ pub async fn create_internal_user( } })?; + let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id( + consts::user_role::INTERNAL_USER_MERCHANT_ID, + ); + let internal_merchant = state .store - .find_merchant_account_by_merchant_id( - key_manager_state, - &common_utils::id_type::MerchantId::get_internal_user_merchant_id( - consts::user_role::INTERNAL_USER_MERCHANT_ID, - ), - &key_store, - ) + .find_merchant_account_by_merchant_id(key_manager_state, &internal_merchant_id, &key_store) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1130,8 +1124,9 @@ pub async fn create_internal_user( common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), UserStatus::Active, ) - .add_entity(domain::InternalLevel { + .add_entity(domain::MerchantLevel { org_id: internal_merchant.organization_id, + merchant_id: internal_merchant_id, }) .insert_in_v1_and_v2(&state) .await @@ -1443,6 +1438,13 @@ pub async fn list_user_roles_details( .to_not_found_response(UserErrors::InternalServerError) .attach_printable("Failed to fetch role info")?; + if requestor_role_info.is_internal() { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Internal roles are not allowed for this operation".to_string(), + ) + .into()); + } + let user_roles_set = state .store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { @@ -1517,12 +1519,6 @@ pub async fn list_user_roles_details( merchant.push(merchant_id.clone()); merchant_profile.push((merchant_id, profile_id)) } - EntityType::Internal => { - return Err(UserErrors::InvalidRoleOperationWithMessage( - "Internal roles are not allowed for this operation".to_string(), - ) - .into()); - } EntityType::Organization => (), }; @@ -1609,11 +1605,6 @@ pub async fn list_user_roles_details( .ok_or(UserErrors::InternalServerError)?; let (merchant, profile) = match entity_type { - EntityType::Internal => { - return Err(UserErrors::InvalidRoleOperationWithMessage( - "Internal roles are not allowed for this operation".to_string(), - )); - } EntityType::Organization => (None, None), EntityType::Merchant => { let merchant_id = &user_role @@ -2623,26 +2614,30 @@ pub async fn list_orgs_for_user( .await .change_context(UserErrors::InternalServerError)?; - let orgs = match role_info.get_entity_type() { - EntityType::Internal => return Err(UserErrors::InvalidRoleOperation.into()), - EntityType::Organization | EntityType::Merchant | EntityType::Profile => state - .store - .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { - user_id: user_from_token.user_id.as_str(), - org_id: None, - merchant_id: None, - profile_id: None, - entity_id: None, - version: None, - status: Some(UserStatus::Active), - limit: None, - }) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .filter_map(|user_role| user_role.org_id) - .collect::<HashSet<_>>(), - }; + if role_info.is_internal() { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Internal roles are not allowed for this operation".to_string(), + ) + .into()); + } + + let orgs = state + .store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: user_from_token.user_id.as_str(), + org_id: None, + merchant_id: None, + profile_id: None, + entity_id: None, + version: None, + status: Some(UserStatus::Active), + limit: None, + }) + .await + .change_context(UserErrors::InternalServerError)? + .into_iter() + .filter_map(|user_role| user_role.org_id) + .collect::<HashSet<_>>(); let resp = futures::future::try_join_all( orgs.iter() @@ -2676,8 +2671,16 @@ pub async fn list_merchants_for_user_in_org( ) .await .change_context(UserErrors::InternalServerError)?; + + if role_info.is_internal() { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Internal roles are not allowed for this operation".to_string(), + ) + .into()); + } + let merchant_accounts = match role_info.get_entity_type() { - EntityType::Organization | EntityType::Internal => state + EntityType::Organization => state .store .list_merchant_accounts_by_organization_id(&(&state).into(), &user_from_token.org_id) .await @@ -2752,7 +2755,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account( .await .change_context(UserErrors::InternalServerError)?; let profiles = match role_info.get_entity_type() { - EntityType::Organization | EntityType::Merchant | EntityType::Internal => state + EntityType::Organization | EntityType::Merchant => state .store .list_profile_by_merchant_id( key_manager_state, @@ -2831,7 +2834,7 @@ pub async fn switch_org_for_user( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve role information")?; - if role_info.get_entity_type() == EntityType::Internal { + if role_info.is_internal() { return Err(UserErrors::InvalidRoleOperationWithMessage( "Org switching not allowed for Internal role".to_string(), ) @@ -2910,126 +2913,54 @@ pub async fn switch_merchant_for_user_in_org( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to retrieve role information")?; - let (org_id, merchant_id, profile_id, role_id) = match role_info.get_entity_type() { - EntityType::Internal => { - let merchant_key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &request.merchant_id, - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(UserErrors::MerchantIdNotFound)?; - - let merchant_account = state - .store - .find_merchant_account_by_merchant_id( - key_manager_state, - &request.merchant_id, - &merchant_key_store, - ) - .await - .to_not_found_response(UserErrors::MerchantIdNotFound)?; - - let profile_id = state - .store - .list_profile_by_merchant_id( - key_manager_state, - &merchant_key_store, - &request.merchant_id, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to list business profiles by merchant_id")? - .pop() - .ok_or(UserErrors::InternalServerError) - .attach_printable("No business profile found for the given merchant_id")? - .get_id() - .to_owned(); - - ( - merchant_account.organization_id, - request.merchant_id, - profile_id, - user_from_token.role_id.clone(), + // Check if the role is internal and handle separately + let (org_id, merchant_id, profile_id, role_id) = if role_info.is_internal() { + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &request.merchant_id, + &state.store.get_master_key().to_vec().into(), ) - } - - EntityType::Organization => { - let merchant_key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &request.merchant_id, - &state.store.get_master_key().to_vec().into(), - ) - .await - .to_not_found_response(UserErrors::MerchantIdNotFound)?; - - let merchant_id = state - .store - .find_merchant_account_by_merchant_id( - key_manager_state, - &request.merchant_id, - &merchant_key_store, - ) - .await - .change_context(UserErrors::MerchantIdNotFound)? - .organization_id - .eq(&user_from_token.org_id) - .then(|| request.merchant_id.clone()) - .ok_or_else(|| { - UserErrors::InvalidRoleOperationWithMessage( - "No such merchant_id found for the user in the org".to_string(), - ) - })?; + .await + .to_not_found_response(UserErrors::MerchantIdNotFound)?; - let profile_id = state - .store - .list_profile_by_merchant_id(key_manager_state, &merchant_key_store, &merchant_id) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to list business profiles by merchant_id")? - .pop() - .ok_or(UserErrors::InternalServerError) - .attach_printable("No business profile found for the merchant_id")? - .get_id() - .to_owned(); - ( - user_from_token.org_id.clone(), - merchant_id, - profile_id, - user_from_token.role_id.clone(), + let merchant_account = state + .store + .find_merchant_account_by_merchant_id( + key_manager_state, + &request.merchant_id, + &merchant_key_store, ) - } - - EntityType::Merchant | EntityType::Profile => { - let user_role = state - .store - .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { - user_id: &user_from_token.user_id, - org_id: Some(&user_from_token.org_id), - merchant_id: Some(&request.merchant_id), - profile_id: None, - entity_id: None, - version: None, - status: Some(UserStatus::Active), - limit: Some(1), - }) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable( - "Failed to list user roles for the given user_id, org_id and merchant_id", - )? - .pop() - .ok_or(UserErrors::InvalidRoleOperationWithMessage( - "No user role associated with the requested merchant_id".to_string(), - ))?; + .await + .to_not_found_response(UserErrors::MerchantIdNotFound)?; - let profile_id = if let Some(profile_id) = &user_role.profile_id { - profile_id.clone() - } else { + let profile_id = state + .store + .list_profile_by_merchant_id( + key_manager_state, + &merchant_key_store, + &request.merchant_id, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to list business profiles by merchant_id")? + .pop() + .ok_or(UserErrors::InternalServerError) + .attach_printable("No business profile found for the given merchant_id")? + .get_id() + .to_owned(); + + ( + merchant_account.organization_id, + request.merchant_id, + profile_id, + user_from_token.role_id.clone(), + ) + } else { + // Match based on the other entity types + match role_info.get_entity_type() { + EntityType::Organization => { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -3038,31 +2969,82 @@ pub async fn switch_merchant_for_user_in_org( &state.store.get_master_key().to_vec().into(), ) .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to retrieve merchant key store by merchant_id")?; + .to_not_found_response(UserErrors::MerchantIdNotFound)?; + + let merchant_id = state + .store + .find_merchant_account_by_merchant_id( + key_manager_state, + &request.merchant_id, + &merchant_key_store, + ) + .await + .change_context(UserErrors::MerchantIdNotFound)? + .organization_id + .eq(&user_from_token.org_id) + .then(|| request.merchant_id.clone()) + .ok_or_else(|| { + UserErrors::InvalidRoleOperationWithMessage( + "No such merchant_id found for the user in the org".to_string(), + ) + })?; - state + let profile_id = state .store .list_profile_by_merchant_id( key_manager_state, &merchant_key_store, - &request.merchant_id, + &merchant_id, ) .await .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to list business profiles for the given merchant_id")? + .attach_printable("Failed to list business profiles by merchant_id")? .pop() .ok_or(UserErrors::InternalServerError) - .attach_printable("No business profile found for the given merchant_id")? + .attach_printable("No business profile found for the merchant_id")? .get_id() - .to_owned() - }; - ( - user_from_token.org_id, - request.merchant_id, - profile_id, - user_role.role_id, - ) + .to_owned(); + ( + user_from_token.org_id.clone(), + merchant_id, + profile_id, + user_from_token.role_id.clone(), + ) + } + + EntityType::Merchant | EntityType::Profile => { + let user_role = state + .store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &user_from_token.user_id, + org_id: Some(&user_from_token.org_id), + merchant_id: Some(&request.merchant_id), + profile_id: None, + entity_id: None, + version: None, + status: Some(UserStatus::Active), + limit: Some(1), + }) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable( + "Failed to list user roles for the given user_id, org_id and merchant_id", + )? + .pop() + .ok_or(UserErrors::InvalidRoleOperationWithMessage( + "No user role associated with the requested merchant_id".to_string(), + ))?; + + let (merchant_id, profile_id) = + utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role) + .await?; + ( + user_from_token.org_id, + merchant_id, + profile_id, + user_role.role_id, + ) + } } }; @@ -3116,7 +3098,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( .attach_printable("Failed to retrieve role information")?; let (profile_id, role_id) = match role_info.get_entity_type() { - EntityType::Internal | EntityType::Organization | EntityType::Merchant => { + EntityType::Organization | EntityType::Merchant => { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index fd9c8c89031..b841f88eca1 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -734,7 +734,6 @@ pub async fn list_users_in_lineage( ) .await? } - EntityType::Internal => HashSet::new(), }; let mut email_map = state @@ -859,10 +858,13 @@ pub async fn list_invitations_for_user( .clone() .ok_or(UserErrors::InternalServerError)?, )), - EntityType::Internal => return Err(report!(UserErrors::InternalServerError)), } - Ok((org_ids, merchant_ids, profile_ids_with_merchant_ids)) + Ok::<_, error_stack::Report<UserErrors>>(( + org_ids, + merchant_ids, + profile_ids_with_merchant_ids, + )) }, )?; @@ -953,7 +955,6 @@ pub async fn list_invitations_for_user( .as_ref() .map(|profile_id| profile_name_map.get(profile_id).cloned()) .ok_or(UserErrors::InternalServerError)?, - EntityType::Internal => return Err(report!(UserErrors::InternalServerError)), }; Ok(user_role_api::ListInvitationForUserResponse { diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index ffc18214c20..d5d655b4a89 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -224,6 +224,13 @@ pub async fn list_roles_with_info( .await .attach_printable("Invalid role_id in JWT")?; + if user_role_info.is_internal() { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Internal roles are not allowed for this operation".to_string(), + ) + .into()); + } + let mut role_info_vec = PREDEFINED_ROLES .iter() .map(|(_, role_info)| role_info.clone()) @@ -256,12 +263,6 @@ pub async fn list_roles_with_info( .attach_printable("Failed to get roles")?, // TODO: Populate this from Db function when support for profile id and profile level custom roles is added EntityType::Profile => Vec::new(), - EntityType::Internal => { - return Err(UserErrors::InvalidRoleOperationWithMessage( - "Internal roles are not allowed for this operation".to_string(), - ) - .into()); - } }; role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from)); @@ -336,13 +337,6 @@ pub async fn list_roles_at_entity_level( .attach_printable("Failed to get roles")?, // TODO: Populate this from Db function when support for profile id and profile level custom roles is added EntityType::Profile => Vec::new(), - - EntityType::Internal => { - return Err(UserErrors::InvalidRoleOperationWithMessage( - "Internal roles are not allowed for this operation".to_string(), - ) - .into()); - } }; role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from)); diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index df42d412989..b271abd1eff 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -31,7 +31,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(), role_name: "internal_admin".to_string(), scope: RoleScope::Organization, - entity_type: EntityType::Internal, + entity_type: EntityType::Merchant, is_invitable: false, is_deletable: false, is_updatable: false, @@ -52,7 +52,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(), role_name: "internal_view_only".to_string(), scope: RoleScope::Organization, - entity_type: EntityType::Internal, + entity_type: EntityType::Merchant, is_invitable: false, is_deletable: false, is_updatable: false, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 725cefb8c41..19d682aeef1 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1136,11 +1136,6 @@ pub struct ProfileLevel { pub profile_id: id_type::ProfileId, } -#[derive(Clone)] -pub struct InternalLevel { - pub org_id: id_type::OrganizationId, -} - #[derive(Clone)] pub struct NewUserRole<E: Clone> { pub user_id: String, @@ -1316,29 +1311,6 @@ impl NewUserRole<MerchantLevel> { } } -impl NewUserRole<InternalLevel> { - pub async fn insert_in_v1_and_v2(self, state: &SessionState) -> UserResult<UserRole> { - let entity = self.entity.clone(); - let internal_merchant_id = id_type::MerchantId::get_internal_user_merchant_id( - consts::user_role::INTERNAL_USER_MERCHANT_ID, - ); - - let new_v1_role = self - .clone() - .convert_to_new_v1_role(entity.org_id.clone(), internal_merchant_id.clone()); - - let new_v2_role = self.convert_to_new_v2_role(EntityInfo { - org_id: entity.org_id.clone(), - merchant_id: Some(internal_merchant_id.clone()), - profile_id: None, - entity_id: internal_merchant_id.get_string_repr().to_owned(), - entity_type: EntityType::Internal, - }); - - Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await - } -} - impl NewUserRole<ProfileLevel> { pub async fn insert_in_v2(self, state: &SessionState) -> UserResult<UserRole> { let entity = self.entity.clone(); diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 9141b91bdd6..f2aae68fcbc 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -239,10 +239,7 @@ pub async fn get_single_merchant_id( .attach_printable("No merchants found for org_id")? .get_id() .clone()), - Some(EntityType::Merchant) - | Some(EntityType::Internal) - | Some(EntityType::Profile) - | None => user_role + Some(EntityType::Merchant) | Some(EntityType::Profile) | None => user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) @@ -263,9 +260,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( )>, > { match entity_type { - EntityType::Internal | EntityType::Organization => { - Err(UserErrors::InvalidRoleOperation.into()) - } + EntityType::Organization => Err(UserErrors::InvalidRoleOperation.into()), EntityType::Merchant => { let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else { return Ok(None); @@ -369,7 +364,7 @@ pub async fn get_single_merchant_id_and_profile_id( .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; let profile_id = match entity_type { - EntityType::Organization | EntityType::Merchant | EntityType::Internal => { + EntityType::Organization | EntityType::Merchant => { let key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -438,14 +433,6 @@ pub fn get_min_entity( | (EntityType::Merchant, Some(EntityType::Profile)) | (EntityType::Profile, Some(EntityType::Profile)) => Ok(EntityType::Profile), - (EntityType::Internal, _) => Ok(EntityType::Internal), - - (EntityType::Organization, Some(EntityType::Internal)) - | (EntityType::Merchant, Some(EntityType::Internal)) - | (EntityType::Profile, Some(EntityType::Internal)) => { - Err(UserErrors::InvalidRoleOperation.into()) - } - (EntityType::Merchant, Some(EntityType::Organization)) | (EntityType::Profile, Some(EntityType::Organization)) | (EntityType::Profile, Some(EntityType::Merchant)) => { diff --git a/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/down.sql b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/down.sql new file mode 100644 index 00000000000..7d206b424e1 --- /dev/null +++ b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +UPDATE user_roles SET entity_type = 'internal' where role_id like 'internal%' and version = 'v2'; diff --git a/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/up.sql b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/up.sql new file mode 100644 index 00000000000..4fc5ea7d314 --- /dev/null +++ b/migrations/2024-09-24-105659_alter_entity_type_internal_to_merchant/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +UPDATE user_roles SET entity_type = 'merchant' WHERE entity_type = 'internal'; \ No newline at end of file
2024-09-24T11:18:33Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Remove internal from entity type. Being internal is the property of role and does not depend on entity type. Even internal role can have the entity types as 'Merchant', 'Org' or 'Profile' ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#6012](https://github.com/juspay/hyperswitch/issues/6012) ## How did you test it? Switch should work fine for users For internal users also switch merchant should work as expected. ``` curl --location 'http://localhost:8080/user/switch/merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "merchant_id": "some_merchant_id" }' ``` The response will give new token after switch ``` { "token": JWT, "token_type": "user_info" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
3ddfe53838c6b039dc5f669ccd23d3035521d691
juspay/hyperswitch
juspay__hyperswitch-5995
Bug: feat(payments): support for card_network filter in payments list - Support for card_network as filters in payments list - Card network values in payments filter values
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 584f81992bd..4034b8cd58e 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4361,6 +4361,8 @@ pub struct PaymentListFilterConstraints { /// The order in which payments list should be sorted #[serde(default)] pub order: Order, + /// The List of all the card networks to filter payments list + pub card_network: Option<Vec<enums::CardNetwork>>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { @@ -4390,6 +4392,8 @@ pub struct PaymentListFiltersV2 { pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, + /// The list of available card networks + pub card_network: Vec<enums::CardNetwork>, } #[derive(Clone, Debug, serde::Serialize)] diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 562e5d205c0..be2b3547110 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1294,6 +1294,7 @@ pub struct PaymentIntentListParams { pub ending_before_id: Option<id_type::PaymentId>, pub limit: Option<u32>, pub order: api_models::payments::Order, + pub card_network: Option<Vec<storage_enums::CardNetwork>>, } impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints { @@ -1327,6 +1328,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo ending_before_id: ending_before, limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)), order: Default::default(), + card_network: None, })) } } @@ -1351,6 +1353,7 @@ impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints { ending_before_id: None, limit: None, order: Default::default(), + card_network: None, })) } } @@ -1373,6 +1376,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF authentication_type, merchant_connector_id, order, + card_network, } = value; if let Some(payment_intent_id) = payment_id { Self::Single { payment_intent_id } @@ -1395,6 +1399,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF ending_before_id: None, limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)), order, + card_network, })) } } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d7899e8b9a9..859796310f0 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3380,6 +3380,7 @@ pub async fn get_payment_filters( status: enums::IntentStatus::iter().collect(), payment_method: payment_method_types_map, authentication_type: enums::AuthenticationType::iter().collect(), + card_network: enums::CardNetwork::iter().collect(), }, )) } diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index 4c7232f6f3f..f5c3deeb18c 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -939,6 +939,9 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { None => query, }; + if let Some(card_network) = &params.card_network { + query = query.filter(pa_dsl::card_network.eq_any(card_network.clone())); + } query } };
2024-09-23T09:15:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Support for card_network as filters in payments list - Card network values in payments filter values ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5995 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Payments filter list Request ``` curl --location 'http://localhost:8080/payments/v2/filter' \ --header 'Authorization: Bearer JWT' \ --data '' ``` Response ``` { "connector": { "connector_name": [ { "connector_label": "connector_label", "merchant_connector_id": "connector_id" } ] }, "currency": [Array of currency values], "status": [Array of status], "payment_method": { [Array of payment methods]}, "authentication_type": [Array of authentication types], "card_network": [ "Visa", "Mastercard", "AmericanExpress", "JCB", "DinersClub", "Discover", "CartesBancaires", "UnionPay", "Interac", "RuPay", "Maestro" ] } ``` 2. Payments list with filter Request ``` curl --location 'http://localhost:8080/payments/list' \ --header 'authorization: Bearer JWT " --data '{"offset":0,"limit":50,"start_time":"2024-08-23T18:30:00Z","card_network":["Visa"]}' ``` Response ``` { "count": 2, "total_count": 2, "data": [ { "payment_id": "pay_TTYRZZpn4GZgyZkvfpLz", "merchant_id": "merchant_1726749985", "status": "succeeded", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "pay_TTYRZZpn4GZgyZkvfpLz_secret_BNl87WI1lhH3h92QwwRi", "created": "2024-09-23T06:52:14.730Z", "currency": "USD", "customer_id": "hyperswitch_sdk_demo_id", "customer": { "id": "hyperswitch_sdk_demo_id", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Default value", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": null, "card_type": null, "card_network": "Visa", "card_issuer": "", "card_issuing_country": null, "card_isin": null, "card_extended_bin": null, "card_exp_month": null, "card_exp_year": null, "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "billing_email@gmail.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "pay_2dJSM6oUYFoKtxtD45jm", "frm_message": null, "metadata": { "order_details": { "amount": 10000, "quantity": 1, "product_name": "Apple iphone 15" } }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_ClRdOxbia1VPXGEvFHe3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_fBms1u3jKBroyqKUax5S", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null }, { "payment_id": "pay_8rF6jCw4J0W4e2eV7WqC", "merchant_id": "merchant_1726749985", "status": "requires_payment_method", "amount": 10000, "net_amount": 10000, "amount_capturable": 10000, "amount_received": null, "connector": null, "client_secret": "pay_8rF6jCw4J0W4e2eV7WqC_secret_LuwsymB20YhQ1MaujKgK", "created": "2024-09-23T06:50:09.337Z", "currency": "USD", "customer_id": "hyperswitch_sdk_demo_id", "customer": { "id": "hyperswitch_sdk_demo_id", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Default value", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": { "card": { "last4": null, "card_type": null, "card_network": "Visa", "card_issuer": "", "card_issuing_country": null, "card_isin": null, "card_extended_bin": null, "card_exp_month": null, "card_exp_year": null, "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "billing_email@gmail.com" }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "order_details": { "amount": 10000, "quantity": 1, "product_name": "Apple iphone 15" } }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_ClRdOxbia1VPXGEvFHe3", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": null, "expires_on": null, "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": null, "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b7139483bb4735b7dfaf7e659ab33a16a90af1db
juspay/hyperswitch
juspay__hyperswitch-6228
Bug: [FEAT] Add benchmarking for encryption/decryption **Description:** Cripta is a service which creates keys and maintains it (includes key rotation etc.) individually for different Merchants and Users. We need to add a tool which benchmarks the internal encryption/decryption implementation, And any changes to the application should not cause any Perf regressions. **Possible implementation:** - Add `benches` folder for different benchmarking scenarios - Use [criterion.rs](https://github.com/bheisler/criterion.rs) for benchmarking - Call [this](https://github.com/juspay/hyperswitch-encryption-service/blob/main/src/core/crypto/crux.rs#L29) fuction in criterion to benchmark ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). - For this issue, please raise a PR on the https://github.com/juspay/hyperswitch-encryption-service repo, and link the issue. Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/Cargo.lock b/Cargo.lock index 8472b79d44e..20f3b17c44f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -91,7 +91,7 @@ dependencies = [ "rand", "sha1", "smallvec", - "tracing", + "tracing 0.1.36", "zstd", ] @@ -115,7 +115,7 @@ dependencies = [ "http", "regex", "serde", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -144,7 +144,7 @@ dependencies = [ "num_cpus", "socket2", "tokio", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -439,7 +439,7 @@ dependencies = [ "time", "tokio", "tower", - "tracing", + "tracing 0.1.36", "zeroize", ] @@ -454,7 +454,7 @@ dependencies = [ "aws-types", "http", "regex", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -472,7 +472,7 @@ dependencies = [ "lazy_static", "percent-encoding", "pin-project-lite", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -551,7 +551,7 @@ dependencies = [ "aws-smithy-http", "aws-types", "http", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -569,7 +569,7 @@ dependencies = [ "regex", "ring", "time", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -604,7 +604,7 @@ dependencies = [ "pin-project-lite", "tokio", "tower", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -625,7 +625,7 @@ dependencies = [ "pin-project-lite", "tokio", "tokio-util 0.7.4", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -640,7 +640,7 @@ dependencies = [ "http-body", "pin-project-lite", "tower", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -695,10 +695,55 @@ dependencies = [ "aws-smithy-types", "http", "rustc_version", - "tracing", + "tracing 0.1.36", "zeroize", ] +[[package]] +name = "axum" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acee9fd5073ab6b045a275b3e709c163dd36c90685219cb21804a147b58dba43" +dependencies = [ + "async-trait", + "axum-core", + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "hyper", + "itoa 1.0.3", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde", + "sync_wrapper", + "tokio", + "tower", + "tower-http", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37e5939e02c56fecd5c017c37df4238c0a839fa76b7f97acdd7efb804fd181cc" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http", + "http-body", + "mime", + "tower-layer", + "tower-service", +] + [[package]] name = "base64" version = "0.13.0" @@ -965,12 +1010,15 @@ dependencies = [ [[package]] name = "dashmap" -version = "4.0.2" +version = "5.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e77a43b28d0668df09411cb0bc9a8c2adc40f9a048afe863e05fd43251e8e39c" +checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc" dependencies = [ "cfg-if", - "num_cpus", + "hashbrown", + "lock_api", + "once_cell", + "parking_lot_core 0.9.3", ] [[package]] @@ -1111,12 +1159,6 @@ dependencies = [ "instant", ] -[[package]] -name = "fixedbitset" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" - [[package]] name = "flate2" version = "1.0.24" @@ -1193,7 +1235,7 @@ dependencies = [ "tokio-native-tls", "tokio-stream", "tokio-util 0.6.10", - "tracing", + "tracing 0.1.36", "tracing-futures", "url", ] @@ -1359,7 +1401,7 @@ dependencies = [ "slab", "tokio", "tokio-util 0.7.4", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -1423,6 +1465,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range-header" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfe8eed0a9285ef776bb792479ea3834e8b94e13d615c2f66d03dd50a435a29" + [[package]] name = "httparse" version = "1.8.0" @@ -1464,7 +1512,7 @@ dependencies = [ "socket2", "tokio", "tower-service", - "tracing", + "tracing 0.1.36", "want", ] @@ -1712,6 +1760,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "matchit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73cbba799671b762df5a175adf59ce145165747bb891505c43d09aefbbf38beb" + [[package]] name = "maud" version = "0.24.0" @@ -1775,12 +1829,6 @@ dependencies = [ "windows-sys", ] -[[package]] -name = "multimap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" - [[package]] name = "nanoid" version = "0.4.0" @@ -1930,8 +1978,6 @@ checksum = "6105e89802af13fdf48c49d7646d3b533a70e536d818aae7e78ba0433d01acb8" dependencies = [ "async-trait", "crossbeam-channel", - "dashmap", - "fnv", "futures-channel", "futures-executor", "futures-util", @@ -1941,26 +1987,80 @@ dependencies = [ "pin-project", "rand", "thiserror", - "tokio", - "tokio-stream", +] + +[[package]] +name = "opentelemetry" +version = "0.18.0" +source = "git+https://github.com/jarnura/opentelemetry-rust?rev=a82056696ca3d26960458269a894e5cf15056ad8#a82056696ca3d26960458269a894e5cf15056ad8" +dependencies = [ + "opentelemetry_api", + "opentelemetry_sdk", ] [[package]] name = "opentelemetry-otlp" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1a6ca9de4c8b00aa7f1a153bd76cb263287155cec642680d79d98706f3d28a" +version = "0.11.0" +source = "git+https://github.com/jarnura/opentelemetry-rust?rev=a82056696ca3d26960458269a894e5cf15056ad8#a82056696ca3d26960458269a894e5cf15056ad8" dependencies = [ "async-trait", "futures", "futures-util", "http", - "opentelemetry", + "opentelemetry 0.18.0", + "opentelemetry-proto", "prost", "thiserror", "tokio", "tonic", - "tonic-build", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.1.0" +source = "git+https://github.com/jarnura/opentelemetry-rust?rev=a82056696ca3d26960458269a894e5cf15056ad8#a82056696ca3d26960458269a894e5cf15056ad8" +dependencies = [ + "futures", + "futures-util", + "opentelemetry 0.18.0", + "prost", + "tonic", +] + +[[package]] +name = "opentelemetry_api" +version = "0.18.0" +source = "git+https://github.com/jarnura/opentelemetry-rust?rev=a82056696ca3d26960458269a894e5cf15056ad8#a82056696ca3d26960458269a894e5cf15056ad8" +dependencies = [ + "fnv", + "futures-channel", + "futures-util", + "indexmap", + "js-sys", + "once_cell", + "pin-project-lite", + "thiserror", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.18.0" +source = "git+https://github.com/jarnura/opentelemetry-rust?rev=a82056696ca3d26960458269a894e5cf15056ad8#a82056696ca3d26960458269a894e5cf15056ad8" +dependencies = [ + "async-trait", + "crossbeam-channel", + "dashmap", + "fnv", + "futures-channel", + "futures-executor", + "futures-util", + "once_cell", + "opentelemetry_api", + "percent-encoding", + "rand", + "thiserror", + "tokio", + "tokio-stream", ] [[package]] @@ -2092,16 +2192,6 @@ dependencies = [ "sha1", ] -[[package]] -name = "petgraph" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5014253a1331579ce62aa67443b4a658c5e7dd03d4bc6d302b94474888143" -dependencies = [ - "fixedbitset", - "indexmap", -] - [[package]] name = "pin-project" version = "1.0.12" @@ -2200,39 +2290,19 @@ dependencies = [ [[package]] name = "prost" -version = "0.9.0" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "444879275cb4fd84958b1a1d5420d15e6fcf7c235fe47f053c9c2a80aceb6001" +checksum = "a0841812012b2d4a6145fae9a6af1534873c32aa67fff26bd09f8fa42c83f95a" dependencies = [ "bytes", "prost-derive", ] -[[package]] -name = "prost-build" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62941722fb675d463659e49c4f3fe1fe792ff24fe5bbaa9c08cd3b98a1c354f5" -dependencies = [ - "bytes", - "heck 0.3.3", - "itertools", - "lazy_static", - "log", - "multimap", - "petgraph", - "prost", - "prost-types", - "regex", - "tempfile", - "which", -] - [[package]] name = "prost-derive" -version = "0.9.0" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9cc1a3263e07e0bf68e96268f37665207b49560d98739662cdfaae215c720fe" +checksum = "164ae68b6587001ca506d3bf7f1000bfa248d0e1217b618108fba4ec1d0cc306" dependencies = [ "anyhow", "itertools", @@ -2241,16 +2311,6 @@ dependencies = [ "syn", ] -[[package]] -name = "prost-types" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534b7a0e836e3c482d2693070f982e39e7611da9695d4d1f5a4b186b51faef0a" -dependencies = [ - "bytes", - "prost", -] - [[package]] name = "quick-error" version = "1.2.3" @@ -2518,7 +2578,7 @@ dependencies = [ "config", "gethostname", "once_cell", - "opentelemetry", + "opentelemetry 0.18.0", "opentelemetry-otlp", "rustc-hash", "serde", @@ -2527,12 +2587,12 @@ dependencies = [ "strum", "time", "tokio", - "tracing", + "tracing 0.1.36", "tracing-actix-web", "tracing-appender", - "tracing-core", - "tracing-opentelemetry", - "tracing-subscriber", + "tracing-core 0.1.29", + "tracing-opentelemetry 0.16.0", + "tracing-subscriber 0.3.15", "vergen", ] @@ -2895,6 +2955,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20518fe4a4c9acf048008599e464deb21beeae3d3578418951a189c235a7a9a8" + [[package]] name = "sysinfo" version = "0.26.4" @@ -3113,7 +3179,7 @@ dependencies = [ "futures-sink", "pin-project-lite", "tokio", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -3127,12 +3193,13 @@ dependencies = [ [[package]] name = "tonic" -version = "0.6.2" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff08f4649d10a70ffa3522ca559031285d8e421d727ac85c60825761818f5d0a" +checksum = "55b9af819e54b8f33d453655bef9b9acc171568fb49523078d0cc4e7484200ec" dependencies = [ "async-stream", "async-trait", + "axum", "base64", "bytes", "futures-core", @@ -3148,26 +3215,14 @@ dependencies = [ "prost-derive", "tokio", "tokio-stream", - "tokio-util 0.6.10", + "tokio-util 0.7.4", "tower", "tower-layer", "tower-service", - "tracing", + "tracing 0.1.36", "tracing-futures", ] -[[package]] -name = "tonic-build" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9403f1bafde247186684b230dc6f38b5cd514584e8bec1dd32514be4745fa757" -dependencies = [ - "proc-macro2", - "prost-build", - "quote", - "syn", -] - [[package]] name = "tower" version = "0.4.13" @@ -3185,7 +3240,26 @@ dependencies = [ "tokio-util 0.7.4", "tower-layer", "tower-service", - "tracing", + "tracing 0.1.36", +] + +[[package]] +name = "tower-http" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c530c8675c1dbf98facee631536fa116b5fb6382d7dd6dc1b118d970eafe3ba" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-range-header", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", ] [[package]] @@ -3210,7 +3284,17 @@ dependencies = [ "log", "pin-project-lite", "tracing-attributes", - "tracing-core", + "tracing-core 0.1.29", +] + +[[package]] +name = "tracing" +version = "0.2.0" +source = "git+https://github.com/jarnura/tracing?rev=16d277227f60788750528e4f4cc1db4f36b0869f#16d277227f60788750528e4f4cc1db4f36b0869f" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-core 0.2.0", ] [[package]] @@ -3220,10 +3304,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee7247a77b494ee07bda43bce40a33e76f885662f11b3dda9894ecfdbe31fa06" dependencies = [ "actix-web", - "opentelemetry", + "opentelemetry 0.17.0", "pin-project", - "tracing", - "tracing-opentelemetry", + "tracing 0.1.36", + "tracing-opentelemetry 0.17.4", "uuid", ] @@ -3235,7 +3319,7 @@ checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e" dependencies = [ "crossbeam-channel", "time", - "tracing-subscriber", + "tracing-subscriber 0.3.15", ] [[package]] @@ -3259,6 +3343,14 @@ dependencies = [ "valuable", ] +[[package]] +name = "tracing-core" +version = "0.2.0" +source = "git+https://github.com/jarnura/tracing?rev=16d277227f60788750528e4f4cc1db4f36b0869f#16d277227f60788750528e4f4cc1db4f36b0869f" +dependencies = [ + "once_cell", +] + [[package]] name = "tracing-futures" version = "0.2.5" @@ -3266,7 +3358,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2" dependencies = [ "pin-project", - "tracing", + "tracing 0.1.36", ] [[package]] @@ -3277,7 +3369,31 @@ checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" dependencies = [ "lazy_static", "log", - "tracing-core", + "tracing-core 0.1.29", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "git+https://github.com/jarnura/tracing?rev=16d277227f60788750528e4f4cc1db4f36b0869f#16d277227f60788750528e4f4cc1db4f36b0869f" +dependencies = [ + "log", + "once_cell", + "tracing-core 0.2.0", +] + +[[package]] +name = "tracing-opentelemetry" +version = "0.16.0" +source = "git+https://github.com/jarnura/tracing?rev=16d277227f60788750528e4f4cc1db4f36b0869f#16d277227f60788750528e4f4cc1db4f36b0869f" +dependencies = [ + "async-trait", + "once_cell", + "opentelemetry 0.18.0", + "tracing 0.2.0", + "tracing-core 0.2.0", + "tracing-log 0.2.0", + "tracing-subscriber 0.3.0", ] [[package]] @@ -3287,11 +3403,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbbe89715c1dbbb790059e2565353978564924ee85017b5fff365c872ff6721f" dependencies = [ "once_cell", - "opentelemetry", - "tracing", - "tracing-core", - "tracing-log", - "tracing-subscriber", + "opentelemetry 0.17.0", + "tracing 0.1.36", + "tracing-core 0.1.29", + "tracing-log 0.1.3", + "tracing-subscriber 0.3.15", ] [[package]] @@ -3301,7 +3417,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc6b213177105856957181934e4920de57730fc69bf42c37ee5bb664d406d9e1" dependencies = [ "serde", - "tracing-core", + "tracing-core 0.1.29", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.0" +source = "git+https://github.com/jarnura/tracing?rev=16d277227f60788750528e4f4cc1db4f36b0869f#16d277227f60788750528e4f4cc1db4f36b0869f" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core 0.2.0", ] [[package]] @@ -3319,9 +3445,9 @@ dependencies = [ "sharded-slab", "smallvec", "thread_local", - "tracing", - "tracing-core", - "tracing-log", + "tracing 0.1.36", + "tracing-core 0.1.29", + "tracing-log 0.1.3", "tracing-serde", ] @@ -3573,17 +3699,6 @@ dependencies = [ "webpki 0.22.0", ] -[[package]] -name = "which" -version = "4.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c831fbbee9e129a8cf93e7747a82da9d95ba8e16621cae60ec2cdc849bacb7b" -dependencies = [ - "either", - "libc", - "once_cell", -] - [[package]] name = "winapi" version = "0.3.9" diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index bfb03e5f827..cdac412b785 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -75,7 +75,7 @@ impl Feature<api::Authorize, types::PaymentsRequestData> ) .await; - metrics::PAYMENT_COUNT.add(1, &[]); // Metrics + metrics::PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics (resp, payment_data) } diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 1b403b8615a..78e837cb757 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -212,7 +212,7 @@ where payment_attempt: &storage::PaymentAttempt, ) -> CustomResult<(), errors::ApiErrorResponse> { if helpers::check_if_operation_confirm(self) { - metrics::TASKS_ADDED_COUNT.add(1, &[]); // Metrics + metrics::TASKS_ADDED_COUNT.add(&metrics::CONTEXT, 1, &[]); // Metrics let schedule_time = payment_sync::get_sync_process_schedule_time( &payment_attempt.connector, diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs index 34c9321501d..cc0b72318b3 100644 --- a/crates/router/src/routes/health.rs +++ b/crates/router/src/routes/health.rs @@ -3,14 +3,14 @@ use router_env::{ tracing::{self, instrument}, }; -use crate::routes::metrics::HEALTH_METRIC; +use crate::routes::metrics; /// . // #[logger::instrument(skip_all, name = "name1", level = "warn", fields( key1 = "val1" ))] #[instrument(skip_all)] // #[actix_web::get("/health")] pub async fn health() -> impl actix_web::Responder { - HEALTH_METRIC.add(1, &[]); + metrics::HEALTH_METRIC.add(&metrics::CONTEXT, 1, &[]); logger::info!("Health was called"); actix_web::HttpResponse::Ok().body("health is good") } diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs index 8cd573aef56..da21095b5d4 100644 --- a/crates/router/src/routes/metrics.rs +++ b/crates/router/src/routes/metrics.rs @@ -4,8 +4,10 @@ use once_cell::sync::Lazy; use router_env::opentelemetry::{ global, metrics::{Counter, Meter}, + Context, }; +pub static CONTEXT: Lazy<Context> = Lazy::new(Context::current); static GLOBAL_METER: Lazy<Meter> = Lazy::new(|| global::meter("ROUTER_API")); pub(crate) static HEALTH_METRIC: Lazy<Counter<u64>> = diff --git a/crates/router/src/scheduler/consumer.rs b/crates/router/src/scheduler/consumer.rs index 41f12853cd5..2b5fb45c0d0 100644 --- a/crates/router/src/scheduler/consumer.rs +++ b/crates/router/src/scheduler/consumer.rs @@ -118,7 +118,7 @@ pub async fn consumer_operations( pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name); - metrics::TASK_CONSUMED.add(1, &[]); + metrics::TASK_CONSUMED.add(&metrics::CONTEXT, 1, &[]); let runner = pt_utils::runner_from_task(task)?; handler.push(tokio::task::spawn(start_workflow( state.clone(), @@ -206,7 +206,7 @@ pub async fn run_executor<'a>( } }, }; - metrics::TASK_PROCESSED.add(1, &[]); + metrics::TASK_PROCESSED.add(&metrics::CONTEXT, 1, &[]); } #[instrument(skip_all)] diff --git a/crates/router/src/scheduler/metrics.rs b/crates/router/src/scheduler/metrics.rs index 7967c0cbc93..1a87248a734 100644 --- a/crates/router/src/scheduler/metrics.rs +++ b/crates/router/src/scheduler/metrics.rs @@ -1,15 +1,15 @@ use once_cell::sync::Lazy; use router_env::opentelemetry::{ global, - metrics::{Counter, Meter, ValueRecorder}, + metrics::{Counter, Histogram, Meter}, + Context, }; +pub static CONTEXT: Lazy<Context> = Lazy::new(Context::current); static PT_METER: Lazy<Meter> = Lazy::new(|| global::meter("PROCESS_TRACKER")); -// Using ValueRecorder till https://bitbucket.org/juspay/orca/pull-requests/319 -// Histogram available in opentelemetry:0.18 -pub(crate) static CONSUMER_STATS: Lazy<ValueRecorder<f64>> = - Lazy::new(|| PT_METER.f64_value_recorder("CONSUMER_OPS").init()); +pub(crate) static CONSUMER_STATS: Lazy<Histogram<f64>> = + Lazy::new(|| PT_METER.f64_histogram("CONSUMER_OPS").init()); macro_rules! create_counter { ($name:ident, $meter:ident) => { diff --git a/crates/router/src/scheduler/producer.rs b/crates/router/src/scheduler/producer.rs index 0c4ab2ca810..f903230d60c 100644 --- a/crates/router/src/scheduler/producer.rs +++ b/crates/router/src/scheduler/producer.rs @@ -125,6 +125,6 @@ pub async fn fetch_producer_tasks( } new_tasks.append(&mut pending_tasks); - metrics::TASKS_PICKED_COUNT.add(new_tasks.len() as u64, &[]); + metrics::TASKS_PICKED_COUNT.add(&metrics::CONTEXT, new_tasks.len() as u64, &[]); Ok(new_tasks) } diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs index d64955ab4a6..cf86bd06316 100644 --- a/crates/router/src/scheduler/utils.rs +++ b/crates/router/src/scheduler/utils.rs @@ -72,7 +72,7 @@ pub async fn divide_and_append_tasks( settings: &SchedulerSettings, ) -> CustomResult<(), errors::ProcessTrackerError> { let batches = divide(tasks, settings); - metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metrics + metrics::BATCHES_CREATED.add(&metrics::CONTEXT, batches.len() as u64, &[]); // Metrics for batch in batches { let result = update_status_and_append(state, flow, batch).await; match result { @@ -209,7 +209,7 @@ pub async fn get_batches( logger::error!(%error, "Error finding batch in stream"); error.change_context(errors::ProcessTrackerError::BatchNotFound) })?; - metrics::BATCHES_CONSUMED.add(1, &[]); + metrics::BATCHES_CONSUMED.add(&metrics::CONTEXT, 1, &[]); let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_iter().map(|(_key, entries)| { entries.into_iter().try_fold( @@ -303,6 +303,7 @@ pub fn add_histogram_metrics( logger::error!(%pickup_schedule_delta, "<- Time delta for scheduled tasks"); let runner_name = runner.clone(); metrics::CONSUMER_STATS.record( + &metrics::CONTEXT, pickup_schedule_delta, &[opentelemetry::KeyValue::new( stream_name.to_owned(), diff --git a/crates/router/src/types/storage/process_tracker.rs b/crates/router/src/types/storage/process_tracker.rs index fa9ac368bac..b460b6ba421 100644 --- a/crates/router/src/types/storage/process_tracker.rs +++ b/crates/router/src/types/storage/process_tracker.rs @@ -77,7 +77,7 @@ impl ProcessTracker { db: &dyn db::Db, schedule_time: PrimitiveDateTime, ) -> Result<(), errors::ProcessTrackerError> { - metrics::TASK_RETRIED.add(1, &[]); + metrics::TASK_RETRIED.add(&metrics::CONTEXT, 1, &[]); db.update_process_tracker( self.clone(), ProcessTrackerUpdate::StatusRetryUpdate { @@ -104,7 +104,7 @@ impl ProcessTracker { ) .await .attach_printable("Failed while updating status of the process")?; - metrics::TASK_FINISHED.add(1, &[]); + metrics::TASK_FINISHED.add(&metrics::CONTEXT, 1, &[]); Ok(()) } } diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml index e97dc09d198..dfe88f6a104 100644 --- a/crates/router_env/Cargo.toml +++ b/crates/router_env/Cargo.toml @@ -12,8 +12,9 @@ build = "src/build.rs" config = { version = "0.13.2", features = ["toml"] } gethostname = "0.2.3" once_cell = "1.15.0" -opentelemetry = { version = "0.17", features = ["rt-tokio-current-thread", "metrics"] } -opentelemetry-otlp = { version = "0.10", features = ["metrics"] } +opentelemetry = { git = "https://github.com/jarnura/opentelemetry-rust", rev = "a82056696ca3d26960458269a894e5cf15056ad8", features = ["rt-tokio-current-thread", "metrics"] } +opentelemetry-otlp = { git = "https://github.com/jarnura/opentelemetry-rust", rev = "a82056696ca3d26960458269a894e5cf15056ad8", features = ["metrics"] } + rustc-hash = "1.1" serde = { version = "1.0.145", features = ["derive"] } serde_json = "1.0.85" @@ -25,7 +26,7 @@ tracing = "0.1.36" tracing-actix-web = { version = "0.6.1", features = ["opentelemetry_0_17"], optional = true } tracing-appender = "0.2.2" tracing-core = "0.1.29" -tracing-opentelemetry = { version = "0.17" } +tracing-opentelemetry = { git = "https://github.com/jarnura/tracing", rev = "16d277227f60788750528e4f4cc1db4f36b0869f" } tracing-subscriber = { version = "0.3.15", default-features = true, features = ["json", "env-filter", "registry"] } vergen = { version = "7.4.2", optional = true } diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index 2eb7f181709..4ba3bbc3429 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -3,20 +3,19 @@ //! use std::{path::PathBuf, time::Duration}; +use once_cell::sync::Lazy; use opentelemetry::{ - global, + global, runtime, sdk::{ - metrics::{selectors, PushController}, + export::metrics::aggregation::cumulative_temporality_selector, + metrics::{controllers::BasicController, selectors::simple}, propagation::TraceContextPropagator, trace, Resource, }, - util::tokio_interval_stream, KeyValue, }; use opentelemetry_otlp::WithExportConfig; use tracing_appender::non_blocking::WorkerGuard; -// use tracing_subscriber::fmt::format::FmtSpan; -// use tracing_bunyan_formatter::JsonStorageLayer; use tracing_subscriber::{ filter, fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer, }; @@ -51,7 +50,7 @@ where #[derive(Debug)] pub struct TelemetryGuard { _log_guards: Vec<WorkerGuard>, - _metric_controller: Option<PushController>, + _metric_controller: Option<BasicController>, } /// @@ -92,29 +91,13 @@ pub fn setup<Str: AsRef<str>>( let file_filter = filter::Targets::new().with_default(conf.file.level.into_level()); let file_layer = FormattingLayer::new(service_name, file_writer).with_filter(file_filter); - // let fmt_layer = fmt::layer() - // .with_writer(file_writer) - // .with_target(true) - // .with_level(true) - // .with_span_events(FmtSpan::ACTIVE) - // .json(); - - // Some(fmt_layer) - //Some(FormattingLayer::new(service_name, file_writer)) Some(file_layer) - // Some(BunyanFormattingLayer::new("router".into(), file_writer)) } else { None }; - let telemetry_layer = match telemetry { - Some(Ok(ref tracer)) => Some(tracing_opentelemetry::layer().with_tracer(tracer.clone())), - _ => None, - }; - // Use 'RUST_LOG' environment variable will override the config settings let subscriber = tracing_subscriber::registry() - .with(telemetry_layer) .with(StorageSubscription) .with(file_writer) .with( @@ -166,15 +149,29 @@ pub fn setup<Str: AsRef<str>>( }) } -fn setup_metrics() -> Option<PushController> { +static HISTOGRAM_BUCKETS: Lazy<[f64; 15]> = Lazy::new(|| { + let mut init = 0.01; + let mut buckets: [f64; 15] = [0.0; 15]; + + for bucket in &mut buckets { + init *= 2.0; + *bucket = init; + } + buckets +}); + +fn setup_metrics() -> Option<BasicController> { opentelemetry_otlp::new_pipeline() - .metrics(tokio::spawn, tokio_interval_stream) + .metrics( + simple::histogram(*HISTOGRAM_BUCKETS), + cumulative_temporality_selector(), + runtime::TokioCurrentThread, + ) .with_exporter( opentelemetry_otlp::new_exporter().tonic().with_env(), // can also config it using with_* functions like the tracing part above. ) .with_period(Duration::from_secs(3)) .with_timeout(Duration::from_secs(10)) - .with_aggregator_selector(selectors::simple::Selector::Exact) .build() .map_err(|err| eprintln!("Failed to Setup Metrics with {:?}", err)) .ok()
2022-11-27T10:31:38Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates ## Description This change includes changes for adding histogram with additional requirement on updating the current telemetry dependencies. (this is a temporary change discussed with @jarnura, for initial deployment of scheduler unit <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context For adding the histogram functionality in the metrics a new version of opentelemetry was required. This change disables certain functionality from the `router_env`crate <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code - [ ] I added unit tests for my changes where possible - [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
d67bd801f621b9784121f516b5ac65328d2aa431
juspay/hyperswitch
juspay__hyperswitch-5990
Bug: [FIX] Remove ToSchema from RefundAggregateResponse and exclude it from OpenAPI documentation ### Feature Description The RefundAggregateResponse type used by the [/refunds/aggregate](https://github.com/juspay/hyperswitch/blob/37925626e6446900f1d16e0e5f184ee472d4be3e/crates/router/src/routes/app.rs#L1004) API is currently annotated with ToSchema, which generates OpenAPI schema documentation for it. However, since this API is internal and should not be exposed to external users, the schema should not be generated or included in the OpenAPI documentation. Current Behavior: - The `RefundAggregateResponse` struct is annotated with ToSchema, which automatically generates OpenAPI documentation. - This results in the exposure of internal API details that should remain hidden from external consumers. Expected Behavior: - Remove the `ToSchema` derive macro from the RefundAggregateResponse struct. - Ensure that this struct and its associated API are excluded from OpenAPI documentation generation. ### Possible Implementation The Api [refunds/aggregate](https://github.com/juspay/hyperswitch/blob/37925626e6446900f1d16e0e5f184ee472d4be3e/crates/router/src/core/refunds.rs#L1098) returns `RefundAggregateResponse` The following code should be modified to remove ToSchema and update the OpenAPI documentation accordingly: ``` #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, } ``` Tasks: - Remove the ToSchema derive macro from the RefundAggregateResponse struct. - Remove any references to RefundAggregateResponse from openapi.rs to ensure it is not documented. - Test to verify that this type is no longer included in the OpenAPI schema. Additional Context: Since the `/refunds/aggregate` API is for internal use only, removing the OpenAPI schema ensures that this internal API remains undocumented for merchants. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 72afa1dc3da..63c01329dfe 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -18158,22 +18158,6 @@ } } }, - "RefundAggregateResponse": { - "type": "object", - "required": [ - "status_with_count" - ], - "properties": { - "status_with_count": { - "type": "object", - "description": "The list of refund status with their count", - "additionalProperties": { - "type": "integer", - "format": "int64" - } - } - } - }, "RefundErrorDetails": { "type": "object", "required": [ diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index f42eb8095b4..ac5e5cb4618 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -346,7 +346,7 @@ pub struct RefundListFilters { pub refund_status: Vec<enums::RefundStatus>, } -#[derive(Clone, Debug, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 28a7f44c7a8..754ec433b77 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -492,7 +492,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, - api_models::refunds::RefundAggregateResponse, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 7c961b2b2b2..84f320778fe 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -432,7 +432,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, - api_models::refunds::RefundAggregateResponse, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse,
2024-10-22T20:13:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Removed all the openapi references to `RefundAggregateResponse`. 1. Removed `ToSchema` trait for `RefundAggregateResponse`. 2. Removed references from `openapi` and `openapi_v2` to `RefundAggregateResponse`. 3. Generated new `openapi_spec` file based on the above changes. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> #5990 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested manually. The references of `RefundAggregateResponse` is removed in openapi generated json file after the modification. <img width="871" alt="image" src="https://github.com/user-attachments/assets/70f23a10-37e9-420e-8031-f41e6b5f11da"> <img width="1015" alt="image" src="https://github.com/user-attachments/assets/614b9c86-2735-445c-8aa0-d54248f944a5"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
aee11c560e427195a0d321dff19c0d33ec60ba64
juspay/hyperswitch
juspay__hyperswitch-5996
Bug: feat(users): Add entity type filter in list users and list roles API Currently list users and list roles API is sending all the users and roles respectively for those who are same entity level and less. We need to add filters in these APIs to send users and roles who are only at particular entity level.
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs index 81b38198cfc..eb09abd471c 100644 --- a/crates/api_models/src/events/user_role.rs +++ b/crates/api_models/src/events/user_role.rs @@ -2,12 +2,12 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ - CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesResponse, - RoleInfoResponseNew, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse, - UpdateRoleRequest, + CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest, + ListRolesResponse, RoleInfoResponseNew, RoleInfoWithGroupsResponse, + RoleInfoWithPermissionsResponse, UpdateRoleRequest, }, AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest, - MerchantSelectRequest, UpdateUserRoleRequest, + ListUsersInEntityRequest, MerchantSelectRequest, UpdateUserRoleRequest, }; common_utils::impl_api_event_type!( @@ -25,6 +25,8 @@ common_utils::impl_api_event_type!( ListRolesResponse, ListRolesAtEntityLevelRequest, RoleInfoResponseNew, - RoleInfoWithGroupsResponse + RoleInfoWithGroupsResponse, + ListUsersInEntityRequest, + ListRolesRequest ) ); diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs index 8e1a0483c07..f2743d6a311 100644 --- a/crates/api_models/src/user_role.rs +++ b/crates/api_models/src/user_role.rs @@ -159,3 +159,8 @@ pub struct Entity { pub entity_id: String, pub entity_type: common_enums::EntityType, } + +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ListUsersInEntityRequest { + pub entity_type: Option<common_enums::EntityType>, +} diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 828dfeb20f8..be467421e65 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -35,6 +35,11 @@ pub struct RoleInfoWithGroupsResponse { pub role_scope: RoleScope, } +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct ListRolesRequest { + pub entity_type: Option<EntityType>, +} + #[derive(Debug, serde::Serialize)] pub struct RoleInfoResponseNew { pub role_id: String, diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index d42f71695a5..fd9c8c89031 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -673,6 +673,7 @@ pub async fn delete_user_role( pub async fn list_users_in_lineage( state: SessionState, user_from_token: auth::UserFromToken, + request: user_role_api::ListUsersInEntityRequest, ) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> { let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, @@ -683,51 +684,55 @@ pub async fn list_users_in_lineage( .await .change_context(UserErrors::InternalServerError)?; - let user_roles_set: HashSet<_> = match requestor_role_info.get_entity_type() { - EntityType::Organization => state - .store - .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload { - user_id: None, - org_id: &user_from_token.org_id, - merchant_id: None, - profile_id: None, - version: None, - }) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .collect(), - EntityType::Merchant => state - .store - .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload { - user_id: None, - org_id: &user_from_token.org_id, - merchant_id: Some(&user_from_token.merchant_id), - profile_id: None, - version: None, - }) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .collect(), + let user_roles_set: HashSet<_> = match utils::user_role::get_min_entity( + requestor_role_info.get_entity_type(), + request.entity_type, + )? { + EntityType::Organization => { + utils::user_role::fetch_user_roles_by_payload( + &state, + ListUserRolesByOrgIdPayload { + user_id: None, + org_id: &user_from_token.org_id, + merchant_id: None, + profile_id: None, + version: None, + }, + request.entity_type, + ) + .await? + } + EntityType::Merchant => { + utils::user_role::fetch_user_roles_by_payload( + &state, + ListUserRolesByOrgIdPayload { + user_id: None, + org_id: &user_from_token.org_id, + merchant_id: Some(&user_from_token.merchant_id), + profile_id: None, + version: None, + }, + request.entity_type, + ) + .await? + } EntityType::Profile => { let Some(profile_id) = user_from_token.profile_id.as_ref() else { return Err(UserErrors::JwtProfileIdMissing.into()); }; - state - .store - .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload { + utils::user_role::fetch_user_roles_by_payload( + &state, + ListUserRolesByOrgIdPayload { user_id: None, org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: Some(profile_id), version: None, - }) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .collect() + }, + request.entity_type, + ) + .await? } EntityType::Internal => HashSet::new(), }; diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 571ae7f995d..ffc18214c20 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -217,6 +217,7 @@ pub async fn update_role( pub async fn list_roles_with_info( state: SessionState, user_from_token: UserFromToken, + request: role_api::ListRolesRequest, ) -> UserResponse<Vec<role_api::RoleInfoResponseNew>> { let user_role_info = user_from_token .get_role_info_from_db(&state) @@ -229,49 +230,57 @@ pub async fn list_roles_with_info( .collect::<Vec<_>>(); let user_role_entity = user_role_info.get_entity_type(); - let custom_roles = match user_role_entity { - EntityType::Organization => state - .store - .list_roles_for_org_by_parameters(&user_from_token.org_id, None, None, None) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to get roles")?, - EntityType::Merchant => state - .store - .list_roles_for_org_by_parameters( - &user_from_token.org_id, - Some(&user_from_token.merchant_id), - None, - None, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to get roles")?, - // TODO: Populate this from Db function when support for profile id and profile level custom roles is added - EntityType::Profile => Vec::new(), - EntityType::Internal => { - return Err(UserErrors::InvalidRoleOperationWithMessage( - "Internal roles are not allowed for this operation".to_string(), - ) - .into()); - } - }; + let custom_roles = + match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? { + EntityType::Organization => state + .store + .list_roles_for_org_by_parameters( + &user_from_token.org_id, + None, + request.entity_type, + None, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get roles")?, + EntityType::Merchant => state + .store + .list_roles_for_org_by_parameters( + &user_from_token.org_id, + Some(&user_from_token.merchant_id), + request.entity_type, + None, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get roles")?, + // TODO: Populate this from Db function when support for profile id and profile level custom roles is added + EntityType::Profile => Vec::new(), + EntityType::Internal => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Internal roles are not allowed for this operation".to_string(), + ) + .into()); + } + }; role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from)); + let list_role_info_response = role_info_vec .into_iter() .filter_map(|role_info| { - if user_role_entity >= role_info.get_entity_type() { - Some(role_api::RoleInfoResponseNew { - role_id: role_info.get_role_id().to_string(), - role_name: role_info.get_role_name().to_string(), - groups: role_info.get_permission_groups().to_vec(), - entity_type: role_info.get_entity_type(), - scope: role_info.get_scope(), - }) - } else { - None - } + let is_lower_entity = user_role_entity >= role_info.get_entity_type(); + let request_filter = request.entity_type.map_or(true, |entity_type| { + entity_type == role_info.get_entity_type() + }); + + (is_lower_entity && request_filter).then_some(role_api::RoleInfoResponseNew { + role_id: role_info.get_role_id().to_string(), + role_name: role_info.get_role_name().to_string(), + groups: role_info.get_permission_groups().to_vec(), + entity_type: role_info.get_entity_type(), + scope: role_info.get_scope(), + }) }) .collect::<Vec<_>>(); diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index b1260b5d7ad..922e7612b14 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -291,16 +291,20 @@ pub async fn get_role_information( .await } -pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn list_users_in_lineage( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<user_role_api::ListUsersInEntityRequest>, +) -> HttpResponse { let flow = Flow::ListUsersInLineage; Box::pin(api::server_wrap( flow, state.clone(), &req, - (), - |state, user_from_token, _, _| { - user_role_core::list_users_in_lineage(state, user_from_token) + query.into_inner(), + |state, user_from_token, request, _| { + user_role_core::list_users_in_lineage(state, user_from_token, request) }, &auth::DashboardNoPermissionAuth, api_locking::LockAction::NotApplicable, @@ -308,15 +312,21 @@ pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest) .await } -pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse { +pub async fn list_roles_with_info( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<role_api::ListRolesRequest>, +) -> HttpResponse { let flow = Flow::ListRolesV2; Box::pin(api::server_wrap( flow, state.clone(), &req, - (), - |state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token), + query.into_inner(), + |state, user_from_token, request, _| { + role_core::list_roles_with_info(state, user_from_token, request) + }, &auth::JWTAuth { permission: Permission::UsersRead, minimum_entity_level: EntityType::Profile, diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index b4008bd0008..9141b91bdd6 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -14,7 +14,7 @@ use storage_impl::errors::StorageError; use crate::{ consts, core::errors::{UserErrors, UserResult}, - db::user_role::ListUserRolesByUserIdPayload, + db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, routes::SessionState, services::authorization::{self as authz, permissions::Permission, roles}, types::domain, @@ -398,3 +398,61 @@ pub async fn get_single_merchant_id_and_profile_id( Ok((merchant_id, profile_id)) } + +pub async fn fetch_user_roles_by_payload( + state: &SessionState, + payload: ListUserRolesByOrgIdPayload<'_>, + request_entity_type: Option<EntityType>, +) -> UserResult<HashSet<UserRole>> { + Ok(state + .store + .list_user_roles_by_org_id(payload) + .await + .change_context(UserErrors::InternalServerError)? + .into_iter() + .filter_map(|user_role| { + let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?; + request_entity_type + .map_or(true, |req_entity_type| entity_type == req_entity_type) + .then_some(user_role) + }) + .collect::<HashSet<_>>()) +} + +pub fn get_min_entity( + user_entity: EntityType, + filter_entity: Option<EntityType>, +) -> UserResult<EntityType> { + match (user_entity, filter_entity) { + (EntityType::Organization, None) + | (EntityType::Organization, Some(EntityType::Organization)) => { + Ok(EntityType::Organization) + } + + (EntityType::Merchant, None) + | (EntityType::Organization, Some(EntityType::Merchant)) + | (EntityType::Merchant, Some(EntityType::Merchant)) => Ok(EntityType::Merchant), + + (EntityType::Profile, None) + | (EntityType::Organization, Some(EntityType::Profile)) + | (EntityType::Merchant, Some(EntityType::Profile)) + | (EntityType::Profile, Some(EntityType::Profile)) => Ok(EntityType::Profile), + + (EntityType::Internal, _) => Ok(EntityType::Internal), + + (EntityType::Organization, Some(EntityType::Internal)) + | (EntityType::Merchant, Some(EntityType::Internal)) + | (EntityType::Profile, Some(EntityType::Internal)) => { + Err(UserErrors::InvalidRoleOperation.into()) + } + + (EntityType::Merchant, Some(EntityType::Organization)) + | (EntityType::Profile, Some(EntityType::Organization)) + | (EntityType::Profile, Some(EntityType::Merchant)) => { + Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!( + "{} level user requesting data for {:?} level", + user_entity, filter_entity + )) + } + } +}
2024-09-23T13:30:11Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Adds entity_type filter in list users and list roles API. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5996. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. List Users ``` curl 'http://localhost:8080/user/user/v2/list' \ -H 'authorization: Bearer JWT' \ ``` This should respond with all the users who are at the same level and lower. ``` curl 'http://localhost:8080/user/user/v2/list?entity_type=organization' \ -H 'authorization: Bearer JWT' \ ``` This can only be hit by org level users and only responds with org level users. ``` curl 'http://localhost:8080/user/user/v2/list?entity_type=merchant' \ -H 'authorization: Bearer JWT' \ ``` This can only be hit by merchant and org level users and only responds with merchant level users. ``` curl 'http://localhost:8080/user/user/v2/list?entity_type=profile' \ -H 'authorization: Bearer JWT' \ ``` This can only be hit by profile, merchant and org level users and only responds with profile level users. Response for all the above curls should follow the same structure ```json [ { "email": "email", "roles": [ { "role_id": "merchant_view_only", "role_name": "merchant_view_only" } ] }, { "email": "email", "roles": [ { "role_id": "merchant_view_only", "role_name": "merchant_view_only" } ] }, { "email": "email", "roles": [ { "role_id": "merchant_view_only", "role_name": "merchant_view_only" } ] }, { "email": "email", "roles": [ { "role_id": "merchant_view_only", "role_name": "merchant_view_only" } ] } ] ``` 2. List Roles ``` curl 'http://localhost:8080/user/role/v2/list' \ -H 'authorization: Bearer JWT'' ``` ``` curl 'http://localhost:8080/user/role/v2/list?entity_type=merchant' \ -H 'authorization: Bearer JWT'' ``` This can only be hit by org and merchant level users and only responds with merchant level roles. ``` curl 'http://localhost:8080/user/role/v2/list?entity_type=profile' \ -H 'authorization: Bearer JWT'' ``` This can only be hit by org, merchant and profile level users and only responds with profile level roles. ``` curl 'http://localhost:8080/user/role/v2/list?entity_type=organization' \ -H 'authorization: Bearer JWT'' ``` This can only be hit by org level users and only responds with org level roles. Response should look like this: ```json [ { "role_id": "merchant_iam_admin", "role_name": "merchant_iam", "entity_type": "merchant", "groups": [ "operations_view", "analytics_view", "users_view", "users_manage", "merchant_details_view" ], "scope": "organization" }, { "role_id": "merchant_developer", "role_name": "merchant_developer", "entity_type": "merchant", "groups": [ "operations_view", "connectors_view", "analytics_view", "users_view", "merchant_details_view", "merchant_details_manage" ], "scope": "organization" }, { "role_id": "merchant_customer_support", "role_name": "customer_support", "entity_type": "merchant", "groups": [ "operations_view", "analytics_view", "users_view", "merchant_details_view" ], "scope": "organization" }, { "role_id": "profile_customer_support", "role_name": "profile_customer_support", "entity_type": "profile", "groups": [ "operations_view", "analytics_view", "users_view", "merchant_details_view" ], "scope": "organization" }, { "role_id": "merchant_admin", "role_name": "merchant_admin", "entity_type": "merchant", "groups": [ "operations_view", "operations_manage", "connectors_view", "connectors_manage", "workflows_view", "workflows_manage", "analytics_view", "users_view", "users_manage", "merchant_details_view", "merchant_details_manage", "recon_ops" ], "scope": "organization" }, { "role_id": "merchant_operator", "role_name": "merchant_operator", "entity_type": "merchant", "groups": [ "operations_view", "operations_manage", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "scope": "organization" }, { "role_id": "profile_operator", "role_name": "profile_operator", "entity_type": "profile", "groups": [ "operations_view", "operations_manage", "connectors_view", "workflows_view", "analytics_view", "users_view", "merchant_details_view" ], "scope": "organization" }, { "role_id": "org_admin", "role_name": "organization_admin", "entity_type": "organization", "groups": [ "operations_view", "operations_manage", "connectors_view", "connectors_manage", "workflows_view", "workflows_manage", "analytics_view", "users_view", "users_manage", "merchant_details_view", "merchant_details_manage", "organization_manage", "recon_ops" ], "scope": "organization" } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
035906e9b1b1a1e52fe970db5d7e028556fa82b4
juspay/hyperswitch
juspay__hyperswitch-5976
Bug: [BUG] [DEUTSCHEBANK] Trim the spaces in IBAN ### Bug Description Trim the spaces in IBAN before sending it in SEPA Mandate Post and Direct Debit requests for Deutsche Bank. ### Expected Behavior No spaces in IBAN in SEPA Mandate Post and Direct Debit requests. ### Actual Behavior Spaces in IBAN in SEPA Mandate Post and Direct Debit requests. ### Steps To Reproduce Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant. 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. 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 --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index 8b3837edd63..30b1d65134a 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -155,7 +155,7 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> Ok(Self::MandatePost(DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval::Click, email_address: item.router_data.request.get_email()?, - iban, + iban: Secret::from(iban.peek().replace(" ", "")), first_name: billing_address.get_first_name()?.clone(), last_name: billing_address.get_last_name()?.clone(), })) @@ -313,7 +313,7 @@ impl PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. - }) => Ok(iban), + }) => Ok(Secret::from(iban.peek().replace(" ", ""))), _ => Err(errors::ConnectorError::MissingRequiredField { field_name: "payment_method_data.bank_debit.sepa_bank_debit.iban" @@ -470,7 +470,7 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> means_of_payment: DeutschebankMeansOfPayment { bank_account: DeutschebankBankAccount { account_holder, - iban, + iban: Secret::from(iban.peek().replace(" ", "")), }, }, mandate: {
2024-09-20T11:49:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Trim the spaces in IBAN before sending it in SEPA Mandate Post and Direct Debit requests for Deutsche Bank. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/5976 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data '{ "amount": 9000, "currency": "EUR", "confirm": true, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "customer_id": "customer123", "payment_method": "bank_debit", "payment_method_type": "sepa", "payment_method_data": { "bank_debit": { "sepa_bank_debit": { "iban": "DE87 1234 5678 1234 5678 90" } } }, "billing": { "address": { "first_name": "joseph", "last_name": "doe" } }, "customer_acceptance": { "acceptance_type": "offline" }, "setup_future_usage": "off_session" }' ``` Response: ``` { "payment_id": "pay_THxTbiKwV1xv7Tmkqe8I", "merchant_id": "merchant_1725539597", "status": "requires_customer_action", "amount": 9000, "net_amount": 9000, "amount_capturable": 9000, "amount_received": null, "connector": "deutschebank", "client_secret": "pay_THxTbiKwV1xv7Tmkqe8I_secret_hx91jywe0lywBW5UrLb0", "created": "2024-09-20T11:05:32.884Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "something@example.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "DE87 **** **** **** **78 90", "bank_account_holder_name": null } }, "billing": null }, "payment_token": "token_LBU2etjaOq7pdJhAPHMk", "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "doe" }, "phone": null, "email": null }, "order_details": null, "email": "something@example.com", "name": "John Doe", "phone": "9999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_THxTbiKwV1xv7Tmkqe8I/merchant_1725539597/pay_THxTbiKwV1xv7Tmkqe8I_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1726830332, "expires": 1726833932, "secret": "epk_fb2f1bbac4204fc2841fd2b74a295fa0" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-20T11:20:32.884Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_R9MnbGoavSYoxTmxMiS2", "payment_method_status": null, "updated": "2024-09-20T11:05:35.073Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5335f2d21ce6f0c11dc84fd56b3cd2c80e8b064f
juspay/hyperswitch
juspay__hyperswitch-6002
Bug: [FEATURE] [CRYPTOPAY] Move connector code to crate hyperswitch_connectors ### Feature Description Connector code for `cryptopay` needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### Possible Implementation Connector code for `cryptopay` needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 48c50936d60..f057b7d4a33 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -1,5 +1,8 @@ pub mod bambora; pub mod bitpay; +pub mod cashtocode; +pub mod coinbase; +pub mod cryptopay; pub mod deutschebank; pub mod fiserv; pub mod fiservemea; @@ -18,8 +21,9 @@ pub mod volt; pub mod worldline; pub use self::{ - bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv, - fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, - nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, - thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline, + bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase, + cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea, + fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay, + novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes, + tsys::Tsys, volt::Volt, worldline::Worldline, }; diff --git a/crates/router/src/connector/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs similarity index 67% rename from crates/router/src/connector/cashtocode.rs rename to crates/hyperswitch_connectors/src/connectors/cashtocode.rs index 2155b80dd81..c72b63aebc0 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs @@ -1,33 +1,41 @@ pub mod transformers; - use base64::Engine; +use common_enums::enums; use common_utils::{ - request::RequestContent, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; -use diesel_models::enums; use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; -use transformers as cashtocode; - -use super::utils as connector_utils; -use crate::{ - configs::settings::{self}, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + api::ApplicationResponse, + router_data::{AccessToken, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - storage, ErrorResponse, Response, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, }, - utils::{ByteSliceExt, BytesExt}, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, Response}, + webhooks, +}; +use masking::{Mask, PeekInterface, Secret}; +use transformers as cashtocode; + +use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Cashtocode { @@ -56,13 +64,13 @@ impl api::RefundExecute for Cashtocode {} impl api::RefundSync for Cashtocode {} fn get_b64_auth_cashtocode( - payment_method_type: &Option<storage::enums::PaymentMethodType>, + payment_method_type: &Option<enums::PaymentMethodType>, auth_type: &transformers::CashtocodeAuth, -) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { +) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { fn construct_basic_auth( username: Option<Secret<String>>, password: Option<Secret<String>>, - ) -> Result<request::Maskable<String>, errors::ConnectorError> { + ) -> Result<masking::Maskable<String>, errors::ConnectorError> { let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?; let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( @@ -77,11 +85,11 @@ fn get_b64_auth_cashtocode( } let auth_header = match payment_method_type { - Some(storage::enums::PaymentMethodType::ClassicReward) => construct_basic_auth( + Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth( auth_type.username_classic.to_owned(), auth_type.password_classic.to_owned(), ), - Some(storage::enums::PaymentMethodType::Evoucher) => construct_basic_auth( + Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth( auth_type.username_evoucher.to_owned(), auth_type.password_evoucher.to_owned(), ), @@ -91,12 +99,8 @@ fn get_b64_auth_cashtocode( Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)]) } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Cashtocode +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Cashtocode { // Not Implemented (R) } @@ -115,7 +119,7 @@ impl ConnectorCommon for Cashtocode { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.cashtocode.base_url.as_ref() } @@ -153,39 +157,26 @@ impl ConnectorValidation for Cashtocode { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Cashtocode -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Cashtocode +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string()) .into(), @@ -193,17 +184,15 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + PaymentsAuthorizeType::get_content_type(self) .to_owned() .into(), )]; @@ -225,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/merchant/paytokens", @@ -236,10 +225,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -250,20 +239,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -272,10 +257,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cashtocode::CashtocodePaymentsResponse = res .response .parse_struct("Cashtocode PaymentsAuthorizeResponse") @@ -283,7 +268,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -299,23 +284,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode { // default implementation of build_request method will be executed fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: transformers::CashtocodePaymentsSyncResponse = res .response .parse_struct("CashtocodePaymentsSyncResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -331,18 +314,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Cashtocode".to_string(), @@ -351,14 +328,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Payments Cancel".to_string(), connector: "Cashtocode".to_string(), @@ -368,21 +343,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } #[async_trait::async_trait] -impl api::IncomingWebhook for Cashtocode { +impl webhooks::IncomingWebhook for Cashtocode { fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let base64_signature = - connector_utils::get_header_key_value("authorization", request.headers)?; + let base64_signature = utils::get_header_key_value("authorization", request.headers)?; let signature = base64_signature.as_bytes().to_owned(); Ok(signature) } async fn verify_webhook_source( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, @@ -412,7 +386,7 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let webhook: transformers::CashtocodePaymentsSyncResponse = request .body @@ -426,14 +400,14 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook: transformers::CashtocodeIncomingWebhook = request .body @@ -445,9 +419,8 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_api_response( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> - { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { let status = "EXECUTED".to_string(); let obj: transformers::CashtocodePaymentsSyncResponse = request .body @@ -455,22 +428,16 @@ impl api::IncomingWebhook for Cashtocode { .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; let response: serde_json::Value = serde_json::json!({ "status": status, "transactionId" : obj.transaction_id}); - Ok(services::api::ApplicationResponse::Json(response)) + Ok(ApplicationResponse::Json(response)) } } -impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::RefundsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::refunds::Execute, - types::RefundsData, - types::RefundsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Execute, RefundsData, RefundsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refunds".to_string(), connector: "Cashtocode".to_string(), @@ -479,8 +446,6 @@ impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::Refu } } -impl ConnectorIntegration<api::refunds::RSync, types::RefundsData, types::RefundsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode { // default implementation of build_request method will be executed } diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs similarity index 81% rename from crates/router/src/connector/cashtocode/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs index e6f4b9e57cf..49493127621 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs @@ -1,18 +1,24 @@ use std::collections::HashMap; +use common_enums::enums; pub use common_utils::request::Method; use common_utils::{ errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit, }; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_request_types::{PaymentsAuthorizeData, ResponseId}, + router_response_types::{PaymentsResponseData, RedirectForm}, + types::PaymentsAuthorizeRouterData, +}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - services, - types::{self, storage::enums}, + types::ResponseRouterData, + utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; #[derive(Default, Debug, Serialize)] @@ -32,7 +38,7 @@ pub struct CashtocodePaymentsRequest { } fn get_mid( - connector_auth_type: &types::ConnectorAuthType, + connector_auth_type: &ConnectorAuthType, payment_method_type: Option<enums::PaymentMethodType>, currency: enums::Currency, ) -> Result<Secret<String>, errors::ConnectorError> { @@ -50,10 +56,10 @@ fn get_mid( } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { +impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit), + (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit), ) -> Result<Self, Self::Error> { let customer_id = item.get_customer_id()?; let url = item.request.get_router_return_url()?; @@ -63,7 +69,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for Cashtoco item.request.currency, )?; match item.payment_method { - diesel_models::enums::PaymentMethod::Reward => Ok(Self { + enums::PaymentMethod::Reward => Ok(Self { amount, transaction_id: item.attempt_id.clone(), currency: item.request.currency, @@ -96,12 +102,12 @@ pub struct CashtocodeAuth { pub merchant_id_evoucher: Option<Secret<String>>, } -impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { +impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType { type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { + ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { let transformed_auths = auth_key_map .iter() .map(|(currency, identity_auth_key)| { @@ -125,13 +131,13 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { } } -impl TryFrom<(&types::ConnectorAuthType, &enums::Currency)> for CashtocodeAuth { +impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: (&types::ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> { + fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> { let (auth_type, currency) = value; - if let types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type { + if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type { if let Some(identity_auth_key) = auth_key_map.get(currency) { let cashtocode_auth: Self = identity_auth_key .to_owned() @@ -199,15 +205,15 @@ pub struct CashtocodePaymentsSyncResponse { fn get_redirect_form_data( payment_method_type: &enums::PaymentMethodType, response_data: CashtocodePaymentsResponseData, -) -> CustomResult<services::RedirectForm, errors::ConnectorError> { +) -> CustomResult<RedirectForm, errors::ConnectorError> { match payment_method_type { - enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form { + enums::PaymentMethodType::ClassicReward => Ok(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: Method::Post, form_fields: Default::default(), }), - enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from(( + enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from(( //here the pay url gets parsed, and query params are sent as formfields as the connector expects response_data.pay_url, Method::Get, @@ -220,27 +226,27 @@ fn get_redirect_form_data( impl<F> TryFrom< - types::ResponseRouterData< + ResponseRouterData< F, CashtocodePaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, - > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> + > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< + item: ResponseRouterData< F, CashtocodePaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (status, response) = match item.response { CashtocodePaymentsResponse::CashtoCodeError(error_data) => ( enums::AttemptStatus::Failure, - Err(types::ErrorResponse { + Err(ErrorResponse { code: error_data.error.to_string(), status_code: item.http_code, message: error_data.error_description, @@ -259,8 +265,8 @@ impl<F> let redirection_data = get_redirect_form_data(payment_method_type, response_data)?; ( enums::AttemptStatus::AuthenticationPending, - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), ), redirection_data: Some(redirection_data), @@ -283,29 +289,17 @@ impl<F> } } -impl<F, T> - TryFrom< - types::ResponseRouterData< - F, - CashtocodePaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - CashtocodePaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction. - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id ), redirection_data: None, diff --git a/crates/router/src/connector/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs similarity index 64% rename from crates/router/src/connector/coinbase.rs rename to crates/hyperswitch_connectors/src/connectors/coinbase.rs index 0c3c0be41db..7b149952ca8 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs @@ -2,31 +2,45 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; -use diesel_models::enums; +use common_enums::enums; +use common_utils::{ + crypto, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; use error_stack::ResultExt; -use transformers as coinbase; - -use self::coinbase::CoinbaseWebhookDetails; -use super::utils; -use crate::{ - configs::settings, - connector::utils as connector_utils, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +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::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundsRouterData, }, - utils::BytesExt, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, + webhooks, +}; +use masking::Mask; +use transformers as coinbase; + +use self::coinbase::CoinbaseWebhookDetails; +use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Debug, Clone)] pub struct Coinbase; @@ -50,9 +64,9 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), @@ -78,14 +92,14 @@ impl ConnectorCommon for Coinbase { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.coinbase.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -128,49 +142,32 @@ impl ConnectorValidation for Coinbase { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Coinbase +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Coinbase { // Not Implemented (R) } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Coinbase -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Coinbase +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Coinbase { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string()) .into(), @@ -178,14 +175,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -195,16 +190,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/charges", self.base_url(_connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = coinbase::CoinbasePaymentsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -212,19 +207,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<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, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -233,17 +224,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("Coinbase PaymentsAuthorizeResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -260,14 +251,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -277,8 +266,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_id = _req .request @@ -294,31 +283,31 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("coinbase PaymentsSyncResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -335,14 +324,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase { fn build_request( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Coinbase".to_string(), @@ -351,19 +338,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Coinbase -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase { fn build_request( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refund".to_string(), connector: "Coinbase".to_string(), @@ -372,22 +354,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Coinbase { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase { // default implementation of build_request method will be executed } #[async_trait::async_trait] -impl api::IncomingWebhook for Coinbase { +impl webhooks::IncomingWebhook for Coinbase { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = @@ -398,7 +380,7 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -409,7 +391,7 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body @@ -422,31 +404,31 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body .parse_struct("CoinbaseWebhookDetails") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; match notif.event.event_type { coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } coinbase::WebhookEventType::Failed => { - Ok(api::IncomingWebhookEvent::PaymentActionRequired) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired) } coinbase::WebhookEventType::Pending => { - Ok(api::IncomingWebhookEvent::PaymentIntentProcessing) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing) } coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => { - Ok(api::IncomingWebhookEvent::EventNotSupported) + Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } } } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs similarity index 87% rename from crates/router/src/connector/coinbase/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs index 82a6add72ee..3633c366c4c 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs @@ -1,15 +1,24 @@ use std::collections::HashMap; -use common_utils::pii; +use common_enums::enums; +use common_utils::{pii, request::Method}; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm}, + types, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - pii::Secret, - services, - types::{self, api, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{ + self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData, + }, }; #[derive(Debug, Default, Eq, PartialEq, Serialize)] @@ -46,10 +55,10 @@ pub struct CoinbaseAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType { +impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type { + fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::HeaderKey { api_key } = _auth_type { Ok(Self { api_key: api_key.to_owned(), }) @@ -112,23 +121,17 @@ pub struct CoinbasePaymentsResponse { data: CoinbasePaymentResponseData, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, CoinbasePaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - CoinbasePaymentsResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let form_fields = HashMap::new(); - let redirection_data = services::RedirectForm::Form { + let redirection_data = RedirectForm::Form { endpoint: item.response.data.hosted_url.to_string(), - method: services::Method::Get, + method: Method::Get, form_fields, }; let timeline = item @@ -138,10 +141,10 @@ impl<F, T> .last() .ok_or(errors::ConnectorError::ResponseHandlingFailed)? .clone(); - let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone()); + let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone()); let attempt_status = timeline.status.clone(); let response_data = timeline.context.map_or( - Ok(types::PaymentsResponseData::TransactionResponse { + Ok(PaymentsResponseData::TransactionResponse { resource_id: connector_id.clone(), redirection_data: Some(redirection_data), mandate_reference: None, @@ -152,9 +155,9 @@ impl<F, T> charge_id: None, }), |context| { - Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{ + Ok(PaymentsResponseData::TransactionUnresolvedResponse{ resource_id: connector_id, - reason: Some(api::enums::UnresolvedResponseReason { + reason: Some(api_models::enums::UnresolvedResponseReason { code: context.to_string(), message: "Please check the transaction in coinbase dashboard and resolve manually" .to_string(), @@ -207,12 +210,12 @@ impl From<RefundStatus> for enums::RefundStatus { #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse {} -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> + for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + _item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Err(errors::ConnectorError::NotImplemented( "try_from RefundsResponseRouterData".to_string(), @@ -221,12 +224,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - _item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + _item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Err(errors::ConnectorError::NotImplemented( "try_from RefundsResponseRouterData".to_string(), diff --git a/crates/router/src/connector/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs similarity index 69% rename from crates/router/src/connector/cryptopay.rs rename to crates/hyperswitch_connectors/src/connectors/cryptopay.rs index 765a07646c6..dcd629f4336 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs @@ -4,35 +4,44 @@ use base64::Engine; use common_utils::{ crypto::{self, GenerateDigest, SignMessage}, date_time, + errors::CustomResult, ext_traits::ByteSliceExt, - request::RequestContent, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hex::encode; -use masking::PeekInterface; +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, PaymentsSyncRouterData}, +}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, + webhooks, +}; +use masking::{Mask, PeekInterface}; use transformers as cryptopay; use self::cryptopay::CryptopayWebhookDetails; -use super::utils; use crate::{ - configs::settings, - consts, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, - }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - transformers::ForeignTryFrom, - ErrorResponse, Response, - }, - utils::BytesExt, + constants::headers, + types::ResponseRouterData, + utils::{self, ForeignTryFrom}, }; #[derive(Clone)] @@ -61,12 +70,8 @@ impl api::RefundExecute for Cryptopay {} impl api::RefundSync for Cryptopay {} impl api::PaymentToken for Cryptopay {} -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Cryptopay +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Cryptopay { // Not Implemented (R) } @@ -77,16 +82,13 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let method = self.get_http_method(); let payload = match method { - common_utils::request::Method::Get => String::default(), - common_utils::request::Method::Post - | common_utils::request::Method::Put - | common_utils::request::Method::Delete - | common_utils::request::Method::Patch => { + Method::Get => String::default(), + Method::Post | Method::Put | Method::Delete | Method::Patch => { let body = self .get_request_body(req, connectors)? .get_inner_value() @@ -121,7 +123,7 @@ where ) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to sign the message")?; - let authz = consts::BASE64_ENGINE.encode(authz); + let authz = common_utils::consts::BASE64_ENGINE.encode(authz); let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz); let headers = vec![ @@ -152,14 +154,14 @@ impl ConnectorCommon for Cryptopay { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.cryptopay.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = cryptopay::CryptopayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -192,32 +194,18 @@ impl ConnectorCommon for Cryptopay { } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Cryptopay -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Cryptopay +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Cryptopay { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string()) .into(), @@ -225,14 +213,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Cryptopay -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -242,16 +228,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/api/invoices", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, @@ -265,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -287,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("Cryptopay PaymentsAuthorizeResponse") @@ -305,8 +287,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P )?), None => None, }; - types::RouterData::foreign_try_from(( - types::ResponseRouterData { + RouterData::foreign_try_from(( + ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -327,7 +309,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P impl ConnectorValidation for Cryptopay { fn validate_psync_reference_id( &self, - _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _data: &PaymentsSyncData, _is_three_ds: bool, _status: common_enums::enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, @@ -337,14 +319,12 @@ impl ConnectorValidation for Cryptopay { } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Cryptopay -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -352,14 +332,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe self.common_get_content_type() } - fn get_http_method(&self) -> services::Method { - services::Method::Get + fn get_http_method(&self) -> Method { + Method::Get } fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let custom_id = req.connector_request_reference_id.clone(); Ok(format!( @@ -370,25 +350,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("cryptopay PaymentsSyncResponse") @@ -403,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe )?), None => None, }; - types::RouterData::foreign_try_from(( - types::ResponseRouterData { + RouterData::foreign_try_from(( + ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -422,38 +402,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {} #[async_trait::async_trait] -impl api::IncomingWebhook for Cryptopay { +impl webhooks::IncomingWebhook for Cryptopay { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = @@ -464,7 +432,7 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -475,7 +443,7 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request @@ -494,8 +462,8 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request .body @@ -503,21 +471,21 @@ impl api::IncomingWebhook for Cryptopay { .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; match notif.data.status { cryptopay::CryptopayPaymentStatus::Completed => { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } cryptopay::CryptopayPaymentStatus::Unresolved => { - Ok(api::IncomingWebhookEvent::PaymentActionRequired) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired) } cryptopay::CryptopayPaymentStatus::Cancelled => { - Ok(api::IncomingWebhookEvent::PaymentIntentFailure) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure) } - _ => Ok(api::IncomingWebhookEvent::EventNotSupported), + _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported), } } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs similarity index 76% rename from crates/router/src/connector/cryptopay/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index cd22890ca52..03a585f76bd 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -1,17 +1,23 @@ +use common_enums::enums; use common_utils::{ pii, types::{MinorUnit, StringMajorUnit}, }; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm}, + types, +}; +use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData}, - consts, - core::errors, - services, - types::{self, domain, storage::enums, transformers::ForeignTryFrom}, + types::ResponseRouterData, + utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData}, }; #[derive(Debug, Serialize)] @@ -51,7 +57,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let cryptopay_request = match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Crypto(ref cryptodata) => { + PaymentMethodData::Crypto(ref cryptodata) => { let pay_currency = cryptodata.get_pay_currency()?; Ok(Self { price_amount: item.amount.clone(), @@ -65,26 +71,24 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> custom_id: item.router_data.connector_request_reference_id.clone(), }) } - domain::PaymentMethodData::Card(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::MandatePayment {} - | domain::PaymentMethodData::Reward {} - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("CryptoPay"), - )) - } + PaymentMethodData::Card(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | 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("CryptoPay"), + )), }?; Ok(cryptopay_request) } @@ -96,10 +100,10 @@ pub struct CryptopayAuthType { pub(super) api_secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType { +impl TryFrom<&ConnectorAuthType> for CryptopayAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { api_key: api_key.to_owned(), api_secret: key1.to_owned(), @@ -140,21 +144,21 @@ pub struct CryptopayPaymentsResponse { impl<F, T> ForeignTryFrom<( - types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, + ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, - )> for types::RouterData<F, T, types::PaymentsResponseData> + )> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( (item, amount_captured_in_minor_units): ( - types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, + ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, ), ) -> Result<Self, Self::Error> { let status = enums::AttemptStatus::from(item.response.data.status.clone()); - let response = if is_payment_failure(status) { + let response = if utils::is_payment_failure(status) { let payment_response = &item.response.data; - Err(types::ErrorResponse { + Err(ErrorResponse { code: payment_response .name .clone() @@ -173,11 +177,9 @@ impl<F, T> .response .data .hosted_page_url - .map(|x| services::RedirectForm::from((x, services::Method::Get))); - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.data.id.clone(), - ), + .map(|x| RedirectForm::from((x, common_utils::request::Method::Get))); + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 1093ef4e6f0..953b6316ff8 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData}, - utils::{self, AddressDetailsData, RouterData as _}, + utils::{self, is_payment_failure, AddressDetailsData, RouterData as _}, }; const PASSWORD: &str = "password"; @@ -605,32 +605,3 @@ pub struct VoltErrorList { pub property: String, pub message: String, } - -fn is_payment_failure(status: enums::AttemptStatus) -> bool { - match status { - common_enums::AttemptStatus::AuthenticationFailed - | common_enums::AttemptStatus::AuthorizationFailed - | common_enums::AttemptStatus::CaptureFailed - | common_enums::AttemptStatus::VoidFailed - | common_enums::AttemptStatus::Failure => true, - common_enums::AttemptStatus::Started - | common_enums::AttemptStatus::RouterDeclined - | common_enums::AttemptStatus::AuthenticationPending - | common_enums::AttemptStatus::AuthenticationSuccessful - | common_enums::AttemptStatus::Authorized - | common_enums::AttemptStatus::Charged - | common_enums::AttemptStatus::Authorizing - | common_enums::AttemptStatus::CodInitiated - | common_enums::AttemptStatus::Voided - | common_enums::AttemptStatus::VoidInitiated - | common_enums::AttemptStatus::CaptureInitiated - | common_enums::AttemptStatus::AutoRefunded - | common_enums::AttemptStatus::PartialCharged - | common_enums::AttemptStatus::PartialChargedAndChargeable - | common_enums::AttemptStatus::Unresolved - | common_enums::AttemptStatus::Pending - | common_enums::AttemptStatus::PaymentMethodAwaited - | common_enums::AttemptStatus::ConfirmationAwaited - | common_enums::AttemptStatus::DeviceDataCollectionPending => false, - } -} diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index c5ca6512a34..4c27e11fc45 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -10,6 +10,8 @@ pub(crate) mod headers { pub(crate) const MERCHANT_ID: &str = "Merchant-ID"; pub(crate) const TIMESTAMP: &str = "Timestamp"; pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version"; + pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key"; + pub(crate) const X_CC_VERSION: &str = "X-CC-Version"; pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key"; pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue"; pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate"; diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index a667c5ddc3c..31052ab0df2 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -91,6 +91,9 @@ macro_rules! default_imp_for_authorize_session_token { default_imp_for_authorize_session_token!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -126,6 +129,9 @@ macro_rules! default_imp_for_calculate_tax { default_imp_for_calculate_tax!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, @@ -160,6 +166,9 @@ macro_rules! default_imp_for_session_update { default_imp_for_session_update!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, @@ -196,6 +205,9 @@ macro_rules! default_imp_for_complete_authorize { default_imp_for_complete_authorize!( connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -229,6 +241,9 @@ macro_rules! default_imp_for_incremental_authorization { default_imp_for_incremental_authorization!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -265,6 +280,9 @@ macro_rules! default_imp_for_create_customer { default_imp_for_create_customer!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -301,6 +319,9 @@ macro_rules! default_imp_for_connector_redirect_response { default_imp_for_connector_redirect_response!( connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -335,6 +356,9 @@ macro_rules! default_imp_for_pre_processing_steps{ default_imp_for_pre_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -371,6 +395,9 @@ macro_rules! default_imp_for_post_processing_steps{ default_imp_for_post_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -407,6 +434,9 @@ macro_rules! default_imp_for_approve { default_imp_for_approve!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -443,6 +473,9 @@ macro_rules! default_imp_for_reject { default_imp_for_reject!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -479,6 +512,9 @@ macro_rules! default_imp_for_webhook_source_verification { default_imp_for_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -516,6 +552,9 @@ macro_rules! default_imp_for_accept_dispute { default_imp_for_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -552,6 +591,9 @@ macro_rules! default_imp_for_submit_evidence { default_imp_for_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -588,6 +630,9 @@ macro_rules! default_imp_for_defend_dispute { default_imp_for_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -633,6 +678,9 @@ macro_rules! default_imp_for_file_upload { default_imp_for_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -671,6 +719,9 @@ macro_rules! default_imp_for_payouts_create { default_imp_for_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -709,6 +760,9 @@ macro_rules! default_imp_for_payouts_retrieve { default_imp_for_payouts_retrieve!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -747,6 +801,9 @@ macro_rules! default_imp_for_payouts_eligibility { default_imp_for_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -785,6 +842,9 @@ macro_rules! default_imp_for_payouts_fulfill { default_imp_for_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -823,6 +883,9 @@ macro_rules! default_imp_for_payouts_cancel { default_imp_for_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -861,6 +924,9 @@ macro_rules! default_imp_for_payouts_quote { default_imp_for_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -899,6 +965,9 @@ macro_rules! default_imp_for_payouts_recipient { default_imp_for_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -937,6 +1006,9 @@ macro_rules! default_imp_for_payouts_recipient_account { default_imp_for_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -975,6 +1047,9 @@ macro_rules! default_imp_for_frm_sale { default_imp_for_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1013,6 +1088,9 @@ macro_rules! default_imp_for_frm_checkout { default_imp_for_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1051,6 +1129,9 @@ macro_rules! default_imp_for_frm_transaction { default_imp_for_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1089,6 +1170,9 @@ macro_rules! default_imp_for_frm_fulfillment { default_imp_for_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1127,6 +1211,9 @@ macro_rules! default_imp_for_frm_record_return { default_imp_for_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1162,6 +1249,9 @@ macro_rules! default_imp_for_revoking_mandates { default_imp_for_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 3bb1abfef21..16e592688ac 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -198,6 +198,9 @@ macro_rules! default_imp_for_new_connector_integration_payment { default_imp_for_new_connector_integration_payment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -235,6 +238,9 @@ macro_rules! default_imp_for_new_connector_integration_refund { default_imp_for_new_connector_integration_refund!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -267,6 +273,9 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token { default_imp_for_new_connector_integration_connector_access_token!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -305,6 +314,9 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute { default_imp_for_new_connector_integration_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -342,6 +354,9 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence { default_imp_for_new_connector_integration_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -379,6 +394,9 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute { default_imp_for_new_connector_integration_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -426,6 +444,9 @@ macro_rules! default_imp_for_new_connector_integration_file_upload { default_imp_for_new_connector_integration_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -465,6 +486,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create { default_imp_for_new_connector_integration_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -504,6 +528,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility { default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -543,6 +570,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill { default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -582,6 +612,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel { default_imp_for_new_connector_integration_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -621,6 +654,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote { default_imp_for_new_connector_integration_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -660,6 +696,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient { default_imp_for_new_connector_integration_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -699,6 +738,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync { default_imp_for_new_connector_integration_payouts_sync!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -738,6 +780,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -775,6 +820,9 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -814,6 +862,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale { default_imp_for_new_connector_integration_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -853,6 +904,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout { default_imp_for_new_connector_integration_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -892,6 +946,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction { default_imp_for_new_connector_integration_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -931,6 +988,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment { default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -970,6 +1030,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return { default_imp_for_new_connector_integration_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1006,6 +1069,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates { default_imp_for_new_connector_integration_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index b2979975e55..f96d715f5be 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -4,7 +4,7 @@ use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount use base64::Engine; use common_enums::{ enums, - enums::{CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation}, + enums::{AttemptStatus, CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation}, }; use common_utils::{ consts::BASE64_ENGINE, @@ -163,6 +163,35 @@ pub(crate) fn convert_back_amount_to_minor_units<T>( .change_context(errors::ConnectorError::AmountConversionFailed) } +pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool { + match status { + AttemptStatus::AuthenticationFailed + | AttemptStatus::AuthorizationFailed + | AttemptStatus::CaptureFailed + | AttemptStatus::VoidFailed + | AttemptStatus::Failure => true, + AttemptStatus::Started + | AttemptStatus::RouterDeclined + | AttemptStatus::AuthenticationPending + | AttemptStatus::AuthenticationSuccessful + | AttemptStatus::Authorized + | AttemptStatus::Charged + | AttemptStatus::Authorizing + | AttemptStatus::CodInitiated + | AttemptStatus::Voided + | AttemptStatus::VoidInitiated + | AttemptStatus::CaptureInitiated + | AttemptStatus::AutoRefunded + | AttemptStatus::PartialCharged + | AttemptStatus::PartialChargedAndChargeable + | AttemptStatus::Unresolved + | AttemptStatus::Pending + | AttemptStatus::PaymentMethodAwaited + | AttemptStatus::ConfirmationAwaited + | AttemptStatus::DeviceDataCollectionPending => false, + } +} + // TODO: Make all traits as `pub(crate) trait` once all connectors are moved. pub trait RouterData { fn get_billing(&self) -> Result<&Address, Error>; @@ -1460,6 +1489,18 @@ fn get_header_field( ))? } +pub trait CryptoData { + fn get_pay_currency(&self) -> Result<String, Error>; +} + +impl CryptoData for hyperswitch_domain_models::payment_method_data::CryptoData { + fn get_pay_currency(&self) -> Result<String, Error> { + self.pay_currency + .clone() + .ok_or_else(missing_field_err("crypto_data.pay_currency")) + } +} + #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index b505f8c8c52..116fc67320f 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -9,10 +9,7 @@ pub mod billwerk; pub mod bluesnap; pub mod boku; pub mod braintree; -pub mod cashtocode; pub mod checkout; -pub mod coinbase; -pub mod cryptopay; pub mod cybersource; pub mod datatrans; pub mod dlocal; @@ -62,12 +59,13 @@ pub mod zen; pub mod zsl; pub use hyperswitch_connectors::connectors::{ - bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank, - fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, - globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay, - nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, stax, - stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, - worldline, worldline::Worldline, + bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode, + coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank, + deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, + fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, + nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, + stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, + volt::Volt, worldline, worldline::Worldline, }; #[cfg(feature = "dummy_connector")] @@ -75,8 +73,7 @@ pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, - billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, - cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, + billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte, globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay, 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 041b5bb7359..3ff93cf9bf0 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -682,10 +682,7 @@ default_imp_for_new_connector_integration_payment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -760,10 +757,7 @@ default_imp_for_new_connector_integration_refund!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -832,10 +826,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -926,10 +917,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1002,10 +990,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1062,10 +1047,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1149,10 +1131,7 @@ default_imp_for_new_connector_integration_file_upload!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1315,10 +1294,7 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1394,10 +1370,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1473,10 +1446,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1552,10 +1522,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1631,10 +1598,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1710,10 +1674,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1789,10 +1750,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1868,10 +1826,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1945,10 +1900,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2111,10 +2063,7 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2190,10 +2139,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2269,10 +2215,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2348,10 +2291,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2427,10 +2367,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2503,10 +2440,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index e364d662e24..f9a6b461a13 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -209,10 +209,7 @@ default_imp_for_complete_authorize!( connector::Bankofamerica, connector::Billwerk, connector::Boku, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -288,10 +285,7 @@ default_imp_for_webhook_source_verification!( connector::Bluesnap, connector::Braintree, connector::Boku, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -376,10 +370,7 @@ default_imp_for_create_customer!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -461,9 +452,6 @@ default_imp_for_connector_redirect_response!( connector::Bankofamerica, connector::Billwerk, connector::Boku, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -630,9 +618,6 @@ default_imp_for_accept_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -739,9 +724,6 @@ default_imp_for_file_upload!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -825,10 +807,7 @@ default_imp_for_submit_evidence!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Cybersource, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -911,10 +890,7 @@ default_imp_for_defend_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Cybersource, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1012,10 +988,7 @@ default_imp_for_pre_processing_steps!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1086,10 +1059,7 @@ default_imp_for_post_processing_steps!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1247,11 +1217,8 @@ default_imp_for_payouts_create!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1333,10 +1300,7 @@ default_imp_for_payouts_retrieve!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1424,11 +1388,8 @@ default_imp_for_payouts_eligibility!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1510,10 +1471,7 @@ default_imp_for_payouts_fulfill!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1593,11 +1551,8 @@ default_imp_for_payouts_cancel!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1680,11 +1635,8 @@ default_imp_for_payouts_quote!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1768,11 +1720,8 @@ default_imp_for_payouts_recipient!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1858,11 +1807,8 @@ default_imp_for_payouts_recipient_account!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1946,11 +1892,8 @@ default_imp_for_approve!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2035,11 +1978,8 @@ default_imp_for_reject!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2214,11 +2154,8 @@ default_imp_for_frm_sale!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2303,11 +2240,8 @@ default_imp_for_frm_checkout!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2392,11 +2326,8 @@ default_imp_for_frm_transaction!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2481,11 +2412,8 @@ default_imp_for_frm_fulfillment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2570,11 +2498,8 @@ default_imp_for_frm_record_return!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2657,10 +2582,7 @@ default_imp_for_incremental_authorization!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2742,10 +2664,7 @@ default_imp_for_revoking_mandates!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2986,10 +2905,7 @@ default_imp_for_authorize_session_token!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -3071,10 +2987,7 @@ default_imp_for_calculate_tax!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -3158,10 +3071,7 @@ default_imp_for_session_update!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal,
2024-09-20T18:00:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/5629 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Cryptopay: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \ --data-raw '{ "amount": 300, "currency": "USD", "confirm": true, "email": "guest@example.com", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "litecoin" } } }' ``` Response: ``` { "payment_id": "pay_D91HEOHsNOK0OJhfM4yo", "merchant_id": "merchant_1727096693", "status": "requires_customer_action", "amount": 300, "net_amount": 300, "amount_capturable": 300, "amount_received": 300, "connector": "cryptopay", "client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N", "created": "2024-09-23T13:19:07.696Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "crypto", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "litecoin" }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1", "payment_link": null, "profile_id": "pro_1pHVbwpinQ6kPONiCARj", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-23T13:34:07.695Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-23T13:19:09.657Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d9270ace8ddde16eca8c45ceb79af3e4d815d7cd
juspay/hyperswitch
juspay__hyperswitch-5979
Bug: [REFACTOR] API Key List and Update endpoints in Hyperswitch V2 Update API Key endpoint in V2, the URLs are registered in the `app.rs` but the necessary changes to it has not been made in `api_keys.rs`. In addition to that, List API Key endpoint for V2 does not work as no such thing exist in `api_keys.rs`. So at present, when that endpoint is hit, you'll receive a 404 as mentioned below: ```curl curl --location --request PUT '{{baseUrl}}/v2/api_keys/{{api_key_id}}' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{mechant_id}}' \ --header 'api-key: {{admin_api_key}}' \ --data '{ "name": "My new Api Key" }' ``` ```json wrong number of parameters: 1 expected 2 ``` List end point: ```curl curl --location '{{baseUrl}}/v2/api_keys/list' \ --header 'x-merchant-id: {{mechant_id}}' \ --header 'api-key: {{admin_api_key}}' ``` ```json wrong number of parameters: 0 expected 1 ``` I'll be fixing this.
diff --git a/api-reference-v2/api-reference/api-key/api-key--list.mdx b/api-reference-v2/api-reference/api-key/api-key--list.mdx new file mode 100644 index 00000000000..5975e9bd6ca --- /dev/null +++ b/api-reference-v2/api-reference/api-key/api-key--list.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/api_keys/list +--- diff --git a/api-reference-v2/mint.json b/api-reference-v2/mint.json index ae48e2b8e76..08bc5868af0 100644 --- a/api-reference-v2/mint.json +++ b/api-reference-v2/mint.json @@ -80,7 +80,8 @@ "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" + "api-reference/api-key/api-key--revoke", + "api-reference/api-key/api-key--list" ] }, { diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index fb679970f3d..c60ea81c7b4 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -1433,6 +1433,60 @@ ] } }, + "/v2/api_keys/list": { + "get": { + "tags": [ + "API Key" + ], + "summary": "API Key - List", + "description": "List all the API Keys associated to a merchant account.", + "operationId": "List all API Keys associated with a merchant account", + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "The maximum number of API Keys to include in the response", + "required": false, + "schema": { + "type": "integer", + "format": "int64", + "nullable": true + } + }, + { + "name": "skip", + "in": "query", + "description": "The number of API Keys to skip when retrieving the list of API keys.", + "required": false, + "schema": { + "type": "integer", + "format": "int64", + "nullable": true + } + } + ], + "responses": { + "200": { + "description": "List of API Keys retrieved successfully", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RetrieveApiKeyResponse" + } + } + } + } + } + }, + "security": [ + { + "admin_api_key": [] + } + ] + } + }, "/v2/customers": { "post": { "tags": [ diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs index 1fc7ce97be8..65cc6b9a25a 100644 --- a/crates/api_models/src/api_keys.rs +++ b/crates/api_models/src/api_keys.rs @@ -154,7 +154,7 @@ pub struct RevokeApiKeyResponse { } /// The constraints that are applicable when listing API Keys associated with a merchant account. -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ListApiKeyConstraints { /// The maximum number of API Keys to include in the response. diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index b8a872ffd25..5816df518bd 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -90,6 +90,7 @@ impl_api_event_type!( CardInfoResponse, CreateApiKeyResponse, CreateApiKeyRequest, + ListApiKeyConstraints, MerchantConnectorDeleteResponse, MerchantConnectorUpdate, MerchantConnectorCreate, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 85865584494..ae999bb0604 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -183,6 +183,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::api_keys::api_key_retrieve, routes::api_keys::api_key_update, routes::api_keys::api_key_revoke, + routes::api_keys::api_key_list, // Routes for events routes::webhook_events::list_initial_webhook_delivery_attempts, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 05fded520f0..ae9818ddee6 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -109,6 +109,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::api_keys::api_key_retrieve, routes::api_keys::api_key_update, routes::api_keys::api_key_revoke, + routes::api_keys::api_key_list, //Routes for customers routes::customers::customers_create, diff --git a/crates/openapi/src/routes/api_keys.rs b/crates/openapi/src/routes/api_keys.rs index 7ed2afe91a1..7527c8a1095 100644 --- a/crates/openapi/src/routes/api_keys.rs +++ b/crates/openapi/src/routes/api_keys.rs @@ -163,3 +163,44 @@ pub async fn api_key_revoke() {} security(("admin_api_key" = [])) )] pub async fn api_key_revoke() {} + +#[cfg(feature = "v1")] +/// API Key - List +/// +/// List all the API Keys associated to a merchant account. +#[utoipa::path( + get, + path = "/api_keys/{merchant_id}/list", + params( + ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"), + ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"), + ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."), + ), + responses( + (status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>), + ), + tag = "API Key", + operation_id = "List all API Keys associated with a merchant account", + security(("admin_api_key" = [])) +)] +pub async fn api_key_list() {} + +#[cfg(feature = "v2")] +/// API Key - List +/// +/// List all the API Keys associated to a merchant account. +#[utoipa::path( + get, + path = "/v2/api_keys/list", + params( + ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"), + ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."), + ), + responses( + (status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>), + ), + tag = "API Key", + operation_id = "List all API Keys associated with a merchant account", + security(("admin_api_key" = [])) +)] +pub async fn api_key_list() {} diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index a00e740b3e6..047e0d9b886 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -9,10 +9,6 @@ use crate::{ types::api as api_types, }; -/// 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. #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyCreate))] pub async fn api_key_create( @@ -78,9 +74,6 @@ pub async fn api_key_create( .await } -/// API Key - Retrieve -/// -/// Retrieve information about the specified API Key. #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))] pub async fn api_key_retrieve( @@ -117,9 +110,6 @@ pub async fn api_key_retrieve( } #[cfg(feature = "v1")] -/// API Key - Retrieve -/// -/// Retrieve information about the specified API Key. #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRetrieve))] pub async fn api_key_retrieve( state: web::Data<AppState>, @@ -150,9 +140,6 @@ pub async fn api_key_retrieve( } #[cfg(feature = "v1")] -/// API Key - Update -/// -/// Update information for the specified API Key. #[instrument(skip_all, fields(flow = ?Flow::ApiKeyUpdate))] pub async fn api_key_update( state: web::Data<AppState>, @@ -190,26 +177,27 @@ pub async fn api_key_update( pub async fn api_key_update( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<(common_utils::id_type::MerchantId, String)>, + key_id: web::Path<String>, json_payload: web::Json<api_types::UpdateApiKeyRequest>, ) -> impl Responder { let flow = Flow::ApiKeyUpdate; - let (merchant_id, key_id) = path.into_inner(); + let api_key_id = key_id.into_inner(); let mut payload = json_payload.into_inner(); - payload.key_id = key_id; - payload.merchant_id.clone_from(&merchant_id); + payload.key_id = api_key_id; api::server_wrap( flow, state, &req, payload, - |state, _, payload, _| api_keys::update_api_key(state, payload), + |state, authentication_data, mut payload, _| { + payload.merchant_id = authentication_data.merchant_account.get_id().to_owned(); + api_keys::update_api_key(state, payload) + }, auth::auth_type( - &auth::AdminApiAuth, - &auth::JWTAuthMerchantFromRoute { - merchant_id, - required_permission: Permission::ApiKeyWrite, + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { + required_permission: Permission::ApiKeyRead, minimum_entity_level: EntityType::Merchant, }, req.headers(), @@ -220,10 +208,6 @@ 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. #[instrument(skip_all, fields(flow = ?Flow::ApiKeyRevoke))] pub async fn api_key_revoke( state: web::Data<AppState>, @@ -283,24 +267,7 @@ pub async fn api_key_revoke( .await } -/// API Key - List -/// -/// List all API Keys associated with your merchant account. -#[utoipa::path( - get, - path = "/api_keys/{merchant_id}/list", - params( - ("merchant_id" = String, Path, description = "The unique identifier for the merchant account"), - ("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"), - ("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."), - ), - responses( - (status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>), - ), - tag = "API Key", - operation_id = "List all API Keys associated with a merchant account", - security(("admin_api_key" = [])) -)] +#[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))] pub async fn api_key_list( state: web::Data<AppState>, @@ -335,3 +302,34 @@ pub async fn api_key_list( ) .await } +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::ApiKeyList))] +pub async fn api_key_list( + state: web::Data<AppState>, + req: HttpRequest, + query: web::Query<api_types::ListApiKeyConstraints>, +) -> impl Responder { + let flow = Flow::ApiKeyList; + let payload = query.into_inner(); + + api::server_wrap( + flow, + state, + &req, + payload, + |state, authentication_data, payload, _| async move { + let merchant_id = authentication_data.merchant_account.get_id().to_owned(); + api_keys::list_api_keys(state, merchant_id, payload.limit, payload.skip).await + }, + auth::auth_type( + &auth::AdminApiAuthWithMerchantIdFromHeader, + &auth::JWTAuthMerchantFromHeader { + required_permission: Permission::ApiKeyRead, + minimum_entity_level: EntityType::Merchant, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + ) + .await +}
2024-09-20T13:18:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR fixes `404` errors thrown by API Key List and Update endpoints. Previously: Update end point: ```curl curl --location --request PUT '{{baseUrl}}/v2/api_keys/{{api_key_id}}' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: {{mechant_id}}' \ --header 'api-key: {{admin_api_key}}' \ --data '{ "name": "My new Api Key" }' ``` ```json wrong number of parameters: 1 expected 2 ``` List end point: ```curl curl --location '{{baseUrl}}/v2/api_keys/list' \ --header 'x-merchant-id: {{mechant_id}}' \ --header 'api-key: {{admin_api_key}}' ``` ```json wrong number of parameters: 0 expected 1 ``` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> endpoints under `v2` flags were not properly handled in `api_keys.rs` file and this PR fixes that. closes #5979 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> tested it by running locally. Create Api Key endpoint: ```curl curl --location 'http://Localhost:8080/v2/api_keys' \ --header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "name": "My Api Key", "expiration": "never" }' ``` ```json { "key_id": "dev_xhm09vaThZEPcxuZMJOG", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My Api Key", "description": null, "api_key": "dev_N0jTf3lRHljowpMGs9IKTPhOYkZXY3Sca8kUpSR5DbtjxaBvfqMIqshU5hx81AJp", "created": "2024-09-20T13:03:00.859Z", "expiration": "never" } ``` Update Api Key endpoint: ```curl curl --location --request PUT 'http://Localhost:8080/v2/api_keys/dev_xhm09vaThZEPcxuZMJOG' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \ --header 'api-key: test_admin' \ --data '{ "name": "My new Api Key" }' ``` ```json { "key_id": "dev_xhm09vaThZEPcxuZMJOG", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My new Api Key", "description": null, "prefix": "dev_N0jTf3lR", "created": "2024-09-20T13:03:00.859Z", "expiration": "never" } ``` List Api Keys endpoint: ```curl curl --location 'http://Localhost:8080/v2/api_keys/list' \ --header 'x-merchant-id: cloth_seller_o6pEetqmlQjhp0kfR7ae' \ --header 'api-key: test_admin' ``` ```json [ { "key_id": "dev_X8F7qFGnO9a1IGIrtuzb", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My Api Key", "description": null, "prefix": "dev_8jfmSMnn", "created": "2024-09-20T13:02:57.150Z", "expiration": "never" }, { "key_id": "dev_F8TDC9bHerHzYdiql80m", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My Api Key", "description": null, "prefix": "dev_g8SO3blK", "created": "2024-09-20T13:02:57.815Z", "expiration": "never" }, { "key_id": "dev_DQ3C3DdFczazUFNc6n0i", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My Api Key", "description": null, "prefix": "dev_GnLRtXQm", "created": "2024-09-20T13:02:58.361Z", "expiration": "never" }, { "key_id": "dev_kdISpxDQBmMpJ8BQuGmH", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My Api Key", "description": null, "prefix": "dev_h34nUAh4", "created": "2024-09-20T13:02:58.796Z", "expiration": "never" }, { "key_id": "dev_WBHT3v4SlWcU4R3R8Wt2", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My Api Key", "description": null, "prefix": "dev_v5jdBEFo", "created": "2024-09-20T13:02:59.806Z", "expiration": "never" }, { "key_id": "dev_qiwCmtE8Lbj24uJYC1wQ", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My Api Key", "description": null, "prefix": "dev_WRaLVEGq", "created": "2024-09-20T13:03:00.335Z", "expiration": "never" }, { "key_id": "dev_xhm09vaThZEPcxuZMJOG", "merchant_id": "cloth_seller_o6pEetqmlQjhp0kfR7ae", "name": "My new Api Key", "description": null, "prefix": "dev_N0jTf3lR", "created": "2024-09-20T13:03:00.859Z", "expiration": "never" } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5fec99b58b0062dbc02fc8fdc1bd8d949d76c51e
juspay/hyperswitch
juspay__hyperswitch-5970
Bug: add `phone` and `country_code` in dynamic fields This is to extend the feature of [collecting address details](https://github.com/juspay/hyperswitch/pull/5418) from wallets to paylater. Additionally also include phone and country_code in the dynamic fields.
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 4fcb0785ea1..41efc6e4c38 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -12335,6 +12335,24 @@ pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> { value: None, }, ), + ( + "billing.phone.number".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.phone.number".to_string(), + display_name: "phone_number".to_string(), + field_type: enums::FieldType::UserPhoneNumber, + value: None, + }, + ), + ( + "billing.phone.country_code".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.phone.country_code".to_string(), + display_name: "dialing_code".to_string(), + field_type: enums::FieldType::UserPhoneNumberCountryCode, + value: None, + }, + ), ]) } @@ -12405,6 +12423,24 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> { value: None, }, ), + ( + "shipping.phone.number".to_string(), + RequiredFieldInfo { + required_field: "shipping.phone.number".to_string(), + display_name: "phone_number".to_string(), + field_type: enums::FieldType::UserPhoneNumber, + value: None, + }, + ), + ( + "shipping.phone.country_code".to_string(), + RequiredFieldInfo { + required_field: "shipping.phone.country_code".to_string(), + display_name: "dialing_code".to_string(), + field_type: enums::FieldType::UserPhoneNumberCountryCode, + value: None, + }, + ), ]) } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 79d1226f13a..7d3742a476d 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3840,7 +3840,11 @@ fn should_collect_shipping_or_billing_details_from_wallet_connector( mut required_fields_hs: HashMap<String, RequiredFieldInfo>, ) -> HashMap<String, RequiredFieldInfo> { match (payment_method, payment_experience_optional) { - (api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient)) => { + (api_enums::PaymentMethod::Wallet, Some(api_enums::PaymentExperience::InvokeSdkClient)) + | ( + api_enums::PaymentMethod::PayLater, + Some(api_enums::PaymentExperience::InvokeSdkClient), + ) => { let always_send_billing_details = business_profile.and_then(|business_profile| { business_profile.always_collect_billing_details_from_wallet_connector });
2024-09-19T14:51:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This is to extend the feature of [collecting address details](https://github.com/juspay/hyperswitch/pull/5418) from wallets to paylater. Additionally also include phone and country_code in the dynamic fields. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant connector of Klarna with klarna payment method enabled. -> Set the below business profile config ``` curl --location 'http://localhost:8080/account/merchant_1726764490/business_profile/pro_XOWZOwYWMAmTV4wEyGgh' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ]' \ --data '{ "collect_billing_details_from_wallet_connector": false, "collect_shipping_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": true, "always_collect_billing_details_from_wallet_connector": true }' ``` ``` { "merchant_id": "merchant_1726764490", "profile_id": "pro_XOWZOwYWMAmTV4wEyGgh", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "cG93fXrQQUtILvsThLoMz2EGwi7b3avGaiEb5NQ2OAbHYbFP2Lx2VigfrdbICkLK", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": true, "always_collect_billing_details_from_wallet_connector": true, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false } ``` -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_EAjkFh4IFwdG0BhppR4qc8duYSjLtl5e2cYy1eADeQ4MAtLazHsE3fpA6wI4cUk9' \ --data '{ "amount": 100000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1726764583" }' ``` ``` { "payment_id": "pay_66ZCSMDS1OQlfVVzAYNf", "merchant_id": "merchant_1726764490", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_66ZCSMDS1OQlfVVzAYNf_secret_pdtSN8kQV4w5SsUXw6La", "created": "2024-09-19T16:49:40.260Z", "currency": "USD", "customer_id": "cu_1726764580", "customer": { "id": "cu_1726764580", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1726764580", "created_at": 1726764580, "expires": 1726768180, "secret": "epk_82cd32e8fe0a4190a5db562353a40f33" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_XOWZOwYWMAmTV4wEyGgh", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-19T17:04:40.260Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-19T16:49:40.288Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` -> Merchant payment method list ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_66ZCSMDS1OQlfVVzAYNf_secret_pdtSN8kQV4w5SsUXw6La' \ --header 'Accept: application/json' \ --header 'api-key:' ``` ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "klarna" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "shipping.address.first_name": { "required_field": "shipping.address.first_name", "display_name": "shipping_first_name", "field_type": "user_shipping_name", "value": null }, "shipping.phone.country_code": { "required_field": "shipping.phone.country_code", "display_name": "dialing_code", "field_type": "user_phone_number_country_code", "value": null }, "shipping.phone.number": { "required_field": "shipping.phone.number", "display_name": "phone_number", "field_type": "user_phone_number", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.line2": { "required_field": "payment_method_data.billing.address.line2", "display_name": "line2", "field_type": "user_address_line2", "value": null }, "shipping.address.last_name": { "required_field": "shipping.address.last_name", "display_name": "shipping_last_name", "field_type": "user_shipping_name", "value": null }, "billing.phone.number": { "required_field": "payment_method_data.billing.phone.number", "display_name": "phone_number", "field_type": "user_phone_number", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "shipping.address.country": { "required_field": "shipping.address.country", "display_name": "country", "field_type": { "user_shipping_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "billing.phone.country_code": { "required_field": "payment_method_data.billing.phone.country_code", "display_name": "dialing_code", "field_type": "user_phone_number_country_code", "value": null }, "shipping.address.state": { "required_field": "shipping.address.state", "display_name": "state", "field_type": "user_shipping_address_state", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "shipping.address.line1": { "required_field": "shipping.address.line1", "display_name": "line1", "field_type": "user_shipping_address_line1", "value": null }, "shipping.address.city": { "required_field": "shipping.address.city", "display_name": "city", "field_type": "user_shipping_address_city", "value": null }, "shipping.address.zip": { "required_field": "shipping.address.zip", "display_name": "zip", "field_type": "user_shipping_address_pincode", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": true, "collect_billing_details_from_wallets": true, "is_tax_calculation_enabled": false } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5942e059e9efa3fa71a13cacc896509515e2f976
juspay/hyperswitch
juspay__hyperswitch-5974
Bug: Missing terms and conditions for the contests. The team should add terms and conditions for the contests like Hacktoberfest.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 926af8c162c..577fe4ae1b7 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -7293,7 +7293,7 @@ }, "FutureUsage": { "type": "string", - "description": "Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.", + "description": "Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.\n- On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment\n- Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment.", "enum": [ "off_session", "on_session" diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 31cb43669b2..bd1cd36f8bd 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1357,6 +1357,8 @@ pub enum IntentStatus { } /// Indicates that you intend to make future payments with the payment methods used for this Payment. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. +/// - On_session - Payment method saved only at hyperswitch when consent is provided by the user. CVV will asked during the returning user payment +/// - Off_session - Payment method saved at both hyperswitch and Processor when consent is provided by the user. No input is required during the returning user payment. #[derive( Clone, Copy,
2024-09-20T10:51:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes this - #5974 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
dccb8d4e629d615a69f6922a96e72f10d3410bfc
juspay/hyperswitch
juspay__hyperswitch-5982
Bug: add `email` in `billing` and `shipping` address of merchant payment method list This is to extend the feature of [collect address details](https://github.com/juspay/hyperswitch/pull/5418) to collect `billing.email` and `shipping.email`. As per this when `"always_collect_shipping_details_from_wallet_connector": true` and `"always_collect_billing_details_from_wallet_connector": true`, if payment method is wallet or paylater, and if payment experience is `"payment_experience_type": "invoke_sdk_client"` then merchant pml will contain `billing.email` and `shipping.email` in addition to existing fields.
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 41efc6e4c38..5719e111759 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -12353,6 +12353,15 @@ pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo> { 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, + }, + ), ]) } @@ -12441,6 +12450,15 @@ pub fn get_shipping_required_fields() -> HashMap<String, RequiredFieldInfo> { value: None, }, ), + ( + "shipping.email".to_string(), + RequiredFieldInfo { + required_field: "shipping.email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + }, + ), ]) }
2024-09-20T13:48:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This is to extend the feature of [collect address details](https://github.com/juspay/hyperswitch/pull/5418) to collect `billing.email` and `shipping.email`. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant account -> Set the below config in the business profile ``` curl --location 'http://localhost:8080/account/merchant_1726839405/business_profile/pro_TwNiv0vtGBct5t1SLyhm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: *' \ --data '{ "collect_billing_details_from_wallet_connector": false, "collect_shipping_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": true, "always_collect_billing_details_from_wallet_connector": true }' ``` ``` { "merchant_id": "merchant_1726839405", "profile_id": "pro_TwNiv0vtGBct5t1SLyhm", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "ODPObMKINwvWuUGwHgikqYs7XC3jpRpnPpicIK4IFP3flJ3ZeEREOzagzyEHOGTz", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": true, "always_collect_billing_details_from_wallet_connector": true, "is_connector_agnostic_mit_enabled": false, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false, "is_network_tokenization_enabled": false } ``` -> Create a connector with wallet or paylater payment method enabled -> Create a payment with confirm false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: ' \ --data '{ "amount": 100000, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1726839665" }' ``` ``` { "payment_id": "pay_mtBJnDsvfQoVztmE4Zl1", "merchant_id": "merchant_1726839405", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_mtBJnDsvfQoVztmE4Zl1_secret_LInppcvLGbtw5KB8YWWj", "created": "2024-09-20T13:37:30.990Z", "currency": "USD", "customer_id": "cu_1726839451", "customer": { "id": "cu_1726839451", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1726839451", "created_at": 1726839450, "expires": 1726843050, "secret": "epk_8f8412ffd628422c8c108e8c75cef572" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_TwNiv0vtGBct5t1SLyhm", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-20T13:52:30.990Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-20T13:37:31.050Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` -> Merchant payment method list ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_mtBJnDsvfQoVztmE4Zl1_secret_LInppcvLGbtw5KB8YWWj' \ --header 'Accept: application/json' \ --header 'api-key: ' ``` ``` { "redirect_url": "https://google.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "klarna" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "shipping.address.country": { "required_field": "shipping.address.country", "display_name": "country", "field_type": { "user_shipping_address_country": { "options": [ "ALL" ] } }, "value": null }, "shipping.address.zip": { "required_field": "shipping.address.zip", "display_name": "zip", "field_type": "user_shipping_address_pincode", "value": null }, "shipping.phone.number": { "required_field": "shipping.phone.number", "display_name": "phone_number", "field_type": "user_phone_number", "value": null }, "shipping.address.line1": { "required_field": "shipping.address.line1", "display_name": "line1", "field_type": "user_shipping_address_line1", "value": null }, "shipping.phone.country_code": { "required_field": "shipping.phone.country_code", "display_name": "dialing_code", "field_type": "user_phone_number_country_code", "value": null }, "shipping.address.city": { "required_field": "shipping.address.city", "display_name": "city", "field_type": "user_shipping_address_city", "value": null }, "billing.address.line2": { "required_field": "payment_method_data.billing.address.line2", "display_name": "line2", "field_type": "user_address_line2", "value": null }, "shipping.email": { "required_field": "shipping.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null }, "shipping.address.state": { "required_field": "shipping.address.state", "display_name": "state", "field_type": "user_shipping_address_state", "value": null }, "billing.phone.country_code": { "required_field": "payment_method_data.billing.phone.country_code", "display_name": "dialing_code", "field_type": "user_phone_number_country_code", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.phone.number": { "required_field": "payment_method_data.billing.phone.number", "display_name": "phone_number", "field_type": "user_phone_number", "value": null }, "shipping.address.last_name": { "required_field": "shipping.address.last_name", "display_name": "shipping_last_name", "field_type": "user_shipping_name", "value": null }, "shipping.address.first_name": { "required_field": "shipping.address.first_name", "display_name": "shipping_first_name", "field_type": "user_shipping_name", "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": true, "collect_billing_details_from_wallets": true, "is_tax_calculation_enabled": false } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c0cac8d9135b14945ce5763327ec16b1578ca2a2
juspay/hyperswitch
juspay__hyperswitch-6001
Bug: [FEATURE] [CASHTOCODE] Move connector code to crate hyperswitch_connectors ### Feature Description Connector code for `cashtocode` needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### Possible Implementation Connector code for `cashtocode` needs to be moved from crate `router` to new crate `hyperswitch_connectors` ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 48c50936d60..f057b7d4a33 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -1,5 +1,8 @@ pub mod bambora; pub mod bitpay; +pub mod cashtocode; +pub mod coinbase; +pub mod cryptopay; pub mod deutschebank; pub mod fiserv; pub mod fiservemea; @@ -18,8 +21,9 @@ pub mod volt; pub mod worldline; pub use self::{ - bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv, - fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, - nexixpay::Nexixpay, novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, - thunes::Thunes, tsys::Tsys, volt::Volt, worldline::Worldline, + bambora::Bambora, bitpay::Bitpay, cashtocode::Cashtocode, coinbase::Coinbase, + cryptopay::Cryptopay, deutschebank::Deutschebank, fiserv::Fiserv, fiservemea::Fiservemea, + fiuu::Fiuu, globepay::Globepay, helcim::Helcim, mollie::Mollie, nexixpay::Nexixpay, + novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, thunes::Thunes, + tsys::Tsys, volt::Volt, worldline::Worldline, }; diff --git a/crates/router/src/connector/cashtocode.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs similarity index 67% rename from crates/router/src/connector/cashtocode.rs rename to crates/hyperswitch_connectors/src/connectors/cashtocode.rs index 2155b80dd81..c72b63aebc0 100644 --- a/crates/router/src/connector/cashtocode.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode.rs @@ -1,33 +1,41 @@ pub mod transformers; - use base64::Engine; +use common_enums::enums; use common_utils::{ - request::RequestContent, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; -use diesel_models::enums; use error_stack::ResultExt; -use masking::{PeekInterface, Secret}; -use transformers as cashtocode; - -use super::utils as connector_utils; -use crate::{ - configs::settings::{self}, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +use hyperswitch_domain_models::{ + api::ApplicationResponse, + router_data::{AccessToken, ErrorResponse, RouterData}, + router_flow_types::{ + access_token_auth::AccessTokenAuth, + payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, + refunds::{Execute, RSync}, }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - storage, ErrorResponse, Response, + router_request_types::{ + AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, + PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, + RefundsData, SetupMandateRequestData, }, - utils::{ByteSliceExt, BytesExt}, + router_response_types::{PaymentsResponseData, RefundsResponseData}, + types::{PaymentsAuthorizeRouterData, PaymentsSyncRouterData}, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, Response}, + webhooks, +}; +use masking::{Mask, PeekInterface, Secret}; +use transformers as cashtocode; + +use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Cashtocode { @@ -56,13 +64,13 @@ impl api::RefundExecute for Cashtocode {} impl api::RefundSync for Cashtocode {} fn get_b64_auth_cashtocode( - payment_method_type: &Option<storage::enums::PaymentMethodType>, + payment_method_type: &Option<enums::PaymentMethodType>, auth_type: &transformers::CashtocodeAuth, -) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { +) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { fn construct_basic_auth( username: Option<Secret<String>>, password: Option<Secret<String>>, - ) -> Result<request::Maskable<String>, errors::ConnectorError> { + ) -> Result<masking::Maskable<String>, errors::ConnectorError> { let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?; let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?; Ok(format!( @@ -77,11 +85,11 @@ fn get_b64_auth_cashtocode( } let auth_header = match payment_method_type { - Some(storage::enums::PaymentMethodType::ClassicReward) => construct_basic_auth( + Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth( auth_type.username_classic.to_owned(), auth_type.password_classic.to_owned(), ), - Some(storage::enums::PaymentMethodType::Evoucher) => construct_basic_auth( + Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth( auth_type.username_evoucher.to_owned(), auth_type.password_evoucher.to_owned(), ), @@ -91,12 +99,8 @@ fn get_b64_auth_cashtocode( Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)]) } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Cashtocode +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Cashtocode { // Not Implemented (R) } @@ -115,7 +119,7 @@ impl ConnectorCommon for Cashtocode { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.cashtocode.base_url.as_ref() } @@ -153,39 +157,26 @@ impl ConnectorValidation for Cashtocode { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Cashtocode -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Cashtocode +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string()) .into(), @@ -193,17 +184,15 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) + PaymentsAuthorizeType::get_content_type(self) .to_owned() .into(), )]; @@ -225,8 +214,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/merchant/paytokens", @@ -236,10 +225,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let amount = connector_utils::convert_amount( + let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, @@ -250,20 +239,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -272,10 +257,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cashtocode::CashtocodePaymentsResponse = res .response .parse_struct("Cashtocode PaymentsAuthorizeResponse") @@ -283,7 +268,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P 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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -299,23 +284,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cashtocode { // default implementation of build_request method will be executed fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: transformers::CashtocodePaymentsSyncResponse = res .response .parse_struct("CashtocodePaymentsSyncResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -331,18 +314,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Cashtocode".to_string(), @@ -351,14 +328,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Payments Cancel".to_string(), connector: "Cashtocode".to_string(), @@ -368,21 +343,20 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR } #[async_trait::async_trait] -impl api::IncomingWebhook for Cashtocode { +impl webhooks::IncomingWebhook for Cashtocode { fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { - let base64_signature = - connector_utils::get_header_key_value("authorization", request.headers)?; + let base64_signature = utils::get_header_key_value("authorization", request.headers)?; let signature = base64_signature.as_bytes().to_owned(); Ok(signature) } async fn verify_webhook_source( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>, @@ -412,7 +386,7 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let webhook: transformers::CashtocodePaymentsSyncResponse = request .body @@ -426,14 +400,14 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_event_type( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let webhook: transformers::CashtocodeIncomingWebhook = request .body @@ -445,9 +419,8 @@ impl api::IncomingWebhook for Cashtocode { fn get_webhook_api_response( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ConnectorError> - { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> { let status = "EXECUTED".to_string(); let obj: transformers::CashtocodePaymentsSyncResponse = request .body @@ -455,22 +428,16 @@ impl api::IncomingWebhook for Cashtocode { .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; let response: serde_json::Value = serde_json::json!({ "status": status, "transactionId" : obj.transaction_id}); - Ok(services::api::ApplicationResponse::Json(response)) + Ok(ApplicationResponse::Json(response)) } } -impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::RefundsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode { fn build_request( &self, - _req: &types::RouterData< - api::refunds::Execute, - types::RefundsData, - types::RefundsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<Execute, RefundsData, RefundsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refunds".to_string(), connector: "Cashtocode".to_string(), @@ -479,8 +446,6 @@ impl ConnectorIntegration<api::refunds::Execute, types::RefundsData, types::Refu } } -impl ConnectorIntegration<api::refunds::RSync, types::RefundsData, types::RefundsResponseData> - for Cashtocode -{ +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode { // default implementation of build_request method will be executed } diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs similarity index 81% rename from crates/router/src/connector/cashtocode/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs index e6f4b9e57cf..49493127621 100644 --- a/crates/router/src/connector/cashtocode/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cashtocode/transformers.rs @@ -1,18 +1,24 @@ use std::collections::HashMap; +use common_enums::enums; pub use common_utils::request::Method; use common_utils::{ errors::CustomResult, ext_traits::ValueExt, id_type, pii::Email, types::FloatMajorUnit, }; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_request_types::{PaymentsAuthorizeData, ResponseId}, + router_response_types::{PaymentsResponseData, RedirectForm}, + types::PaymentsAuthorizeRouterData, +}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - services, - types::{self, storage::enums}, + types::ResponseRouterData, + utils::{self, PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; #[derive(Default, Debug, Serialize)] @@ -32,7 +38,7 @@ pub struct CashtocodePaymentsRequest { } fn get_mid( - connector_auth_type: &types::ConnectorAuthType, + connector_auth_type: &ConnectorAuthType, payment_method_type: Option<enums::PaymentMethodType>, currency: enums::Currency, ) -> Result<Secret<String>, errors::ConnectorError> { @@ -50,10 +56,10 @@ fn get_mid( } } -impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { +impl TryFrom<(&PaymentsAuthorizeRouterData, FloatMajorUnit)> for CashtocodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - (item, amount): (&types::PaymentsAuthorizeRouterData, FloatMajorUnit), + (item, amount): (&PaymentsAuthorizeRouterData, FloatMajorUnit), ) -> Result<Self, Self::Error> { let customer_id = item.get_customer_id()?; let url = item.request.get_router_return_url()?; @@ -63,7 +69,7 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, FloatMajorUnit)> for Cashtoco item.request.currency, )?; match item.payment_method { - diesel_models::enums::PaymentMethod::Reward => Ok(Self { + enums::PaymentMethod::Reward => Ok(Self { amount, transaction_id: item.attempt_id.clone(), currency: item.request.currency, @@ -96,12 +102,12 @@ pub struct CashtocodeAuth { pub merchant_id_evoucher: Option<Secret<String>>, } -impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { +impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType { type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { - types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { + ConnectorAuthType::CurrencyAuthKey { auth_key_map } => { let transformed_auths = auth_key_map .iter() .map(|(currency, identity_auth_key)| { @@ -125,13 +131,13 @@ impl TryFrom<&types::ConnectorAuthType> for CashtocodeAuthType { } } -impl TryFrom<(&types::ConnectorAuthType, &enums::Currency)> for CashtocodeAuth { +impl TryFrom<(&ConnectorAuthType, &enums::Currency)> for CashtocodeAuth { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(value: (&types::ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> { + fn try_from(value: (&ConnectorAuthType, &enums::Currency)) -> Result<Self, Self::Error> { let (auth_type, currency) = value; - if let types::ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type { + if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type { if let Some(identity_auth_key) = auth_key_map.get(currency) { let cashtocode_auth: Self = identity_auth_key .to_owned() @@ -199,15 +205,15 @@ pub struct CashtocodePaymentsSyncResponse { fn get_redirect_form_data( payment_method_type: &enums::PaymentMethodType, response_data: CashtocodePaymentsResponseData, -) -> CustomResult<services::RedirectForm, errors::ConnectorError> { +) -> CustomResult<RedirectForm, errors::ConnectorError> { match payment_method_type { - enums::PaymentMethodType::ClassicReward => Ok(services::RedirectForm::Form { + enums::PaymentMethodType::ClassicReward => Ok(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: Method::Post, form_fields: Default::default(), }), - enums::PaymentMethodType::Evoucher => Ok(services::RedirectForm::from(( + enums::PaymentMethodType::Evoucher => Ok(RedirectForm::from(( //here the pay url gets parsed, and query params are sent as formfields as the connector expects response_data.pay_url, Method::Get, @@ -220,27 +226,27 @@ fn get_redirect_form_data( impl<F> TryFrom< - types::ResponseRouterData< + ResponseRouterData< F, CashtocodePaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, - > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> + > for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< + item: ResponseRouterData< F, CashtocodePaymentsResponse, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, + PaymentsAuthorizeData, + PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let (status, response) = match item.response { CashtocodePaymentsResponse::CashtoCodeError(error_data) => ( enums::AttemptStatus::Failure, - Err(types::ErrorResponse { + Err(ErrorResponse { code: error_data.error.to_string(), status_code: item.http_code, message: error_data.error_description, @@ -259,8 +265,8 @@ impl<F> let redirection_data = get_redirect_form_data(payment_method_type, response_data)?; ( enums::AttemptStatus::AuthenticationPending, - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), ), redirection_data: Some(redirection_data), @@ -283,29 +289,17 @@ impl<F> } } -impl<F, T> - TryFrom< - types::ResponseRouterData< - F, - CashtocodePaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, - > for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - CashtocodePaymentsSyncResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, CashtocodePaymentsSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { Ok(Self { status: enums::AttemptStatus::Charged, // Charged status is hardcoded because cashtocode do not support Psync, and we only receive webhooks when payment is succeeded, this tryFrom is used for CallConnectorAction. - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( item.data.attempt_id.clone(), //in response they only send PayUrl, so we use attempt_id as connector_transaction_id ), redirection_data: None, diff --git a/crates/router/src/connector/coinbase.rs b/crates/hyperswitch_connectors/src/connectors/coinbase.rs similarity index 64% rename from crates/router/src/connector/coinbase.rs rename to crates/hyperswitch_connectors/src/connectors/coinbase.rs index 0c3c0be41db..7b149952ca8 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase.rs @@ -2,31 +2,45 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent}; -use diesel_models::enums; +use common_enums::enums; +use common_utils::{ + crypto, + errors::CustomResult, + ext_traits::ByteSliceExt, + request::{Method, Request, RequestBuilder, RequestContent}, +}; use error_stack::ResultExt; -use transformers as coinbase; - -use self::coinbase::CoinbaseWebhookDetails; -use super::utils; -use crate::{ - configs::settings, - connector::utils as connector_utils, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, +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::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - ErrorResponse, Response, + PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + RefundsRouterData, }, - utils::BytesExt, }; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, + webhooks, +}; +use masking::Mask; +use transformers as coinbase; + +use self::coinbase::CoinbaseWebhookDetails; +use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Debug, Clone)] pub struct Coinbase; @@ -50,9 +64,9 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + _connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let mut header = vec![ ( headers::CONTENT_TYPE.to_string(), @@ -78,14 +92,14 @@ impl ConnectorCommon for Coinbase { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.coinbase.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -128,49 +142,32 @@ impl ConnectorValidation for Coinbase { match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - connector_utils::construct_not_supported_error_report(capture_method, self.id()), + utils::construct_not_supported_error_report(capture_method, self.id()), ), } } } -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Coinbase +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Coinbase { // Not Implemented (R) } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase { //TODO: implement sessions flow } -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Coinbase -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Coinbase +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Coinbase { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string()) .into(), @@ -178,14 +175,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -195,16 +190,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/charges", self.base_url(_connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = coinbase::CoinbasePaymentsRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -212,19 +207,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<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, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -233,17 +224,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("Coinbase PaymentsAuthorizeResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -260,14 +251,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Coinbase { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -277,8 +266,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_url( &self, - _req: &types::PaymentsSyncRouterData, - _connectors: &settings::Connectors, + _req: &PaymentsSyncRouterData, + _connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_id = _req .request @@ -294,31 +283,31 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: coinbase::CoinbasePaymentsResponse = res .response .parse_struct("coinbase PaymentsSyncResponse") .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(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -335,14 +324,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase { fn build_request( &self, - _req: &types::PaymentsCaptureRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &PaymentsCaptureRouterData, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "Coinbase".to_string(), @@ -351,19 +338,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme } } -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Coinbase -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Coinbase -{ +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase { fn build_request( &self, - _req: &types::RefundsRouterData<api::Execute>, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RefundsRouterData<Execute>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refund".to_string(), connector: "Coinbase".to_string(), @@ -372,22 +354,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon } } -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Coinbase { +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase { // default implementation of build_request method will be executed } #[async_trait::async_trait] -impl api::IncomingWebhook for Coinbase { +impl webhooks::IncomingWebhook for Coinbase { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = @@ -398,7 +380,7 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -409,7 +391,7 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body @@ -422,31 +404,31 @@ impl api::IncomingWebhook for Coinbase { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body .parse_struct("CoinbaseWebhookDetails") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; match notif.event.event_type { coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } coinbase::WebhookEventType::Failed => { - Ok(api::IncomingWebhookEvent::PaymentActionRequired) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired) } coinbase::WebhookEventType::Pending => { - Ok(api::IncomingWebhookEvent::PaymentIntentProcessing) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing) } coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => { - Ok(api::IncomingWebhookEvent::EventNotSupported) + Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported) } } } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif: CoinbaseWebhookDetails = request .body diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs similarity index 87% rename from crates/router/src/connector/coinbase/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs index 82a6add72ee..3633c366c4c 100644 --- a/crates/router/src/connector/coinbase/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs @@ -1,15 +1,24 @@ use std::collections::HashMap; -use common_utils::pii; +use common_enums::enums; +use common_utils::{pii, request::Method}; use error_stack::ResultExt; +use hyperswitch_domain_models::{ + router_data::{ConnectorAuthType, RouterData}, + router_flow_types::refunds::{Execute, RSync}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm}, + types, +}; +use hyperswitch_interfaces::errors; +use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, - core::errors, - pii::Secret, - services, - types::{self, api, storage::enums}, + types::{RefundsResponseRouterData, ResponseRouterData}, + utils::{ + self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData as OtherRouterData, + }, }; #[derive(Debug, Default, Eq, PartialEq, Serialize)] @@ -46,10 +55,10 @@ pub struct CoinbaseAuthType { pub(super) api_key: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for CoinbaseAuthType { +impl TryFrom<&ConnectorAuthType> for CoinbaseAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(_auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::HeaderKey { api_key } = _auth_type { + fn try_from(_auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::HeaderKey { api_key } = _auth_type { Ok(Self { api_key: api_key.to_owned(), }) @@ -112,23 +121,17 @@ pub struct CoinbasePaymentsResponse { data: CoinbasePaymentResponseData, } -impl<F, T> - TryFrom<types::ResponseRouterData<F, CoinbasePaymentsResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F, T> TryFrom<ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData< - F, - CoinbasePaymentsResponse, - T, - types::PaymentsResponseData, - >, + item: ResponseRouterData<F, CoinbasePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let form_fields = HashMap::new(); - let redirection_data = services::RedirectForm::Form { + let redirection_data = RedirectForm::Form { endpoint: item.response.data.hosted_url.to_string(), - method: services::Method::Get, + method: Method::Get, form_fields, }; let timeline = item @@ -138,10 +141,10 @@ impl<F, T> .last() .ok_or(errors::ConnectorError::ResponseHandlingFailed)? .clone(); - let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id.clone()); + let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id.clone()); let attempt_status = timeline.status.clone(); let response_data = timeline.context.map_or( - Ok(types::PaymentsResponseData::TransactionResponse { + Ok(PaymentsResponseData::TransactionResponse { resource_id: connector_id.clone(), redirection_data: Some(redirection_data), mandate_reference: None, @@ -152,9 +155,9 @@ impl<F, T> charge_id: None, }), |context| { - Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{ + Ok(PaymentsResponseData::TransactionUnresolvedResponse{ resource_id: connector_id, - reason: Some(api::enums::UnresolvedResponseReason { + reason: Some(api_models::enums::UnresolvedResponseReason { code: context.to_string(), message: "Please check the transaction in coinbase dashboard and resolve manually" .to_string(), @@ -207,12 +210,12 @@ impl From<RefundStatus> for enums::RefundStatus { #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse {} -impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> - for types::RefundsRouterData<api::Execute> +impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> + for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - _item: types::RefundsResponseRouterData<api::Execute, RefundResponse>, + _item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Err(errors::ConnectorError::NotImplemented( "try_from RefundsResponseRouterData".to_string(), @@ -221,12 +224,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>> } } -impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> - for types::RefundsRouterData<api::RSync> -{ +impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - _item: types::RefundsResponseRouterData<api::RSync, RefundResponse>, + _item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Err(errors::ConnectorError::NotImplemented( "try_from RefundsResponseRouterData".to_string(), diff --git a/crates/router/src/connector/cryptopay.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs similarity index 69% rename from crates/router/src/connector/cryptopay.rs rename to crates/hyperswitch_connectors/src/connectors/cryptopay.rs index 765a07646c6..dcd629f4336 100644 --- a/crates/router/src/connector/cryptopay.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay.rs @@ -4,35 +4,44 @@ use base64::Engine; use common_utils::{ crypto::{self, GenerateDigest, SignMessage}, date_time, + errors::CustomResult, ext_traits::ByteSliceExt, - request::RequestContent, + request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hex::encode; -use masking::PeekInterface; +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, PaymentsSyncRouterData}, +}; +use hyperswitch_interfaces::{ + api::{self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{PaymentsAuthorizeType, PaymentsSyncType, Response}, + webhooks, +}; +use masking::{Mask, PeekInterface}; use transformers as cryptopay; use self::cryptopay::CryptopayWebhookDetails; -use super::utils; use crate::{ - configs::settings, - consts, - core::errors::{self, CustomResult}, - events::connector_api_logs::ConnectorEvent, - headers, - services::{ - self, - request::{self, Mask}, - ConnectorIntegration, ConnectorValidation, - }, - types::{ - self, - api::{self, ConnectorCommon, ConnectorCommonExt}, - transformers::ForeignTryFrom, - ErrorResponse, Response, - }, - utils::BytesExt, + constants::headers, + types::ResponseRouterData, + utils::{self, ForeignTryFrom}, }; #[derive(Clone)] @@ -61,12 +70,8 @@ impl api::RefundExecute for Cryptopay {} impl api::RefundSync for Cryptopay {} impl api::PaymentToken for Cryptopay {} -impl - ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Cryptopay +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Cryptopay { // Not Implemented (R) } @@ -77,16 +82,13 @@ where { fn build_headers( &self, - req: &types::RouterData<Flow, Request, Response>, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &RouterData<Flow, Request, Response>, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let method = self.get_http_method(); let payload = match method { - common_utils::request::Method::Get => String::default(), - common_utils::request::Method::Post - | common_utils::request::Method::Put - | common_utils::request::Method::Delete - | common_utils::request::Method::Patch => { + Method::Get => String::default(), + Method::Post | Method::Put | Method::Delete | Method::Patch => { let body = self .get_request_body(req, connectors)? .get_inner_value() @@ -121,7 +123,7 @@ where ) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to sign the message")?; - let authz = consts::BASE64_ENGINE.encode(authz); + let authz = common_utils::consts::BASE64_ENGINE.encode(authz); let auth_string: String = format!("HMAC {}:{}", auth.api_key.peek(), authz); let headers = vec![ @@ -152,14 +154,14 @@ impl ConnectorCommon for Cryptopay { "application/json" } - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.cryptopay.base_url.as_ref() } fn get_auth_header( &self, - auth_type: &types::ConnectorAuthType, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = cryptopay::CryptopayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( @@ -192,32 +194,18 @@ impl ConnectorCommon for Cryptopay { } } -impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken> - for Cryptopay -{ -} +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cryptopay {} -impl - ConnectorIntegration< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - > for Cryptopay +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Cryptopay { fn build_request( &self, - _req: &types::RouterData< - api::SetupMandate, - types::SetupMandateRequestData, - types::PaymentsResponseData, - >, - _connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, + _connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err( errors::ConnectorError::NotImplemented("Setup Mandate flow for Cryptopay".to_string()) .into(), @@ -225,14 +213,12 @@ impl } } -impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> - for Cryptopay -{ +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cryptopay { fn get_headers( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -242,16 +228,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, + _req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}/api/invoices", self.base_url(connectors))) } fn get_request_body( &self, - req: &types::PaymentsAuthorizeRouterData, - _connectors: &settings::Connectors, + req: &PaymentsAuthorizeRouterData, + _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, @@ -265,20 +251,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn build_request( &self, - req: &types::PaymentsAuthorizeRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsAuthorizeType::get_url( - self, req, connectors, - )?) + RequestBuilder::new() + .method(Method::Post) + .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsAuthorizeType::get_headers( - self, req, connectors, - )?) - .set_body(types::PaymentsAuthorizeType::get_request_body( + .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) + .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), @@ -287,10 +269,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn handle_response( &self, - data: &types::PaymentsAuthorizeRouterData, + data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("Cryptopay PaymentsAuthorizeResponse") @@ -305,8 +287,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P )?), None => None, }; - types::RouterData::foreign_try_from(( - types::ResponseRouterData { + RouterData::foreign_try_from(( + ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -327,7 +309,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P impl ConnectorValidation for Cryptopay { fn validate_psync_reference_id( &self, - _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData, + _data: &PaymentsSyncData, _is_three_ds: bool, _status: common_enums::enums::AttemptStatus, _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>, @@ -337,14 +319,12 @@ impl ConnectorValidation for Cryptopay { } } -impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Cryptopay -{ +impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Cryptopay { fn get_headers( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } @@ -352,14 +332,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe self.common_get_content_type() } - fn get_http_method(&self) -> services::Method { - services::Method::Get + fn get_http_method(&self) -> Method { + Method::Get } fn get_url( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let custom_id = req.connector_request_reference_id.clone(); Ok(format!( @@ -370,25 +350,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn build_request( &self, - req: &types::PaymentsSyncRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + req: &PaymentsSyncRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( - services::RequestBuilder::new() - .method(services::Method::Get) - .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) + RequestBuilder::new() + .method(Method::Get) + .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() - .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) + .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, - data: &types::PaymentsSyncRouterData, + data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, - ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> { + ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: cryptopay::CryptopayPaymentsResponse = res .response .parse_struct("cryptopay PaymentsSyncResponse") @@ -403,8 +383,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe )?), None => None, }; - types::RouterData::foreign_try_from(( - types::ResponseRouterData { + RouterData::foreign_try_from(( + ResponseRouterData { response, data: data.clone(), http_code: res.status_code, @@ -422,38 +402,26 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe } } -impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cryptopay {} -impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Cryptopay -{ -} +impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cryptopay {} #[async_trait::async_trait] -impl api::IncomingWebhook for Cryptopay { +impl webhooks::IncomingWebhook for Cryptopay { fn get_webhook_source_verification_algorithm( &self, - _request: &api::IncomingWebhookRequestDetails<'_>, + _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let base64_signature = @@ -464,7 +432,7 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_source_verification_message( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { @@ -475,7 +443,7 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_object_reference_id( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request @@ -494,8 +462,8 @@ impl api::IncomingWebhook for Cryptopay { fn get_webhook_event_type( &self, - request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request .body @@ -503,21 +471,21 @@ impl api::IncomingWebhook for Cryptopay { .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; match notif.data.status { cryptopay::CryptopayPaymentStatus::Completed => { - Ok(api::IncomingWebhookEvent::PaymentIntentSuccess) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess) } cryptopay::CryptopayPaymentStatus::Unresolved => { - Ok(api::IncomingWebhookEvent::PaymentActionRequired) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired) } cryptopay::CryptopayPaymentStatus::Cancelled => { - Ok(api::IncomingWebhookEvent::PaymentIntentFailure) + Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure) } - _ => Ok(api::IncomingWebhookEvent::EventNotSupported), + _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported), } } fn get_webhook_resource_object( &self, - request: &api::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let notif: CryptopayWebhookDetails = request diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs similarity index 76% rename from crates/router/src/connector/cryptopay/transformers.rs rename to crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs index cd22890ca52..03a585f76bd 100644 --- a/crates/router/src/connector/cryptopay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/cryptopay/transformers.rs @@ -1,17 +1,23 @@ +use common_enums::enums; use common_utils::{ pii, types::{MinorUnit, StringMajorUnit}, }; +use hyperswitch_domain_models::{ + payment_method_data::PaymentMethodData, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, + router_request_types::ResponseId, + router_response_types::{PaymentsResponseData, RedirectForm}, + types, +}; +use hyperswitch_interfaces::{consts, errors}; use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData}, - consts, - core::errors, - services, - types::{self, domain, storage::enums, transformers::ForeignTryFrom}, + types::ResponseRouterData, + utils::{self, CryptoData, ForeignTryFrom, PaymentsAuthorizeRequestData}, }; #[derive(Debug, Serialize)] @@ -51,7 +57,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> item: &CryptopayRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let cryptopay_request = match item.router_data.request.payment_method_data { - domain::PaymentMethodData::Crypto(ref cryptodata) => { + PaymentMethodData::Crypto(ref cryptodata) => { let pay_currency = cryptodata.get_pay_currency()?; Ok(Self { price_amount: item.amount.clone(), @@ -65,26 +71,24 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>> custom_id: item.router_data.connector_request_reference_id.clone(), }) } - domain::PaymentMethodData::Card(_) - | domain::PaymentMethodData::CardRedirect(_) - | domain::PaymentMethodData::Wallet(_) - | domain::PaymentMethodData::PayLater(_) - | domain::PaymentMethodData::BankRedirect(_) - | domain::PaymentMethodData::BankDebit(_) - | domain::PaymentMethodData::BankTransfer(_) - | domain::PaymentMethodData::MandatePayment {} - | domain::PaymentMethodData::Reward {} - | domain::PaymentMethodData::RealTimePayment(_) - | domain::PaymentMethodData::Upi(_) - | domain::PaymentMethodData::Voucher(_) - | domain::PaymentMethodData::GiftCard(_) - | domain::PaymentMethodData::OpenBanking(_) - | domain::PaymentMethodData::CardToken(_) - | domain::PaymentMethodData::NetworkToken(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("CryptoPay"), - )) - } + PaymentMethodData::Card(_) + | PaymentMethodData::CardRedirect(_) + | PaymentMethodData::Wallet(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankRedirect(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | 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("CryptoPay"), + )), }?; Ok(cryptopay_request) } @@ -96,10 +100,10 @@ pub struct CryptopayAuthType { pub(super) api_secret: Secret<String>, } -impl TryFrom<&types::ConnectorAuthType> for CryptopayAuthType { +impl TryFrom<&ConnectorAuthType> for CryptopayAuthType { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { - if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { api_key: api_key.to_owned(), api_secret: key1.to_owned(), @@ -140,21 +144,21 @@ pub struct CryptopayPaymentsResponse { impl<F, T> ForeignTryFrom<( - types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, + ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, - )> for types::RouterData<F, T, types::PaymentsResponseData> + )> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn foreign_try_from( (item, amount_captured_in_minor_units): ( - types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>, + ResponseRouterData<F, CryptopayPaymentsResponse, T, PaymentsResponseData>, Option<MinorUnit>, ), ) -> Result<Self, Self::Error> { let status = enums::AttemptStatus::from(item.response.data.status.clone()); - let response = if is_payment_failure(status) { + let response = if utils::is_payment_failure(status) { let payment_response = &item.response.data; - Err(types::ErrorResponse { + Err(ErrorResponse { code: payment_response .name .clone() @@ -173,11 +177,9 @@ impl<F, T> .response .data .hosted_page_url - .map(|x| services::RedirectForm::from((x, services::Method::Get))); - Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.data.id.clone(), - ), + .map(|x| RedirectForm::from((x, common_utils::request::Method::Get))); + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.data.id.clone()), redirection_data, mandate_reference: None, connector_metadata: None, diff --git a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs index 1093ef4e6f0..953b6316ff8 100644 --- a/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/volt/transformers.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{RefreshTokenRouterData, RefundsResponseRouterData, ResponseRouterData}, - utils::{self, AddressDetailsData, RouterData as _}, + utils::{self, is_payment_failure, AddressDetailsData, RouterData as _}, }; const PASSWORD: &str = "password"; @@ -605,32 +605,3 @@ pub struct VoltErrorList { pub property: String, pub message: String, } - -fn is_payment_failure(status: enums::AttemptStatus) -> bool { - match status { - common_enums::AttemptStatus::AuthenticationFailed - | common_enums::AttemptStatus::AuthorizationFailed - | common_enums::AttemptStatus::CaptureFailed - | common_enums::AttemptStatus::VoidFailed - | common_enums::AttemptStatus::Failure => true, - common_enums::AttemptStatus::Started - | common_enums::AttemptStatus::RouterDeclined - | common_enums::AttemptStatus::AuthenticationPending - | common_enums::AttemptStatus::AuthenticationSuccessful - | common_enums::AttemptStatus::Authorized - | common_enums::AttemptStatus::Charged - | common_enums::AttemptStatus::Authorizing - | common_enums::AttemptStatus::CodInitiated - | common_enums::AttemptStatus::Voided - | common_enums::AttemptStatus::VoidInitiated - | common_enums::AttemptStatus::CaptureInitiated - | common_enums::AttemptStatus::AutoRefunded - | common_enums::AttemptStatus::PartialCharged - | common_enums::AttemptStatus::PartialChargedAndChargeable - | common_enums::AttemptStatus::Unresolved - | common_enums::AttemptStatus::Pending - | common_enums::AttemptStatus::PaymentMethodAwaited - | common_enums::AttemptStatus::ConfirmationAwaited - | common_enums::AttemptStatus::DeviceDataCollectionPending => false, - } -} diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index c5ca6512a34..4c27e11fc45 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -10,6 +10,8 @@ pub(crate) mod headers { pub(crate) const MERCHANT_ID: &str = "Merchant-ID"; pub(crate) const TIMESTAMP: &str = "Timestamp"; pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version"; + pub(crate) const X_CC_API_KEY: &str = "X-CC-Api-Key"; + pub(crate) const X_CC_VERSION: &str = "X-CC-Version"; pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key"; pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue"; pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate"; diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index a667c5ddc3c..31052ab0df2 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -91,6 +91,9 @@ macro_rules! default_imp_for_authorize_session_token { default_imp_for_authorize_session_token!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -126,6 +129,9 @@ macro_rules! default_imp_for_calculate_tax { default_imp_for_calculate_tax!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, @@ -160,6 +166,9 @@ macro_rules! default_imp_for_session_update { default_imp_for_session_update!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Helcim, @@ -196,6 +205,9 @@ macro_rules! default_imp_for_complete_authorize { default_imp_for_complete_authorize!( connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -229,6 +241,9 @@ macro_rules! default_imp_for_incremental_authorization { default_imp_for_incremental_authorization!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -265,6 +280,9 @@ macro_rules! default_imp_for_create_customer { default_imp_for_create_customer!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -301,6 +319,9 @@ macro_rules! default_imp_for_connector_redirect_response { default_imp_for_connector_redirect_response!( connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -335,6 +356,9 @@ macro_rules! default_imp_for_pre_processing_steps{ default_imp_for_pre_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -371,6 +395,9 @@ macro_rules! default_imp_for_post_processing_steps{ default_imp_for_post_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -407,6 +434,9 @@ macro_rules! default_imp_for_approve { default_imp_for_approve!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -443,6 +473,9 @@ macro_rules! default_imp_for_reject { default_imp_for_reject!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -479,6 +512,9 @@ macro_rules! default_imp_for_webhook_source_verification { default_imp_for_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -516,6 +552,9 @@ macro_rules! default_imp_for_accept_dispute { default_imp_for_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -552,6 +591,9 @@ macro_rules! default_imp_for_submit_evidence { default_imp_for_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -588,6 +630,9 @@ macro_rules! default_imp_for_defend_dispute { default_imp_for_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -633,6 +678,9 @@ macro_rules! default_imp_for_file_upload { default_imp_for_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -671,6 +719,9 @@ macro_rules! default_imp_for_payouts_create { default_imp_for_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -709,6 +760,9 @@ macro_rules! default_imp_for_payouts_retrieve { default_imp_for_payouts_retrieve!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -747,6 +801,9 @@ macro_rules! default_imp_for_payouts_eligibility { default_imp_for_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -785,6 +842,9 @@ macro_rules! default_imp_for_payouts_fulfill { default_imp_for_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -823,6 +883,9 @@ macro_rules! default_imp_for_payouts_cancel { default_imp_for_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -861,6 +924,9 @@ macro_rules! default_imp_for_payouts_quote { default_imp_for_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -899,6 +965,9 @@ macro_rules! default_imp_for_payouts_recipient { default_imp_for_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -937,6 +1006,9 @@ macro_rules! default_imp_for_payouts_recipient_account { default_imp_for_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -975,6 +1047,9 @@ macro_rules! default_imp_for_frm_sale { default_imp_for_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1013,6 +1088,9 @@ macro_rules! default_imp_for_frm_checkout { default_imp_for_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1051,6 +1129,9 @@ macro_rules! default_imp_for_frm_transaction { default_imp_for_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1089,6 +1170,9 @@ macro_rules! default_imp_for_frm_fulfillment { default_imp_for_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1127,6 +1211,9 @@ macro_rules! default_imp_for_frm_record_return { default_imp_for_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1162,6 +1249,9 @@ macro_rules! default_imp_for_revoking_mandates { default_imp_for_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 3bb1abfef21..16e592688ac 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -198,6 +198,9 @@ macro_rules! default_imp_for_new_connector_integration_payment { default_imp_for_new_connector_integration_payment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -235,6 +238,9 @@ macro_rules! default_imp_for_new_connector_integration_refund { default_imp_for_new_connector_integration_refund!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -267,6 +273,9 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token { default_imp_for_new_connector_integration_connector_access_token!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -305,6 +314,9 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute { default_imp_for_new_connector_integration_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -342,6 +354,9 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence { default_imp_for_new_connector_integration_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -379,6 +394,9 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute { default_imp_for_new_connector_integration_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -426,6 +444,9 @@ macro_rules! default_imp_for_new_connector_integration_file_upload { default_imp_for_new_connector_integration_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -465,6 +486,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create { default_imp_for_new_connector_integration_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -504,6 +528,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility { default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -543,6 +570,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill { default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -582,6 +612,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel { default_imp_for_new_connector_integration_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -621,6 +654,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote { default_imp_for_new_connector_integration_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -660,6 +696,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient { default_imp_for_new_connector_integration_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -699,6 +738,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync { default_imp_for_new_connector_integration_payouts_sync!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -738,6 +780,9 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -775,6 +820,9 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -814,6 +862,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale { default_imp_for_new_connector_integration_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -853,6 +904,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout { default_imp_for_new_connector_integration_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -892,6 +946,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction { default_imp_for_new_connector_integration_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -931,6 +988,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment { default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -970,6 +1030,9 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return { default_imp_for_new_connector_integration_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, @@ -1006,6 +1069,9 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates { default_imp_for_new_connector_integration_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index b2979975e55..f96d715f5be 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -4,7 +4,7 @@ use api_models::payments::{self, Address, AddressDetails, OrderDetailsWithAmount use base64::Engine; use common_enums::{ enums, - enums::{CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation}, + enums::{AttemptStatus, CanadaStatesAbbreviation, FutureUsage, UsStatesAbbreviation}, }; use common_utils::{ consts::BASE64_ENGINE, @@ -163,6 +163,35 @@ pub(crate) fn convert_back_amount_to_minor_units<T>( .change_context(errors::ConnectorError::AmountConversionFailed) } +pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool { + match status { + AttemptStatus::AuthenticationFailed + | AttemptStatus::AuthorizationFailed + | AttemptStatus::CaptureFailed + | AttemptStatus::VoidFailed + | AttemptStatus::Failure => true, + AttemptStatus::Started + | AttemptStatus::RouterDeclined + | AttemptStatus::AuthenticationPending + | AttemptStatus::AuthenticationSuccessful + | AttemptStatus::Authorized + | AttemptStatus::Charged + | AttemptStatus::Authorizing + | AttemptStatus::CodInitiated + | AttemptStatus::Voided + | AttemptStatus::VoidInitiated + | AttemptStatus::CaptureInitiated + | AttemptStatus::AutoRefunded + | AttemptStatus::PartialCharged + | AttemptStatus::PartialChargedAndChargeable + | AttemptStatus::Unresolved + | AttemptStatus::Pending + | AttemptStatus::PaymentMethodAwaited + | AttemptStatus::ConfirmationAwaited + | AttemptStatus::DeviceDataCollectionPending => false, + } +} + // TODO: Make all traits as `pub(crate) trait` once all connectors are moved. pub trait RouterData { fn get_billing(&self) -> Result<&Address, Error>; @@ -1460,6 +1489,18 @@ fn get_header_field( ))? } +pub trait CryptoData { + fn get_pay_currency(&self) -> Result<String, Error>; +} + +impl CryptoData for hyperswitch_domain_models::payment_method_data::CryptoData { + fn get_pay_currency(&self) -> Result<String, Error> { + self.pay_currency + .clone() + .ok_or_else(missing_field_err("crypto_data.pay_currency")) + } +} + #[macro_export] macro_rules! unimplemented_payment_method { ($payment_method:expr, $connector:expr) => { diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index b505f8c8c52..116fc67320f 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -9,10 +9,7 @@ pub mod billwerk; pub mod bluesnap; pub mod boku; pub mod braintree; -pub mod cashtocode; pub mod checkout; -pub mod coinbase; -pub mod cryptopay; pub mod cybersource; pub mod datatrans; pub mod dlocal; @@ -62,12 +59,13 @@ pub mod zen; pub mod zsl; pub use hyperswitch_connectors::connectors::{ - bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank, - fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, - globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, nexixpay, - nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, stax, - stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, - worldline, worldline::Worldline, + bambora, bambora::Bambora, bitpay, bitpay::Bitpay, cashtocode, cashtocode::Cashtocode, + coinbase, coinbase::Coinbase, cryptopay, cryptopay::Cryptopay, deutschebank, + deutschebank::Deutschebank, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, + fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, mollie, mollie::Mollie, + nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, + stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, + volt::Volt, worldline, worldline::Worldline, }; #[cfg(feature = "dummy_connector")] @@ -75,8 +73,7 @@ pub use self::dummyconnector::DummyConnector; pub use self::{ aci::Aci, adyen::Adyen, adyenplatform::Adyenplatform, airwallex::Airwallex, authorizedotnet::Authorizedotnet, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, - billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, - cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay, + billwerk::Billwerk, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, checkout::Checkout, cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, forte::Forte, globalpay::Globalpay, gocardless::Gocardless, gpayments::Gpayments, iatapay::Iatapay, itaubank::Itaubank, klarna::Klarna, mifinity::Mifinity, multisafepay::Multisafepay, 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 041b5bb7359..3ff93cf9bf0 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -682,10 +682,7 @@ default_imp_for_new_connector_integration_payment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -760,10 +757,7 @@ default_imp_for_new_connector_integration_refund!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -832,10 +826,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -926,10 +917,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1002,10 +990,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1062,10 +1047,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1149,10 +1131,7 @@ default_imp_for_new_connector_integration_file_upload!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1315,10 +1294,7 @@ default_imp_for_new_connector_integration_payouts_create!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1394,10 +1370,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1473,10 +1446,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1552,10 +1522,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1631,10 +1598,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1710,10 +1674,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1789,10 +1750,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1868,10 +1826,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1945,10 +1900,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2111,10 +2063,7 @@ default_imp_for_new_connector_integration_frm_sale!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2190,10 +2139,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2269,10 +2215,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2348,10 +2291,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2427,10 +2367,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -2503,10 +2440,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index e364d662e24..f9a6b461a13 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -209,10 +209,7 @@ default_imp_for_complete_authorize!( connector::Bankofamerica, connector::Billwerk, connector::Boku, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -288,10 +285,7 @@ default_imp_for_webhook_source_verification!( connector::Bluesnap, connector::Braintree, connector::Boku, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -376,10 +370,7 @@ default_imp_for_create_customer!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -461,9 +452,6 @@ default_imp_for_connector_redirect_response!( connector::Bankofamerica, connector::Billwerk, connector::Boku, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -630,9 +618,6 @@ default_imp_for_accept_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -739,9 +724,6 @@ default_imp_for_file_upload!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, - connector::Coinbase, - connector::Cryptopay, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -825,10 +807,7 @@ default_imp_for_submit_evidence!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Cybersource, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -911,10 +890,7 @@ default_imp_for_defend_dispute!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Cybersource, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1012,10 +988,7 @@ default_imp_for_pre_processing_steps!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1086,10 +1059,7 @@ default_imp_for_post_processing_steps!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Coinbase, - connector::Cryptopay, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1247,11 +1217,8 @@ default_imp_for_payouts_create!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1333,10 +1300,7 @@ default_imp_for_payouts_retrieve!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -1424,11 +1388,8 @@ default_imp_for_payouts_eligibility!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1510,10 +1471,7 @@ default_imp_for_payouts_fulfill!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1593,11 +1551,8 @@ default_imp_for_payouts_cancel!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1680,11 +1635,8 @@ default_imp_for_payouts_quote!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1768,11 +1720,8 @@ default_imp_for_payouts_recipient!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Forte, @@ -1858,11 +1807,8 @@ default_imp_for_payouts_recipient_account!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -1946,11 +1892,8 @@ default_imp_for_approve!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2035,11 +1978,8 @@ default_imp_for_reject!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2214,11 +2154,8 @@ default_imp_for_frm_sale!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2303,11 +2240,8 @@ default_imp_for_frm_checkout!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2392,11 +2326,8 @@ default_imp_for_frm_transaction!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2481,11 +2412,8 @@ default_imp_for_frm_fulfillment!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2570,11 +2498,8 @@ default_imp_for_frm_record_return!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, connector::Cybersource, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2657,10 +2582,7 @@ default_imp_for_incremental_authorization!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2742,10 +2664,7 @@ default_imp_for_revoking_mandates!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Datatrans, connector::Dlocal, connector::Ebanx, @@ -2986,10 +2905,7 @@ default_imp_for_authorize_session_token!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -3071,10 +2987,7 @@ default_imp_for_calculate_tax!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal, @@ -3158,10 +3071,7 @@ default_imp_for_session_update!( connector::Bluesnap, connector::Boku, connector::Braintree, - connector::Cashtocode, connector::Checkout, - connector::Cryptopay, - connector::Coinbase, connector::Cybersource, connector::Datatrans, connector::Dlocal,
2024-09-20T18:00:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/5629 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Cryptopay: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_23PxPwqBujt8VbpD0hwiNIqNHY5HNa82ZKPJEfN2Ex2y9CE2RcPNiNCeBMIMBifB' \ --data-raw '{ "amount": 300, "currency": "USD", "confirm": true, "email": "guest@example.com", "return_url": "https://google.com", "payment_method": "crypto", "payment_method_type": "crypto_currency", "payment_experience": "redirect_to_url", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "litecoin" } } }' ``` Response: ``` { "payment_id": "pay_D91HEOHsNOK0OJhfM4yo", "merchant_id": "merchant_1727096693", "status": "requires_customer_action", "amount": 300, "net_amount": 300, "amount_capturable": 300, "amount_received": 300, "connector": "cryptopay", "client_secret": "pay_D91HEOHsNOK0OJhfM4yo_secret_5vTYDEJXX4cI83WnlJ4N", "created": "2024-09-23T13:19:07.696Z", "currency": "USD", "customer_id": null, "customer": { "id": null, "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "crypto", "payment_method_data": { "crypto": { "pay_currency": "LTC", "network": "litecoin" }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_D91HEOHsNOK0OJhfM4yo/merchant_1727096693/pay_D91HEOHsNOK0OJhfM4yo_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": "redirect_to_url", "payment_method_type": "crypto_currency", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "63f933ba-aadb-446b-b80a-58f70abb38e1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_D91HEOHsNOK0OJhfM4yo_1", "payment_link": null, "profile_id": "pro_1pHVbwpinQ6kPONiCARj", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RsWL9yopYx8fWkdxALEU", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-23T13:34:07.695Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-23T13:19:09.657Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` Note: Local testing not available for coinbase and cashtocode due to unavailability of credentials. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d9270ace8ddde16eca8c45ceb79af3e4d815d7cd
juspay/hyperswitch
juspay__hyperswitch-5965
Bug: [REFACTOR] Update Database Connection Functions for Read Operations ### Feature Description Currently, in our codebase, we are using `pg_connection_write` for database operations even when performing read operations, which is inefficient. The `pg_connection_write` function should only be used when we need to perform write operations. For read operations, we should use `pg_connection_read` to optimize resource usage. ### Possible Implementation Find occurrences of the usage of `pg_connection_write` for read operations and replace them with `pg_connection_read` in the following files: - `crates/router/src/db/role.rs` - `crates/router/src/db/user.rs` - `crates/router/src/db/user_role.rs` - `crates/router/src/db/dashboard_metadata.rs` 1. Open each of the specified files and search for functions that are performing read operations (for e.g., `find_by_*`, `get_*`) but are using `pg_connection_write`. 2. Replace the usage of `pg_connection_write` with `pg_connection_read` in these functions. 3. Ensure that the database calls still behave correctly and no write operations are mistakenly changed. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index f8aee34c49c..742c03dde4a 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -99,7 +99,7 @@ impl DashboardMetadataInterface for Store { org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::DashboardMetadata::find_user_scoped_dashboard_metadata( &conn, user_id.to_owned(), @@ -118,7 +118,7 @@ impl DashboardMetadataInterface for Store { org_id: &id_type::OrganizationId, data_keys: Vec<enums::DashboardMetadata>, ) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata( &conn, merchant_id.to_owned(), diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index 20a4922d165..ce009d38a9e 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -80,7 +80,7 @@ impl RoleInterface for Store { &self, role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id(&conn, role_id) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -93,7 +93,7 @@ impl RoleInterface for Store { merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Role, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_in_merchant_scope(&conn, role_id, merchant_id, org_id) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -105,7 +105,7 @@ impl RoleInterface for Store { role_id: &str, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Role, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::Role::find_by_role_id_in_org_scope(&conn, role_id, org_id) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -140,7 +140,7 @@ impl RoleInterface for Store { merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::Role::list_roles(&conn, merchant_id, org_id) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -154,7 +154,7 @@ impl RoleInterface for Store { entity_type: Option<enums::EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::Role::generic_roles_list_for_org( &conn, org_id.to_owned(), diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index c9244eb12b4..3cf68551b52 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -71,7 +71,7 @@ impl UserInterface for Store { &self, user_email: &pii::Email, ) -> CustomResult<storage::User, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_email(&conn, user_email) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -82,7 +82,7 @@ impl UserInterface for Store { &self, user_id: &str, ) -> CustomResult<storage::User, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::User::find_by_user_id(&conn, user_id) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -127,7 +127,7 @@ impl UserInterface for Store { &self, user_ids: Vec<String>, ) -> CustomResult<Vec<storage::User>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::User::find_users_by_user_ids(&conn, user_ids) .await .map_err(|error| report!(errors::StorageError::from(error))) diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index b589d375975..ceec7dd77d9 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -102,7 +102,7 @@ impl UserRoleInterface for Store { profile_id: Option<&id_type::ProfileId>, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::UserRole::find_by_user_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(),
2024-09-30T19:50:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR refactors the database connection logic by changing the function from `pg_connection_write()` to `pg_connection_read()` for functions that only perform read operations from the database. This is an internal change aimed at optimizing resource usage. All user-facing APIs should continue to function as expected without any disruptions. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context This change is required to improve efficiency by ensuring that we use the appropriate connection type for read operations. It resolves the inefficiency of using write connections for read-only database queries. - Fixes https://github.com/juspay/hyperswitch/issues/5965 ## How did you test it? - Verified that all user-related APIs are working without any issues. - All existing test cases for database read and write operations passed successfully. - Confirmed that this internal change does not affect the functionality of user-facing APIs. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
edd099886da9c46800a646fe809796a08eb78c99
juspay/hyperswitch
juspay__hyperswitch-5966
Bug: [BUG] Bug in merchant connector account create - delete flows ### Bug Description There is a problem with how the `configs` table is updated. The problem arises when a user deletes a connector and then adds the same one, the config isn't cleaned from the connector when it's deleted, and the new connector (with the same type) is appended to the array. It looks something like this: ```json [{"connector":"adyen","merchant_connector_id":"mca_123XXX"}, //old one, already deleted {"connector":"adyen","merchant_connector_id":"mca_456XXX"}] //new one ``` When a payment (or payout or anything else connector related) is being created the router looks at the first occurrence of the connector (which is already deleted) and then looks at the `merchant_connector_account` table for an already deleted `merchant_connector_id`, unsurprisingly does not find it and throws an error. Affects both payment and payout processors ### Expected Behavior I think either the payment connector delete function should clean the config array of the deleted connector, or the update function should prepend the config instead of appending. ### Actual Behavior The delete function does not clean the config and then just appends it when new creator of same type is added ### Steps To Reproduce To reproduce: 1. Create a merchant connector account of any type 2. Delete it 3. Create the same connector 4. Try to make a payment with that connector 5. Get error 404: ```json { "error": { "type": "invalid_request", "message": "Merchant connector account does not exist in our records", "code": "HE_02", "reason": "mca_123XXX does not exist" } } ``` ### Context For The Bug Trace for update config: ```sh at crates/diesel_models/src/query/generics.rs:247 in router::db::configs::update_config_in_database in storage_impl::redis::cache::publish_and_redact in router::db::configs::update_config_by_key in core::routing::helpers::update_merchant_default_config in router::core::retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists ``` ### Environment Are you using hyperswitch hosted version? No If not (or if building/running locally), please provide the following details: 1. Operating System or Linux distribution: Ubuntu 22.04 2. Rust version (output of `rustc --version`): `rustc 1.80.1 (3f5fd8dd4 2024-08-06)` 3. App version (output of `cargo r --features vergen -- --version`): `2024.08.27` (not running the latest version but checked the functions responsible and there weren't any changes) ### Have you spent some time checking if this bug has been raised before? - [x] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 781b5e3710a..f0adf49c1e8 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3327,6 +3327,16 @@ pub enum PresenceOfCustomerDuringPayment { Absent, } +impl From<ConnectorType> for TransactionType { + fn from(connector_type: ConnectorType) -> Self { + match connector_type { + #[cfg(feature = "payouts")] + ConnectorType::PayoutProcessor => Self::Payout, + _ => Self::Payment, + } + } +} + #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, Default, ToSchema)] pub enum TaxCalculationOverride { /// Skip calling the external tax provider diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 055c428b1fb..26a3be0863c 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1931,6 +1931,65 @@ impl<'a> MerchantDefaultConfigUpdate<'a> { } Ok(()) } + + async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists( + &self, + ) -> RouterResult<()> { + let mut default_routing_config = routing::helpers::get_merchant_default_config( + self.store, + self.merchant_id.get_string_repr(), + self.transaction_type, + ) + .await?; + + let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config( + self.store, + self.profile_id.get_string_repr(), + self.transaction_type, + ) + .await?; + + if let Some(routable_connector_val) = self.routable_connector { + let choice = routing_types::RoutableConnectorChoice { + choice_kind: routing_types::RoutableChoiceKind::FullStruct, + connector: *routable_connector_val, + merchant_connector_id: Some(self.merchant_connector_id.clone()), + }; + if default_routing_config.contains(&choice) { + default_routing_config.retain(|mca| { + mca.merchant_connector_id + .as_ref() + .map_or(true, |merchant_connector_id| { + merchant_connector_id != self.merchant_connector_id + }) + }); + routing::helpers::update_merchant_default_config( + self.store, + self.merchant_id.get_string_repr(), + default_routing_config.clone(), + self.transaction_type, + ) + .await?; + } + if default_routing_config_for_profile.contains(&choice.clone()) { + default_routing_config_for_profile.retain(|mca| { + mca.merchant_connector_id + .as_ref() + .map_or(true, |merchant_connector_id| { + merchant_connector_id != self.merchant_connector_id + }) + }); + routing::helpers::update_merchant_default_config( + self.store, + self.profile_id.get_string_repr(), + default_routing_config_for_profile.clone(), + self.transaction_type, + ) + .await?; + } + } + Ok(()) + } } #[cfg(feature = "v2")] struct DefaultFallbackRoutingConfigUpdate<'a> { @@ -1970,6 +2029,40 @@ impl<'a> DefaultFallbackRoutingConfigUpdate<'a> { } Ok(()) } + + async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists( + &self, + ) -> RouterResult<()> { + let profile_wrapper = ProfileWrapper::new(self.business_profile.clone()); + let default_routing_config_for_profile = + &mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?; + if let Some(routable_connector_val) = self.routable_connector { + let choice = routing_types::RoutableConnectorChoice { + choice_kind: routing_types::RoutableChoiceKind::FullStruct, + connector: *routable_connector_val, + merchant_connector_id: Some(self.merchant_connector_id.clone()), + }; + if default_routing_config_for_profile.contains(&choice.clone()) { + default_routing_config_for_profile.retain(|mca| { + mca.merchant_connector_id + .as_ref() + .map_or(true, |merchant_connector_id| { + merchant_connector_id != self.merchant_connector_id + }) + }); + + profile_wrapper + .update_default_fallback_routing_of_connectors_under_profile( + self.store, + default_routing_config_for_profile, + self.key_manager_state, + &self.key_store, + ) + .await? + } + } + Ok(()) + } } #[cfg(any(feature = "v1", feature = "v2", feature = "olap"))] #[async_trait::async_trait] @@ -3139,7 +3232,7 @@ pub async fn delete_connector( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; - let _mca = db + let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, @@ -3161,6 +3254,26 @@ pub async fn delete_connector( id: merchant_connector_id.get_string_repr().to_string(), })?; + // delete the mca from the config as well + let merchant_default_config_delete = MerchantDefaultConfigUpdate { + routable_connector: &Some( + common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { + errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector_name", + } + })?, + ), + merchant_connector_id: &mca.get_id(), + store: db, + merchant_id: &merchant_id, + profile_id: &mca.profile_id, + transaction_type: &mca.connector_type.into(), + }; + + merchant_default_config_delete + .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() + .await?; + let response = api::MerchantConnectorDeleteResponse { merchant_id, merchant_connector_id, @@ -3207,6 +3320,32 @@ pub async fn delete_connector( id: id.clone().get_string_repr().to_string(), })?; + let business_profile = db + .find_business_profile_by_profile_id(key_manager_state, &key_store, &mca.profile_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { + id: mca.profile_id.get_string_repr().to_owned(), + })?; + + let merchant_default_config_delete = DefaultFallbackRoutingConfigUpdate { + routable_connector: &Some( + common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { + errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector_name", + } + })?, + ), + merchant_connector_id: &mca.get_id(), + store: db, + business_profile, + key_store, + key_manager_state, + }; + + merchant_default_config_delete + .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() + .await?; + let response = api::MerchantConnectorDeleteResponse { merchant_id: merchant_id.clone(), id,
2024-09-23T13:34:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Fixes #5966 (in both v1 and v2). Now the router cleans up the configs table (or business_profile in v2) when a connector is deleted. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Added a payment and payout processor, checked if values are present in config, deleted and rechecked. v1: ![v1test](https://github.com/user-attachments/assets/fad9e25a-edc0-4bdd-9835-e577c1d43d05) v2: ![v2test](https://github.com/user-attachments/assets/2e6f311b-c860-407a-9c61-8162c77f6ec8) ## Test on Integ - Create any 2 MCA's ``` curl --location 'http://localhost:8080/account/merchant_1733401776/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "stripe", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "{{api_key}}" }, "connector_label": "stripe_US_default7777", "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 1, "maximum_amount": 200000, "recurring_enabled": false, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 1, "maximum_amount": 200000, "recurring_enabled": false, "installment_payment_enabled": false } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "minimum_amount": 1, "maximum_amount": 50000, "recurring_enabled": false, "installment_payment_enabled": false }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "minimum_amount": 600, "maximum_amount": 800, "recurring_enabled": false, "installment_payment_enabled": false } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "affirm", "payment_experience": "redirect_to_url", "card_networks": null, "minimum_amount": 1, "maximum_amount": 50000, "recurring_enabled": false, "installment_payment_enabled": false } ] } ], "metadata": { "city": "NY", "unit": "245" } }' ``` - Do the list for default fallback routing connectors, the connector should be present ``` curl --location 'http://localhost:8080/routing/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWQyMTRiZjUtMjgyYS00OWRiLWIzMjEtZGM3ZTExODRlNTliIiwibWVyY2hhbnRfaWQiOiJzZW5kZXJfbmV0Iiwicm9sZV9pZCI6ImludGVybmFsX3ZpZXdfb25seSIsImV4cCI6MTcyMTMxMDI0NCwib3JnX2lkIjoib3JnX2JmQXZqZWZRMG5oTjVJVm95VTZGIn0.hCH_Pd0d2d08ESOUy1PMGfyuh5TzXQLfi0wBIev1O6U' \ --data '' ``` - Delete the one of those 2 MCA's ``` curl --location --request DELETE 'http://localhost:8080/account/merchant_1733401776/connectors/mca_jIEg3gZxzs54aMMrhT9D' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' ``` - The list for default fallback routing connectors, the connector shouldn't be present ``` curl --location 'http://localhost:8080/routing/default/profile' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWQyMTRiZjUtMjgyYS00OWRiLWIzMjEtZGM3ZTExODRlNTliIiwibWVyY2hhbnRfaWQiOiJzZW5kZXJfbmV0Iiwicm9sZV9pZCI6ImludGVybmFsX3ZpZXdfb25seSIsImV4cCI6MTcyMTMxMDI0NCwib3JnX2lkIjoib3JnX2JmQXZqZWZRMG5oTjVJVm95VTZGIn0.hCH_Pd0d2d08ESOUy1PMGfyuh5TzXQLfi0wBIev1O6U' \ --data '' ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
64383915bda5693df1cecf6cc5683e8b9aaef99b
juspay/hyperswitch
juspay__hyperswitch-5969
Bug: Add support for Samsung Pay payment method This is to support for Samsung pay as a payment method. This also needs to add a new field in merchant connector account create `connector_wallet_details` which is required to collect the required credentials for Samsung Pay. As this column in the data base stores the data in the encrypted format we also want to migrate apple pay certificates from metadata to `connector_wallet_details`, for which we are inserting apple pay details passed in the metadata to connector_wallet_details. Once the frontend changes are done to pass the apple pay credentials in the connector_wallet_details this fallback can be removed.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 5465d902388..a250a8a9c37 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -5521,6 +5521,27 @@ } } }, + "ConnectorWalletDetails": { + "type": "object", + "properties": { + "apple_pay_combined": { + "type": "object", + "description": "This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow", + "nullable": true + }, + "apple_pay": { + "type": "object", + "description": "This field is for our legacy Apple Pay flow that contains the Apple Pay certificates and credentials for only iOS Apple Pay flow", + "nullable": true + }, + "samsung_pay": { + "type": "object", + "description": "This field contains the Samsung Pay certificates and credentials", + "nullable": true + } + }, + "additionalProperties": false + }, "CountryAlpha2": { "type": "string", "enum": [ @@ -9254,6 +9275,14 @@ } ], "nullable": true + }, + "connector_wallets_details": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorWalletDetails" + } + ], + "nullable": true } }, "additionalProperties": false @@ -9450,6 +9479,14 @@ } ], "nullable": true + }, + "connector_wallets_details": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorWalletDetails" + } + ], + "nullable": true } }, "additionalProperties": false @@ -9591,6 +9628,14 @@ } ], "nullable": true + }, + "connector_wallets_details": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorWalletDetails" + } + ], + "nullable": true } }, "additionalProperties": false @@ -9716,6 +9761,14 @@ } ], "nullable": true + }, + "connector_wallets_details": { + "allOf": [ + { + "$ref": "#/components/schemas/ConnectorWalletDetails" + } + ], + "nullable": true } }, "additionalProperties": false @@ -17929,15 +17982,164 @@ } } }, - "SamsungPayWalletData": { + "SamsungPayAmountDetails": { "type": "object", "required": [ - "token" + "option", + "currency_code", + "total" ], "properties": { - "token": { + "option": { + "$ref": "#/components/schemas/SamsungPayAmountFormat" + }, + "currency_code": { + "$ref": "#/components/schemas/Currency" + }, + "total": { + "type": "string", + "description": "The total amount of the transaction", + "example": "38.02" + } + } + }, + "SamsungPayAmountFormat": { + "type": "string", + "enum": [ + "FORMAT_TOTAL_PRICE_ONLY", + "FORMAT_TOTAL_ESTIMATED_AMOUNT" + ] + }, + "SamsungPayMerchantPaymentInformation": { + "type": "object", + "required": [ + "name", + "url", + "country_code" + ], + "properties": { + "name": { + "type": "string", + "description": "Merchant name, this will be displayed on the Samsung Pay screen" + }, + "url": { + "type": "string", + "description": "Merchant domain that process payments" + }, + "country_code": { + "$ref": "#/components/schemas/CountryAlpha2" + } + } + }, + "SamsungPayProtocolType": { + "type": "string", + "enum": [ + "PROTOCOL3DS" + ] + }, + "SamsungPaySessionTokenResponse": { + "type": "object", + "required": [ + "version", + "service_id", + "order_number", + "merchant", + "amount", + "protocol", + "allowed_brands" + ], + "properties": { + "version": { + "type": "string", + "description": "Samsung Pay API version" + }, + "service_id": { + "type": "string", + "description": "Samsung Pay service ID to which session call needs to be made" + }, + "order_number": { + "type": "string", + "description": "Order number of the transaction" + }, + "merchant": { + "$ref": "#/components/schemas/SamsungPayMerchantPaymentInformation" + }, + "amount": { + "$ref": "#/components/schemas/SamsungPayAmountDetails" + }, + "protocol": { + "$ref": "#/components/schemas/SamsungPayProtocolType" + }, + "allowed_brands": { + "type": "array", + "items": { + "type": "string" + }, + "description": "List of supported card brands" + } + } + }, + "SamsungPayTokenData": { + "type": "object", + "required": [ + "version", + "data" + ], + "properties": { + "type": { + "type": "string", + "description": "3DS type used by Samsung Pay", + "nullable": true + }, + "version": { "type": "string", - "description": "The encrypted payment token from Samsung" + "description": "3DS version used by Samsung Pay" + }, + "data": { + "type": "string", + "description": "Samsung Pay encrypted payment credential data" + } + } + }, + "SamsungPayWalletCredentials": { + "type": "object", + "required": [ + "card_brand", + "card_last4digits", + "3_d_s" + ], + "properties": { + "method": { + "type": "string", + "description": "Specifies authentication method used", + "nullable": true + }, + "recurring_payment": { + "type": "boolean", + "description": "Value if credential is enabled for recurring payment", + "nullable": true + }, + "card_brand": { + "type": "string", + "description": "Brand of the payment card" + }, + "card_last4digits": { + "type": "string", + "description": "Last 4 digits of the card number" + }, + "3_d_s": { + "$ref": "#/components/schemas/SamsungPayTokenData" + } + } + }, + "SamsungPayWalletData": { + "type": "object", + "required": [ + "payment_credential" + ], + "properties": { + "payment_credential": { + "$ref": "#/components/schemas/SamsungPayWalletCredentials" } } }, @@ -18145,6 +18347,27 @@ } ] }, + { + "allOf": [ + { + "$ref": "#/components/schemas/SamsungPaySessionTokenResponse" + }, + { + "type": "object", + "required": [ + "wallet_name" + ], + "properties": { + "wallet_name": { + "type": "string", + "enum": [ + "samsung_pay" + ] + } + } + } + ] + }, { "allOf": [ { diff --git a/config/config.example.toml b/config/config.example.toml index a6af984b01f..861785dc34c 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -534,6 +534,7 @@ credit = { currency = "USD,GBP,EUR" } debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } +samsung_pay = { currency = "USD,GBP,EUR" } [pm_filters.stax] credit = { currency = "USD" } diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index abb50a2c2f0..3a54c5ef08f 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -304,6 +304,7 @@ credit = { currency = "USD,GBP,EUR" } debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } +samsung_pay = { currency = "USD,GBP,EUR" } [pm_filters.volt] open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"} diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 38799c23858..ec3737a5c64 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -278,6 +278,7 @@ credit = { currency = "USD,GBP,EUR" } debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } +samsung_pay = { currency = "USD,GBP,EUR" } [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" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 2217a72429c..1c605ef35ac 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -281,6 +281,7 @@ credit = { currency = "USD,GBP,EUR" } debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } +samsung_pay = { currency = "USD,GBP,EUR" } [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" diff --git a/config/development.toml b/config/development.toml index 43130cb78f2..6e56d5bb14d 100644 --- a/config/development.toml +++ b/config/development.toml @@ -449,6 +449,7 @@ credit = { currency = "USD,GBP,EUR" } debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } +samsung_pay = { currency = "USD,GBP,EUR" } [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" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 2c6b12a88a0..15038da0125 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -414,6 +414,7 @@ credit = { currency = "USD,GBP,EUR" } debit = { currency = "USD,GBP,EUR" } apple_pay = { currency = "USD,GBP,EUR" } google_pay = { currency = "USD,GBP,EUR" } +samsung_pay = { currency = "USD,GBP,EUR" } [pm_filters.helcim] credit = { currency = "USD" } diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 3b9a8e1c983..cbbb17525b6 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -736,6 +736,10 @@ pub struct MerchantConnectorCreate { /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + #[schema(value_type = Option<ConnectorWalletDetails>)] + pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v2")] @@ -873,6 +877,10 @@ pub struct MerchantConnectorCreate { /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + #[schema(value_type = Option<ConnectorWalletDetails>)] + pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v1")] @@ -1093,6 +1101,10 @@ pub struct MerchantConnectorResponse { #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + #[schema(value_type = Option<ConnectorWalletDetails>)] + pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v2")] @@ -1212,6 +1224,10 @@ pub struct MerchantConnectorResponse { #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + #[schema(value_type = Option<ConnectorWalletDetails>)] + pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v1")] @@ -1318,6 +1334,10 @@ pub struct MerchantConnectorListResponse { #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + #[schema(value_type = Option<ConnectorWalletDetails>)] + pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v1")] @@ -1408,6 +1428,10 @@ pub struct MerchantConnectorListResponse { #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + #[schema(value_type = Option<ConnectorWalletDetails>)] + pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v2")] @@ -1503,6 +1527,28 @@ pub struct MerchantConnectorUpdate { /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + #[schema(value_type = Option<ConnectorWalletDetails>)] + pub connector_wallets_details: Option<ConnectorWalletDetails>, +} + +#[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")] + #[schema(value_type = Option<Object>)] + pub apple_pay_combined: Option<pii::SecretSerdeValue>, + /// This field is for our legacy Apple Pay flow that contains the Apple Pay certificates and credentials for only iOS Apple Pay flow + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option<Object>)] + pub apple_pay: Option<pii::SecretSerdeValue>, + /// This field contains the Samsung Pay certificates and credentials + #[serde(skip_serializing_if = "Option::is_none")] + #[schema(value_type = Option<Object>)] + pub samsung_pay: Option<pii::SecretSerdeValue>, } /// 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." @@ -1588,6 +1634,9 @@ pub struct MerchantConnectorUpdate { /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, + + /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials + pub connector_wallets_details: Option<ConnectorWalletDetails>, } #[cfg(feature = "v2")] diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 715bf3c3544..59cc0e0548f 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2788,9 +2788,37 @@ impl GetAddressFromPaymentMethodData for WalletData { #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { - /// The encrypted payment token from Samsung + pub payment_credential: SamsungPayWalletCredentials, +} + +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct SamsungPayWalletCredentials { + /// Specifies authentication method used + pub method: Option<String>, + /// Value if credential is enabled for recurring payment + pub recurring_payment: Option<bool>, + /// Brand of the payment card + pub card_brand: String, + /// Last 4 digits of the card number + #[serde(rename = "card_last4digits")] + pub card_last_four_digits: String, + /// Samsung Pay token data + #[serde(rename = "3_d_s")] + pub token_data: SamsungPayTokenData, +} + +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct SamsungPayTokenData { + /// 3DS type used by Samsung Pay + #[serde(rename = "type")] + pub three_ds_type: Option<String>, + /// 3DS version used by Samsung Pay + pub version: String, + /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] - pub token: Secret<String>, + pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -4789,6 +4817,20 @@ pub struct GpaySessionTokenData { pub data: GpayMetaData, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SamsungPaySessionTokenData { + #[serde(rename = "samsung_pay")] + pub data: SamsungPayMetadata, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SamsungPayMetadata { + pub service_id: String, + pub merchant_display_name: String, + pub merchant_business_country: api_enums::CountryAlpha2, + pub allowed_brands: Vec<String>, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, @@ -4954,6 +4996,8 @@ pub struct SessionTokenForSimplifiedApplePay { pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), + /// The session response structure for Samsung Pay + SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal @@ -5011,6 +5055,68 @@ pub struct GooglePaySessionResponse { pub secrets: Option<SecretInfoToInitiateSdk>, } +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct SamsungPaySessionTokenResponse { + /// Samsung Pay API version + pub version: String, + /// Samsung Pay service ID to which session call needs to be made + pub service_id: String, + /// Order number of the transaction + pub order_number: String, + /// Field containing merchant information + #[serde(rename = "merchant")] + pub merchant_payment_information: SamsungPayMerchantPaymentInformation, + /// Field containing the payment amount + pub amount: SamsungPayAmountDetails, + /// Payment protocol type + pub protocol: SamsungPayProtocolType, + /// List of supported card brands + pub allowed_brands: Vec<String>, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum SamsungPayProtocolType { + Protocol3ds, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct SamsungPayMerchantPaymentInformation { + /// Merchant name, this will be displayed on the Samsung Pay screen + pub name: String, + /// Merchant domain that process payments + pub url: String, + /// Merchant country code + #[schema(value_type = CountryAlpha2, example = "US")] + pub country_code: api_enums::CountryAlpha2, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "lowercase")] +pub struct SamsungPayAmountDetails { + #[serde(rename = "option")] + /// Amount format to be displayed + pub amount_format: SamsungPayAmountFormat, + /// The currency code + #[schema(value_type = Currency, example = "USD")] + pub currency_code: api_enums::Currency, + /// The total amount of the transaction + #[serde(rename = "total")] + #[schema(value_type = String, example = "38.02")] + pub total_amount: StringMajorUnit, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum SamsungPayAmountFormat { + /// Display the total amount only + FormatTotalPriceOnly, + /// Display "Total (Estimated amount)" and total amount + FormatTotalEstimatedAmount, +} + #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index fe39da67a93..68ade2909b4 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -56,7 +56,7 @@ impl DashboardRequestPayload { | (Connector::Stripe, WeChatPay) => { Some(api_models::enums::PaymentExperience::DisplayQrCode) } - (_, GooglePay) | (_, ApplePay) => { + (_, GooglePay) | (_, ApplePay) | (_, PaymentMethodType::SamsungPay) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } _ => Some(api_models::enums::PaymentExperience::RedirectToUrl), diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index b21bedd880c..9f505f26712 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -135,10 +135,30 @@ pub struct MifinityData { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] - +#[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { - /// The encrypted payment token from Samsung - pub token: Secret<String>, + pub payment_credential: SamsungPayWalletCredentials, +} + +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct SamsungPayWalletCredentials { + pub method: Option<String>, + pub recurring_payment: Option<bool>, + pub card_brand: String, + #[serde(rename = "card_last4digits")] + pub card_last_four_digits: String, + #[serde(rename = "3_d_s")] + pub token_data: SamsungPayTokenData, +} + +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct SamsungPayTokenData { + #[serde(rename = "type")] + pub three_ds_type: Option<String>, + pub version: String, + pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] @@ -670,9 +690,7 @@ impl From<api_models::payments::WalletData> for WalletData { }) } api_models::payments::WalletData::SamsungPay(samsung_pay_data) => { - Self::SamsungPay(Box::new(SamsungPayWalletData { - token: samsung_pay_data.token, - })) + Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data))) } api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {}, api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {}, @@ -736,6 +754,24 @@ impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData { } } +impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData { + fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self { + Self { + payment_credential: SamsungPayWalletCredentials { + method: value.payment_credential.method, + recurring_payment: value.payment_credential.recurring_payment, + card_brand: value.payment_credential.card_brand, + card_last_four_digits: value.payment_credential.card_last_four_digits, + token_data: SamsungPayTokenData { + three_ds_type: value.payment_credential.token_data.three_ds_type, + version: value.payment_credential.token_data.version, + data: value.payment_credential.token_data.data, + }, + }, + } + } +} + impl From<api_models::payments::PayLaterData> for PayLaterData { fn from(value: api_models::payments::PayLaterData) -> Self { match value { diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs index e36707af6b0..f9c407ff587 100644 --- a/crates/hyperswitch_interfaces/src/errors.rs +++ b/crates/hyperswitch_interfaces/src/errors.rs @@ -41,6 +41,8 @@ pub enum ConnectorError { FailedToObtainCertificate, #[error("Connector meta data not found")] NoConnectorMetaData, + #[error("Connector wallet details not found")] + NoConnectorWalletDetails, #[error("Failed to obtain certificate key")] FailedToObtainCertificateKey, #[error("This step has not been implemented for: {0}")] diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs index b98b854fba8..858c013f41d 100644 --- a/crates/kgraph_utils/benches/evaluation.rs +++ b/crates/kgraph_utils/benches/evaluation.rs @@ -71,6 +71,7 @@ fn build_test_data( pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, additional_merchant_data: None, + connector_wallets_details: None, }; #[cfg(feature = "v1")] @@ -95,6 +96,7 @@ fn build_test_data( pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, additional_merchant_data: None, + connector_wallets_details: None, }; let config = CountryCurrencyFilter { connector_configs: HashMap::new(), diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs index 7d04f5d4238..2ec0cbe8031 100644 --- a/crates/kgraph_utils/src/mca.rs +++ b/crates/kgraph_utils/src/mca.rs @@ -759,6 +759,7 @@ mod tests { pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, additional_merchant_data: None, + connector_wallets_details: None, }; #[cfg(feature = "v1")] let stripe_account = MerchantConnectorResponse { @@ -818,6 +819,7 @@ mod tests { pm_auth_config: None, status: api_enums::ConnectorStatus::Inactive, additional_merchant_data: None, + connector_wallets_details: None, }; let config_map = kgraph_types::CountryCurrencyFilter { diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index b626b7d4418..3d56a42222f 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -271,6 +271,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::UIWidgetFormLayout, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, + api_models::admin::ConnectorWalletDetails, api_models::admin::MerchantRecipientData, api_models::admin::MerchantAccountData, api_models::admin::MerchantConnectorUpdate, @@ -408,6 +409,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GpayTokenizationData, api_models::payments::GooglePayPaymentMethodInfo, api_models::payments::ApplePayWalletData, + api_models::payments::SamsungPayWalletCredentials, + api_models::payments::SamsungPayTokenData, api_models::payments::ApplepayPaymentMethod, api_models::payments::PaymentsCancelRequest, api_models::payments::PaymentListConstraints, @@ -429,6 +432,11 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayRedirectData, api_models::payments::GooglePayThirdPartySdk, api_models::payments::GooglePaySessionResponse, + api_models::payments::SamsungPaySessionTokenResponse, + api_models::payments::SamsungPayMerchantPaymentInformation, + api_models::payments::SamsungPayAmountDetails, + api_models::payments::SamsungPayAmountFormat, + api_models::payments::SamsungPayProtocolType, api_models::payments::GpayShippingAddressParameters, api_models::payments::GpayBillingAddressParameters, api_models::payments::GpayBillingAddressFormat, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index f12d6a7b567..0dbf5f9cdcf 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -197,6 +197,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::UIWidgetFormLayout, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, + api_models::admin::ConnectorWalletDetails, api_models::admin::MerchantRecipientData, api_models::admin::MerchantAccountData, api_models::admin::MerchantConnectorUpdate, @@ -335,6 +336,13 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::GooglePayPaymentMethodInfo, api_models::payments::ApplePayWalletData, api_models::payments::ApplepayPaymentMethod, + api_models::payments::SamsungPaySessionTokenResponse, + api_models::payments::SamsungPayMerchantPaymentInformation, + api_models::payments::SamsungPayAmountDetails, + api_models::payments::SamsungPayAmountFormat, + api_models::payments::SamsungPayProtocolType, + api_models::payments::SamsungPayWalletCredentials, + api_models::payments::SamsungPayTokenData, api_models::payments::PaymentsCancelRequest, api_models::payments::PaymentListConstraints, api_models::payments::PaymentListResponse, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index e915d05c358..1d49a99106e 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2083,7 +2083,7 @@ impl<'a> TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> domain::WalletData::SamsungPay(samsung_data) => { let data = SamsungPayPmData { payment_type: PaymentType::Samsungpay, - samsung_pay_token: samsung_data.token.to_owned(), + samsung_pay_token: samsung_data.payment_credential.token_data.data.to_owned(), }; Ok(AdyenPaymentMethod::SamsungPay(Box::new(data))) } diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index fc35cab773a..e83e5c33052 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -436,12 +436,27 @@ pub struct FluidData { pub const FLUID_DATA_DESCRIPTOR: &str = "RklEPUNPTU1PTi5BUFBMRS5JTkFQUC5QQVlNRU5U"; +pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT"; + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayPaymentInformation { fluid_data: FluidData, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SamsungPayTokenizedCard { + transaction_type: TransactionType, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SamsungPayPaymentInformation { + fluid_data: FluidData, + tokenized_card: SamsungPayTokenizedCard, +} + #[derive(Debug, Serialize)] #[serde(untagged)] pub enum PaymentInformation { @@ -450,6 +465,7 @@ pub enum PaymentInformation { ApplePay(Box<ApplePayPaymentInformation>), ApplePayToken(Box<ApplePayTokenPaymentInformation>), MandatePayment(Box<MandatePaymentInformation>), + SamsungPay(Box<SamsungPayPaymentInformation>), NetworkToken(Box<NetworkTokenPaymentInformation>), } @@ -504,12 +520,15 @@ pub struct AdditionalAmount { pub enum PaymentSolution { ApplePay, GooglePay, + SamsungPay, } #[derive(Debug, Serialize)] pub enum TransactionType { #[serde(rename = "1")] ApplePay, + #[serde(rename = "1")] + SamsungPay, } impl From<PaymentSolution> for String { @@ -517,6 +536,7 @@ impl From<PaymentSolution> for String { let payment_solution = match solution { PaymentSolution::ApplePay => "001", PaymentSolution::GooglePay => "012", + PaymentSolution::SamsungPay => "008", }; payment_solution.to_string() } @@ -575,7 +595,7 @@ impl let mut commerce_indicator = solution .as_ref() .map(|pm_solution| match pm_solution { - PaymentSolution::ApplePay => network + PaymentSolution::ApplePay | PaymentSolution::SamsungPay => network .as_ref() .map(|card_network| match card_network.to_lowercase().as_str() { "amex" => "aesk", @@ -1491,6 +1511,66 @@ impl } } +impl + TryFrom<( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + Box<domain::SamsungPayWalletData>, + )> for CybersourcePaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, samsung_pay_data): ( + &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, + Box<domain::SamsungPayWalletData>, + ), + ) -> 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 payment_information = + PaymentInformation::SamsungPay(Box::new(SamsungPayPaymentInformation { + fluid_data: FluidData { + value: Secret::from( + consts::BASE64_ENGINE + .encode(samsung_pay_data.payment_credential.token_data.data.peek()), + ), + descriptor: Some( + consts::BASE64_ENGINE.encode(FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY), + ), + }, + tokenized_card: SamsungPayTokenizedCard { + transaction_type: TransactionType::SamsungPay, + }, + })); + + let processing_information = ProcessingInformation::try_from(( + item, + Some(PaymentSolution::SamsungPay), + Some(samsung_pay_data.payment_credential.card_brand), + ))?; + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(Vec::<MerchantDefinedInformation>::foreign_from); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information: None, + merchant_defined_information, + }) + } +} + impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> for CybersourcePaymentsRequest { @@ -1588,6 +1668,9 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> domain::WalletData::GooglePay(google_pay_data) => { Self::try_from((item, google_pay_data)) } + domain::WalletData::SamsungPay(samsung_pay_data) => { + Self::try_from((item, samsung_pay_data)) + } domain::WalletData::AliPayQr(_) | domain::WalletData::AliPayRedirect(_) | domain::WalletData::AliPayHkRedirect(_) @@ -1604,7 +1687,6 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> | domain::WalletData::MobilePayRedirect(_) | domain::WalletData::PaypalRedirect(_) | domain::WalletData::PaypalSdk(_) - | domain::WalletData::SamsungPay(_) | domain::WalletData::TwintRedirect {} | domain::WalletData::VippsRedirect {} | domain::WalletData::TouchNGoRedirect(_) diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 95b02f0cdb3..19b44a2bf8e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2125,10 +2125,14 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect } else { None }, - connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details( - state, &key_store, &metadata, - ) - .await?, + connector_wallets_details: + helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates( + state, + &key_store, + &metadata, + &self.connector_wallets_details, + ) + .await?, }) } } @@ -2302,10 +2306,14 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect } else { None }, - connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details( - state, &key_store, &metadata, - ) - .await?, + connector_wallets_details: + helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates( + state, + &key_store, + &metadata, + &self.connector_wallets_details, + ) + .await?, }) } } @@ -2436,7 +2444,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, - connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(state, &key_store, &self.metadata).await?, + connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?, additional_merchant_data: if let Some(mcd) = merchant_recipient_data { Some(domain_types::crypto_operation( key_manager_state, @@ -2601,7 +2609,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate { applepay_verified_domains: None, pm_auth_config: self.pm_auth_config.clone(), status: connector_status, - connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(state, &key_store, &self.metadata).await?, + connector_wallets_details: helpers::get_encrypted_connector_wallets_details_with_apple_pay_certificates(state, &key_store, &self.metadata, &self.connector_wallets_details).await?, test_mode: self.test_mode, business_country: self.business_country, business_label: self.business_label.clone(), diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index 0dca02bf79d..88e1eb80618 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -162,6 +162,7 @@ pub async fn update_mca( pm_auth_config: None, test_mode: None, additional_merchant_data: None, + connector_wallets_details: None, }; #[cfg(feature = "v2")] let request = MerchantConnectorUpdate { @@ -177,6 +178,7 @@ pub async fn update_mca( pm_auth_config: None, merchant_id: merchant_id.clone(), additional_merchant_data: None, + connector_wallets_details: None, }; let mca_response = admin::update_connector(state.clone(), &merchant_id, None, &connector_id, request).await?; diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index d2812447ed8..847aef2ba3b 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -185,6 +185,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::FailedToObtainAuthType | errors::ConnectorError::FailedToObtainCertificate | errors::ConnectorError::NoConnectorMetaData + | errors::ConnectorError::NoConnectorWalletDetails | errors::ConnectorError::FailedToObtainCertificateKey | errors::ConnectorError::FlowNotSupported { .. } | errors::ConnectorError::CaptureMethodNotSupported @@ -284,7 +285,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> errors::ConnectorError::InvalidWallet | errors::ConnectorError::ResponseHandlingFailed | errors::ConnectorError::FailedToObtainCertificate | - errors::ConnectorError::NoConnectorMetaData | + errors::ConnectorError::NoConnectorMetaData | errors::ConnectorError::NoConnectorWalletDetails | errors::ConnectorError::FailedToObtainCertificateKey | errors::ConnectorError::CaptureMethodNotSupported | errors::ConnectorError::MissingConnectorMandateID | @@ -370,6 +371,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::FailedToObtainAuthType | errors::ConnectorError::FailedToObtainCertificate | errors::ConnectorError::NoConnectorMetaData + | errors::ConnectorError::NoConnectorWalletDetails | errors::ConnectorError::FailedToObtainCertificateKey | errors::ConnectorError::NotImplemented(_) | errors::ConnectorError::NotSupported { .. } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 54d8dc230c7..6159776a551 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -496,6 +496,62 @@ async fn create_applepay_session_token( } } +fn create_samsung_pay_session_token( + router_data: &types::PaymentsSessionRouterData, + header_payload: api_models::payments::HeaderPayload, +) -> RouterResult<types::PaymentsSessionRouterData> { + let samsung_pay_wallet_details = router_data + .connector_wallets_details + .clone() + .parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData") + .change_context(errors::ConnectorError::NoConnectorWalletDetails) + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_wallets_details".to_string(), + expected_format: "samsung_pay_metadata_format".to_string(), + })?; + + let required_amount_type = StringMajorUnitForConnector; + let samsung_pay_amount = required_amount_type + .convert( + router_data.request.minor_amount, + router_data.request.currency, + ) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert amount to string major unit for Samsung Pay".to_string(), + })?; + + let merchant_domain = header_payload + .x_merchant_domain + .get_required_value("samsung pay domain") + .attach_printable("Failed to get domain for samsung pay session call")?; + + Ok(types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::SamsungPay(Box::new( + payment_types::SamsungPaySessionTokenResponse { + version: "2".to_string(), + service_id: samsung_pay_wallet_details.data.service_id, + order_number: router_data.payment_id.clone(), + merchant_payment_information: + payment_types::SamsungPayMerchantPaymentInformation { + name: samsung_pay_wallet_details.data.merchant_display_name, + url: merchant_domain, + country_code: samsung_pay_wallet_details.data.merchant_business_country, + }, + amount: payment_types::SamsungPayAmountDetails { + amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly, + currency_code: router_data.request.currency, + total_amount: samsung_pay_amount, + }, + protocol: payment_types::SamsungPayProtocolType::Protocol3ds, + allowed_brands: samsung_pay_wallet_details.data.allowed_brands, + }, + )), + }), + ..router_data.clone() + }) +} + fn get_session_request_for_simplified_apple_pay( apple_pay_merchant_identifier: String, session_token_data: payment_types::SessionTokenForSimplifiedApplePay, @@ -881,6 +937,9 @@ impl RouterDataSession for types::PaymentsSessionRouterData { api::GetToken::GpayMetadata => { create_gpay_session_token(state, self, connector, business_profile) } + api::GetToken::SamsungPayMetadata => { + create_samsung_pay_session_token(self, header_payload) + } api::GetToken::ApplePayMetadata => { create_applepay_session_token( state, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 81d9130db85..7447323d9f0 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4467,30 +4467,34 @@ pub fn is_apple_pay_simplified_flow( )) } -pub async fn get_encrypted_apple_pay_connector_wallets_details( +// This function will return the encrypted connector wallets details with Apple Pay certificates +// Currently apple pay certifiactes are stored in the metadata which is not encrypted. +// In future we want those certificates to be encrypted and stored in the connector_wallets_details. +// As part of migration fallback this function checks apple pay details are present in connector_wallets_details +// If yes, it will encrypt connector_wallets_details and store it in the database. +// If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it. +pub async fn get_encrypted_connector_wallets_details_with_apple_pay_certificates( state: &SessionState, key_store: &domain::MerchantKeyStore, connector_metadata: &Option<masking::Secret<tera::Value>>, + connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>, ) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> { - let apple_pay_metadata = get_applepay_metadata(connector_metadata.clone()) - .map_err(|error| { - logger::error!( - "Apple pay metadata parsing failed in get_encrypted_apple_pay_connector_wallets_details {:?}", - error - ) - }) - .ok(); + let connector_wallet_details_with_apple_pay_metadata_optional = + get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional) + .await?; - let connector_apple_pay_details = apple_pay_metadata - .map(|metadata| { - serde_json::to_value(metadata) + let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional + .map(|details| { + serde_json::to_value(details) .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to serialize apple pay metadata as JSON") + .attach_printable("Failed to serialize Apple Pay metadata as JSON") }) .transpose()? .map(masking::Secret::new); + let key_manager_state: KeyManagerState = state.into(); - let encrypted_connector_apple_pay_details = connector_apple_pay_details + let encrypted_connector_wallets_details = connector_wallets_details + .clone() .async_lift(|wallets_details| async { types::crypto_operation( &key_manager_state, @@ -4505,7 +4509,86 @@ pub async fn get_encrypted_apple_pay_connector_wallets_details( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while encrypting connector wallets details")?; - Ok(encrypted_connector_apple_pay_details) + + Ok(encrypted_connector_wallets_details) +} + +async fn get_apple_pay_metadata_if_needed( + connector_metadata: &Option<masking::Secret<tera::Value>>, + connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>, +) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> { + if let Some(connector_wallets_details) = connector_wallets_details_optional { + if connector_wallets_details.apple_pay_combined.is_some() + || connector_wallets_details.apple_pay.is_some() + { + return Ok(Some(connector_wallets_details.clone())); + } + // Otherwise, merge Apple Pay metadata + return get_and_merge_apple_pay_metadata( + connector_metadata.clone(), + Some(connector_wallets_details.clone()), + ) + .await; + } + + // If connector_wallets_details_optional is None, attempt to get Apple Pay metadata + get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await +} + +async fn get_and_merge_apple_pay_metadata( + connector_metadata: Option<masking::Secret<tera::Value>>, + connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>, +) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> { + let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata) + .map_err(|error| { + logger::error!( + "Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}", + error + ); + }) + .ok(); + + if let Some(apple_pay_metadata) = apple_pay_metadata_optional { + let updated_wallet_details = match apple_pay_metadata { + api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined( + apple_pay_combined_metadata, + ) => { + let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?; + + api_models::admin::ConnectorWalletDetails { + apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)), + apple_pay: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.apple_pay.clone()), + samsung_pay: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.samsung_pay.clone()), + } + } + api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => { + let metadata_json = serde_json::to_value(apple_pay_metadata) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to serialize Apple Pay metadata as JSON")?; + + api_models::admin::ConnectorWalletDetails { + apple_pay: Some(masking::Secret::new(metadata_json)), + apple_pay_combined: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.apple_pay_combined.clone()), + samsung_pay: connector_wallets_details_optional + .as_ref() + .and_then(|d| d.samsung_pay.clone()), + } + } + }; + + return Ok(Some(updated_wallet_details)); + } + + // Return connector_wallets_details if no Apple Pay metadata was found + Ok(connector_wallets_details_optional) } pub fn get_applepay_metadata( diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index f12cd71cdb0..1807369a029 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -490,6 +490,7 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken { match value { api_models::enums::PaymentMethodType::GooglePay => Self::GpayMetadata, api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata, + api_models::enums::PaymentMethodType::SamsungPay => Self::SamsungPayMetadata, api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata, _ => Self::Connector, } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 34dea537b2d..dd5e47b1005 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -190,6 +190,7 @@ pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>; #[derive(Clone, Eq, PartialEq, Debug)] pub enum GetToken { GpayMetadata, + SamsungPayMetadata, ApplePayMetadata, PaypalSdkMetadata, Connector, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index a6f6d7c4c5a..a503f24d94c 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1068,6 +1068,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount> }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), + connector_wallets_details: item + .connector_wallets_details + .map(|data| { + data.into_inner() + .expose() + .parse_value::<api_models::admin::ConnectorWalletDetails>( + "ConnectorWalletDetails", + ) + .attach_printable("Unable to deserialize connector_wallets_details") + .change_context(errors::ApiErrorResponse::InternalServerError) + }) + .transpose()?, }; #[cfg(feature = "v2")] let response = Self { @@ -1096,6 +1108,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount> }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), + connector_wallets_details: item + .connector_wallets_details + .map(|data| { + data.into_inner() + .expose() + .parse_value::<api_models::admin::ConnectorWalletDetails>( + "ConnectorWalletDetails", + ) + .attach_printable("Unable to deserialize connector_wallets_details") + .change_context(errors::ApiErrorResponse::InternalServerError) + }) + .transpose()?, }; Ok(response) } @@ -1191,6 +1215,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount> }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), + connector_wallets_details: item + .connector_wallets_details + .map(|data| { + data.into_inner() + .expose() + .parse_value::<api_models::admin::ConnectorWalletDetails>( + "ConnectorWalletDetails", + ) + .attach_printable("Unable to deserialize connector_wallets_details") + .change_context(errors::ApiErrorResponse::InternalServerError) + }) + .transpose()?, }; #[cfg(feature = "v1")] let response = Self { @@ -1235,6 +1271,18 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount> }) .transpose()? .map(api_models::admin::AdditionalMerchantData::foreign_from), + connector_wallets_details: item + .connector_wallets_details + .map(|data| { + data.into_inner() + .expose() + .parse_value::<api_models::admin::ConnectorWalletDetails>( + "ConnectorWalletDetails", + ) + .attach_printable("Unable to deserialize connector_wallets_details") + .change_context(errors::ApiErrorResponse::InternalServerError) + }) + .transpose()?, }; Ok(response) }
2024-09-19T08:10:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This pr is to support for Samsung pay as a payment method. This pr also adds a new field in merchant connector account create `connector_wallet_details` which is required to collect the required credentials for Samsung Pay. As this column in the data base stores the data in the encrypted format we also want to migrate apple pay certificates from metadata to `connector_wallet_details`, for which we are inserting apple pay details passed in the metadata to connector_wallet_details. Once the frontend changes are done to pass the apple pay credentials in the connector_wallet_details this fallback can be removed. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test Samsung Pay flow -> Enable Samsung Pay payment method for the connector ``` { "connector_type": "payment_processor", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_secret": "api_secret", "key1": "key1", "api_key": "api_key" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "invoke_sdk_client", "payment_method_type": "klarna" } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "payment_experience": "redirect_to_url", "payment_method_type": "klarna" } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "Discover", "DinersClub" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard" ], "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "ach", "recurring_enabled": true, "installment_payment_enabled": true, "minimum_amount": 0, "maximum_amount": 10000 } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "samsung_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "paypal", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "connector_wallets_details": { "samsung_pay": { "service_id": "49400558c67f4a97b3925f", "merchant_display_name": "Hyperswitch", "merchant_business_country": "IN", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } }, "connector_webhook_details": { "merchant_secret": "merchant_secret" } } ``` -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \ --data '{ "amount": 100000, "currency": "INR", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1726743607" }' ``` ``` { "payment_id": "pay_on1wv5l8OM8A3VuDe2GN", "merchant_id": "merchant_1726725490", "status": "requires_payment_method", "amount": 100000, "net_amount": 100000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi", "created": "2024-09-19T11:00:15.562Z", "currency": "INR", "customer_id": "cu_1726743615", "customer": { "id": "cu_1726743615", "name": null, "email": null, "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": null, "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1726743615", "created_at": 1726743615, "expires": 1726747215, "secret": "epk_3d5ad79c88554ee7bf0748ae18ecd05b" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_XdGC3A6KTKR5n2WDLON5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-19T11:15:15.562Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-19T11:00:15.680Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` -> Session call ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'x-browser-name: Safari' \ --header 'x-merchant-domain: sdk-test-app.netlify.app' \ --header 'api-key: pk_dev_c23e25c5054241288a778316e463e309' \ --data '{ "payment_id": "pay_on1wv5l8OM8A3VuDe2GN", "wallets": [], "client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi" }' ``` ``` { "payment_id": "pay_on1wv5l8OM8A3VuDe2GN", "client_secret": "pay_on1wv5l8OM8A3VuDe2GN_secret_o5JrhSWuWKjcUgrvASpi", "session_token": [ { "wallet_name": "samsung_pay", "version": "2", "service_id": "49400558c67f4a97b3925f", "order_number": "pay_on1wv5l8OM8A3VuDe2GN", "merchant": { "name": "Hyperswitch", "url": "sdk-test-app.netlify.app", "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "INR", "total": "1000.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } ] } ``` -> Confirm call ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cjSDZPveYx7AbdI5cMRMuPKVdteJ7aIi3ULRasYhU89JtFRZWp9BeNn7PQDLQv8W' \ --data-raw '{ "amount": 1, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 1, "customer_id": "custhype123", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "payment_method": "wallet", "payment_method_type": "samsung_pay", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "payment_method_data": { "wallet": { "samsung_pay": { "payment_credential": { "card_brand": "visa", "recurring_payment": false, "card_last4digits": "1234", "method": "3DS", "3_d_s": { "type": "S", "version": "100", "data": "encrypted samsung pay data" } } } } } }' ``` ``` { "payment_id": "pay_0lHEl7IAq7cFn680x4HJ", "merchant_id": "merchant_1726725490", "status": "failed", "amount": 1, "net_amount": 1, "amount_capturable": 0, "amount_received": null, "connector": "cybersource", "client_secret": "pay_0lHEl7IAq7cFn680x4HJ_secret_3bsNpl8N5rArpWizVWik", "created": "2024-09-19T11:28:58.596Z", "currency": "USD", "customer_id": "custhype123", "customer": { "id": "custhype123", "name": "Joseph Doe", "email": "something@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "wallet", "payment_method_data": { "wallet": {}, "billing": null }, "payment_token": null, "shipping": null, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "something@gmail.com", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "next_action": null, "cancellation_reason": null, "error_code": "INVALID_DATA", "error_message": "Declined - One or more fields in the request contains invalid data, detailed_error_information: paymentInformation.fluidData.value : INVALID_DATA", "unified_code": "UE_000", "unified_message": "Something went wrong", "payment_experience": null, "payment_method_type": "samsung_pay", "connector_label": "cybersource_US_default_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "custhype123", "created_at": 1726745338, "expires": 1726748938, "secret": "epk_48f2e9de3ad641578f3df9e9a46d9c80" }, "manual_retry_allowed": true, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_XdGC3A6KTKR5n2WDLON5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_TO5NdOnj3ohWTfxBKGsc", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-19T11:43:58.596Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-19T11:29:00.222Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` The status will be failed as Samsung does not have a test card and cybersource returns invalid data error for live cards ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
5942e059e9efa3fa71a13cacc896509515e2f976
juspay/hyperswitch
juspay__hyperswitch-5963
Bug: fix(dashboard_metadata): Fix prod intent emails Currently prod intent emails are not going to biz email. Email are working on custom integ, integ main pod and custom sandbox pod with some code changes. Need to check if sandbox main pod is also able to send emails.
diff --git a/config/config.example.toml b/config/config.example.toml index be0532622bb..a6af984b01f 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -375,10 +375,12 @@ wildcard_origin = false # If true, allows any origin to make req # EmailClient configuration. Only applicable when the `email` feature flag is enabled. [email] -sender_email = "example@example.com" # Sender email -aws_region = "" # AWS region used by AWS SES -allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email -active_email_client = "SES" # The currently active email client +sender_email = "example@example.com" # Sender email +aws_region = "" # AWS region used by AWS SES +allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email +active_email_client = "SES" # The currently active email client +recon_recipient_email = "recon@example.com" # Recipient email for recon request email +prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email # Configuration for aws ses, applicable when the active email client is SES [email.aws_ses] @@ -745,4 +747,4 @@ delete_token_url= "" # base url to delete token from token service check_token_status_url= "" # base url to check token status from token service [network_tokenization_supported_connectors] -connector_list = "cybersource" # Supported connectors for network tokenization \ No newline at end of file +connector_list = "cybersource" # Supported connectors for network tokenization diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 9bbf137d2ce..62350376271 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -60,6 +60,8 @@ sender_email = "example@example.com" # Sender email aws_region = "" # AWS region used by AWS SES allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email active_email_client = "SES" # The currently active email client +recon_recipient_email = "recon@example.com" # Recipient email for recon request email +prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email # Configuration for aws ses, applicable when the active email client is SES [email.aws_ses] @@ -300,9 +302,6 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p [user_auth_methods] encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table -[recipient_emails] -recon = "recon@example.com" - [network_tokenization_service] # Network Tokenization Service Configuration generate_token_url= "" # base url to generate token fetch_token_url= "" # base url to fetch token @@ -311,4 +310,4 @@ public_key= "" # public key to encrypt data for token service private_key= "" # private key to decrypt response payload from token service key_id= "" # key id to encrypt data for token service delete_token_url= "" # base url to delete token from token service -check_token_status_url= "" # base url to check token status from token service \ No newline at end of file +check_token_status_url= "" # base url to check token status from token service diff --git a/config/development.toml b/config/development.toml index f9f1ebc1202..43130cb78f2 100644 --- a/config/development.toml +++ b/config/development.toml @@ -301,6 +301,8 @@ sender_email = "example@example.com" aws_region = "" allowed_unverified_days = 1 active_email_client = "SES" +recon_recipient_email = "recon@example.com" +prod_intent_recipient_email = "business@example.com" [email.aws_ses] email_role_arn = "" @@ -732,11 +734,8 @@ encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC69 [locker_based_open_banking_connectors] connector_list = "" -[recipient_emails] -recon = "recon@example.com" - [network_tokenization_supported_card_networks] card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] -connector_list = "cybersource" \ No newline at end of file +connector_list = "cybersource" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 698800f082d..379f491a4f6 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -591,9 +591,6 @@ ach = { country = "US", currency = "USD" } [locker_based_open_banking_connectors] connector_list = "" -[recipient_emails] -recon = "recon@example.com" - [network_tokenization_supported_card_networks] card_networks = "Visa, AmericanExpress, Mastercard" @@ -609,3 +606,17 @@ check_token_status_url= "" [network_tokenization_supported_connectors] connector_list = "cybersource" + +# EmailClient configuration. Only applicable when the `email` feature flag is enabled. +[email] +sender_email = "example@example.com" # Sender email +aws_region = "" # AWS region used by AWS SES +allowed_unverified_days = 1 # Number of days the api calls ( with jwt token ) can be made without verifying the email +active_email_client = "SES" # The currently active email client +recon_recipient_email = "recon@example.com" # Recipient email for recon request email +prod_intent_recipient_email = "business@example.com" # Recipient email for prod intent email + +# Configuration for aws ses, applicable when the active email client is SES +[email.aws_ses] +email_role_arn = "" # The amazon resource name ( arn ) of the role which has permission to send emails +sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session. diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs index fc577a012c3..5751de95c12 100644 --- a/crates/external_services/src/email.rs +++ b/crates/external_services/src/email.rs @@ -137,6 +137,12 @@ pub struct EmailSettings { /// The active email client to use pub active_email_client: AvailableEmailClients, + + /// Recipient email for recon emails + pub recon_recipient_email: pii::Email, + + /// Recipient email for recon emails + pub prod_intent_recipient_email: pii::Email, } /// Errors that could occur from EmailClient. diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 604dce5047c..8c893b88319 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -498,7 +498,6 @@ pub(crate) async fn fetch_raw_secrets( decision: conf.decision, locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, grpc_client: conf.grpc_client, - recipient_emails: conf.recipient_emails, network_tokenization_supported_card_networks: conf .network_tokenization_supported_card_networks, network_tokenization_service, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 7d6dfd26eae..675b8c44e2a 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -6,7 +6,7 @@ use std::{ #[cfg(feature = "olap")] use analytics::{opensearch::OpenSearchConfig, ReportConfig}; use api_models::{enums, payment_methods::RequiredFieldInfo}; -use common_utils::{ext_traits::ConfigExt, pii::Email}; +use common_utils::ext_traits::ConfigExt; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] @@ -122,7 +122,6 @@ pub struct Settings<S: SecretState> { pub decision: Option<DecisionConfig>, pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList, pub grpc_client: GrpcClientSettings, - pub recipient_emails: RecipientMails, pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks, pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>, pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, @@ -941,11 +940,6 @@ pub struct ServerTls { pub certificate: PathBuf, } -#[derive(Debug, Deserialize, Clone, Default)] -pub struct RecipientMails { - pub recon: Email, -} - fn deserialize_hashmap_inner<K, V>( value: HashMap<String, String>, ) -> Result<HashMap<K, HashSet<V>>, String> diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 1a2b2ef60a4..6ac2b08e6bb 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -5,7 +5,6 @@ pub const MAX_NAME_LENGTH: usize = 70; /// The max length of company name and merchant should be same /// because we are deriving the merchant name from company name pub const MAX_COMPANY_NAME_LENGTH: usize = MAX_ALLOWED_MERCHANT_NAME_LENGTH; -pub const BUSINESS_EMAIL: &str = "neeraj.kumar@juspay.in"; pub const RECOVERY_CODES_COUNT: usize = 8; pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index fa9944ee8ee..55ec8cea7a9 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -34,7 +34,7 @@ pub async fn send_recon_request( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, recipient_email: domain::UserEmail::from_pii_email( - state.conf.recipient_emails.recon.clone(), + state.conf.email.recon_recipient_email.clone(), ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to convert recipient's email to UserEmail")?, diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 47639fed717..32ad135a7d6 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -484,7 +484,7 @@ async fn insert_metadata( state.conf.proxy.https_url.as_ref(), ) .await; - logger::info!(?send_email_result); + logger::info!(prod_intent_email=?send_email_result); } } diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 35bc9f06d9a..1c4ce79ac8c 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -413,9 +413,9 @@ pub struct BizEmailProd { impl BizEmailProd { pub fn new(state: &SessionState, data: ProdIntent) -> UserResult<Self> { Ok(Self { - recipient_email: (domain::UserEmail::new( - consts::user::BUSINESS_EMAIL.to_string().into(), - ))?, + recipient_email: domain::UserEmail::from_pii_email( + state.conf.email.prod_intent_recipient_email.clone(), + )?, settings: state.conf.clone(), subject: "New Prod Intent", user_name: data.poc_name.unwrap_or_default().into(), diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index 5814f64f759..3abdfdd3abe 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -1,4 +1,4 @@ -use std::{net::IpAddr, str::FromStr}; +use std::{net::IpAddr, ops::Not, str::FromStr}; use actix_web::http::header::HeaderMap; use api_models::user::dashboard_metadata::{ @@ -11,6 +11,7 @@ use diesel_models::{ }; use error_stack::{report, ResultExt}; use masking::Secret; +use router_env::logger; use crate::{ core::errors::{UserErrors, UserResult}, @@ -284,8 +285,16 @@ fn not_contains_string(value: &Option<String>, value_to_be_checked: &str) -> boo } pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool { - not_contains_string(&data.poc_email, "juspay") - && not_contains_string(&data.business_website, "juspay") - && not_contains_string(&data.business_website, "hyperswitch") - && not_contains_string(&Some(user_email), "juspay") + let poc_email_check = not_contains_string(&data.poc_email, "juspay"); + let business_website_check = not_contains_string(&data.business_website, "juspay") + && not_contains_string(&data.business_website, "hyperswitch"); + let user_email_check = not_contains_string(&Some(user_email), "juspay"); + + if (poc_email_check && business_website_check && user_email_check).not() { + logger::info!(prod_intent_email = poc_email_check); + logger::info!(prod_intent_email = business_website_check); + logger::info!(prod_intent_email = user_email_check); + } + + poc_email_check && business_website_check && user_email_check } diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index ed15e8893bd..82a21f9fc9c 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -368,5 +368,15 @@ global_tenant = { schema = "public", redis_key_prefix = "" } [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} -[recipient_emails] -recon = "recon@example.com" +[email] +sender_email = "example@example.com" +aws_region = "" +allowed_unverified_days = 1 +active_email_client = "SES" +recon_recipient_email = "recon@example.com" +prod_intent_recipient_email = "business@example.com" + +[email.aws_ses] +email_role_arn = "" +sts_role_session_name = "" +
2024-09-19T12:17:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - This PR add recipient emails for recon and prod_intent under email config. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> `config/config.example.toml` `config/deployments/env_specific.toml` `config/development.toml` `config/docker_compose.toml` `loadtest/config/development.toml` ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5963. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/user/data' \ --header 'Content-Type: application/json' \ --header 'Authorization: ••••••' \ --data ' { "ProdIntent": { "is_completed": true, "legal_business_name": "test", "business_label": "test", "business_location": "US", "display_name": "test", "poc_email": "test", "business_type": "test", "business_identifier": "test", "business_website": "test", "poc_name": "test", "poc_contact": "test", "comments": "test" } } ' ``` The above API should send prod intent email to configured prod intent email. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
82574c0e8e7eb69e9f21eedc765145c724960cd5
juspay/hyperswitch
juspay__hyperswitch-5956
Bug: [BUG] using FRM with Signifyd throws 5xx ### Bug Description Enabling Signifyd FRM connector for payments, and using this for a payment throws 5xx. This is due to Signifyd sending 303 which is not handled in HyperSwitch. Signifyd throws 303 as the URL is malformed. https://api.signifyd.com//v3/orders/events/sales as opposed to https://api.signifyd.com/v3/orders/events/sales ### Expected Behavior Calling any Signifyd API should return an expected status code. ### Actual Behavior Calling any Signifyd API returns 303 - which is not handled in the response handler of `execute_connector_processing_step` leading to 500 - Something went wrong. ### Steps To Reproduce 1. Enable FRM via Signifyd for a payment connector 2. Create a payment 3. 5xx is thrown in API response ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs index 6ba2dce9861..4ee36d8966b 100644 --- a/crates/router/src/connector/signifyd.rs +++ b/crates/router/src/connector/signifyd.rs @@ -237,7 +237,7 @@ impl Ok(format!( "{}{}", self.base_url(connectors), - "/v3/orders/events/sales" + "v3/orders/events/sales" )) } @@ -325,7 +325,7 @@ impl Ok(format!( "{}{}", self.base_url(connectors), - "/v3/orders/events/checkouts" + "v3/orders/events/checkouts" )) } @@ -413,7 +413,7 @@ impl Ok(format!( "{}{}", self.base_url(connectors), - "/v3/orders/events/transactions" + "v3/orders/events/transactions" )) } @@ -503,7 +503,7 @@ impl Ok(format!( "{}{}", self.base_url(connectors), - "/v3/orders/events/fulfillments" + "v3/orders/events/fulfillments" )) } @@ -593,7 +593,7 @@ impl Ok(format!( "{}{}", self.base_url(connectors), - "/v3/orders/events/returns/records" + "v3/orders/events/returns/records" )) }
2024-09-19T09:26:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Described in #5956 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Fixes 5xx thrown by payments API when FRM flows are consumed. ## How did you test it? Locally - using an increased stack size. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
7076ae9244e26c08c61fdca328237963b3797a5a
juspay/hyperswitch
juspay__hyperswitch-5961
Bug: [REFACTOR]: [PAYU] Add amount conversion framework to Payu ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.payu.in/reference/refund_transaction_api) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/hyperswitch_connectors/src/connectors/payu.rs b/crates/hyperswitch_connectors/src/connectors/payu.rs index 05f983b8fbb..ad2479f19e4 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu.rs @@ -6,6 +6,7 @@ use common_utils::{ errors::CustomResult, ext_traits::ByteSliceExt, request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -43,11 +44,22 @@ use transformers as payu; use crate::{ constants::headers, types::{RefreshTokenRouterData, ResponseRouterData}, + utils, utils::construct_not_supported_error_report, }; -#[derive(Debug, Clone)] -pub struct Payu; +#[derive(Clone)] +pub struct Payu { + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), +} + +impl Payu { + pub fn new() -> &'static Self { + &Self { + amount_converter: &MinorUnitForConnector, + } + } +} impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payu where @@ -538,7 +550,15 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = payu::PayuPaymentsRequest::try_from(req)?; + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount, + req.request.currency, + )?; + + let connector_router_data = payu::PayuRouterData::try_from((amount, req))?; + + let connector_req = payu::PayuPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -625,7 +645,14 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payu { req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_req = payu::PayuRefundRequest::try_from(req)?; + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_refund_amount, + req.request.currency, + )?; + + let connector_router_data = payu::PayuRouterData::try_from((amount, req))?; + let connector_req = payu::PayuRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs index 4ebc09a0023..9bdb52de4f0 100644 --- a/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/payu/transformers.rs @@ -3,6 +3,7 @@ use common_enums::enums; use common_utils::{ consts::BASE64_ENGINE, pii::{Email, IpAddress}, + types::MinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ @@ -24,12 +25,28 @@ use crate::{ const WALLET_IDENTIFIER: &str = "PBL"; -#[derive(Debug, Serialize, Eq, PartialEq)] +#[derive(Debug, Serialize)] +pub struct PayuRouterData<T> { + pub amount: MinorUnit, + pub router_data: T, +} + +impl<T> TryFrom<(MinorUnit, T)> for PayuRouterData<T> { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> { + Ok(Self { + amount, + router_data: item, + }) + } +} + +#[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct PayuPaymentsRequest { customer_ip: Secret<String, IpAddress>, merchant_pos_id: Secret<String>, - total_amount: i64, + total_amount: MinorUnit, currency_code: enums::Currency, description: String, pay_methods: PayuPaymentMethod, @@ -77,11 +94,13 @@ pub enum PayuWalletCode { Jp, } -impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { +impl TryFrom<&PayuRouterData<&types::PaymentsAuthorizeRouterData>> for PayuPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { - let auth_type = PayuAuthType::try_from(&item.connector_auth_type)?; - let payment_method = match item.request.payment_method_data.clone() { + fn try_from( + item: &PayuRouterData<&types::PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let auth_type = PayuAuthType::try_from(&item.router_data.connector_auth_type)?; + let payment_method = match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Card(ccard) => Ok(PayuPaymentMethod { pay_method: PayuPaymentMethodData::Card(PayuCard::Card { number: ccard.card_number, @@ -119,7 +138,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { "Unknown payment method".to_string(), )), }?; - let browser_info = item.request.browser_info.clone().ok_or( + let browser_info = item.router_data.request.browser_info.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "browser_info", }, @@ -134,10 +153,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest { .to_string(), ), merchant_pos_id: auth_type.merchant_pos_id, - ext_order_id: Some(item.connector_request_reference_id.clone()), - total_amount: item.request.amount, - currency_code: item.request.currency, - description: item.description.clone().ok_or( + ext_order_id: Some(item.router_data.connector_request_reference_id.clone()), + total_amount: item.amount.to_owned(), + currency_code: item.router_data.request.currency, + description: item.router_data.description.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "item.description", }, @@ -488,10 +507,10 @@ impl<F, T> TryFrom<ResponseRouterData<F, PayuPaymentsSyncResponse, T, PaymentsRe } } -#[derive(Default, Debug, Eq, PartialEq, Serialize)] +#[derive(Default, Debug, Serialize)] pub struct PayuRefundRequestData { description: String, - amount: Option<i64>, + amount: Option<MinorUnit>, } #[derive(Default, Debug, Serialize)] @@ -499,12 +518,12 @@ pub struct PayuRefundRequest { refund: PayuRefundRequestData, } -impl<F> TryFrom<&types::RefundsRouterData<F>> for PayuRefundRequest { +impl<F> TryFrom<&PayuRouterData<&types::RefundsRouterData<F>>> for PayuRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + fn try_from(item: &PayuRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { refund: PayuRefundRequestData { - description: item.request.reason.clone().ok_or( + description: item.router_data.request.reason.clone().ok_or( errors::ConnectorError::MissingRequiredField { field_name: "item.request.reason", }, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index b85ae5bfab2..a3046213272 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -458,7 +458,7 @@ impl ConnectorData { enums::Connector::Payone => { Ok(ConnectorEnum::Old(Box::new(connector::Payone::new()))) } - enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(&connector::Payu))), + enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))), enums::Connector::Placetopay => { Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new()))) } diff --git a/crates/router/tests/connectors/payu.rs b/crates/router/tests/connectors/payu.rs index b0e5e9ec6a1..9bb3785bbd6 100644 --- a/crates/router/tests/connectors/payu.rs +++ b/crates/router/tests/connectors/payu.rs @@ -11,7 +11,7 @@ impl Connector for Payu { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Payu; utils::construct_connector_data_old( - Box::new(&Payu), + Box::new(Payu::new()), types::Connector::Payu, types::api::GetToken::Connector, None,
2024-10-02T14:12:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds amount conversion framework to payu, for sending to connector. fixes #5961 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
a3ea62f88524a360b666cacfbc1cf239f6be8797
juspay/hyperswitch
juspay__hyperswitch-5952
Bug: [CHORE]: update docker compose toml ### Feature Description remove the network_tokenization_service config ### Possible Implementation remove the network_tokenization_service config ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 698800f082d..f0d44db4d5e 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -597,15 +597,5 @@ recon = "recon@example.com" [network_tokenization_supported_card_networks] card_networks = "Visa, AmericanExpress, Mastercard" -[network_tokenization_service] -generate_token_url= "" -fetch_token_url= "" -token_service_api_key= "" -public_key= "" -private_key= "" -key_id= "" -delete_token_url= "" -check_token_status_url= "" - [network_tokenization_supported_connectors] connector_list = "cybersource"
2024-09-19T06:58:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> remove the network_tokenization_service from the config ![image](https://github.com/user-attachments/assets/fc2f85f5-656c-4d80-b756-fa3b84f2d20b) ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Test is not required ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
769111c20b0f745a5e4fc3ed6c9a705f277c3d5b
juspay/hyperswitch
juspay__hyperswitch-5958
Bug: fix: add time_range constraint to retrieve payment attempt list Currently, to retrieve the total count for payments, we use a query that gets the total count of attempts based on the last active attempt ID. To enhance performance, we need to add a time_range to the query. This will ensure that the query is executed only for the given time constraint, improving efficiency by narrowing the search to a specific time period.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 5465d902388..3690bcf24db 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -18569,6 +18569,7 @@ }, "TimeRange": { "type": "object", + "description": "A type representing a range of time for filtering, including a mandatory start time and an optional end time.", "required": [ "start_time" ], diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs index 401c606ccf9..dd1aa3c1bbd 100644 --- a/crates/analytics/src/disputes/metrics.rs +++ b/crates/analytics/src/disputes/metrics.rs @@ -4,15 +4,11 @@ mod total_dispute_lost_amount; use std::collections::HashSet; -use api_models::{ - analytics::{ - disputes::{ - DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier, - }, - Granularity, - }, - payments::TimeRange, +use api_models::analytics::{ + disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier}, + Granularity, }; +use common_utils::types::TimeRange; use diesel_models::enums as storage_enums; use time::PrimitiveDateTime; diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 7486ab50a51..e0235c67bed 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -1,10 +1,12 @@ use api_models::{ analytics::search::SearchIndex, errors::types::{ApiError, ApiErrorResponse}, - payments::TimeRange, }; use aws_config::{self, meta::region::RegionProviderChain, Region}; -use common_utils::errors::{CustomResult, ErrorSwitch}; +use common_utils::{ + errors::{CustomResult, ErrorSwitch}, + types::TimeRange, +}; use error_stack::ResultExt; use hyperswitch_domain_models::errors::{StorageError, StorageResult}; use opensearch::{ diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 7abef472068..0379ec09547 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -1,5 +1,6 @@ use std::collections::HashSet; +pub use common_utils::types::TimeRange; use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo}; use masking::Secret; @@ -14,8 +15,6 @@ use self::{ refunds::{RefundDimensions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, }; -pub use crate::payments::TimeRange; - pub mod active_payments; pub mod api_event; pub mod auth_events; diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs index b962f60cae0..24dd0effcbb 100644 --- a/crates/api_models/src/analytics/search.rs +++ b/crates/api_models/src/analytics/search.rs @@ -1,9 +1,7 @@ -use common_utils::hashing::HashedString; +use common_utils::{hashing::HashedString, types::TimeRange}; use masking::WithType; use serde_json::Value; -use crate::payments::TimeRange; - #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct SearchFilters { pub payment_method: Option<Vec<String>>, diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 13966c464d5..41e958cb3f4 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -39,8 +39,6 @@ use crate::{ verifications::*, }; -impl ApiEventMetric for TimeRange {} - impl ApiEventMetric for GetPaymentIntentFiltersRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Analytics) diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 715bf3c3544..b0866cfb265 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4204,7 +4204,7 @@ pub struct PaymentListFilterConstraints { pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] - pub time_range: Option<TimeRange>, + pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list @@ -4295,20 +4295,6 @@ pub enum SortBy { Desc, } -#[derive( - Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, -)] -pub struct TimeRange { - /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed - #[serde(with = "common_utils::custom_serde::iso8601")] - #[serde(alias = "startTime")] - pub start_time: PrimitiveDateTime, - /// The end time to filter payments list or to get list of filters. If not passed the default time is now - #[serde(default, with = "common_utils::custom_serde::iso8601::option")] - #[serde(alias = "endTime")] - pub end_time: Option<PrimitiveDateTime>, -} - #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 10771df4ccd..34e1bbe5449 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -704,7 +704,7 @@ pub struct PayoutListConstraints { /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] - pub time_range: Option<payments::TimeRange>, + pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] @@ -732,7 +732,7 @@ pub struct PayoutListFilterConstraints { /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] - pub time_range: Option<payments::TimeRange>, + pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index edc0e75bdf2..237a903d80c 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -1,12 +1,12 @@ use std::collections::HashMap; -use common_utils::pii; pub use common_utils::types::{ChargeRefunds, MinorUnit}; +use common_utils::{pii, types::TimeRange}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; -use super::payments::{AmountFilter, TimeRange}; +use super::payments::AmountFilter; use crate::{ admin::{self, MerchantConnectorInfo}, enums, diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 16d0fd9b30a..2b1571617e8 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -1,7 +1,7 @@ use common_enums::{PaymentMethod, PaymentMethodType}; use serde::Serialize; -use crate::id_type; +use crate::{id_type, types::TimeRange}; pub trait ApiEventMetric { fn get_api_event_type(&self) -> Option<ApiEventsType> { @@ -139,3 +139,5 @@ impl<T: ApiEventMetric> ApiEventMetric for &T { T::get_api_event_type(self) } } + +impl ApiEventMetric for TimeRange {} diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 6acf5000ced..2206744ef0b 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -28,6 +28,7 @@ use rust_decimal::{ }; use semver::Version; use serde::{de::Visitor, Deserialize, Deserializer, Serialize}; +use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{ @@ -582,6 +583,21 @@ impl StringMajorUnit { } } +/// A type representing a range of time for filtering, including a mandatory start time and an optional end time. +#[derive( + Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema, +)] +pub struct TimeRange { + /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed + #[serde(with = "crate::custom_serde::iso8601")] + #[serde(alias = "startTime")] + pub start_time: PrimitiveDateTime, + /// The end time to filter payments list or to get list of filters. If not passed the default time is now + #[serde(default, with = "crate::custom_serde::iso8601::option")] + #[serde(alias = "endTime")] + pub end_time: Option<PrimitiveDateTime>, +} + #[cfg(test)] mod amount_conversion_tests { #![allow(clippy::unwrap_used)] diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs index fa80b0990d1..48941330ec6 100644 --- a/crates/diesel_models/src/query/payment_attempt.rs +++ b/crates/diesel_models/src/query/payment_attempt.rs @@ -351,6 +351,7 @@ impl PaymentAttempt { payment_method: Option<Vec<enums::PaymentMethod>>, payment_method_type: Option<Vec<enums::PaymentMethodType>>, authentication_type: Option<Vec<enums::AuthenticationType>>, + time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, ) -> StorageResult<i64> { @@ -360,6 +361,14 @@ impl PaymentAttempt { .filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned())) .into_boxed(); + if let Some(time_range) = time_range { + filter = filter.filter(dsl::created_at.ge(time_range.start_time)); + + if let Some(end_time) = time_range.end_time { + filter = filter.filter(dsl::created_at.le(end_time)); + } + } + if let Some(connector) = connector { filter = filter.filter(dsl::connector.eq_any(connector)); } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 24a79e2905e..003509b2039 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -156,6 +156,7 @@ pub trait PaymentAttemptInterface { payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>, authentication_type: Option<Vec<storage_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, + time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<i64, errors::StorageError>; diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index f5b719fe370..619ebcce68a 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -94,7 +94,7 @@ pub trait PaymentIntentInterface { &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: storage_enums::MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>; @@ -108,7 +108,7 @@ pub trait PaymentIntentInterface { &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, - constraints: &api_models::payments::TimeRange, + constraints: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError>; #[cfg(all( @@ -1458,8 +1458,8 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo } } -impl From<api_models::payments::TimeRange> for PaymentIntentFetchConstraints { - fn from(value: api_models::payments::TimeRange) -> Self { +impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints { + fn from(value: common_utils::types::TimeRange) -> Self { Self::List(Box::new(PaymentIntentListParams { offset: 0, starting_at: Some(value.start_time), diff --git a/crates/hyperswitch_domain_models/src/payouts.rs b/crates/hyperswitch_domain_models/src/payouts.rs index 952028fab30..8c6d751ebec 100644 --- a/crates/hyperswitch_domain_models/src/payouts.rs +++ b/crates/hyperswitch_domain_models/src/payouts.rs @@ -52,8 +52,8 @@ impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints } } -impl From<api_models::payments::TimeRange> for PayoutFetchConstraints { - fn from(value: api_models::payments::TimeRange) -> Self { +impl From<common_utils::types::TimeRange> for PayoutFetchConstraints { + fn from(value: common_utils::types::TimeRange) -> Self { Self::List(Box::new(PayoutListParams { offset: 0, starting_at: Some(value.start_time), diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs index 42037c3c2d9..eb43089e448 100644 --- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs +++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs @@ -67,7 +67,7 @@ pub trait PayoutsInterface { async fn filter_payouts_by_time_range_constraints( &self, _merchant_id: &id_type::MerchantId, - _time_range: &api_models::payments::TimeRange, + _time_range: &common_utils::types::TimeRange, _storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, errors::StorageError>; diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs index 3b3a79407d0..4016754510a 100644 --- a/crates/hyperswitch_domain_models/src/refunds.rs +++ b/crates/hyperswitch_domain_models/src/refunds.rs @@ -6,7 +6,7 @@ pub struct RefundListConstraints { pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>, pub limit: Option<i64>, pub offset: Option<i64>, - pub time_range: Option<api_models::payments::TimeRange>, + pub time_range: Option<common_utils::types::TimeRange>, pub amount_filter: Option<api_models::payments::AmountFilter>, pub connector: Option<Vec<String>>, pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index b626b7d4418..d1746a63dde 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -194,6 +194,7 @@ Never share your secret api keys. Keep them guarded and secure. ), components(schemas( common_utils::types::MinorUnit, + common_utils::types::TimeRange, common_utils::link_utils::GenericLinkUiConfig, common_utils::link_utils::EnabledPaymentMethod, api_models::refunds::RefundRequest, @@ -466,7 +467,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, api_models::refunds::RefundAggregateResponse, - api_models::payments::TimeRange, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index f12d6a7b567..b7771dc5e0a 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -119,6 +119,7 @@ Never share your secret api keys. Keep them guarded and secure. ), components(schemas( common_utils::types::MinorUnit, + common_utils::types::TimeRange, common_utils::link_utils::GenericLinkUiConfig, common_utils::link_utils::EnabledPaymentMethod, api_models::refunds::RefundRequest, @@ -392,7 +393,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, api_models::refunds::RefundAggregateResponse, - api_models::payments::TimeRange, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse, diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs index ff5936fc296..30b73eb4c6a 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -516,7 +516,7 @@ pub async fn get_aggregates_for_disputes( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: api::TimeRange, + time_range: common_utils::types::TimeRange, ) -> RouterResponse<dispute_models::DisputesAggregateResponse> { let db = state.store.as_ref(); let dispute_status_with_count = db diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 30d619efedc..b8255cfcfe5 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3108,6 +3108,7 @@ pub async fn apply_filters_on_payments( constraints.payment_method_type, constraints.authentication_type, constraints.merchant_connector_id, + constraints.time_range, pi_fetch_constraints.get_profile_id_list(), merchant.storage_scheme, ) @@ -3128,7 +3129,7 @@ pub async fn get_filters_for_payments( state: SessionState, merchant: domain::MerchantAccount, merchant_key_store: domain::MerchantKeyStore, - time_range: api::TimeRange, + time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PaymentListFilters> { let db = state.store.as_ref(); let pi = db @@ -3249,7 +3250,7 @@ pub async fn get_aggregates_for_payments( state: SessionState, merchant: domain::MerchantAccount, profile_id_list: Option<Vec<id_type::ProfileId>>, - time_range: api::TimeRange, + time_range: common_utils::types::TimeRange, ) -> RouterResponse<api::PaymentsAggregateResponse> { let db = state.store.as_ref(); let intent_status_with_count = db diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index d0c0b2d3cde..c160acb50c2 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -996,7 +996,7 @@ pub async fn payouts_list_available_filters_core( state: SessionState, merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: api::TimeRange, + time_range: common_utils::types::TimeRange, _locale: &str, ) -> RouterResponse<api::PayoutListFilters> { let db = state.store.as_ref(); diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 0f7abf44b14..118f4b81766 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -904,7 +904,7 @@ pub async fn refund_list( pub async fn refund_filter_list( state: SessionState, merchant_account: domain::MerchantAccount, - req: api_models::payments::TimeRange, + req: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundListMetaData> { let db = state.store; let filter_list = db @@ -1098,7 +1098,7 @@ pub async fn get_filters_for_refunds( pub async fn get_aggregates_for_refunds( state: SessionState, merchant: domain::MerchantAccount, - time_range: api::TimeRange, + time_range: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundAggregateResponse> { let db = state.store.as_ref(); let refund_status_with_count = db diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index 1d45cfd405f..a44528fde43 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -52,7 +52,7 @@ pub trait DisputeInterface { &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>; } @@ -141,7 +141,7 @@ impl DisputeInterface for Store { &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::Dispute::get_dispute_status_with_count( @@ -390,7 +390,7 @@ impl DisputeInterface for MockDb { &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 394c48c1cd8..9b51946c5c4 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -634,7 +634,7 @@ impl DisputeInterface for KafkaStore { &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { self.diesel_store .get_dispute_status_with_count(merchant_id, profile_id_list, time_range) @@ -1605,6 +1605,7 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type: Option<Vec<common_enums::PaymentMethodType>>, authentication_type: Option<Vec<common_enums::AuthenticationType>>, merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, + time_range: Option<common_utils::types::TimeRange>, profile_id_list: Option<Vec<id_type::ProfileId>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::DataStorageError> { @@ -1617,6 +1618,7 @@ impl PaymentAttemptInterface for KafkaStore { payment_method_type, authentication_type, merchant_connector_id, + time_range, profile_id_list, storage_scheme, ) @@ -1750,7 +1752,7 @@ impl PaymentIntentInterface for KafkaStore { &self, state: &KeyManagerState, merchant_id: &id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, key_store: &domain::MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> { @@ -1770,7 +1772,7 @@ impl PaymentIntentInterface for KafkaStore { &self, merchant_id: &id_type::MerchantId, profile_id_list: Option<Vec<id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::DataStorageError> { self.diesel_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) @@ -2233,7 +2235,7 @@ impl PayoutsInterface for KafkaStore { async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> { self.diesel_store @@ -2532,7 +2534,7 @@ impl RefundInterface for KafkaStore { async fn filter_refund_by_meta_constraints( &self, merchant_id: &id_type::MerchantId, - refund_details: &api_models::payments::TimeRange, + refund_details: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { self.diesel_store @@ -2544,7 +2546,7 @@ impl RefundInterface for KafkaStore { async fn get_refund_status_with_count( &self, merchant_id: &id_type::MerchantId, - constraints: &api_models::payments::TimeRange, + constraints: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { self.diesel_store diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 808f82b00a4..dbe7534ee28 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -80,7 +80,7 @@ pub trait RefundInterface { async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, - refund_details: &api_models::payments::TimeRange, + refund_details: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>; @@ -88,7 +88,7 @@ pub trait RefundInterface { async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, - constraints: &api_models::payments::TimeRange, + constraints: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; @@ -817,7 +817,7 @@ mod storage { async fn filter_refund_by_meta_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, - refund_details: &api_models::payments::TimeRange, + refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -831,7 +831,7 @@ mod storage { async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, - constraints: &api_models::payments::TimeRange, + constraints: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; @@ -1135,7 +1135,7 @@ impl RefundInterface for MockDb { async fn filter_refund_by_meta_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, - refund_details: &api_models::payments::TimeRange, + refund_details: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> { let refunds = self.refunds.lock().await; @@ -1182,7 +1182,7 @@ impl RefundInterface for MockDb { async fn get_refund_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> { let refunds = self.refunds.lock().await; diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 5d8f7120f40..50a26ceae89 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -11,7 +11,7 @@ use super::app::AppState; use crate::{ core::disputes, services::{api, authentication as auth}, - types::api::{disputes as dispute_types, payments::TimeRange}, + types::api::disputes as dispute_types, }; /// Disputes - Retrieve Dispute @@ -413,7 +413,7 @@ pub async fn delete_dispute_evidence( pub async fn get_disputes_aggregate( state: web::Data<AppState>, req: HttpRequest, - query_param: web::Query<TimeRange>, + query_param: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::DisputesAggregate; let query_param = query_param.into_inner(); @@ -443,7 +443,7 @@ pub async fn get_disputes_aggregate( pub async fn get_disputes_aggregate_profile( state: web::Data<AppState>, req: HttpRequest, - query_param: web::Query<TimeRange>, + query_param: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::DisputesAggregate; let query_param = query_param.into_inner(); diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 82407976c6e..c8f4f5e4dd0 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -987,7 +987,7 @@ pub async fn profile_payments_list_by_filter( pub async fn get_filters_for_payments( state: web::Data<app::AppState>, req: actix_web::HttpRequest, - payload: web::Json<payment_types::TimeRange>, + payload: web::Json<common_utils::types::TimeRange>, ) -> impl Responder { let flow = Flow::PaymentsList; let payload = payload.into_inner(); @@ -1065,7 +1065,7 @@ pub async fn get_payment_filters_profile( pub async fn get_payments_aggregates( state: web::Data<app::AppState>, req: actix_web::HttpRequest, - payload: web::Query<payment_types::TimeRange>, + payload: web::Query<common_utils::types::TimeRange>, ) -> impl Responder { let flow = Flow::PaymentsAggregate; let payload = payload.into_inner(); @@ -1780,7 +1780,7 @@ impl GetLockingInput for payment_types::PaymentsManualUpdateRequest { pub async fn get_payments_aggregates_profile( state: web::Data<app::AppState>, req: actix_web::HttpRequest, - payload: web::Query<payment_types::TimeRange>, + payload: web::Query<common_utils::types::TimeRange>, ) -> impl Responder { let flow = Flow::PaymentsAggregate; let payload = payload.into_inner(); diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index 1b614330ebd..28b2afe2bee 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -8,8 +8,6 @@ use common_utils::consts; use router_env::{instrument, tracing, Flow}; use super::app::AppState; -#[cfg(feature = "olap")] -use crate::types::api::payments as payment_types; use crate::{ core::{api_locking, payouts::*}, headers::ACCEPT_LANGUAGE, @@ -375,7 +373,7 @@ pub async fn payouts_list_by_filter_profile( pub async fn payouts_list_available_filters_for_merchant( state: web::Data<AppState>, req: HttpRequest, - json_payload: web::Json<payment_types::TimeRange>, + json_payload: web::Json<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::PayoutsFilter; let payload = json_payload.into_inner(); @@ -408,7 +406,7 @@ pub async fn payouts_list_available_filters_for_merchant( pub async fn payouts_list_available_filters_for_profile( state: web::Data<AppState>, req: HttpRequest, - json_payload: web::Json<payment_types::TimeRange>, + json_payload: web::Json<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::PayoutsFilter; let payload = json_payload.into_inner(); diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index d21c351a927..40184c5fcfa 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -318,7 +318,7 @@ pub async fn refunds_list_profile( pub async fn refunds_filter_list( state: web::Data<AppState>, req: HttpRequest, - payload: web::Json<api_models::payments::TimeRange>, + payload: web::Json<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::RefundsList; Box::pin(api::server_wrap( @@ -426,7 +426,7 @@ pub async fn get_refunds_filters_profile( pub async fn get_refunds_aggregates( state: web::Data<AppState>, req: HttpRequest, - query_params: web::Query<api_models::payments::TimeRange>, + query_params: web::Query<common_utils::types::TimeRange>, ) -> HttpResponse { let flow = Flow::RefundsAggregate; let query_params = query_params.into_inner(); diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 449d1c725c5..575725d4874 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -13,7 +13,7 @@ pub use api_models::payments::{ PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, - TimeRange, UrlDetails, VerifyRequest, VerifyResponse, WalletData, + UrlDetails, VerifyRequest, VerifyResponse, WalletData, }; use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs index 79b9a90343e..45f2073708b 100644 --- a/crates/router/src/types/storage/dispute.rs +++ b/crates/router/src/types/storage/dispute.rs @@ -19,7 +19,7 @@ pub trait DisputeDbExt: Sized { conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>; } @@ -84,7 +84,7 @@ impl DisputeDbExt for Dispute { conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> { let mut query = <Self as HasTable>::table() .group_by(dsl::dispute_status) diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index 8e0040abfae..350c1032261 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -29,7 +29,7 @@ pub trait RefundDbExt: Sized { async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - refund_list_details: &api_models::payments::TimeRange, + refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>; async fn get_refunds_count( @@ -41,7 +41,7 @@ pub trait RefundDbExt: Sized { async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>; } @@ -158,7 +158,7 @@ impl RefundDbExt for Refund { async fn filter_by_meta_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - refund_list_details: &api_models::payments::TimeRange, + refund_list_details: &common_utils::types::TimeRange, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> { let start_time = refund_list_details.start_time; @@ -299,7 +299,7 @@ impl RefundDbExt for Refund { async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> { let mut query = <Self as HasTable>::table() .group_by(dsl::refund_status) diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs index 1a4595bdbbe..7abde140991 100644 --- a/crates/storage_impl/src/mock_db/payment_attempt.rs +++ b/crates/storage_impl/src/mock_db/payment_attempt.rs @@ -52,6 +52,7 @@ impl PaymentAttemptInterface for MockDb { _payment_method_type: Option<Vec<PaymentMethodType>>, _authentication_type: Option<Vec<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>>, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<i64, StorageError> { diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index 4cf8272650a..e0328871e33 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -41,7 +41,7 @@ impl PaymentIntentInterface for MockDb { &self, _state: &KeyManagerState, _merchant_id: &common_utils::id_type::MerchantId, - _time_range: &api_models::payments::TimeRange, + _time_range: &common_utils::types::TimeRange, _key_store: &MerchantKeyStore, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<PaymentIntent>, StorageError> { @@ -57,7 +57,7 @@ impl PaymentIntentInterface for MockDb { &self, _merchant_id: &common_utils::id_type::MerchantId, _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - _time_range: &api_models::payments::TimeRange, + _time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> { // [#172]: Implement function for `MockDb` Err(StorageError::MockDbError)? diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs index 5f2cc8824e5..c72a08a1823 100644 --- a/crates/storage_impl/src/mock_db/payouts.rs +++ b/crates/storage_impl/src/mock_db/payouts.rs @@ -86,7 +86,7 @@ impl PayoutsInterface for MockDb { async fn filter_payouts_by_time_range_constraints( &self, _merchant_id: &common_utils::id_type::MerchantId, - _time_range: &api_models::payments::TimeRange, + _time_range: &common_utils::types::TimeRange, _storage_scheme: storage_enums::MerchantStorageScheme, ) -> CustomResult<Vec<Payouts>, StorageError> { // TODO: Implement function for `MockDb` diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index d1df6861657..9974393e100 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -403,6 +403,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method_type: Option<Vec<PaymentMethodType>>, authentication_type: Option<Vec<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>>, _storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { @@ -426,6 +427,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> { payment_method, payment_method_type, authentication_type, + time_range, profile_id_list, merchant_connector_id, ) @@ -1289,6 +1291,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type: Option<Vec<PaymentMethodType>>, authentication_type: Option<Vec<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>>, storage_scheme: MerchantStorageScheme, ) -> CustomResult<i64, errors::StorageError> { @@ -1301,6 +1304,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { payment_method_type, authentication_type, merchant_connector_id, + time_range, profile_id_list, storage_scheme, ) diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index cb58eac4b61..97fa5873cae 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -378,7 +378,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { @@ -402,7 +402,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { self.router_store .get_intent_status_with_count(merchant_id, profile_id_list, time_range) @@ -747,7 +747,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { &self, state: &KeyManagerState, merchant_id: &common_utils::id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, merchant_key_store: &MerchantKeyStore, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<PaymentIntent>, StorageError> { @@ -773,7 +773,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { &self, merchant_id: &common_utils::id_type::MerchantId, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { let conn = connection::pg_connection_read(self).await.switch()?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs index b6e1c1ac35f..2a49b01458f 100644 --- a/crates/storage_impl/src/payouts/payouts.rs +++ b/crates/storage_impl/src/payouts/payouts.rs @@ -368,7 +368,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> { async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { self.router_store @@ -772,7 +772,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> { async fn filter_payouts_by_time_range_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, - time_range: &api_models::payments::TimeRange, + time_range: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> error_stack::Result<Vec<Payouts>, StorageError> { let payout_filters = (*time_range).into();
2024-09-19T11:00:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Add time range to filter total count for payment attempt list. - Move `TimeRange` type to common utils so that it can be used in diesel models and across all the other api models ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes #5958 ## How did you test it? The expected behaviour is same, the query that is getting printed, is now also considering time range. ``` SELECT COUNT(*) FROM "payment_attempt" WHERE ((("payment_attempt"."merchant_id" = $1) AND ("payment_attempt"."attempt_id" = ANY($2))) AND ("payment_attempt"."created_at" >= $3)) -- binds: [MerchantId("merchant_1726040792"), [], 2024-08-19 18:30:00.0] ``` Request ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "start_time": "2024-08-19T18:30:00Z" }' ``` Response: ``` { "count": 0, "total_count": 0, "data": [] } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
6a6ce17506932e0843140ef5b02ed201d0524d5d
juspay/hyperswitch
juspay__hyperswitch-5944
Bug: feat(refunds) : profile level refunds aggregate Support for disputes aggregate at profile level
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 118f4b81766..0f3dfa44c10 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1098,11 +1098,17 @@ pub async fn get_filters_for_refunds( pub async fn get_aggregates_for_refunds( state: SessionState, merchant: domain::MerchantAccount, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: common_utils::types::TimeRange, ) -> RouterResponse<api_models::refunds::RefundAggregateResponse> { let db = state.store.as_ref(); let refund_status_with_count = db - .get_refund_status_with_count(merchant.get_id(), &time_range, merchant.storage_scheme) + .get_refund_status_with_count( + merchant.get_id(), + profile_id_list, + &time_range, + merchant.storage_scheme, + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to find status count")?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index ff7e8145c33..0190718791f 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2546,11 +2546,12 @@ impl RefundInterface for KafkaStore { async fn get_refund_status_with_count( &self, merchant_id: &id_type::MerchantId, + profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, storage_scheme: MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { self.diesel_store - .get_refund_status_with_count(merchant_id, constraints, storage_scheme) + .get_refund_status_with_count(merchant_id, profile_id_list, constraints, storage_scheme) .await } diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index dbe7534ee28..cf092ad410e 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -88,6 +88,7 @@ pub trait RefundInterface { async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; @@ -265,11 +266,12 @@ mod storage { async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &api_models::payments::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id, time_range) + <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, time_range) .await .map_err(|error|report!(errors::StorageError::from(error))) } @@ -831,11 +833,12 @@ mod storage { async fn get_refund_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, constraints: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id, constraints) + <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, constraints) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -1182,6 +1185,7 @@ impl RefundInterface for MockDb { async fn get_refund_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> { @@ -1194,7 +1198,17 @@ impl RefundInterface for MockDb { let filtered_refunds = refunds .iter() - .filter(|refund| refund.created_at >= start_time && refund.created_at <= end_time) + .filter(|refund| { + refund.created_at >= start_time + && refund.created_at <= end_time + && profile_id_list + .as_ref() + .zip(refund.profile_id.as_ref()) + .map(|(received_profile_list, received_profile_id)| { + received_profile_list.contains(received_profile_id) + }) + .unwrap_or(true) + }) .cloned() .collect::<Vec<diesel_models::refund::Refund>>(); diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 01a48c56401..a8a7ea7d56f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1002,6 +1002,10 @@ impl Refunds { .service(web::resource("/filter").route(web::post().to(refunds_filter_list))) .service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters))) .service(web::resource("/aggregate").route(web::get().to(get_refunds_aggregates))) + .service( + web::resource("/profile/aggregate") + .route(web::get().to(get_refunds_aggregate_profile)), + ) .service( web::resource("/v2/profile/filter") .route(web::get().to(get_refunds_filters_profile)), diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index 40184c5fcfa..aaea6d4c99e 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -436,7 +436,7 @@ pub async fn get_refunds_aggregates( &req, query_params, |state, auth: auth::AuthenticationData, req, _| { - get_aggregates_for_refunds(state, auth.merchant_account, req) + get_aggregates_for_refunds(state, auth.merchant_account, None, req) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), @@ -473,3 +473,38 @@ pub async fn refunds_manual_update( )) .await } + +#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] +#[cfg(feature = "olap")] +pub async fn get_refunds_aggregate_profile( + state: web::Data<AppState>, + req: HttpRequest, + query_params: web::Query<common_utils::types::TimeRange>, +) -> HttpResponse { + let flow = Flow::RefundsAggregate; + let query_params = query_params.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + query_params, + |state, auth: auth::AuthenticationData, req, _| { + get_aggregates_for_refunds( + state, + auth.merchant_account, + auth.profile_id.map(|profile_id| vec![profile_id]), + req, + ) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Profile, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index 350c1032261..8076c2c7a6e 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -41,6 +41,7 @@ pub trait RefundDbExt: Sized { async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>; } @@ -299,6 +300,7 @@ impl RefundDbExt for Refund { async fn get_refund_status_with_count( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &common_utils::types::TimeRange, ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> { let mut query = <Self as HasTable>::table() @@ -307,6 +309,10 @@ impl RefundDbExt for Refund { .filter(dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); + if let Some(profile_id) = profile_id_list { + query = query.filter(dsl::profile_id.eq_any(profile_id)); + } + query = query.filter(dsl::created_at.ge(time_range.start_time)); query = match time_range.end_time {
2024-09-18T06:32:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add support for profile level refunds aggregate - For now it will have list of intent status along with the their count for a given time range. ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request : ``` curl --location 'http://localhost:8080/refunds/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \ --header 'Authorization: Bearer JWT' \ --data '' ``` Response ``` { "status_with_count": { "success": 3, "pending": 0, "failure": 0, "manual_review": 0, "transaction_failure": 0 } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
dccb8d4e629d615a69f6922a96e72f10d3410bfc
juspay/hyperswitch
juspay__hyperswitch-5946
Bug: fix(external_services): add proto compilation under a feature flag add proto compilation under a feature flag
diff --git a/config/config.example.toml b/config/config.example.toml index a6af984b01f..8345185238d 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -748,3 +748,7 @@ check_token_status_url= "" # base url to check token status from token servic [network_tokenization_supported_connectors] connector_list = "cybersource" # Supported connectors for network tokenization + +[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration +host = "localhost" # Client Host +port = 7000 # Client Port diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 62350376271..319cdafed1d 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -311,3 +311,7 @@ private_key= "" # private key to decrypt response payload from to key_id= "" # key id to encrypt data for token service delete_token_url= "" # base url to delete token from token service check_token_status_url= "" # base url to check token status from token service + +[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration +host = "localhost" # Client Host +port = 7000 # Client Port diff --git a/crates/external_services/Cargo.toml b/crates/external_services/Cargo.toml index a882cdc9f51..fd7391c13bc 100644 --- a/crates/external_services/Cargo.toml +++ b/crates/external_services/Cargo.toml @@ -13,7 +13,7 @@ email = ["dep:aws-config"] aws_s3 = ["dep:aws-config", "dep:aws-sdk-s3"] hashicorp-vault = ["dep:vaultrs"] v1 = ["hyperswitch_interfaces/v1"] -dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread"] +dynamic_routing = ["dep:prost", "dep:tonic", "dep:tonic-reflection", "dep:tonic-types", "dep:api_models", "tokio/macros", "tokio/rt-multi-thread" , "dep:tonic-build", "dep:router_env"] [dependencies] async-trait = "0.1.79" @@ -49,7 +49,8 @@ api_models = { version = "0.1.0", path = "../api_models", optional = true } [build-dependencies] -tonic-build = "0.12" +tonic-build = { version = "0.12" , optional = true } +router_env = { version = "0.1.0", path = "../router_env", default-features = false, optional = true } [lints] workspace = true diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs index 61e19f308d8..605ef699715 100644 --- a/crates/external_services/build.rs +++ b/crates/external_services/build.rs @@ -1,15 +1,13 @@ -use std::{env, path::PathBuf}; - #[allow(clippy::expect_used)] fn main() -> Result<(), Box<dyn std::error::Error>> { - // Get the directory of the current crate - let crate_dir = env::var("CARGO_MANIFEST_DIR")?; - let proto_file = PathBuf::from(crate_dir) - .join("..") - .join("..") - .join("proto") - .join("success_rate.proto"); - // Compile the .proto file - tonic_build::compile_protos(proto_file).expect("Failed to compile protos "); + #[cfg(feature = "dynamic_routing")] + { + // Get the directory of the current crate + let proto_file = router_env::workspace_path() + .join("proto") + .join("success_rate.proto"); + // Compile the .proto file + tonic_build::compile_protos(proto_file).expect("Failed to compile success rate proto file"); + } Ok(()) } diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs index 17bd43ca3a8..2681bffb0ce 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing.rs @@ -112,12 +112,12 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> { let params = success_rate_based_config .params .map(|vec| { - vec.into_iter().fold(String::new(), |mut acc_vec, params| { - if !acc_vec.is_empty() { - acc_vec.push(':') + vec.into_iter().fold(String::new(), |mut acc_str, params| { + if !acc_str.is_empty() { + acc_str.push(':') } - acc_vec.push_str(params.to_string().as_str()); - acc_vec + acc_str.push_str(params.to_string().as_str()); + acc_str }) }) .get_required_value("params") @@ -177,12 +177,12 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Channel> { let params = success_rate_based_config .params .map(|vec| { - vec.into_iter().fold(String::new(), |mut acc_vec, params| { - if !acc_vec.is_empty() { - acc_vec.push(':') + vec.into_iter().fold(String::new(), |mut acc_str, params| { + if !acc_str.is_empty() { + acc_str.push(':') } - acc_vec.push_str(params.to_string().as_str()); - acc_vec + acc_str.push_str(params.to_string().as_str()); + acc_str }) }) .get_required_value("params")
2024-09-18T10:38:19Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description add proto build under the dynamic_routing feature flag. Now the application would run without having to install protoc ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Cannot be tested as it is for compiling the application without having to mandatorily install proton ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c8f7232a3001be1fc5d8b0fedfd703030df83789
juspay/hyperswitch
juspay__hyperswitch-5947
Bug: [REFACTOR]: [FISERV] Add amount conversion framework to Fiserv ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://docs.fiserv.dev/public/reference/createpaymenturl) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :sparkles: Are you willing to submit a PR? ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv.rs b/crates/hyperswitch_connectors/src/connectors/fiserv.rs index e80c57454a0..50eebb99518 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv.rs @@ -1,13 +1,12 @@ pub mod transformers; -use std::fmt::Debug; - use base64::Engine; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -44,12 +43,23 @@ use time::OffsetDateTime; use transformers as fiserv; use uuid::Uuid; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{construct_not_implemented_error_report, convert_amount}, +}; -#[derive(Debug, Clone)] -pub struct Fiserv; +#[derive(Clone)] +pub struct Fiserv { + amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} impl Fiserv { + pub fn new() -> &'static Self { + &Self { + amount_converter: &FloatMajorUnitForConnector, + } + } pub fn generate_authorization_signature( &self, auth: fiserv::FiservAuthType, @@ -194,7 +204,7 @@ impl ConnectorValidation for Fiserv { | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( - utils::construct_not_implemented_error_report(capture_method, self.id()), + construct_not_implemented_error_report(capture_method, self.id()), ), } } @@ -421,12 +431,12 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = fiserv::FiservRouterData::try_from(( - &self.get_currency_unit(), + let amount_to_capture = convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + let router_obj = fiserv::FiservRouterData::try_from((amount_to_capture, req))?; let connector_req = fiserv::FiservCaptureRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -530,12 +540,12 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = fiserv::FiservRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let router_obj = fiserv::FiservRouterData::try_from((amount, req))?; let connector_req = fiserv::FiservPaymentsRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -624,12 +634,12 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Fiserv req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let router_obj = fiserv::FiservRouterData::try_from(( - &self.get_currency_unit(), + let refund_amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let router_obj = fiserv::FiservRouterData::try_from((refund_amount, req))?; let connector_req = fiserv::FiservRefundRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs index d6e2cd54db7..8f9a15e49c2 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs @@ -1,5 +1,5 @@ use common_enums::enums; -use common_utils::{ext_traits::ValueExt, pii}; +use common_utils::{ext_traits::ValueExt, pii, types::FloatMajorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, @@ -9,7 +9,7 @@ use hyperswitch_domain_models::{ router_response_types::{PaymentsResponseData, RefundsResponseData}, types, }; -use hyperswitch_interfaces::{api, errors}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -23,22 +23,14 @@ use crate::{ #[derive(Debug, Serialize)] pub struct FiservRouterData<T> { - pub amount: String, + pub amount: FloatMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for FiservRouterData<T> { +impl<T> TryFrom<(FloatMajorUnit, T)> for FiservRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, router_data): ( - &api::CurrencyUnit, - enums::Currency, - i64, - T, - ), - ) -> Result<Self, Self::Error> { - let amount = utils::get_amount_as_string(currency_unit, amount, currency)?; + fn try_from((amount, router_data): (FloatMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data, @@ -89,8 +81,7 @@ pub struct GooglePayToken { #[derive(Default, Debug, Serialize)] pub struct Amount { - #[serde(serialize_with = "utils::str_to_f32")] - total: String, + total: FloatMajorUnit, currency: String, } @@ -143,7 +134,7 @@ impl TryFrom<&FiservRouterData<&types::PaymentsAuthorizeRouterData>> for FiservP ) -> Result<Self, Self::Error> { let auth: FiservAuthType = FiservAuthType::try_from(&item.router_data.connector_auth_type)?; let amount = Amount { - total: item.amount.clone(), + total: item.amount, currency: item.router_data.request.currency.to_string(), }; let transaction_details = TransactionDetails { @@ -484,7 +475,7 @@ impl TryFrom<&FiservRouterData<&types::PaymentsCaptureRouterData>> for FiservCap })?; Ok(Self { amount: Amount { - total: item.amount.clone(), + total: item.amount, currency: item.router_data.request.currency.to_string(), }, transaction_details: TransactionDetails { @@ -579,7 +570,7 @@ impl<F> TryFrom<&FiservRouterData<&types::RefundsRouterData<F>>> for FiservRefun })?; Ok(Self { amount: Amount { - total: item.amount.clone(), + total: item.amount, currency: item.router_data.request.currency.to_string(), }, merchant_details: MerchantDetails { diff --git a/crates/hyperswitch_connectors/src/connectors/helcim.rs b/crates/hyperswitch_connectors/src/connectors/helcim.rs index 844eab7825f..79b950063c3 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim.rs @@ -1,5 +1,4 @@ pub mod transformers; -use std::fmt::Debug; use api_models::webhooks::IncomingWebhookEvent; use common_enums::enums; @@ -7,6 +6,7 @@ use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, + types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ @@ -49,11 +49,21 @@ use transformers as helcim; use crate::{ constants::headers, types::ResponseRouterData, - utils::{to_connector_meta, PaymentsAuthorizeRequestData}, + utils::{convert_amount, to_connector_meta, PaymentsAuthorizeRequestData}, }; -#[derive(Debug, Clone)] -pub struct Helcim; +#[derive(Clone)] +pub struct Helcim { + amount_convertor: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), +} + +impl Helcim { + pub fn new() -> &'static Self { + &Self { + amount_convertor: &FloatMajorUnitForConnector, + } + } +} impl api::Payment for Helcim {} impl api::PaymentSession for Helcim {} @@ -305,13 +315,13 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = helcim::HelcimRouterData::try_from(( - &self.get_currency_unit(), + let connector_router_data = convert_amount( + self.amount_convertor, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; - let connector_req = helcim::HelcimPaymentsRequest::try_from(&connector_router_data)?; + )?; + let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?; + let connector_req = helcim::HelcimPaymentsRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -484,13 +494,13 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = helcim::HelcimRouterData::try_from(( - &self.get_currency_unit(), + let connector_router_data = convert_amount( + self.amount_convertor, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; - let connector_req = helcim::HelcimCaptureRequest::try_from(&connector_router_data)?; + )?; + let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?; + let connector_req = helcim::HelcimCaptureRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -651,13 +661,13 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Helcim req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = helcim::HelcimRouterData::try_from(( - &self.get_currency_unit(), + let connector_router_data = convert_amount( + self.amount_convertor, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; - let connector_req = helcim::HelcimRefundRequest::try_from(&connector_router_data)?; + )?; + let router_obj = helcim::HelcimRouterData::try_from((connector_router_data, req))?; + let connector_req = helcim::HelcimRefundRequest::try_from(&router_obj)?; Ok(RequestContent::Json(Box::new(connector_req))) } diff --git a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs index 0a5453a49d0..d890bd88ac3 100644 --- a/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/helcim/transformers.rs @@ -1,5 +1,8 @@ use common_enums::enums; -use common_utils::pii::{Email, IpAddress}; +use common_utils::{ + pii::{Email, IpAddress}, + types::FloatMajorUnit, +}; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{Card, PaymentMethodData}, @@ -15,10 +18,7 @@ use hyperswitch_domain_models::{ RefundsRouterData, SetupMandateRouterData, }, }; -use hyperswitch_interfaces::{ - api::{self}, - errors, -}; +use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -33,16 +33,13 @@ use crate::{ #[derive(Debug, Serialize)] pub struct HelcimRouterData<T> { - pub amount: f64, + pub amount: FloatMajorUnit, pub router_data: T, } -impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for HelcimRouterData<T> { +impl<T> TryFrom<(FloatMajorUnit, T)> for HelcimRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T), - ) -> Result<Self, Self::Error> { - let amount = crate::utils::get_amount_as_f64(currency_unit, amount, currency)?; + fn try_from((amount, item): (FloatMajorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data: item, @@ -77,7 +74,7 @@ pub struct HelcimVerifyRequest { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct HelcimPaymentsRequest { - amount: f64, + amount: FloatMajorUnit, currency: enums::Currency, ip_address: Secret<String, IpAddress>, card_data: HelcimCard, @@ -115,8 +112,8 @@ pub struct HelcimInvoice { pub struct HelcimLineItems { description: String, quantity: u8, - price: f64, - total: f64, + price: FloatMajorUnit, + total: FloatMajorUnit, } #[derive(Debug, Serialize)] @@ -514,7 +511,7 @@ impl<F> #[serde(rename_all = "camelCase")] pub struct HelcimCaptureRequest { pre_auth_transaction_id: u64, - amount: f64, + amount: FloatMajorUnit, ip_address: Secret<String, IpAddress>, #[serde(skip_serializing_if = "Option::is_none")] ecommerce: Option<bool>, @@ -637,7 +634,7 @@ impl<F> #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct HelcimRefundRequest { - amount: f64, + amount: FloatMajorUnit, original_transaction_id: u64, ip_address: Secret<String, IpAddress>, #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index ce40e373462..fd26e459539 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -57,7 +57,6 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use once_cell::sync::Lazy; use regex::Regex; use router_env::logger; -use serde::Serializer; use serde_json::Value; use time::PrimitiveDateTime; @@ -344,16 +343,6 @@ pub(crate) fn construct_not_implemented_error_report( .into() } -pub(crate) fn str_to_f32<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error> -where - S: Serializer, -{ - let float_value = value.parse::<f64>().map_err(|_| { - serde::ser::Error::custom("Invalid string, cannot be converted to float value") - })?; - serializer.serialize_f64(float_value) -} - pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method"; pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String { diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 99d577c657b..3247395ad7e 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -432,7 +432,9 @@ impl ConnectorData { enums::Connector::Elavon => { Ok(ConnectorEnum::Old(Box::new(connector::Elavon::new()))) } - enums::Connector::Fiserv => Ok(ConnectorEnum::Old(Box::new(&connector::Fiserv))), + enums::Connector::Fiserv => { + Ok(ConnectorEnum::Old(Box::new(connector::Fiserv::new()))) + } enums::Connector::Fiservemea => { Ok(ConnectorEnum::Old(Box::new(connector::Fiservemea::new()))) } @@ -453,7 +455,9 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(&connector::Gocardless))) } // enums::Connector::Hipay => Ok(ConnectorEnum::Old(Box::new(connector::Hipay))), - enums::Connector::Helcim => Ok(ConnectorEnum::Old(Box::new(&connector::Helcim))), + enums::Connector::Helcim => { + Ok(ConnectorEnum::Old(Box::new(connector::Helcim::new()))) + } enums::Connector::Iatapay => { Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new()))) } diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs index 7f13de31004..78235278ed9 100644 --- a/crates/router/tests/connectors/fiserv.rs +++ b/crates/router/tests/connectors/fiserv.rs @@ -16,7 +16,7 @@ impl utils::Connector for FiservTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Fiserv; utils::construct_connector_data_old( - Box::new(&Fiserv), + Box::new(Fiserv::new()), types::Connector::Fiserv, types::api::GetToken::Connector, None, diff --git a/crates/router/tests/connectors/helcim.rs b/crates/router/tests/connectors/helcim.rs index 761b07736ce..5b02e2f8431 100644 --- a/crates/router/tests/connectors/helcim.rs +++ b/crates/router/tests/connectors/helcim.rs @@ -11,7 +11,7 @@ impl utils::Connector for HelcimTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Helcim; utils::construct_connector_data_old( - Box::new(&Helcim), + Box::new(Helcim::new()), types::Connector::Helcim, types::api::GetToken::Connector, None,
2025-02-21T08:52:43Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> added **FloatMajorUnit** for amount conversion for **Fiserv** added **FloatMajorUnit** for amount conversion for **Helcim** ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> fixes #6256 and #6019 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested through postman: - Create a MCA for **fiserv**: - Create a Payment with **fiserv**: request: ``` { "amount": 10000, "currency": "USD", "amount_to_capture": 10000, "confirm": true, "profile_id": {{profile_id}}, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "customer_id": "customer123", "phone_country_code": "+1", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4147463011110083", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 6540, "account_name": "transaction_processing" } ], "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "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" }, "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "125.0.0.1", "user_agent": "amet irure esse" } }, //Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find more in the doc. "connector_metadata": { "noon": { "order_category": "pay" } }, "payment_link": false, "payment_link_config": { "theme": "", "logo": "", "seller_name": "", "sdk_layout": "", "display_sdk_only": false, "enabled_saved_payment_method": false }, "payment_type": "normal", "request_incremental_authorization": false, "merchant_order_reference_id": "test_ord", "session_expiry": 900 } ``` response: - The payment should be succeeded ``` { "payment_id": "pay_9mnPycKv5V2w9aNCHyO8", "merchant_id": "merchant_1740127595", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "fiserv", "client_secret": "pay_9mnPycKv5V2w9aNCHyO8_secret_X4CTRqm4Ldyx6L7s2OPa", "created": "2025-02-21T08:46:50.624Z", "currency": "USD", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0083", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "414746", "card_extended_bin": null, "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "9999999999", "country_code": "+91" }, "email": "guest@example.com" }, "order_details": [ { "brand": null, "amount": 6540, "category": null, "quantity": 1, "tax_rate": null, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "customer@gmail.com", "name": "John Doe", "phone": "9999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1740127610, "expires": 1740131210, "secret": "epk_a6328125a3ad471d88ef13493272c1cc" }, "manual_retry_allowed": false, "connector_transaction_id": "6f2fdeb7a1884bc0957c0f977644c30c", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": { "apple_pay": null, "airwallex": null, "noon": { "order_category": "pay" } }, "feature_metadata": null, "reference_id": "CHG015117c1ffa76779d655a830730d7add1a", "payment_link": null, "profile_id": "pro_IxmWaGQVX320n30wDNuM", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_o2Tw2yV2oWr4vEC5b22q", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-21T09:01:50.623Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "128.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-21T08:46:54.326Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": "test_ord", "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` using curl : <img width="614" alt="Screenshot 2025-03-11 at 10 48 50 PM" src="https://github.com/user-attachments/assets/da58c0b9-6dbf-4bab-94d3-37817eac3479" /> <img width="1496" alt="Screenshot 2025-03-11 at 10 51 03 PM" src="https://github.com/user-attachments/assets/e2f6e5f6-40d6-4253-ac82-9ea6da361eac" /> - Create a MCA for **helcim**: - Create a Payment with **helcim**: ``` { "amount": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 100, "customer_id": "helcim", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5413330089099130", "card_exp_month": "01", "card_exp_year": "28", "card_holder_name": "joseph Doe", "card_cvc": "100" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "browser_info": { "color_depth": 24, "java_enabled": true, "java_script_enabled": true, "language": "en-US", "screen_height": 1080, "screen_width": 1920, "time_zone": 123, "ip_address": "192.168.1.1", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "os_type": "Windows", "os_version": "10", "device_model": "Desktop" }, "order_details": [{ "product_name":"something", "quantity": 4, "amount" : 400 }] } ``` response: - The payment should be succeeded ``` { "payment_id": "pay_TORNbtguEZUEleC3kYt5", "merchant_id": "merchant_1740386925", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "helcim", "client_secret": "pay_TORNbtguEZUEleC3kYt5_secret_PLV79VNxPEreoif4WfRh", "created": "2025-02-24T08:49:05.760Z", "currency": "USD", "customer_id": "helcim", "customer": { "id": "helcim", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "9130", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "541333", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "28", "card_holder_name": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": [ { "brand": null, "amount": 400, "category": null, "quantity": 4, "tax_rate": null, "product_id": null, "product_name": "something", "product_type": null, "sub_category": null, "product_img_link": null, "product_tax_code": null, "total_tax_amount": null, "requires_shipping": null } ], "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "helcim", "created_at": 1740386945, "expires": 1740390545, "secret": "epk_79d58a8d4ee84ef7bd0e66d4ffa2d471" }, "manual_retry_allowed": false, "connector_transaction_id": "32476974", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_TORNbtguEZUEleC3kYt5_1", "payment_link": null, "profile_id": "pro_1daddCjtZeUez131YwqB", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_b16Kuzg7hY5sPy9NgQUV", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-02-24T09:04:05.759Z", "fingerprint": null, "browser_info": { "os_type": "Windows", "language": "en-US", "time_zone": 123, "ip_address": "192.168.1.1", "os_version": "10", "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36", "color_depth": 24, "device_model": "Desktop", "java_enabled": true, "screen_width": 1920, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 1080, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2025-02-24T08:49:09.053Z", "split_payments": null, "frm_metadata": null, "extended_authorization_applied": null, "capture_before": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null, "card_discovery": "manual" } ``` using curl : <img width="1168" alt="Screenshot 2025-03-11 at 11 09 50 PM" src="https://github.com/user-attachments/assets/48ee3269-56fe-45ce-85ac-8a57a72b0640" /> <img width="1496" alt="Screenshot 2025-03-11 at 11 10 41 PM" src="https://github.com/user-attachments/assets/860742b5-d26b-4c4d-91dd-325a39ee5082" /> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
24aa00341f907e7b77df9348f62d1416cc098691
juspay/hyperswitch
juspay__hyperswitch-5942
Bug: [REFACTOR]: [CYBERSOURCE] Add amount conversion framework to Cybersource ### :memo: Feature Description Currently, amounts are represented as `i64` values throughout the application. We want to introduce a `Unit` struct that explicitly states the denomination. A new type, `MinorUnit`, has been added to standardize the flow of amounts across the application. This type will now be used by all the connector flows. Rather than handling conversions in each connector, we will centralize the conversion logic in one place within the core of the application. ### :hammer: Possible Implementation - For each connector, we need to create an amount conversion function. Connectors will specify the format they require, and the core framework will handle the conversion accordingly. - Connectors should invoke the `convert` function to receive the amount in their required format. - Refer to the [connector documentation](https://developer.cybersource.com/docs/cybs/en-us/api-fields/reference/all/so/api-fields/original-transaction-amount.html) to determine the required amount format for each connector. - You can refer [this PR](https://github.com/juspay/hyperswitch/pull/4825) for more context. 🔖 Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/` , `crates/router/src/types/api.rs` , `crates/router/tests/connectors/` ### :package: Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### :package: Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### :package: Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest. ### :sparkles: Are you willing to submit a PR?
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 2a271acb62b..433a3139d52 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -603,7 +603,6 @@ impl StringMajorUnit { pub fn zero() -> Self { Self("0".to_string()) } - /// Get string amount from struct to be removed in future pub fn get_amount_as_string(&self) -> String { self.0.clone() diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 806cf67b2da..06f448e075a 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -1,9 +1,10 @@ pub mod transformers; -use std::fmt::Debug; - use base64::Engine; -use common_utils::request::RequestContent; +use common_utils::{ + request::RequestContent, + types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector}, +}; use diesel_models::enums; use error_stack::{report, Report, ResultExt}; use masking::{ExposeInterface, PeekInterface}; @@ -12,7 +13,7 @@ use time::OffsetDateTime; use transformers as cybersource; use url::Url; -use super::utils::{PaymentsAuthorizeRequestData, RouterData}; +use super::utils::{convert_amount, PaymentsAuthorizeRequestData, RouterData}; use crate::{ configs::settings, connector::{ @@ -36,9 +37,18 @@ use crate::{ utils::BytesExt, }; -#[derive(Debug, Clone)] -pub struct Cybersource; +#[derive(Clone)] +pub struct Cybersource { + amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), +} +impl Cybersource { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMajorUnitForConnector, + } + } +} impl Cybersource { pub fn generate_digest(&self, payload: &[u8]) -> String { let payload_digest = digest::digest(&digest::SHA256, payload); @@ -617,20 +627,20 @@ impl req: &types::PaymentsPreProcessingRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let minor_amount = req.request - .currency + .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "currency", - })?, + field_name: "minor_amount", + })?; + let currency = req.request - .amount + .currency .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "amount", - })?, - req, - ))?; + field_name: "currency", + })?; + let amount = convert_amount(self.amount_converter, minor_amount, currency)?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePreProcessingRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -718,12 +728,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme req: &types::PaymentsCaptureRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, req.request.currency, - req.request.amount_to_capture, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePaymentsCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -922,12 +932,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); if req.is_three_ds() && req.request.is_card() && (req.request.connector_mandate_id().is_none() @@ -1068,12 +1078,12 @@ impl ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::PayoutsResp req: &types::PayoutsRouterData<api::PoFulfill>, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.destination_currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePayoutFulfillRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1193,12 +1203,12 @@ impl req: &types::PaymentsCompleteAuthorizeRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let amount = convert_amount( + self.amount_converter, + req.request.minor_amount, req.request.currency, - req.request.amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); let connector_req = cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1317,20 +1327,21 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let minor_amount = req.request - .currency + .minor_amount .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "Currency", - })?, + field_name: "Amount", + })?; + let currency = req.request - .amount + .currency .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "Amount", - })?, - req, - ))?; + field_name: "Currency", + })?; + let amount = convert_amount(self.amount_converter, minor_amount, currency)?; + let connector_router_data = cybersource::CybersourceRouterData::from((amount, req)); + let connector_req = cybersource::CybersourceVoidRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1443,12 +1454,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon req: &types::RefundExecuteRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let refund_amount = convert_amount( + self.amount_converter, + req.request.minor_refund_amount, req.request.currency, - req.request.refund_amount, - req, - ))?; + )?; + let connector_router_data = cybersource::CybersourceRouterData::from((refund_amount, req)); let connector_req = cybersource::CybersourceRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) @@ -1609,12 +1620,14 @@ impl req: &types::PaymentsIncrementalAuthorizationRouterData, _connectors: &settings::Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - let connector_router_data = cybersource::CybersourceRouterData::try_from(( - &self.get_currency_unit(), + let minor_additional_amount = MinorUnit::new(req.request.additional_amount); + let additional_amount = convert_amount( + self.amount_converter, + minor_additional_amount, req.request.currency, - req.request.additional_amount, - req, - ))?; + )?; + let connector_router_data = + cybersource::CybersourceRouterData::from((additional_amount, req)); let connector_request = cybersource::CybersourcePaymentsIncrementalAuthorizationRequest::try_from( &connector_router_data, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 2ea36e3e35e..2174eb3bc50 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -9,7 +9,7 @@ use common_enums::FutureUsage; use common_utils::{ ext_traits::{OptionExt, ValueExt}, pii, - types::SemanticVersion, + types::{SemanticVersion, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -41,21 +41,16 @@ use crate::{ #[derive(Debug, Serialize)] pub struct CybersourceRouterData<T> { - pub amount: String, + pub amount: StringMajorUnit, pub router_data: 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): (&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)?; - Ok(Self { +impl<T> From<(StringMajorUnit, T)> for CybersourceRouterData<T> { + fn from((amount, router_data): (StringMajorUnit, T)) -> Self { + Self { amount, - router_data: item, - }) + router_data, + } } } @@ -93,7 +88,7 @@ impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { let order_information = OrderInformationWithBill { amount_details: Amount { - total_amount: "0".to_string(), + total_amount: StringMajorUnit::zero(), currency: item.request.currency, }, bill_to: Some(bill_to), @@ -526,14 +521,14 @@ pub struct OrderInformation { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Amount { - total_amount: String, + total_amount: StringMajorUnit, currency: api_models::enums::Currency, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct AdditionalAmount { - additional_amount: String, + additional_amount: StringMajorUnit, currency: String, } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index f5fa2d9a37e..975b219a26c 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -367,7 +367,7 @@ impl ConnectorData { Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new()))) } enums::Connector::Cybersource => { - Ok(ConnectorEnum::Old(Box::new(&connector::Cybersource))) + Ok(ConnectorEnum::Old(Box::new(connector::Cybersource::new()))) } enums::Connector::Datatrans => { Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs index 0116b52f4ed..1accece7fa6 100644 --- a/crates/router/tests/connectors/cybersource.rs +++ b/crates/router/tests/connectors/cybersource.rs @@ -14,7 +14,7 @@ impl utils::Connector for Cybersource { fn get_data(&self) -> api::ConnectorData { use router::connector::Cybersource; utils::construct_connector_data_old( - Box::new(&Cybersource), + Box::new(Cybersource::new()), types::Connector::Cybersource, api::GetToken::Connector, None,
2024-10-16T07:06:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> added StringMajorUnit for amount conversion ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> fixes #5942 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested through postman: - Create a MCA for cybersource: - Create a Payment with Cybersource: ``` { "amount": 499, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "test_rec7", "email": "guest@example.com", "request_external_three_ds_authentication": true, "customer_acceptance": { "acceptance_type": "online" }, "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "Test Holder", "card_cvc": "737" } }, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "authentication_type": "no_three_ds" } ``` - The payment should be succeeded ``` { "payment_id": "pay_LGt7Tbil8tLko2OpVHqJ", "merchant_id": "merchant_1730121122", "status": "succeeded", "amount": 499, "net_amount": 499, "shipping_cost": null, "amount_capturable": 0, "amount_received": 499, "connector": "cybersource", "client_secret": "pay_LGt7Tbil8tLko2OpVHqJ_secret_dycae051HVaAJYXSCdCH", "created": "2024-10-28T13:12:22.609Z", "currency": "USD", "customer_id": "test_rec7", "customer": { "id": "test_rec7", "name": null, "email": "guest@example.com", "phone": null, "phone_country_code": null }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "4242", "card_type": null, "card_network": "Visa", "card_issuer": null, "card_issuing_country": null, "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": { "resultCode": "M", "resultCodeRaw": "M" } }, "authentication_data": null }, "billing": null }, "payment_token": "token_LyziBYSQnkubuQbE91YF", "shipping": null, "billing": { "address": { "city": "test", "country": "US", "line1": "here", "line2": "there", "line3": "anywhere", "zip": "560095", "state": "Washington", "first_name": "One", "last_name": "Two" }, "phone": { "number": "1234567890", "country_code": "+1" }, "email": "guest@example.com" }, "order_details": null, "email": "guest@example.com", "name": null, "phone": null, "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "test_rec7", "created_at": 1730121142, "expires": 1730124742, "secret": "epk_bb3a50134caa4214ad2ea7b534184d26" }, "manual_retry_allowed": false, "connector_transaction_id": "7301211437366791304951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_LGt7Tbil8tLko2OpVHqJ_1", "payment_link": null, "profile_id": "pro_2pDEf41cwojHtrM9xItk", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_AFVVYXejTDoWa4IgaPnw", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-10-28T13:27:22.609Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-10-28T13:12:24.692Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - Check cybersource dashboard with respective connector_transaction_id to get the transaction data - the amount in dashboard should match with the amount passed in request. ![image](https://github.com/user-attachments/assets/c9644519-1638-4a09-a6b0-3c56c1adabd0) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
55fe82fdcd78df9608842190f1423088740d1087
juspay/hyperswitch
juspay__hyperswitch-5940
Bug: [REFACTOR] Move Hardcoded Email Subjects to Constants Across the User Related Files ### Feature Description In the current implementation, email subjects are hardcoded at multiple places across the codebase when constructing email content. To improve maintainability and avoid magic strings, each unique subject should be moved to its own constant. The goal of this issue is to identify all the places where email subjects are hardcoded, create a corresponding constant for each one, and replace the hardcoded values with the newly defined constants. ### Possible Implementation - Search the codebase for all instances where email subjects are hardcoded. Example: https://github.com/juspay/hyperswitch/blob/b2364414edab6d44e276f2133bc988610693f155/crates/router/src/core/user.rs#L707 - For each unique subject, create a new constant in `crates/router/src/consts/user.rs`. - Refactor the code by replacing the hardcoded subjects with their respective constants. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 9e70cb2b96b..728933a4614 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -86,6 +86,11 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day #[cfg(feature = "email")] pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_"; +pub const EMAIL_SUBJECT_API_KEY_EXPIRY: &str = "API Key Expiry Notice"; +pub const EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST: &str = "Dashboard Pro Feature Request by"; +pub const EMAIL_SUBJECT_APPROVAL_RECON_REQUEST: &str = + "Approval of Recon Request - Access Granted to Recon Dashboard"; + pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_"; #[cfg(feature = "olap")] diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 6ac2b08e6bb..5984a876503 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -26,3 +26,10 @@ pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes pub const REDIS_SSO_PREFIX: &str = "SSO_"; pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes + +/// Email subject +pub const EMAIL_SUBJECT_SIGNUP: &str = "Welcome to the Hyperswitch community!"; +pub const EMAIL_SUBJECT_INVITATION: &str = "You have been invited to join Hyperswitch Community!"; +pub const EMAIL_SUBJECT_MAGIC_LINK: &str = "Unlock Hyperswitch: Use Your Magic Link to Sign In"; +pub const EMAIL_SUBJECT_RESET_PASSWORD: &str = "Get back to Hyperswitch - Reset Your Password Now"; +pub const EMAIL_SUBJECT_NEW_PROD_INTENT: &str = "New Prod Intent"; diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index d5f824e0cce..ea3459709c6 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -39,7 +39,8 @@ pub async fn send_recon_request( .attach_printable("Failed to convert recipient's email to UserEmail")?, settings: state.conf.clone(), subject: format!( - "Dashboard Pro Feature Request by {}", + "{} {}", + consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST, user_email.expose().peek() ), }; @@ -145,7 +146,7 @@ pub async fn recon_merchant_account_update( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, settings: state.conf.clone(), - subject: "Approval of Recon Request - Access Granted to Recon Dashboard", + subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST, }; if req.recon_status == enums::ReconStatus::Active { diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index f36ecc18116..d5a9c143bea 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -75,7 +75,7 @@ pub async fn signup_with_merchant_id( recipient_email: user_from_db.get_email().try_into()?, user_name: domain::UserName::new(user_from_db.get_name())?, settings: state.conf.clone(), - subject: "Get back to Hyperswitch - Reset Your Password Now", + subject: consts::user::EMAIL_SUBJECT_RESET_PASSWORD, auth_id, }; @@ -204,7 +204,7 @@ pub async fn connect_account( recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), user_name: domain::UserName::new(user_from_db.get_name())?, - subject: "Unlock Hyperswitch: Use Your Magic Link to Sign In", + subject: consts::user::EMAIL_SUBJECT_MAGIC_LINK, auth_id, }; @@ -254,7 +254,7 @@ pub async fn connect_account( let email_contents = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), - subject: "Welcome to the Hyperswitch community!", + subject: consts::user::EMAIL_SUBJECT_SIGNUP, auth_id, }; @@ -374,7 +374,7 @@ pub async fn forgot_password( recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), user_name: domain::UserName::new(user_from_db.get_name())?, - subject: "Get back to Hyperswitch - Reset Your Password Now", + subject: consts::user::EMAIL_SUBJECT_RESET_PASSWORD, auth_id, }; @@ -702,7 +702,7 @@ async fn handle_existing_user_invitation( recipient_email: invitee_email, user_name: domain::UserName::new(invitee_user_from_db.get_name())?, settings: state.conf.clone(), - subject: "You have been invited to join Hyperswitch Community!", + subject: consts::user::EMAIL_SUBJECT_INVITATION, entity, auth_id: auth_id.clone(), }; @@ -823,7 +823,7 @@ async fn handle_new_user_invitation( recipient_email: invitee_email, user_name: domain::UserName::new(new_user.get_name())?, settings: state.conf.clone(), - subject: "You have been invited to join Hyperswitch Community!", + subject: consts::user::EMAIL_SUBJECT_INVITATION, entity, auth_id: auth_id.clone(), }; @@ -942,7 +942,7 @@ pub async fn resend_invite( recipient_email: invitee_email, user_name: domain::UserName::new(user.get_name())?, settings: state.conf.clone(), - subject: "You have been invited to join Hyperswitch Community!", + subject: consts::user::EMAIL_SUBJECT_INVITATION, entity: email_types::Entity { entity_id, entity_type, @@ -1823,7 +1823,7 @@ pub async fn send_verification_mail( let email_contents = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user.email)?, settings: state.conf.clone(), - subject: "Welcome to the Hyperswitch community!", + subject: consts::user::EMAIL_SUBJECT_SIGNUP, auth_id, }; diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 1c4ce79ac8c..cedd17828f1 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -417,7 +417,7 @@ impl BizEmailProd { state.conf.email.prod_intent_recipient_email.clone(), )?, settings: state.conf.clone(), - subject: "New Prod Intent", + subject: consts::user::EMAIL_SUBJECT_NEW_PROD_INTENT, user_name: data.poc_name.unwrap_or_default().into(), poc_email: data.poc_email.unwrap_or_default().into(), legal_business_name: data.legal_business_name.unwrap_or_default(), diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index b26e9862e81..c04e4c5d576 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -6,7 +6,7 @@ use router_env::{logger, metrics::add_attributes}; use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState}; use crate::{ - errors, + consts, errors, logger::error, routes::{metrics, SessionState}, services::email::types::ApiKeyExpiryReminder, @@ -81,7 +81,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { ); errors::ProcessTrackerError::EApiErrorResponse })?, - subject: "API Key Expiry Notice", + subject: consts::EMAIL_SUBJECT_API_KEY_EXPIRY, expires_in: *expires_in, api_key_name, prefix,
2024-09-26T11:47:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Change the hardcoded email subject to constants ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context refactor based on this issue - #5940 [link](https://github.com/juspay/hyperswitch/issues/5940) Closes #5940. ## How did you test it? This is an internal change for email subjects. There should be no affect. All email subjects like magic link, invite should be properly sent as before. [change_apply_before.txt](https://github.com/user-attachments/files/17147768/change_apply_before.txt) [change_apply_after.txt](https://github.com/user-attachments/files/17147771/change_apply_after.txt) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
05080259132fb12cdef40a999bd02b6fe2beeeaa
juspay/hyperswitch
juspay__hyperswitch-5934
Bug: feat(opensearch): restrict search view access based on user roles and permissions To fix the issue raised here: [https://github.com/juspay/hyperswitch-cloud/issues/6759](https://github.com/juspay/hyperswitch-cloud/issues/6759) - Currently, a profile level user is able to see the other profile payments list when using global-search, irrespective of whether he has permissions or not. But the user will not be able to view the details related to the payments upon clicking the particular payment. - This behaviour should be fixed by restricting the profiles / merchants to be searched based on the user roles associated with the role_id and the permissions associated with the user role - Now, only if the use role has the necessary READ permissions to access the indexes, he would be able to search the payments related to that particular profile/merchant. - The search_params should now be constructed with only those ProfileLevel / MerchantLevel / OrgLevel entities which will be searched through the opensearch query.
diff --git a/config/dashboard.toml b/config/dashboard.toml index 4cafdd49ab3..87c00721736 100644 --- a/config/dashboard.toml +++ b/config/dashboard.toml @@ -35,5 +35,6 @@ global_search=true dispute_analytics=true configure_pmts=false branding=false +user_management_revamp=true totp=true live_users_counter=false \ No newline at end of file diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 149c77212a0..3be9688d8f7 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -104,6 +104,8 @@ pub enum OpenSearchError { IndexAccessNotPermittedError(SearchIndex), #[error("Opensearch unknown error")] UnknownError, + #[error("Opensearch access forbidden error")] + AccessForbiddenError, } impl ErrorSwitch<OpenSearchError> for QueryBuildingError { @@ -159,6 +161,12 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError { Self::UnknownError => { ApiErrorResponse::InternalServerError(ApiError::new("IR", 6, "Unknown error", None)) } + Self::AccessForbiddenError => ApiErrorResponse::ForbiddenCommonResource(ApiError::new( + "IR", + 7, + "Access Forbidden error", + None, + )), } } } diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index a0b6606c227..89159bcff86 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1,6 +1,11 @@ pub use analytics::*; pub mod routes { + use std::{ + collections::{HashMap, HashSet}, + sync::Arc, + }; + use actix_web::{web, Responder, Scope}; use analytics::{ api_event::api_events_core, connector_events::connector_events_core, enums::AuthInfo, @@ -21,13 +26,13 @@ pub mod routes { GetSdkEventMetricRequest, ReportRequest, }; use common_enums::EntityType; - use common_utils::id_type::{MerchantId, OrganizationId}; use error_stack::{report, ResultExt}; + use futures::{stream::FuturesUnordered, StreamExt}; use crate::{ - consts::opensearch::OPENSEARCH_INDEX_PERMISSIONS, + consts::opensearch::SEARCH_INDEXES, core::{api_locking, errors::user::UserErrors, verification::utils}, - db::user::UserInterface, + db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload}, routes::AppState, services::{ api, @@ -35,7 +40,7 @@ pub mod routes { authorization::{permissions::Permission, roles::RoleInfo}, ApplicationResponse, }, - types::domain::UserEmail, + types::{domain::UserEmail, storage::UserRole}, }; pub struct Analytics; @@ -1838,25 +1843,89 @@ pub mod routes { .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)?; - let permissions = role_info.get_permissions_set(); - let accessible_indexes: Vec<_> = OPENSEARCH_INDEX_PERMISSIONS + let permission_groups = role_info.get_permission_groups(); + if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { + return Err(OpenSearchError::AccessForbiddenError)?; + } + let user_roles: HashSet<UserRole> = state + .store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &auth.user_id, + org_id: Some(&auth.org_id), + merchant_id: None, + profile_id: None, + entity_id: None, + version: None, + status: None, + limit: None, + }) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)? + .into_iter() + .collect(); + + let state = Arc::new(state); + let role_info_map: HashMap<String, RoleInfo> = user_roles .iter() - .filter(|(_, perm)| perm.iter().any(|p| permissions.contains(p))) - .map(|(i, _)| *i) + .map(|user_role| { + let state = Arc::clone(&state); + let role_id = user_role.role_id.clone(); + let org_id = user_role.org_id.clone().unwrap_or_default(); + async move { + RoleInfo::from_role_id_in_org_scope(&state, &role_id, &org_id) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError) + .map(|role_info| (role_id, role_info)) + } + }) + .collect::<FuturesUnordered<_>>() + .collect::<Vec<_>>() + .await + .into_iter() + .collect::<Result<HashMap<_, _>, _>>()?; + + let filtered_user_roles: Vec<&UserRole> = user_roles + .iter() + .filter(|user_role| { + let user_role_id = &user_role.role_id; + if let Some(role_info) = role_info_map.get(user_role_id) { + let permissions = role_info.get_permission_groups(); + permissions.contains(&common_enums::PermissionGroup::OperationsView) + } else { + false + } + }) .collect(); - let merchant_id: MerchantId = auth.merchant_id; - let org_id: OrganizationId = auth.org_id; - let search_params: Vec<AuthInfo> = vec![AuthInfo::MerchantLevel { - org_id: org_id.clone(), - merchant_ids: vec![merchant_id.clone()], - }]; + let search_params: Vec<AuthInfo> = filtered_user_roles + .iter() + .filter_map(|user_role| { + user_role + .get_entity_id_and_type() + .and_then(|(_, entity_type)| match entity_type { + EntityType::Profile => Some(AuthInfo::ProfileLevel { + org_id: user_role.org_id.clone()?, + merchant_id: user_role.merchant_id.clone()?, + profile_ids: vec![user_role.profile_id.clone()?], + }), + EntityType::Merchant => Some(AuthInfo::MerchantLevel { + org_id: user_role.org_id.clone()?, + merchant_ids: vec![user_role.merchant_id.clone()?], + }), + EntityType::Organization => Some(AuthInfo::OrgLevel { + org_id: user_role.org_id.clone()?, + }), + }) + }) + .collect(); analytics::search::msearch_results( &state.opensearch_client, req, search_params, - accessible_indexes, + SEARCH_INDEXES.to_vec(), ) .await .map(ApplicationResponse::Json) @@ -1898,20 +1967,82 @@ pub mod routes { .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError)?; - let permissions = role_info.get_permissions_set(); - let _ = OPENSEARCH_INDEX_PERMISSIONS + let permission_groups = role_info.get_permission_groups(); + if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { + return Err(OpenSearchError::AccessForbiddenError)?; + } + let user_roles: HashSet<UserRole> = state + .store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &auth.user_id, + org_id: Some(&auth.org_id), + merchant_id: None, + profile_id: None, + entity_id: None, + version: None, + status: None, + limit: None, + }) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)? + .into_iter() + .collect(); + let state = Arc::new(state); + let role_info_map: HashMap<String, RoleInfo> = user_roles .iter() - .filter(|(ind, _)| *ind == index) - .find(|i| i.1.iter().any(|p| permissions.contains(p))) - .ok_or(OpenSearchError::IndexAccessNotPermittedError(index))?; + .map(|user_role| { + let state = Arc::clone(&state); + let role_id = user_role.role_id.clone(); + let org_id = user_role.org_id.clone().unwrap_or_default(); + async move { + RoleInfo::from_role_id_in_org_scope(&state, &role_id, &org_id) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError) + .map(|role_info| (role_id, role_info)) + } + }) + .collect::<FuturesUnordered<_>>() + .collect::<Vec<_>>() + .await + .into_iter() + .collect::<Result<HashMap<_, _>, _>>()?; - let merchant_id: MerchantId = auth.merchant_id; - let org_id: OrganizationId = auth.org_id; - let search_params: Vec<AuthInfo> = vec![AuthInfo::MerchantLevel { - org_id: org_id.clone(), - merchant_ids: vec![merchant_id.clone()], - }]; + let filtered_user_roles: Vec<&UserRole> = user_roles + .iter() + .filter(|user_role| { + let user_role_id = &user_role.role_id; + if let Some(role_info) = role_info_map.get(user_role_id) { + let permissions = role_info.get_permission_groups(); + permissions.contains(&common_enums::PermissionGroup::OperationsView) + } else { + false + } + }) + .collect(); + let search_params: Vec<AuthInfo> = filtered_user_roles + .iter() + .filter_map(|user_role| { + user_role + .get_entity_id_and_type() + .and_then(|(_, entity_type)| match entity_type { + EntityType::Profile => Some(AuthInfo::ProfileLevel { + org_id: user_role.org_id.clone()?, + merchant_id: user_role.merchant_id.clone()?, + profile_ids: vec![user_role.profile_id.clone()?], + }), + EntityType::Merchant => Some(AuthInfo::MerchantLevel { + org_id: user_role.org_id.clone()?, + merchant_ids: vec![user_role.merchant_id.clone()?], + }), + EntityType::Organization => Some(AuthInfo::OrgLevel { + org_id: user_role.org_id.clone()?, + }), + }) + }) + .collect(); analytics::search::search_results(&state.opensearch_client, req, search_params) .await .map(ApplicationResponse::Json) diff --git a/crates/router/src/consts/opensearch.rs b/crates/router/src/consts/opensearch.rs index fc1c071439a..277b0e946ba 100644 --- a/crates/router/src/consts/opensearch.rs +++ b/crates/router/src/consts/opensearch.rs @@ -1,22 +1,12 @@ use api_models::analytics::search::SearchIndex; -use crate::services::authorization::permissions::Permission; - -pub const OPENSEARCH_INDEX_PERMISSIONS: &[(SearchIndex, &[Permission])] = &[ - ( +pub const fn get_search_indexes() -> [SearchIndex; 4] { + [ SearchIndex::PaymentAttempts, - &[Permission::PaymentRead, Permission::PaymentWrite], - ), - ( SearchIndex::PaymentIntents, - &[Permission::PaymentRead, Permission::PaymentWrite], - ), - ( SearchIndex::Refunds, - &[Permission::RefundRead, Permission::RefundWrite], - ), - ( SearchIndex::Disputes, - &[Permission::DisputeRead, Permission::DisputeWrite], - ), -]; + ] +} + +pub const SEARCH_INDEXES: [SearchIndex; 4] = get_search_indexes();
2024-09-18T06:53:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Fixes the issue raised here: [https://github.com/juspay/hyperswitch-cloud/issues/6759](https://github.com/juspay/hyperswitch-cloud/issues/6759) - Currently, a profile level user is able to see the other profile payments list when using global-search, irrespective of whether he has permissions or not. But the user will not be able to view the details related to the payments upon clicking the particular payment. - This PR fixes this behaviour by restricting the profiles / merchants to be searched based on the user roles associated with the role_id and the permissions associated with the user role - Now, only if the use role has the necessary READ permissions to access the indexes, he would be able to search the payments related to that particular profile/merchant. - The `search_params` will now be constructed with only those ProfileLevel / MerchantLevel / OrgLevel entities which will be searched through the opensearch query. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> To preserve confidentiality of the payment details ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Try to search payments of a profile from another profile which doesn't have access to the profile where the payments are present. Results should not show up while using global search. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e7da0474ec63c9953098ee808543e22e114291cf
juspay/hyperswitch
juspay__hyperswitch-5917
Bug: [FIX] Add Limit Parameter to User Role List for Org Function ### Feature Description Description: The function [generic_user_roles_list_for_org_and_extra](https://github.com/juspay/hyperswitch/blob/a94cf25bb6eb40fafc5327aceffac8292b47b001/crates/diesel_models/src/query/user_role.rs#L270) currently fetches all roles for a give organisation and additional parameters. To improve performance and allow better control over data retrieval, we need to add a limit parameter to restrict the number of results returned. ``` pub async fn generic_user_roles_list_for_org_and_extra( conn: &PgPooledConn, user_id: Option<String>, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, version: Option<UserRoleVersion>, ) -> StorageResult<Vec<Self>> ``` Task: - Modify the existing function generic_user_roles_list_for_org_and_extra to include an optional limit parameter (Option<u32>). - Pass this limit parameter down to the database query to restrict the number of user roles returned. - Ensure the limit parameter is optional, and when it's not provided, the function should return all results as it currently does. ### Possible Implementation - Add an additional parameter limit: `Option<type>` to the function signature of `generic_user_roles_list_for_org_and_extra` - Modify the query logic to apply the limit if it is provided. - Ensure the modified function still works with existing code that doesn't use the limit parameter. ( For older implementations, where this function is getting called, pass limit as `None` so that it doesn't change expected behaviour) Additional Context: This change is analogous to the `generic_user_roles_list_for_user` function, which already includes a limit parameter. You can refer to that function’s implementation for guidance. ### How to Test For testing, we can check where this `generic_user_roles_list_for_user` is used, currently this function is invoked from db function `list_user_roles_by_user_id` and this function is getting called from many core function, like `list_merchants_for_user_in_org` , `list_orgs_for_user`. We can hit `user/list/merchants` api to invoke this `list_merchants_for_user_in_org` core function: Signup: ``` curl --location 'http://localhost:8080/user/signup' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data-raw '{ "email": "email1@gmail.com", "password": "Pass@123" }' ``` Response: ``` { "token": "JWT", "token_type": "totp" } ``` We will get intermediate token for setting up 2FA, it is skippable: Skip 2FA, we will be getting a login token: ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \ --header 'Authorization: Bearer Intermediate_Token' ``` ``` { "token": "JWT", "token_type": "user_info" } ``` It depicts successful signup, default one merchant_id has been created. (Baisically one org, with one merchant and one profile) Now we can call `list/merchant`: ``` curl --location 'http://localhost:8080/user/list/merchant' \ --header 'Authorization: Bearer LOGIN_JWT' ``` Response: ``` [ { "merchant_id": "merchant_test" "merchant_name": null } ] ``` We can create more merchant accounts: ``` curl --location 'http://localhost:8080/user/create_merchant' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer LoginJWT' \ --data '{ "company_name": "hyperswitch" }' ``` And if we try got get list it now, it will show more merchant_ids in list. Limit parameter in the function that controls how much data we need for our use case, say, sometimes we only want to get first one from list, we can just pass limit one instead of fetching whole list. Acceptance Criteria: - The function should accept an optional limit parameter. - When a limit is provided, the number of results returned by the query should not exceed the limit. - Tests the behaviour with and without the limit parameter. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index 5ef09715211..2496d22447e 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -258,6 +258,7 @@ impl UserRole { merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, version: Option<UserRoleVersion>, + limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() .filter(dsl::org_id.eq(org_id)) @@ -279,6 +280,10 @@ impl UserRole { query = query.filter(dsl::version.eq(version)); } + if let Some(limit) = limit { + query = query.limit(limit.into()); + } + router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); match generics::db_metrics::track_database_call::<Self, _, _>( diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 2cd715ac357..1d188168e5c 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -614,6 +614,7 @@ pub async fn list_users_in_lineage( merchant_id: None, profile_id: None, version: None, + limit: None, }, request.entity_type, ) @@ -628,6 +629,7 @@ pub async fn list_users_in_lineage( merchant_id: Some(&user_from_token.merchant_id), profile_id: None, version: None, + limit: None, }, request.entity_type, ) @@ -646,6 +648,7 @@ pub async fn list_users_in_lineage( merchant_id: Some(&user_from_token.merchant_id), profile_id: Some(profile_id), version: None, + limit: None, }, request.entity_type, ) diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index b589d375975..1fa70afa73f 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -19,6 +19,7 @@ pub struct ListUserRolesByOrgIdPayload<'a> { pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, pub version: Option<enums::UserRoleVersion>, + pub limit: Option<u32>, } pub struct ListUserRolesByUserIdPayload<'a> { @@ -193,6 +194,7 @@ impl UserRoleInterface for Store { payload.merchant_id.cloned(), payload.profile_id.cloned(), payload.version, + payload.limit, ) .await .map_err(|error| report!(errors::StorageError::from(error)))
2024-10-01T16:00:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR adds the `limit` parameter to the `generic_user_roles_list_for_org_and_extra` function. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fixes #5917 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> When having 5a1d2b3633e4fc8862f61bed9b5810eac2a313cb in: ```shell curl 'http://localhost:8080/user/user/v2/list' \ -H 'authorization: Bearer JWT' \ ``` yields ``` [{"email":"email1@gmail.com","roles":[{"role_id":"org_admin","role_name":"organization_admin"}]}] ``` **Outdated** by 5a1d2b3633e4fc8862f61bed9b5810eac2a313cb: Both _queries_ ```shell curl 'http://localhost:8080/user/user/v2/list' \ -H 'authorization: Bearer JWT' \ ``` ```shell curl 'http://localhost:8080/user/user/v2/list?limit=10' \ -H 'authorization: Bearer JWT' \ ``` yield: ``` [{"email":"email1@gmail.com","roles":[{"role_id":"org_admin","role_name":"organization_admin"}]}] ``` The _query_ ```shell curl 'http://localhost:8080/user/user/v2/list?limit=0' \ -H 'authorization: Bearer JWT' \ ``` yields: ``` [] ``` The _query_ ```shell curl 'http://localhost:8080/user/user/v2/list?limit=-10' \ -H 'authorization: Bearer JWT' \ ``` errors with: ``` Query deserialize error: invalid digit found in string ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
19a8474d8731ed7149b541f02ad237e30c4c9f24
juspay/hyperswitch
juspay__hyperswitch-5913
Bug: [CYPRESS_FRAMEWORK] Re-use config update commands **Description:** Cypress is the testing framework that Hyperswitch uses to run automated tests. Having good grip on Javascript to work on Cypress is a must. Cypress makes use of custom [commands](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/commands.js) to make requests and parse responses instead of having the exchange put in a spec file. This increases the code redundancy. Custom commands are versatile that helps in reducing command duplication. These commands should be generic and should be capable of handling multiple requests of same / similar type. **The problem:** Currently, there exist `3` implementations that makes update config request for different purposes: - [autoRetryConfig](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/commands.js#L2229-L2255) - [setMaxAutoRetries](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/commands.js#L2257-L2282) - [stepUp](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/commands.js#L2312-L2334) These are called by [Retries](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js) tests under Routing specs. **Getting started:** Go through the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress. In short: ```sh cd cypress-tests npm ci ``` **Possible implementation:** Refactor config update `context`s in the spec file (for example: [Update max auto retries](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js#L102-L108), [Enable auto retries](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js#L46-L48), [Step up](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js#L482C10-L483C14)) and pass as all the necessary data into the new unified command in [commands](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/commands.js) **Additional info:** - Language: Javascript - Difficulty: Easy ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
2024-10-02T12:55:09Z
## Type of Change - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD This pull request resolves issue #5913 ## Description This PR refactors the existing Cypress commands used for configuration updates (autoRetryConfig, setMaxAutoRetries, and stepUp) into a single unified command cy.updateConfig. The refactor helps reduce redundancy in the codebase by consolidating multiple similar implementations into one versatile command that can handle configuration changes for auto retries, max retries, and step-up flows. ## Key Changes -Combined autoRetryConfig, setMaxAutoRetries, and stepUp into the cy.updateConfig command. -Updated the Retries.cy.js test cases to use the new unified command for disabling/enabling auto retries and step-up configurations. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context The refactor was necessary to reduce code duplication and improve maintainability. By creating a unified command, we ensure that future changes to configuration updates are centralized in one place, making the code easier to manage and extend. ## How did you test it? Tested manually and with cypress command. ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
19a8474d8731ed7149b541f02ad237e30c4c9f24
juspay/hyperswitch
juspay__hyperswitch-5915
Bug: [CYPRESS_FRAMEWORK] Verify URL after redirection **Description:** Cypress is the testing framework that Hyperswitch uses to run automated tests as it helps test both backend as well as frontend in a single shot that includes redirection flows like `3ds` and `bank redirect`. Redirection tests in Cypress at present do not validate the end URL. This can lead to unnecessary complication and false positives when running tests that involve redirection say, 3ds tests, bank redirect tests, bank transfer tests and etc., The task is to refactor the [verifyReturnUrl function](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/redirectionHandler.js#L397-L414) in [redirection handler](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/redirectionHandler.js) to validate the URL **Getting started:** Go through the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress. **Possible implementation:** - Refactor the [verifyReturnUrl](https://github.com/juspay/hyperswitch/blob/45c19a1729af3f4b80bde2661868cb213138df86/cypress-tests/cypress/support/redirectionHandler.js#L397-L414) function in [redirection handler](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/support/redirectionHandler.js) support file - Verify that `redirection_url` has status that equates to either succeeded or processing. Fail the test otherwise Example: Below is the `redirection_url` that has the terminal status of the payment after redirection. `verifyReturnUrl` function should parse `redirection_url` and validate the status. redirection_url: `https://duckduckgo.com/?payment_id=pay_K29MmxZKI9rDhhSY7sb8&status=succeeded` **Additional info:** - Language: Javascript - Difficulty: Easy ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
2024-10-01T10:33:37Z
## Type of Change - [ ] Bugfix - [ ] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD This pull request Resolve #5915 ## Description This PR refactors the verifyReturnUrl function to validate the redirection_url and ensure that the payment status is either succeeded or processing. If the status is invalid, the test will now fail, preventing false positives in redirection tests like 3DS or bank redirects. ###Key Changes: - Parse the redirection_url query string to extract the status parameter. - Validate the status against the allowed values (succeeded or processing). - Fail the test if the status is not one of the expected values. - Maintain the existing redirection validation process (e.g., origin matching). ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context This change improves the reliability of Cypress redirection tests by ensuring that the final redirection URL reflects a valid payment status, preventing false positives and ensuring tests behave as expected for flows like 3DS and bank redirects. ## How did you test it? Ran against Integ environment for Stripe: <img width="555" alt="image" src="https://github.com/user-attachments/assets/0dc3fb11-4f2c-4731-9f23-8a3a0dc9ab94" /> when the validation fails, below is the kind of error we get: <img width="551" alt="image" src="https://github.com/user-attachments/assets/e15418f2-ad97-4502-b342-a220c2d7fc7b" /> ## Checklist - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [x] I added unit tests for my changes where possible
d8d8c400bbda49b9a0cd5edbe37e929ae6d38eb4
juspay/hyperswitch
juspay__hyperswitch-5906
Bug: fix(user_roles): Profile level user_roles are not being updated Currently, updating a profile level user role causes update user role API to break and throw error. This is because profile_id from the token is not being populated in the DB calls. This makes the API unable to find the user role to be updated.
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 868d2e65a24..d42f71695a5 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -119,7 +119,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - None, + user_from_token.profile_id.as_ref(), UserRoleVersion::V2, ) .await @@ -165,7 +165,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - None, + user_from_token.profile_id.as_ref(), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id.clone(), @@ -184,7 +184,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - None, + user_from_token.profile_id.as_ref(), UserRoleVersion::V1, ) .await @@ -230,7 +230,7 @@ pub async fn update_user_role( user_to_be_updated.get_user_id(), &user_from_token.org_id, &user_from_token.merchant_id, - None, + user_from_token.profile_id.as_ref(), UserRoleUpdate::UpdateRole { role_id: req.role_id.clone(), modified_by: user_from_token.user_id,
2024-09-16T11:36:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Currently, profile level user_roles are not being updated. This PR fixes it. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5906. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl 'http://localhost:8080/user/user/update_role' \ -H 'authorization: Bearer JWT' \ --data-raw '{"email":"email","role_id":"profile_iam_admin"}' ``` Response: 200 OK. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
90ebd54ec9dfabf03ee85c0d0e7d96755a135083
juspay/hyperswitch
juspay__hyperswitch-5941
Bug: Update and Retrieve PM APIs ### Feature Description - Update Payment methods API - Retrieve Payment Method API
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 6c93b0bb5bd..1a82dc0e26b 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -374,7 +374,7 @@ pub struct PaymentMethodUpdate { #[serde(deny_unknown_fields)] pub struct PaymentMethodUpdate { /// payment method data to be passed - pub payment_method_data: Option<PaymentMethodUpdateData>, + pub payment_method_data: PaymentMethodUpdateData, /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] @@ -990,6 +990,27 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl From<CardDetail> for CardDetailFromLocker { + fn from(item: CardDetail) -> Self { + Self { + issuer_country: item.card_issuing_country, + last4_digits: Some(item.card_number.get_last4()), + card_number: Some(item.card_number), + expiry_month: Some(item.card_exp_month), + expiry_year: Some(item.card_exp_year), + card_holder_name: item.card_holder_name, + nick_name: item.nick_name, + card_isin: None, + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type.map(|card| card.to_string()), + saved_to_locker: true, + card_fingerprint: None, + } + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<CardDetail> for CardDetailsPaymentMethod { fn from(item: CardDetail) -> Self { diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 1f4fd00bbc5..9e70cb2b96b 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -144,6 +144,10 @@ pub const ADD_VAULT_REQUEST_URL: &str = "/vault/add"; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/fingerprint"; +/// Vault Retrieve request url +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/vault/retrieve"; + /// Vault Header content type #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json"; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index cb26494b70d..8841ad7f383 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -25,7 +25,7 @@ use common_utils::{consts::DEFAULT_LOCALE, id_type}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::{ crypto::{self, Encryptable}, - ext_traits::{AsyncExt, Encode, ValueExt}, + ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, fp_utils::when, generate_id, request::RequestContent, @@ -80,7 +80,7 @@ const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE"; const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS"; #[instrument(skip_all)] -pub async fn retrieve_payment_method( +pub async fn retrieve_payment_method_core( pm_data: &Option<domain::PaymentMethodData>, state: &SessionState, payment_intent: &PaymentIntent, @@ -877,16 +877,24 @@ pub async fn create_payment_method( .await .attach_printable("Failed to add Payment method to DB")?; - let vaulting_result = - vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await; + let payment_method_data = pm_types::PaymentMethodVaultingData::from(req.payment_method_data); + + let vaulting_result = vault_payment_method( + state, + &payment_method_data, + merchant_account, + key_store, + None, + ) + .await; let response = match vaulting_result { Ok(resp) => { let pm_update = create_pm_additional_data_update( - &req.payment_method_data, + &payment_method_data, state, key_store, - Some(resp.vault_id), + Some(resp.vault_id.get_string_repr().clone()), Some(req.payment_method), Some(req.payment_method_type), ) @@ -1041,16 +1049,24 @@ pub async fn payment_method_intent_confirm( .await .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - let vaulting_result = - vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await; + let payment_method_data = pm_types::PaymentMethodVaultingData::from(req.payment_method_data); + + let vaulting_result = vault_payment_method( + state, + &payment_method_data, + merchant_account, + key_store, + None, + ) + .await; let response = match vaulting_result { Ok(resp) => { let pm_update = create_pm_additional_data_update( - &req.payment_method_data, + &payment_method_data, state, key_store, - Some(resp.vault_id), + Some(resp.vault_id.get_string_repr().clone()), Some(req.payment_method), Some(req.payment_method_type), ) @@ -1220,15 +1236,17 @@ pub async fn create_payment_method_for_intent( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub async fn create_pm_additional_data_update( - pmd: &api::PaymentMethodCreateData, + pmd: &pm_types::PaymentMethodVaultingData, state: &SessionState, key_store: &domain::MerchantKeyStore, vault_id: Option<String>, payment_method: Option<api_enums::PaymentMethod>, payment_method_type: Option<api_enums::PaymentMethodType>, ) -> RouterResult<storage::PaymentMethodUpdate> { - let card = match pmd.clone() { - api::PaymentMethodCreateData::Card(card) => api::PaymentMethodsData::Card(card.into()), + let card = match pmd { + pm_types::PaymentMethodVaultingData::Card(card) => { + api::PaymentMethodsData::Card(card.clone().into()) + } }; let pmd: Encryptable<Secret<serde_json::Value>> = @@ -1255,15 +1273,17 @@ pub async fn create_pm_additional_data_update( #[instrument(skip_all)] pub async fn vault_payment_method( state: &SessionState, - pmd: &api::PaymentMethodCreateData, + pmd: &pm_types::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, + existing_vault_id: Option<String>, ) -> RouterResult<pm_types::AddVaultResponse> { let db = &*state.store; // get fingerprint_id from locker let fingerprint_id_from_locker = cards::get_fingerprint_id_from_locker(state, pmd) .await + .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get fingerprint_id from vault")?; // throw back error if payment method is duplicated @@ -1286,7 +1306,10 @@ pub async fn vault_payment_method( )?; let resp_from_locker = - cards::vault_payment_method_in_locker(state, merchant_account, pmd).await?; + cards::vault_payment_method_in_locker(state, merchant_account, pmd, existing_vault_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to vault payment method in locker")?; Ok(resp_from_locker) } @@ -1656,6 +1679,152 @@ async fn generate_saved_pm_response( Ok(pma) } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn retrieve_payment_method( + state: SessionState, + pm: api::PaymentMethodId, + key_store: domain::MerchantKeyStore, + merchant_account: domain::MerchantAccount, +) -> RouterResponse<api::PaymentMethodResponse> { + let db = state.store.as_ref(); + let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to generate GlobalPaymentMethodId")?; + + let payment_method = db + .find_payment_method( + &((&state).into()), + &key_store, + &pm_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let pmd = payment_method + .payment_method_data + .clone() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<api::PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + api::PaymentMethodsData::Card(card) => { + Some(api::PaymentMethodResponseData::Card(card.into())) + } + _ => None, + }); + + let resp = api::PaymentMethodResponse { + merchant_id: payment_method.merchant_id.to_owned(), + customer_id: payment_method.customer_id.to_owned(), + payment_method_id: payment_method.id.get_string_repr().to_string(), + payment_method: payment_method.payment_method, + payment_method_type: payment_method.payment_method_type, + metadata: payment_method.metadata.clone(), + created: Some(payment_method.created_at), + recurring_enabled: false, + last_used_at: Some(payment_method.last_used_at), + client_secret: payment_method.client_secret.clone(), + payment_method_data: pmd, + }; + + Ok(services::ApplicationResponse::Json(resp)) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn update_payment_method( + state: SessionState, + merchant_account: domain::MerchantAccount, + req: api::PaymentMethodUpdate, + payment_method_id: &str, + key_store: domain::MerchantKeyStore, +) -> RouterResponse<api::PaymentMethodResponse> { + let db = state.store.as_ref(); + + let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(payment_method_id.to_string()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to generate GlobalPaymentMethodId")?; + + let payment_method = db + .find_payment_method( + &((&state).into()), + &key_store, + &pm_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + let current_vault_id = payment_method.locker_id.clone(); + + when( + payment_method.status == enums::PaymentMethodStatus::AwaitingData, + || { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: "This Payment method is awaiting data and hence cannot be updated" + .to_string(), + }) + }, + )?; + + let pmd: pm_types::PaymentMethodVaultingData = cards::retrieve_payment_method_from_vault( + &state, + &merchant_account, + &payment_method.customer_id, + &payment_method, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve payment method from vault")? + .data + .expose() + .parse_struct("PaymentMethodCreateData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse PaymentMethodCreateData")?; + + let vault_request_data = + pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, req.payment_method_data); + + let vaulting_response = vault_payment_method( + &state, + &vault_request_data, + &merchant_account, + &key_store, + current_vault_id, // using current vault_id for now, will have to refactor this + ) // to generate new one on each vaulting later on + .await + .attach_printable("Failed to add payment method in vault")?; + + let pm_update = create_pm_additional_data_update( + &vault_request_data, + &state, + &key_store, + Some(vaulting_response.vault_id.get_string_repr().clone()), + payment_method.payment_method, + payment_method.payment_method_type, + ) + .await + .attach_printable("Unable to create Payment method data")?; + + let payment_method = db + .update_payment_method( + &((&state).into()), + &key_store, + payment_method, + pm_update, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment method in db")?; + + let response = pm_transforms::generate_payment_method_response(&payment_method)?; + + // Add a PT task to handle payment_method delete from vault + + Ok(services::ApplicationResponse::Json(response)) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl pm_types::SavedPMLPaymentsInfo { pub async fn form_payments_info( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index a7ae7f9ca50..578655a927d 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1418,26 +1418,26 @@ pub async fn get_fingerprint_id_from_locker< >( state: &routes::SessionState, data: &D, -) -> errors::RouterResult<String> { +) -> errors::CustomResult<String, errors::VaultError> { let key = data.get_vaulting_data_key(); let data = serde_json::to_value(data) - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode Vaulting data to value")? .to_string(); let payload = pm_types::VaultFingerprintRequest { key, data } .encode_to_vec() - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode VaultFingerprintRequest")?; let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::VaultAPIError) .attach_printable("Failed to get response from locker")?; let fingerprint_resp: pm_types::VaultFingerprintResponse = resp .parse_struct("VaultFingerprintResp") - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into VaultFingerprintResp")?; Ok(fingerprint_resp.fingerprint_id) @@ -1448,31 +1448,70 @@ pub async fn get_fingerprint_id_from_locker< pub async fn vault_payment_method_in_locker( state: &routes::SessionState, merchant_account: &domain::MerchantAccount, - pmd: &api::PaymentMethodCreateData, -) -> errors::RouterResult<pm_types::AddVaultResponse> { + pmd: &pm_types::PaymentMethodVaultingData, + existing_vault_id: Option<String>, +) -> errors::CustomResult<pm_types::AddVaultResponse, errors::VaultError> { let payload = pm_types::AddVaultRequest { entity_id: merchant_account.get_id().to_owned(), - vault_id: uuid::Uuid::now_v7().to_string(), - data: pmd.clone(), + vault_id: pm_types::VaultId::generate( + existing_vault_id.unwrap_or(uuid::Uuid::now_v7().to_string()), + ), + data: pmd, ttl: state.conf.locker.ttl_for_storage_in_secs, } .encode_to_vec() - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::RequestEncodingFailed) .attach_printable("Failed to encode AddVaultRequest")?; let resp = call_to_vault::<pm_types::AddVault>(state, payload) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::VaultAPIError) .attach_printable("Failed to get response from locker")?; let stored_pm_resp: pm_types::AddVaultResponse = resp .parse_struct("AddVaultResponse") - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::ResponseDeserializationFailed) .attach_printable("Failed to parse data into AddVaultResponse")?; Ok(stored_pm_resp) } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn retrieve_payment_method_from_vault( + state: &routes::SessionState, + merchant_account: &domain::MerchantAccount, + customer_id: &id_type::CustomerId, + pm: &domain::PaymentMethod, +) -> errors::CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> { + let payload = pm_types::VaultRetrieveRequest { + entity_id: merchant_account.get_id().to_owned(), + vault_id: pm_types::VaultId::generate( + pm.locker_id + .clone() + .ok_or(errors::VaultError::MissingRequiredField { + field_name: "locker_id", + }) + .attach_printable("Missing locker_id for VaultRetrieveRequest")?, + ), + } + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode VaultRetrieveRequest")?; + + let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) + .await + .change_context(errors::VaultError::VaultAPIError) + .attach_printable("Failed to get response from locker")?; + + let stored_pm_resp: pm_types::VaultRetrieveResponse = resp + .parse_struct("VaultRetrieveResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to parse data into VaultRetrieveResponse")?; + + Ok(stored_pm_resp) +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -1783,18 +1822,6 @@ pub async fn update_customer_payment_method( } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn update_customer_payment_method( - _state: routes::SessionState, - _merchant_account: domain::MerchantAccount, - _req: api::PaymentMethodUpdate, - _payment_method_id: &str, - _key_store: domain::MerchantKeyStore, -) -> errors::RouterResponse<api::PaymentMethodResponse> { - todo!() -} - #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -5378,17 +5405,6 @@ pub async fn retrieve_payment_method( )) } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn retrieve_payment_method( - state: routes::SessionState, - pm: api::PaymentMethodId, - key_store: domain::MerchantKeyStore, - merchant_account: domain::MerchantAccount, -) -> errors::RouterResponse<api::PaymentMethodResponse> { - todo!() -} - #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index ab21add60a8..78770c34579 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -15,6 +15,8 @@ use josekit::jwe; use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use crate::types::payment_methods as pm_types; use crate::{ configs::settings, core::errors::{self, CustomResult}, @@ -520,6 +522,29 @@ pub fn mk_add_card_response_hs( todo!() } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub fn generate_pm_vaulting_req_from_update_request( + pm_create: pm_types::PaymentMethodVaultingData, + pm_update: api::PaymentMethodUpdateData, +) -> pm_types::PaymentMethodVaultingData { + match (pm_create, pm_update) { + ( + pm_types::PaymentMethodVaultingData::Card(card_create), + api::PaymentMethodUpdateData::Card(update_card), + ) => pm_types::PaymentMethodVaultingData::Card(api::CardDetail { + card_number: card_create.card_number, + card_exp_month: card_create.card_exp_month, + card_exp_year: card_create.card_exp_year, + card_issuing_country: card_create.card_issuing_country, + card_network: card_create.card_network, + card_issuer: card_create.card_issuer, + card_type: card_create.card_type, + card_holder_name: update_card.card_holder_name, + nick_name: update_card.nick_name, + }), + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn generate_payment_method_response( pm: &domain::PaymentMethod, @@ -798,6 +823,15 @@ pub fn get_card_detail( Ok(card_detail) } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl From<api::PaymentMethodCreateData> for pm_types::PaymentMethodVaultingData { + fn from(item: api::PaymentMethodCreateData) -> Self { + match item { + api::PaymentMethodCreateData::Card(card) => Self::Card(card), + } + } +} + //------------------------------------------------TokenizeService------------------------------------------------ pub fn mk_crud_locker_request( locker: &settings::Locker, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 23ac67c910d..4e484bda6c4 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2226,15 +2226,16 @@ pub async fn make_pm_data<'a, F: Clone, R, D>( } (Some(_), _) => { - let (payment_method_data, payment_token) = payment_methods::retrieve_payment_method( - &request, - state, - &payment_data.payment_intent, - &payment_data.payment_attempt, - merchant_key_store, - Some(business_profile), - ) - .await?; + let (payment_method_data, payment_token) = + payment_methods::retrieve_payment_method_core( + &request, + state, + &payment_data.payment_intent, + &payment_data.payment_attempt, + merchant_key_store, + Some(business_profile), + ) + .await?; payment_data.token = payment_token; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 9ff768c56fb..d5f73921a9d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1087,7 +1087,12 @@ impl PaymentMethods { .service( web::resource("/{id}/confirm-intent") .route(web::post().to(confirm_payment_method_intent_api)), - ); + ) + .service( + web::resource("/{id}/update_saved_payment_method") + .route(web::patch().to(payment_method_update_api)), + ) + .service(web::resource("/{id}").route(web::get().to(payment_method_retrieve_api))); route } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 725d6af81af..3e3aada154f 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -15,7 +15,7 @@ use super::app::{AppState, SessionState}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::core::payment_methods::{ create_payment_method, list_customer_payment_method_util, payment_method_intent_confirm, - payment_method_intent_create, + payment_method_intent_create, retrieve_payment_method, update_payment_method, }; use crate::{ core::{ @@ -180,6 +180,65 @@ pub async fn confirm_payment_method_intent_api( .await } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))] +pub async fn payment_method_update_api( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, + json_payload: web::Json<payment_methods::PaymentMethodUpdate>, +) -> HttpResponse { + let flow = Flow::PaymentMethodsUpdate; + let payment_method_id = path.into_inner(); + let payload = json_payload.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, req, _| { + update_payment_method( + state, + auth.merchant_account, + req, + &payment_method_id, + auth.key_store, + ) + }, + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))] +pub async fn payment_method_retrieve_api( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> HttpResponse { + let flow = Flow::PaymentMethodsRetrieve; + let payload = web::Json(PaymentMethodId { + payment_method_id: path.into_inner(), + }) + .into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, pm, _| { + retrieve_payment_method(state, pm, auth.key_store, auth.merchant_account) + }, + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] pub async fn migrate_payment_method_api( state: web::Data<AppState>, @@ -667,6 +726,10 @@ pub async fn render_pm_collect_link( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsRetrieve))] pub async fn payment_method_retrieve_api( state: web::Data<AppState>, @@ -693,6 +756,10 @@ pub async fn payment_method_retrieve_api( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsUpdate))] pub async fn payment_method_update_api( state: web::Data<AppState>, diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 28d387771b5..d66bf079d42 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -8,8 +8,8 @@ pub use api_models::payment_methods::{ PaymentMethodIntentConfirm, PaymentMethodIntentConfirmInternal, PaymentMethodIntentCreate, PaymentMethodList, PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate, - PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, - TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + PaymentMethodUpdateData, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, + TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, }; #[cfg(all( any(feature = "v2", feature = "v1"), diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index e55516fc3af..a1c0f8156fa 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -1,5 +1,7 @@ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::generate_id; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use masking::Secret; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::{ @@ -19,6 +21,21 @@ pub trait VaultingDataInterface { fn get_vaulting_data_key(&self) -> String; } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VaultId(String); + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl VaultId { + pub fn get_string_repr(&self) -> &String { + &self.0 + } + + pub fn generate(id: String) -> Self { + Self(id) + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultFingerprintRequest { @@ -36,7 +53,7 @@ pub struct VaultFingerprintResponse { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultRequest<D> { pub entity_id: common_utils::id_type::MerchantId, - pub vault_id: String, + pub vault_id: VaultId, pub data: D, pub ttl: i64, } @@ -45,7 +62,7 @@ pub struct AddVaultRequest<D> { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultResponse { pub entity_id: common_utils::id_type::MerchantId, - pub vault_id: String, + pub vault_id: VaultId, pub fingerprint_id: Option<String>, } @@ -57,6 +74,10 @@ pub struct AddVault; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetVaultFingerprint; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VaultRetrieve; + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[async_trait::async_trait] impl VaultingInterface for AddVault { @@ -75,7 +96,21 @@ impl VaultingInterface for GetVaultFingerprint { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[async_trait::async_trait] -impl VaultingDataInterface for api::PaymentMethodCreateData { +impl VaultingInterface for VaultRetrieve { + fn get_vaulting_request_url() -> &'static str { + consts::VAULT_RETRIEVE_REQUEST_URL + } +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub enum PaymentMethodVaultingData { + Card(api::CardDetail), +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[async_trait::async_trait] +impl VaultingDataInterface for PaymentMethodVaultingData { fn get_vaulting_data_key(&self) -> String { match &self { Self::Card(card) => card.card_number.to_string(), @@ -101,3 +136,16 @@ pub struct SavedPMLPaymentsInfo { pub off_session_payment_flag: bool, pub is_connector_agnostic_mit_enabled: bool, } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VaultRetrieveRequest { + pub entity_id: common_utils::id_type::MerchantId, + pub vault_id: VaultId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VaultRetrieveResponse { + pub data: Secret<String>, +}
2024-09-18T08:09:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Update PM API for v2 - Retrieve PM API for v2 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Vault dev is incomplete so cannot be tested. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4eec6ca4b05202dea1f5400007c5f143142b65e4
juspay/hyperswitch
juspay__hyperswitch-5898
Bug: feat(disputes): add support for disputes aggregate 1. Support for disputes aggregate 2. Support for disputes aggregate in profile level
diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rs index 5c2a2cc03d2..a1340b5aa5a 100644 --- a/crates/api_models/src/disputes.rs +++ b/crates/api_models/src/disputes.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use masking::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; @@ -208,3 +210,9 @@ pub struct DeleteEvidenceRequest { /// Evidence Type to be deleted pub evidence_type: EvidenceType, } + +#[derive(Clone, Debug, serde::Serialize)] +pub struct DisputesAggregateResponse { + /// Different status of disputes with their count + pub status_with_count: HashMap<DisputeStatus, i64>, +} diff --git a/crates/api_models/src/events/dispute.rs b/crates/api_models/src/events/dispute.rs index 1ea6f4e8552..57f91330cc9 100644 --- a/crates/api_models/src/events/dispute.rs +++ b/crates/api_models/src/events/dispute.rs @@ -1,7 +1,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use super::{ - DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve, SubmitEvidenceRequest, + DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve, + DisputesAggregateResponse, SubmitEvidenceRequest, }; impl ApiEventMetric for SubmitEvidenceRequest { @@ -32,3 +33,9 @@ impl ApiEventMetric for DeleteEvidenceRequest { }) } } + +impl ApiEventMetric for DisputesAggregateResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::ResourceListAPI) + } +} diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 10c9dae2cc1..691b683aa3e 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1832,6 +1832,7 @@ pub enum DisputeStage { serde::Serialize, strum::Display, strum::EnumString, + strum::EnumIter, ToSchema, )] #[router_derive::diesel_enum(storage_type = "db_enum")] diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs index 8835f5f95a8..ff5936fc296 100644 --- a/crates/router/src/core/disputes.rs +++ b/crates/router/src/core/disputes.rs @@ -3,6 +3,9 @@ use common_utils::ext_traits::{Encode, ValueExt}; use error_stack::ResultExt; use router_env::{instrument, tracing}; pub mod transformers; +use std::collections::HashMap; + +use strum::IntoEnumIterator; use super::{ errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt}, @@ -507,3 +510,31 @@ pub async fn delete_evidence( })?; Ok(services::ApplicationResponse::StatusOk) } + +#[instrument(skip(state))] +pub async fn get_aggregates_for_disputes( + state: SessionState, + merchant: domain::MerchantAccount, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, + time_range: api::TimeRange, +) -> RouterResponse<dispute_models::DisputesAggregateResponse> { + let db = state.store.as_ref(); + let dispute_status_with_count = db + .get_dispute_status_with_count(merchant.get_id(), profile_id_list, &time_range) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to retrieve disputes aggregate")?; + + let mut status_map: HashMap<storage_enums::DisputeStatus, i64> = + dispute_status_with_count.into_iter().collect(); + + for status in storage_enums::DisputeStatus::iter() { + status_map.entry(status).or_default(); + } + + Ok(services::ApplicationResponse::Json( + dispute_models::DisputesAggregateResponse { + status_with_count: status_map, + }, + )) +} diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index abe469dc32a..1d45cfd405f 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use error_stack::report; use router_env::{instrument, tracing}; @@ -45,6 +47,13 @@ pub trait DisputeInterface { this: storage::Dispute, dispute: storage::DisputeUpdate, ) -> CustomResult<storage::Dispute, errors::StorageError>; + + async fn get_dispute_status_with_count( + &self, + merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>; } #[async_trait::async_trait] @@ -126,6 +135,24 @@ impl DisputeInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) } + + #[instrument(skip_all)] + async fn get_dispute_status_with_count( + &self, + merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Dispute::get_dispute_status_with_count( + &conn, + merchant_id, + profile_id_list, + time_range, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } } #[async_trait::async_trait] @@ -358,6 +385,50 @@ impl DisputeInterface for MockDb { Ok(dispute_to_update.clone()) } + + async fn get_dispute_status_with_count( + &self, + merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { + let locked_disputes = self.disputes.lock().await; + + let filtered_disputes_data = locked_disputes + .iter() + .filter(|d| { + d.merchant_id == *merchant_id + && d.created_at >= time_range.start_time + && time_range + .end_time + .as_ref() + .map(|received_end_time| received_end_time >= &d.created_at) + .unwrap_or(true) + && profile_id_list + .as_ref() + .zip(d.profile_id.as_ref()) + .map(|(received_profile_list, received_profile_id)| { + received_profile_list.contains(received_profile_id) + }) + .unwrap_or(true) + }) + .cloned() + .collect::<Vec<storage::Dispute>>(); + + Ok(filtered_disputes_data + .into_iter() + .fold( + HashMap::new(), + |mut acc: HashMap<common_enums::DisputeStatus, i64>, value| { + acc.entry(value.dispute_status) + .and_modify(|value| *value += 1) + .or_insert(1); + acc + }, + ) + .into_iter() + .collect::<Vec<(common_enums::DisputeStatus, i64)>>()) + } } #[cfg(test)] diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 6c620c4fcdc..3a473891feb 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -629,6 +629,17 @@ impl DisputeInterface for KafkaStore { .find_disputes_by_merchant_id_payment_id(merchant_id, payment_id) .await } + + async fn get_dispute_status_with_count( + &self, + merchant_id: &id_type::MerchantId, + profile_id_list: Option<Vec<id_type::ProfileId>>, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> { + self.diesel_store + .get_dispute_status_with_count(merchant_id, profile_id_list, time_range) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index da1a50b82ee..b0fd1091296 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1463,6 +1463,13 @@ impl Disputes { web::resource("/accept/{dispute_id}") .route(web::post().to(disputes::accept_dispute)), ) + .service( + web::resource("/aggregate").route(web::get().to(disputes::get_disputes_aggregate)), + ) + .service( + web::resource("/profile/aggregate") + .route(web::get().to(disputes::get_disputes_aggregate_profile)), + ) .service( web::resource("/evidence") .route(web::post().to(disputes::submit_dispute_evidence)) diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index 98ba33a64b4..5d8f7120f40 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -11,7 +11,7 @@ use super::app::AppState; use crate::{ core::disputes, services::{api, authentication as auth}, - types::api::disputes as dispute_types, + types::api::{disputes as dispute_types, payments::TimeRange}, }; /// Disputes - Retrieve Dispute @@ -408,3 +408,68 @@ pub async fn delete_dispute_evidence( )) .await } + +#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))] +pub async fn get_disputes_aggregate( + state: web::Data<AppState>, + req: HttpRequest, + query_param: web::Query<TimeRange>, +) -> HttpResponse { + let flow = Flow::DisputesAggregate; + let query_param = query_param.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + query_param, + |state, auth, req, _| { + disputes::get_aggregates_for_disputes(state, auth.merchant_account, None, req) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuth { + permission: Permission::DisputeRead, + minimum_entity_level: EntityType::Merchant, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[instrument(skip_all, fields(flow = ?Flow::DisputesAggregate))] +pub async fn get_disputes_aggregate_profile( + state: web::Data<AppState>, + req: HttpRequest, + query_param: web::Query<TimeRange>, +) -> HttpResponse { + let flow = Flow::DisputesAggregate; + let query_param = query_param.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + query_param, + |state, auth, req, _| { + disputes::get_aggregates_for_disputes( + state, + auth.merchant_account, + auth.profile_id.map(|profile_id| vec![profile_id]), + req, + ) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuth { + permission: Permission::DisputeRead, + minimum_entity_level: EntityType::Profile, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index e63b00cd9bf..774e6c75bb4 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -175,6 +175,7 @@ impl From<Flow> for ApiIdentifier { | Flow::DisputesEvidenceSubmit | Flow::AttachDisputeEvidence | Flow::RetrieveDisputeEvidence + | Flow::DisputesAggregate | Flow::DeleteDisputeEvidence => Self::Disputes, Flow::CardsInfo => Self::CardsInfo, diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs index 2728b29bc07..79b9a90343e 100644 --- a/crates/router/src/types/storage/dispute.rs +++ b/crates/router/src/types/storage/dispute.rs @@ -14,6 +14,13 @@ pub trait DisputeDbExt: Sized { merchant_id: &common_utils::id_type::MerchantId, dispute_list_constraints: api_models::disputes::DisputeListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError>; + + async fn get_dispute_status_with_count( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>; } #[async_trait::async_trait] @@ -72,4 +79,38 @@ impl DisputeDbExt for Dispute { .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering records by predicate") } + + async fn get_dispute_status_with_count( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> { + let mut query = <Self as HasTable>::table() + .group_by(dsl::dispute_status) + .select((dsl::dispute_status, diesel::dsl::count_star())) + .filter(dsl::merchant_id.eq(merchant_id.to_owned())) + .into_boxed(); + + if let Some(profile_id) = profile_id_list { + query = query.filter(dsl::profile_id.eq_any(profile_id)); + } + + query = query.filter(dsl::created_at.ge(time_range.start_time)); + + query = match time_range.end_time { + Some(ending_at) => query.filter(dsl::created_at.le(ending_at)), + None => query, + }; + + logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); + + db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( + query.get_results_async::<(common_enums::DisputeStatus, i64)>(conn), + db_metrics::DatabaseOperation::Count, + ) + .await + .change_context(errors::DatabaseError::NotFound) + .attach_printable_lazy(|| "Error filtering records by predicate") + } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index d815325a814..310f5ccecbf 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -290,6 +290,8 @@ pub enum Flow { AttachDisputeEvidence, /// Delete Dispute Evidence flow DeleteDisputeEvidence, + /// Disputes aggregate flow + DisputesAggregate, /// Retrieve Dispute Evidence flow RetrieveDisputeEvidence, /// Invalidate cache flow
2024-09-16T09:50:34Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add support for disputes aggregate - Add support for profile level disputes aggregate - For now it will have list of intent status along with the their count for a given time range. ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5898 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> **Dispute Aggregate** Request: ``` curl --location 'http://localhost:8080/disputes/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \ --header 'Authorization: Bearer JWT' \ --data '' ``` Response : ``` { "status_with_count": { "dispute_cancelled": 0, "dispute_expired": 3, "dispute_lost": 2, "dispute_opened": 0, "dispute_accepted": 0, "dispute_challenged": 0, "dispute_won": 0 } } ``` **Profile level Dispute aggregate** Request ``` curl --location 'http://localhost:8080/disputes/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \ --header 'Authorization: Bearer JWT' \ --data '' ``` Response ``` { "status_with_count": { "dispute_lost": 2, "dispute_accepted": 0, "dispute_opened": 0, "dispute_challenged": 0, "dispute_expired": 3, "dispute_cancelled": 0, "dispute_won": 0 } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
90ebd54ec9dfabf03ee85c0d0e7d96755a135083
juspay/hyperswitch
juspay__hyperswitch-5914
Bug: [CYPRESS_FRAMEWORK] Run Cypress tests in parallel **Description:** Cypress tests are resource intensive and consume a lot of memory and power. But that should not stop us from running them in parallel even if they consume a lot of resources. At present, Cypress tests here at Hyperswitch is run in sequential and consumes a lot of time given that each connector consumes at least 10+ mins and we've 10+ connector to run tests for. With that said, the task is to parallelize the tests that are run and with that said, the consumption can be reduced drastically (1+ hour(s) to mere 15 mins). > [!IMPORTANT] > **Cypress cloud is a no go** Below is the shell script that runs helps run the test in both sequential and parallel ways: ```sh #!/bin/bash CONNECTORS=("adyen" "bankofamerica" "bluesnap" "cybersource" "iatapay" "nmi" "paypal" "stripe" "trustpay") # Function to run tests run_tests() { mkdir -p results local pids=() for connector in "${CONNECTORS[@]}"; do if [[ $parallel == true ]]; then CYPRESS_CONNECTOR="${connector}" npm run cypress:ci > results/${connector}.txt 2>&1 & pids+=($!) else printf "\rRunning Cypress tests against the connector: ${connector}" CYPRESS_CONNECTOR="${connector}" npm run cypress:ci > results/${connector}.txt 2>&1 local exit_code=$? if [[ $exit_code -ne 0 && $exit_code -ge 128 ]]; then exit 1 fi sleep 3 fi done if [[ $parallel == true ]]; then for pid in "${pids[@]}"; do wait $pid done fi } # Check if running in parallel if [[ "${1}" == "--parallel" ]]; then printf "WARNING: Parallel tests are flaky and may not work as expected.\n" eval run_tests true else eval run_tests false fi ``` To execute the script: ```sh # to run tests sequentially, which can take an hour+ sh run-cypress.sh # to run tests in parallel, consumes around 15 - 20 mins, at the cost of resources sh run-cypress.sh --parallel ``` **Getting started:** Go through the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress. In short: ```sh cd cypress-tests npm ci ``` **Possible implementation:** - Shell script above is attached for reference - Make use of `gnu-parallel` to reduce the complexity of the script. The advantage here is that, it also make the script more future proof, manageable, easier to read and understand - As a bonus, the same functionality can be implemented in JavaScript directly into Cypress via its configs is a plus >[!WARNING] > **Make sure that before this task is picked, the machine is capable enough to run at least 2 connector tests in parallel**. Running Cypress tests in parallel is too resource intensive! > Please go through the Cypress [docs](https://docs.cypress.io/guides/getting-started/installing-cypress#CPU) to learn whether you're machine meets minimum requirements.
diff --git a/scripts/execute_cypress.sh b/scripts/execute_cypress.sh new file mode 100755 index 00000000000..1f1219ee717 --- /dev/null +++ b/scripts/execute_cypress.sh @@ -0,0 +1,188 @@ +#! /usr/bin/env bash + +set -euo pipefail + +# Initialize tmp_file globally +tmp_file="" + +# Define arrays for services, etc. +# Read service arrays from environment variables +read -r -a payments <<< "${PAYMENTS_CONNECTORS[@]:-}" +read -r -a payouts <<< "${PAYOUTS_CONNECTORS[@]:-}" +read -r -a payment_method_list <<< "${PAYMENT_METHOD_LIST[@]:-}" +read -r -a routing <<< "${ROUTING[@]:-}" + +# Define arrays +connector_map=() +failed_connectors=() + +# Define an associative array to map environment variables to service names +declare -A services=( + ["PAYMENTS_CONNECTORS"]="payments" + ["PAYOUTS_CONNECTORS"]="payouts" + ["PAYMENT_METHOD_LIST"]="payment_method_list" + ["ROUTING"]="routing" +) + +# Function to print messages in color +function print_color() { + # Input params + local color="$1" + local message="$2" + + # Define colors + local reset='\033[0m' + local red='\033[0;31m' + local green='\033[0;32m' + local yellow='\033[0;33m' + + # Use indirect reference to get the color value + echo -e "${!color}${message}${reset}" +} +export -f print_color + +# Function to check if a command exists +function command_exists() { + command -v "$1" > /dev/null 2>&1 +} + +# Function to read service arrays from environment variables +function read_service_arrays() { + # Loop through the associative array and check if each service is exported + for var in "${!services[@]}"; do + if [[ -n "${!var+x}" ]]; then + connector_map+=("${services[$var]}") + else + print_color "yellow" "Environment variable ${var} is not set. Skipping..." + fi + done +} + +# Function to execute Cypress tests +function execute_test() { + if [[ $# -lt 3 ]]; then + print_color "red" "ERROR: Insufficient arguments provided to execute_test." + exit 1 + fi + + local connector="$1" + local service="$2" + local tmp_file="$3" + + print_color "yellow" "Executing tests for ${service} with connector ${connector}..." + + export REPORT_NAME="${service}_${connector}_report" + + if ! CYPRESS_CONNECTOR="$connector" npm run "cypress:$service"; then + echo "${service}-${connector}" >> "${tmp_file}" + fi +} +export -f execute_test + +# Function to run tests +function run_tests() { + local jobs="${1:-1}" + tmp_file=$(mktemp) + + # Ensure temporary file is removed on script exit + trap 'cleanup' EXIT + + for service in "${connector_map[@]}"; do + declare -n connectors="$service" + + if [[ ${#connectors[@]} -eq 0 ]]; then + # Service-level test (e.g., payment-method-list or routing) + [[ $service == "payment_method_list" ]] && service="payment-method-list" + + echo "Running ${service} tests without connectors..." + export REPORT_NAME="${service}_report" + + if ! npm run "cypress:${service}"; then + echo "${service}" >> "${tmp_file}" + fi + else + # Connector-specific tests (e.g., payments or payouts) + print_color "yellow" "Running tests for service: '${service}' with connectors: [${connectors[*]}] in batches of ${jobs}..." + + # Execute tests in parallel + printf '%s\n' "${connectors[@]}" | parallel --jobs "${jobs}" execute_test {} "${service}" "${tmp_file}" + fi + done + + # Collect failed connectors + if [[ -s "${tmp_file}" ]]; then + failed_connectors=($(< "${tmp_file}")) + print_color "red" "One or more connectors failed to run:" + printf '%s\n' "${failed_connectors[@]}" + exit 1 + else + print_color "green" "Cypress tests execution successful!" + fi +} + +# Function to check and install dependencies +function check_dependencies() { + # parallel and npm are mandatory dependencies. exit the script if not found. + local dependencies=("parallel" "npm") + + for cmd in "${dependencies[@]}"; do + if ! command_exists "$cmd"; then + print_color "red" "ERROR: ${cmd^} is not installed!" + exit 1 + else + print_color "green" "${cmd^} is installed already!" + + if [[ ${cmd} == "npm" ]]; then + npm ci || { + print_color "red" "Command \`npm ci\` failed!" + exit 1 + } + fi + fi + done +} + +# Cleanup function to handle exit +function cleanup() { + print_color "yellow" "Cleaning up..." + if [[ -d "cypress-tests" ]]; then + cd - + fi + + if [[ -n "${tmp_file}" && -f "${tmp_file}" ]]; then + rm -f "${tmp_file}" + fi +} + +# Main function +function main() { + local command="${1:-}" + local jobs="${2:-5}" + + # Ensure script runs from 'cypress-tests' directory + if [[ "$(basename "$PWD")" != "cypress-tests" ]]; then + print_color "yellow" "Changing directory to 'cypress-tests'..." + cd cypress-tests || { + print_color "red" "ERROR: Directory 'cypress-tests' not found!" + exit 1 + } + fi + + check_dependencies + read_service_arrays + + case "$command" in + --parallel | -p) + print_color "yellow" "WARNING: Running Cypress tests in parallel is more resource-intensive!" + # At present, parallel execution is restricted to not run out of memory + # But can be scaled up by passing the value as an argument + run_tests "$jobs" + ;; + *) + run_tests 1 + ;; + esac +} + +# Execute the main function with passed arguments +main "$@"
2024-10-04T09:33:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR makes it possible for us to run Cypress tests in parallel by leveraging `gnu-parallel`. At present, we'll only be running against 5 connectors namely, - payments: bluesnap, cybersource, stripe - payouts: adyen and wise w.r.t pml and other connectors, there are some failures within the tests that needs to be addressed. >[!IMPORTANT] > Cypress in parallel is resource heavy and running it in batch of 3+ will result in unintended consequences like abrupt failures due to resource limitation. Running Cypress tests in parallel also puts up a challenge where when a specific test fails for 2 connectors at the same time, test against both the connectors stops abruptly. This is because of the file name conflict as we not have the privilege to change the names of the screenshots while capturing but only after the screenshot is captured. To address this, the format of screenshot has been changed where screenshot directories are changed based on the connectors (just because we now have the privilege to change directories in real time). Also, a similar issue with reports have also been addressed. Documentation has been updated to address the usage of `scripts/execute_cypress.sh` script. In short, ```sh source .env scripts/execute_cypress.sh --parallel <jobs_count> ``` >[!NOTE] > make sure that service variables (PAYMENTS, PAYOUTS, PAYMENT_METHOD_LIST, ROUTING) is exported along with CYPRESS env variables in the `.env` file. Check README for more info. > if `--parallel` is not passed, tests will run in sequential manner by setting jobs to `1` ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> When Cypress tests are run in sequential, it takes about `1h10m+` to run against `10+` prod connectors. With `parallel`, we'll bring that down to nearly `15m`. This should close https://github.com/juspay/hyperswitch/issues/5914 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Tested locally: These are known failures. <img width="576" alt="image" src="https://github.com/user-attachments/assets/12788d3f-f816-4395-9799-316546595823"> The ones that passed is `Stripe` and hence it is not in `failed_connector` list. https://github.com/juspay/hyperswitch/actions/runs/11177572035/job/31077505520?pr=6225 https://github.com/juspay/hyperswitch/actions/runs/11384335020/job/31673789059 ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `prettier . --write` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d06d19fc96e1a74d20e2fe3613f86d541947e0ae
juspay/hyperswitch
juspay__hyperswitch-5924
Bug: [FEATURE] [DEUTSCHEBANK] Implement subsequent mandate payments via SEPA ### Feature Description Implement SEPA mandate payments for Deutschebank. ### Possible Implementation Implement SEPA mandate payments for Deutschebank. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b0866cfb265..535a5abffce 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1042,6 +1042,7 @@ pub struct ConnectorMandateReferenceId { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, pub update_history: Option<Vec<UpdateHistory>>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs index 30e67babe89..a861155afb3 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -50,7 +50,10 @@ use transformers as deutschebank; use crate::{ constants::headers, types::ResponseRouterData, - utils::{self, PaymentsCompleteAuthorizeRequestData, RefundsRequestData}, + utils::{ + self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + RefundsRequestData, + }, }; #[derive(Clone)] @@ -182,6 +185,16 @@ impl ConnectorValidation for Deutschebank { ), } } + + fn validate_mandate_payment( + &self, + pm_type: Option<enums::PaymentMethodType>, + pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + let mandate_supported_pmd = + std::collections::HashSet::from([utils::PaymentMethodDataType::SepaBankDebit]); + utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) + } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Deutschebank { @@ -302,13 +315,26 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, - _req: &PaymentsAuthorizeRouterData, + req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}/services/v2.1/managedmandate", - self.base_url(connectors) - )) + if req.request.connector_mandate_id().is_none() { + Ok(format!( + "{}/services/v2.1/managedmandate", + self.base_url(connectors) + )) + } else { + let event_id = req.connector_request_reference_id.clone(); + let tx_action = if req.request.is_auto_capture()? { + "authorization" + } else { + "preauthorization" + }; + Ok(format!( + "{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}", + self.base_url(connectors) + )) + } } fn get_request_body( @@ -356,17 +382,31 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: deutschebank::DeutschebankMandatePostResponse = res - .response - .parse_struct("Deutschebank 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, - }) + if data.request.connector_mandate_id().is_none() { + let response: deutschebank::DeutschebankMandatePostResponse = res + .response + .parse_struct("DeutschebankMandatePostResponse") + .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, + }) + } else { + let response: deutschebank::DeutschebankPaymentsResponse = res + .response + .parse_struct("DeutschebankPaymentsAuthorizeResponse") + .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( diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index dc146dc38d4..8b3837edd63 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; use common_enums::enums; -use common_utils::{pii::Email, types::MinorUnit}; +use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, RouterData}, @@ -13,7 +14,9 @@ use hyperswitch_domain_models::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, ResponseId, }, - router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, + router_response_types::{ + MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, RefundsRouterData, @@ -26,8 +29,8 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ - AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, - RefundsRequestData, RouterData as OtherRouterData, + self, AddressDetailsData, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData, }, }; @@ -113,7 +116,7 @@ pub enum DeutschebankSEPAApproval { } #[derive(Debug, Serialize, PartialEq)] -pub struct DeutschebankPaymentsRequest { +pub struct DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval, email_address: Email, iban: Secret<String>, @@ -121,6 +124,13 @@ pub struct DeutschebankPaymentsRequest { last_name: Secret<String>, } +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum DeutschebankPaymentsRequest { + MandatePost(DeutschebankMandatePostRequest), + DirectDebit(DeutschebankDirectDebitRequest), +} + impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> for DeutschebankPaymentsRequest { @@ -128,16 +138,71 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> fn try_from( item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let billing_address = item.router_data.get_billing_address()?; - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => Ok(Self { - approval_by: DeutschebankSEPAApproval::Click, - email_address: item.router_data.request.get_email()?, - iban, - first_name: billing_address.get_first_name()?.clone(), - last_name: billing_address.get_last_name()?.clone(), - }), - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + match item + .router_data + .request + .mandate_id + .clone() + .and_then(|mandate_id| mandate_id.mandate_reference_id) + { + None => { + if item.router_data.request.is_mandate_payment() { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { + iban, .. + }) => { + let billing_address = item.router_data.get_billing_address()?; + Ok(Self::MandatePost(DeutschebankMandatePostRequest { + approval_by: DeutschebankSEPAApproval::Click, + email_address: item.router_data.request.get_email()?, + iban, + first_name: billing_address.get_first_name()?.clone(), + last_name: billing_address.get_last_name()?.clone(), + })) + } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()), + } + } else { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "setup_future_usage or customer_acceptance.acceptance_type", + } + .into()) + } + } + Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => { + let mandate_metadata: DeutschebankMandateMetadata = mandate_data + .mandate_metadata + .ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)? + .clone() + .parse_value("DeutschebankMandateMetadata") + .change_context(errors::ConnectorError::ParsingFailed)?; + Ok(Self::DirectDebit(DeutschebankDirectDebitRequest { + amount_total: DeutschebankAmount { + amount: item.amount, + currency: item.router_data.request.currency, + }, + means_of_payment: DeutschebankMeansOfPayment { + bank_account: DeutschebankBankAccount { + account_holder: mandate_metadata.account_holder, + iban: mandate_metadata.iban, + }, + }, + mandate: DeutschebankMandate { + reference: mandate_metadata.reference, + signed_on: mandate_metadata.signed_on, + }, + })) + } + Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) + | Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()) + } } } } @@ -176,6 +241,14 @@ impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus { } } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankMandateMetadata { + account_holder: Secret<String>, + iban: Secret<String>, + reference: Secret<String>, + signed_on: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankMandatePostResponse { rc: String, @@ -207,14 +280,14 @@ impl PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let signed_on = match item.response.approval_date { + let signed_on = match item.response.approval_date.clone() { Some(date) => date.chars().take(10).collect(), None => time::OffsetDateTime::now_utc().date().to_string(), }; - match item.response.reference { + match item.response.reference.clone() { Some(reference) => Ok(Self { status: if item.response.rc == "0" { - match item.response.state { + match item.response.state.clone() { Some(state) => common_enums::AttemptStatus::from(state), None => common_enums::AttemptStatus::Failure, } @@ -227,11 +300,29 @@ impl endpoint: item.data.request.get_complete_authorize_url()?, method: common_utils::request::Method::Get, form_fields: HashMap::from([ - ("reference".to_string(), reference), - ("signed_on".to_string(), signed_on), + ("reference".to_string(), reference.clone()), + ("signed_on".to_string(), signed_on.clone()), ]), }), - mandate_reference: None, + mandate_reference: Some(MandateReference { + connector_mandate_id: item.response.mandate_id, + payment_method_id: None, + mandate_metadata: Some(serde_json::json!(DeutschebankMandateMetadata { + account_holder: item.data.get_billing_address()?.get_full_name()?, + iban: match item.data.request.payment_method_data.clone() { + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { + iban, + .. + }) => Ok(iban), + _ => Err(errors::ConnectorError::MissingRequiredField { + field_name: + "payment_method_data.bank_debit.sepa_bank_debit.iban" + }), + }?, + reference: Secret::from(reference), + signed_on, + })), + }), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -248,6 +339,49 @@ impl } } +impl + TryFrom< + ResponseRouterData< + Authorize, + DeutschebankPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + Authorize, + DeutschebankPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: if item.response.rc == "0" { + match item.data.request.is_auto_capture()? { + true => common_enums::AttemptStatus::Charged, + false => common_enums::AttemptStatus::Authorized, + } + } else { + common_enums::AttemptStatus::Failure + }, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.tx_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, + }), + ..item.data + }) + } +} + #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct DeutschebankAmount { amount: MinorUnit, @@ -268,7 +402,7 @@ pub struct DeutschebankBankAccount { #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMandate { reference: Secret<String>, - signed_on: Secret<String>, + signed_on: String, } #[derive(Debug, Serialize, PartialEq)] @@ -319,14 +453,12 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> })? .to_owned(), ); - let signed_on = Secret::from( - queries_params - .get("signed_on") - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "signed_on", - })? - .to_owned(), - ); + let signed_on = queries_params + .get("signed_on") + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "signed_on", + })? + .to_owned(); match item.router_data.request.payment_method_data.clone() { Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. })) => { @@ -349,7 +481,10 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> }, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()), } } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs index fdec3d0e1eb..7f88903e867 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs @@ -170,13 +170,6 @@ pub enum ResponseType { UnsupportedMediaType, } -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum FiservemeaResponseType { - TransactionResponse, - ErrorResponse, -} - #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum FiservemeaTransactionType { @@ -329,7 +322,7 @@ fn map_status( pub struct FiservemeaPaymentsResponse { response_type: Option<ResponseType>, #[serde(rename = "type")] - fiservemea_type: Option<FiservemeaResponseType>, + fiservemea_type: Option<String>, client_request_id: Option<String>, api_trace_id: Option<String>, ipg_transaction_id: String, @@ -526,7 +519,7 @@ pub struct FiservemeaError { #[derive(Debug, Serialize, Deserialize)] pub struct FiservemeaErrorResponse { #[serde(rename = "type")] - fiservemea_type: Option<FiservemeaResponseType>, + fiservemea_type: Option<String>, client_request_id: Option<String>, api_trace_id: Option<String>, pub response_type: Option<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index b400555305d..56da53c2873 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -787,6 +787,7 @@ impl<F> MandateReference { connector_mandate_id: Some(id.clone()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index df0b63833d9..a9451f6156a 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -242,6 +242,7 @@ pub struct RecurringMandatePaymentData { pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::enums::Currency>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index cb682514c83..79a78efb538 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -82,6 +82,7 @@ pub struct TaxCalculationResponseData { pub struct MandateReference { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs index e36707af6b0..06f197ebf0b 100644 --- a/crates/hyperswitch_interfaces/src/errors.rs +++ b/crates/hyperswitch_interfaces/src/errors.rs @@ -56,6 +56,8 @@ pub enum ConnectorError { CaptureMethodNotSupported, #[error("Missing connector mandate ID")] MissingConnectorMandateID, + #[error("Missing connector mandate metadata")] + MissingConnectorMandateMetadata, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")] diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 5842143ad44..46f312b38f2 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -746,6 +746,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index e915d05c358..361ebece299 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3294,6 +3294,7 @@ pub fn get_adyen_response( .map(|mandate_id| types::MandateReference { connector_mandate_id: Some(mandate_id.expose()), payment_method_id: None, + mandate_metadata: None, }); let network_txn_id = response.additional_data.and_then(|additional_data| { additional_data diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 57563c276f5..868409dafc7 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -398,6 +398,7 @@ impl<F, T> format!("{customer_profile_id}-{payment_profile_id}") }), payment_method_id: None, + mandate_metadata: None, }, ), connector_metadata: None, @@ -1109,6 +1110,7 @@ impl<F, T> }, ), payment_method_id: None, + mandate_metadata: None, } }); diff --git a/crates/router/src/connector/bamboraapac/transformers.rs b/crates/router/src/connector/bamboraapac/transformers.rs index 3c197699309..819c918338e 100644 --- a/crates/router/src/connector/bamboraapac/transformers.rs +++ b/crates/router/src/connector/bamboraapac/transformers.rs @@ -280,6 +280,7 @@ impl<F> Some(types::MandateReference { connector_mandate_id, payment_method_id: None, + mandate_metadata: None, }) } else { None @@ -463,6 +464,7 @@ impl<F> mandate_reference: Some(types::MandateReference { connector_mandate_id: Some(connector_mandate_id), payment_method_id: None, + mandate_metadata: None, }), connector_metadata: None, network_txn_id: None, diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 46a522c7378..f47ab4139e8 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -359,6 +359,7 @@ impl<F, T> .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, } }); let mut mandate_status = @@ -1487,6 +1488,7 @@ fn get_payment_response( .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(types::PaymentsResponseData::TransactionResponse { diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 22982ceb213..05d8c1c559d 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -443,6 +443,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, @@ -617,6 +618,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, @@ -698,6 +700,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, @@ -761,6 +764,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index fc35cab773a..9ad4f0604a4 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -2227,6 +2227,7 @@ fn get_payment_response( .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(types::PaymentsResponseData::TransactionResponse { @@ -2947,6 +2948,7 @@ impl .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); let mut mandate_status = enums::AttemptStatus::foreign_from(( item.response diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index efc6661b447..19568ae4671 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -261,6 +261,7 @@ fn get_payment_response( .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }) }); match status { diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index f3250602dbc..ff2f9d95026 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -512,6 +512,7 @@ impl<F> let mandate_reference = Some(MandateReference { connector_mandate_id: Some(item.response.mandates.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -664,6 +665,7 @@ impl<F> let mandate_reference = MandateReference { connector_mandate_id: Some(item.data.request.get_connector_mandate_id()?), payment_method_id: None, + mandate_metadata: None, }; Ok(Self { status: enums::AttemptStatus::from(item.response.payments.status), diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index c44cf14ab65..547a38ad849 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -982,6 +982,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }), connector_metadata: None, network_txn_id: None, diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 43cb4cecec8..55b2fbe4176 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -358,6 +358,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { status: enums::AttemptStatus::foreign_from(( diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index b7df6829da4..5d987174273 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -574,6 +574,7 @@ impl<F, T> .map(|subscription_data| types::MandateReference { connector_mandate_id: Some(subscription_data.identifier.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { status, diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 2547443484e..f280d3a42a2 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1602,6 +1602,7 @@ where .map(|id| types::MandateReference { connector_mandate_id: Some(id), payment_method_id: None, + mandate_metadata: None, }), // we don't need to save session token for capture, void flow so ignoring if it is not present connector_metadata: if let Some(token) = response.session_token { diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 0bb10c9845a..8c2ad2ef979 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -418,6 +418,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }); let status = enums::AttemptStatus::foreign_from(( item.response.transaction_status, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index c12e478b08e..e0ab598d76d 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -250,6 +250,7 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData { mandate_reference: value.buyer_key.clone().map(|buyer_key| MandateReference { connector_mandate_id: Some(buyer_key.expose()), payment_method_id: None, + mandate_metadata: None, }), connector_metadata: None, network_txn_id: None, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 910cb94e929..2129ad327c2 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2389,6 +2389,7 @@ impl<F, T> types::MandateReference { connector_mandate_id, payment_method_id, + mandate_metadata: None, } }); @@ -2583,6 +2584,7 @@ impl<F, T> types::MandateReference { connector_mandate_id, payment_method_id: Some(payment_method_id), + mandate_metadata: None, } }); @@ -2673,6 +2675,7 @@ impl<F, T> types::MandateReference { connector_mandate_id, payment_method_id, + mandate_metadata: None, } }); let status = enums::AttemptStatus::from(item.response.status); diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index 761fc43982b..be3cf4a1cef 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -1778,6 +1778,7 @@ fn get_payment_response( .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(types::PaymentsResponseData::TransactionResponse { @@ -1963,6 +1964,7 @@ impl .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); let mut mandate_status = enums::AttemptStatus::foreign_from(( item.response diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index d2812447ed8..549857494f0 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -189,6 +189,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::FlowNotSupported { .. } | errors::ConnectorError::CaptureMethodNotSupported | errors::ConnectorError::MissingConnectorMandateID + | errors::ConnectorError::MissingConnectorMandateMetadata | errors::ConnectorError::MissingConnectorTransactionID | errors::ConnectorError::MissingConnectorRefundID | errors::ConnectorError::MissingApplePayTokenData @@ -288,6 +289,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> errors::ConnectorError::FailedToObtainCertificateKey | errors::ConnectorError::CaptureMethodNotSupported | errors::ConnectorError::MissingConnectorMandateID | + errors::ConnectorError::MissingConnectorMandateMetadata | errors::ConnectorError::MissingConnectorTransactionID | errors::ConnectorError::MissingConnectorRefundID | errors::ConnectorError::MissingApplePayTokenData | @@ -376,6 +378,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::FlowNotSupported { .. } | errors::ConnectorError::CaptureMethodNotSupported | errors::ConnectorError::MissingConnectorMandateID + | errors::ConnectorError::MissingConnectorMandateMetadata | errors::ConnectorError::MissingConnectorTransactionID | errors::ConnectorError::MissingConnectorRefundID | errors::ConnectorError::MissingApplePayTokenData diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 85ae8641373..3a55bf77771 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4093,6 +4093,9 @@ where payment_method_info.get_id().clone(), ), update_history: None, + mandate_metadata: mandate_reference_record + .mandate_metadata + .clone(), }, )); payment_data.set_recurring_mandate_payment_data( @@ -4103,6 +4106,8 @@ where .original_payment_authorized_amount, original_payment_authorized_currency: mandate_reference_record .original_payment_authorized_currency, + mandate_metadata: mandate_reference_record + .mandate_metadata.clone(), }); connector_choice = Some((connector_data, mandate_reference_id.clone())); diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index e9dca13dc80..ac6c236f536 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -802,6 +802,7 @@ pub async fn get_token_for_recurring_mandate( payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, + mandate_metadata: None, }), payment_method_type: payment_method.payment_method_type, mandate_connector: Some(mandate_connector_details), @@ -816,6 +817,7 @@ pub async fn get_token_for_recurring_mandate( payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, + mandate_metadata: None, }), payment_method_type: payment_method.payment_method_type, mandate_connector: Some(mandate_connector_details), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index c75cc29ce51..658a02f7d08 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -681,6 +681,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ), payment_method_id: None, update_history: None, + mandate_metadata: None, }, ), ), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 0731def9453..4b931d68f1e 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -398,7 +398,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa api_models::payments::ConnectorMandateReferenceId{ connector_mandate_id: connector_id.connector_mandate_id, payment_method_id: connector_id.payment_method_id, - update_history: None + update_history: None, + mandate_metadata: None, } )) } @@ -437,6 +438,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ), payment_method_id: None, update_history: None, + mandate_metadata: None, }, ), ), diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 90ca49c9746..09292224cae 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1504,21 +1504,24 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( 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() { + let (connector_mandate_id, mandate_metadata) = match router_data.response.clone() { Ok(resp) => match resp { types::PaymentsResponseData::TransactionResponse { ref mandate_reference, .. } => { if let Some(mandate_ref) = mandate_reference { - mandate_ref.connector_mandate_id.clone() + ( + mandate_ref.connector_mandate_id.clone(), + mandate_ref.mandate_metadata.clone(), + ) } else { - None + (None, None) } } - _ => None, + _ => (None, None), }, - Err(_) => None, + Err(_) => (None, None), }; if let Some(payment_method) = payment_data.payment_method_info.clone() { let connector_mandate_details = @@ -1529,6 +1532,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( payment_data.payment_attempt.currency, payment_data.payment_attempt.merchant_connector_id.clone(), connector_mandate_id, + mandate_metadata, )?; payment_methods::cards::update_payment_method_connector_mandate_details( state, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index c5e7cebac34..c69595d1893 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -329,7 +329,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa api_models::payments::MandateIds { mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None }, + api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None, mandate_metadata:connector_id.mandate_metadata, }, )) } }), diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 2d81aecb30e..ca8c6718aa7 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -148,18 +148,21 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; - let connector_mandate_id = match responses { + let (connector_mandate_id, mandate_metadata) = match responses { types::PaymentsResponseData::TransactionResponse { ref mandate_reference, .. } => { if let Some(mandate_ref) = mandate_reference { - mandate_ref.connector_mandate_id.clone() + ( + mandate_ref.connector_mandate_id.clone(), + mandate_ref.mandate_metadata.clone(), + ) } else { - None + (None, None) } } - _ => None, + _ => (None, None), }; let check_for_mit_mandates = save_payment_method_data .request @@ -178,6 +181,7 @@ where currency, merchant_connector_id.clone(), connector_mandate_id.clone(), + mandate_metadata.clone(), ) } else { None @@ -373,6 +377,7 @@ where currency, merchant_connector_id.clone(), connector_mandate_id.clone(), + mandate_metadata.clone(), )?; payment_methods::cards::update_payment_method_connector_mandate_details(state, @@ -479,6 +484,7 @@ where currency, merchant_connector_id.clone(), connector_mandate_id.clone(), + mandate_metadata.clone(), )?; payment_methods::cards::update_payment_method_connector_mandate_details( state, @@ -1160,6 +1166,7 @@ pub fn add_connector_mandate_details_in_payment_method( authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, + mandate_metadata: Option<serde_json::Value>, ) -> Option<storage::PaymentsMandateReference> { let mut mandate_details = HashMap::new(); @@ -1173,6 +1180,7 @@ pub fn add_connector_mandate_details_in_payment_method( payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, + mandate_metadata, }, ); Some(storage::PaymentsMandateReference(mandate_details)) @@ -1188,6 +1196,7 @@ pub fn update_connector_mandate_details_in_payment_method( authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, + mandate_metadata: Option<serde_json::Value>, ) -> RouterResult<Option<serde_json::Value>> { let mandate_reference = match payment_method.connector_mandate_details { Some(_) => { @@ -1208,6 +1217,7 @@ pub fn update_connector_mandate_details_in_payment_method( payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, + mandate_metadata: mandate_metadata.clone(), }; mandate_details.map(|mut payment_mandate_reference| { payment_mandate_reference @@ -1218,6 +1228,7 @@ pub fn update_connector_mandate_details_in_payment_method( payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, + mandate_metadata: mandate_metadata.clone(), }); payment_mandate_reference }) @@ -1231,6 +1242,7 @@ pub fn update_connector_mandate_details_in_payment_method( authorized_currency, merchant_connector_id, connector_mandate_id, + mandate_metadata, ), }; let connector_mandate_details = mandate_reference diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index 34c5714e126..bb1b801edb6 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -124,6 +124,7 @@ pub struct PaymentsMandateReferenceRecord { pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2024-09-17T11:42:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Implement SEPA mandate payments for Deutschebank. These mandate details will be stored in the payment_methods table in the connector_mandate_details. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/5924 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Payments Intent Create: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data '{ "amount": 1650, "currency": "EUR", "confirm": false, "customer_id": "customer123", "setup_future_usage": "off_session" }' ``` Response: ``` { "payment_id": "pay_u8nPxFlL3ZUW94kkzrI1", "merchant_id": "merchant_1725539597", "status": "requires_payment_method", "amount": 1650, "net_amount": 1650, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_u8nPxFlL3ZUW94kkzrI1_secret_npQbKdQHon2g7tthKxeB", "created": "2024-09-17T12:59:17.770Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "something@example.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "something@example.com", "name": "John Doe", "phone": "9999999999", "return_url": null, "authentication_type": null, "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1726577957, "expires": 1726581557, "secret": "epk_46a85e0e97b645a1bb2f838483b3bf70" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-17T13:14:17.769Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-17T12:59:17.902Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` 2. Payments Confirm: Request: ``` curl --location 'http://localhost:8080/payments/pay_u8nPxFlL3ZUW94kkzrI1/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data-raw '{ "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "customer_id": "customer123", "payment_method": "bank_debit", "payment_method_type": "sepa", "payment_method_data": { "bank_debit": { "sepa_bank_debit": { "iban": "DE87123456781234567890" } } }, "billing": { "address": { "first_name": "joseph", "last_name": "Doe" } }, "email": "something@example.com", "customer_acceptance": { "acceptance_type": "offline" } }' ``` Response: ``` { "payment_id": "pay_u8nPxFlL3ZUW94kkzrI1", "merchant_id": "merchant_1725539597", "status": "requires_customer_action", "amount": 1650, "net_amount": 1650, "amount_capturable": 1650, "amount_received": null, "connector": "deutschebank", "client_secret": "pay_u8nPxFlL3ZUW94kkzrI1_secret_npQbKdQHon2g7tthKxeB", "created": "2024-09-17T12:59:17.770Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "something@example.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "DE871************67890", "bank_account_holder_name": null } }, "billing": null }, "payment_token": "token_K3jaclrwRSo2guy2kfn1", "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "something@example.com", "name": "John Doe", "phone": "9999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_u8nPxFlL3ZUW94kkzrI1/merchant_1725539597/pay_u8nPxFlL3ZUW94kkzrI1_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-17T13:14:17.769Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_8qqABCQOMAznGanjmLhz", "payment_method_status": null, "updated": "2024-09-17T12:59:36.782Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` 3. Creating payment using payment_method_id: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data '{ "amount": 179, "currency": "EUR", "confirm": true, "customer_id": "customer123", "recurring_details": { "type": "payment_method_id", "data": "pm_8qqABCQOMAznGanjmLhz" }, "off_session": true }' ``` Response: ``` { "payment_id": "pay_zeindrGrgMlzJscKZdAC", "merchant_id": "merchant_1725539597", "status": "succeeded", "amount": 179, "net_amount": 179, "amount_capturable": 0, "amount_received": 179, "connector": "deutschebank", "client_secret": "pay_zeindrGrgMlzJscKZdAC_secret_W4q8bNJWw2yH7MVaC70L", "created": "2024-09-17T13:24:07.080Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "something@example.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": true, "capture_on": null, "capture_method": null, "payment_method": "bank_debit", "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "something@example.com", "name": "John Doe", "phone": "9999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1726579447, "expires": 1726583047, "secret": "epk_d80c49dcbeb1431cadf357b9c6d64ad9" }, "manual_retry_allowed": false, "connector_transaction_id": "nz17xcQ3x7q7kecPExgV0s", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-17T13:39:07.079Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_8qqABCQOMAznGanjmLhz", "payment_method_status": "active", "updated": "2024-09-17T13:24:08.282Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
a94cf25bb6eb40fafc5327aceffac8292b47b001
juspay/hyperswitch
juspay__hyperswitch-5895
Bug: [CYPRESS] : Add Noon Connector **Description:** This task involves adding a connector for the Noon functionality in Cypress. For reference, similar connectors have already been implemented in the repository. You can refer to the existing connectors here: https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils **Pre-requisites:** - Cypress is the testing framework that Hyperswitch is using to run automated tests. Having good grip on Javascript to work on Cypress is a must. - Please follow the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress. **Steps:** 1. Add the Noon connector .js files under the PaymentUtils directory: [PaymentUtils Directory](https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils) 2. Add the card details and corresponding test case functions for Noon, following the format used in the [Cybersource.js connector](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js). 3. In the Noon connector, map the test cases and statuses properly. To do this, use the below dashboard credentials where Noon is already configured, test the flows, and then assign the correct statuses. URL: https://integ.hyperswitch.io Username, Password: Please drop a comment requesting credentials. The Creds are only shared on request **Test Cases:** - Add test cases only for card payments. - Test creds for noon https://docs.noonpayments.com/test/cards **Postman collection for reference** https://www.postman.com/altimetry-participant-63653904/hyperswitch Note: - Test cases for other payment methods should be skipped. ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
2024-11-19T06:46:36Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description Add Noon Connector for Cypress Automation Note : Noon supports only 3ds payments , so all the no_three_ds payments are skipped ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Noon connector was not available in the cypress automation ## How did you test it? <img width="710" alt="image" src="https://github.com/user-attachments/assets/88aec323-824c-49e3-b51e-67d469c9826a"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
65bf75a75e1e7d705de3ee3e9080a7a86099ffc3
juspay/hyperswitch
juspay__hyperswitch-5893
Bug: [CYPRESS] : Add Checkout Connector **Description:** This task involves adding a payment connector for the checkout functionality in Cypress. For reference, similar connectors have already been implemented in the repository. You can refer to the existing connectors here: https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils **Pre-requisites:** - Cypress is the testing framework that Hyperswitch is using to run automated tests. Having good grip on Javascript to work on Cypress is a must. - Please follow the [README](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/readme.md) for guidelines on file structure, formatting and instructions on how to set up and run Cypress. **Steps:** 1. Add the checkout connector .js files under the PaymentUtils directory: [PaymentUtils Directory](https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentUtils) 2. Add the card details and corresponding test case functions for checkout, following the format used in the [Cybersource.js connector](https://github.com/juspay/hyperswitch/blob/main/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js). 3. In the checkout connector, map the test cases and statuses properly. To do this, use the below dashboard credentials where checkout is already configured, test the flows, and then assign the correct statuses. URL: https://integ.hyperswitch.io Username, Password: Please drop a comment requesting credentials. The Creds are only shared on request **Test Cases:** - Add test cases only for card payments. **Postman collection for reference** https://www.postman.com/altimetry-participant-63653904/hyperswitch Note: - Test cases for other payment methods should be skipped. - The test cases are already written under PaymentTest: - [PaymentTest Directory](https://github.com/juspay/hyperswitch/tree/main/cypress-tests/cypress/e2e/PaymentTest).Just map the test cases and their statuses in the config.js file. ### Submission Process: - Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself. - Once assigned, submit a pull request (PR). - Maintainers will review and provide feedback, if any. - Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules). Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
2024-11-13T13:36:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description Add Checkout Connector for Cypress Automation ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Checkout connector was not available in the cypress automation ## How did you test it? Cypress Tests - Checkout <img width="710" alt="image" src="https://github.com/user-attachments/assets/75bc70aa-8bc5-43f6-ad28-ac33c7bcf6de"> - NMI <img width="710" alt="image" src="https://github.com/user-attachments/assets/cb4b4b21-8a93-4a88-8e67-5172d0847ca4"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
600cf44684912192f0bf1b9566fd0a7daae9f54c
juspay/hyperswitch
juspay__hyperswitch-5888
Bug: [BUG] remove redundant DB calls when FRM feature is not enabled ### Bug Description FRM is a payment feature which is integrated in HyperSwitch behind `frm` feature flag. There are some DB queries (which are generally not behind a feature flag) which are being executed even when `frm` feature is disabled. ### Expected Behavior Underlying DB queries should be executed only when the feature which requires it is enabled. In this case, FRM DB queries should be executed only when `frm` is enabled ### Actual Behavior FRM DB queries are being executed regardless of `frm` feature flag ### Steps To Reproduce --- ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes/No If yes, please provide the value of the `x-request-id` response header to help us debug your issue. 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 --features vergen -- --version`): `` ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 38cf72a3e2f..9c5b632eff0 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -136,13 +136,17 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); - let frm_response = db - .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) - .await - .change_context(errors::ApiErrorResponse::PaymentNotFound) - .attach_printable_lazy(|| { - format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_account.get_id().get_string_repr()) - }); + let frm_response = if cfg!(feature = "frm") { + db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable_lazy(|| { + format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_account.get_id().get_string_repr()) + }) + .ok() + } else { + None + }; let payment_data = PaymentData { flow: PhantomData, @@ -180,7 +184,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> multiple_capture_data: None, redirect_response: None, surcharge_details: None, - frm_message: frm_response.ok(), + frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 570337a5555..3d67dadd34d 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -117,13 +117,17 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P let currency = payment_attempt.currency.get_required_value("currency")?; let amount = payment_attempt.get_total_amount().into(); - let frm_response = db - .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) - .await - .change_context(errors::ApiErrorResponse::PaymentNotFound) - .attach_printable_lazy(|| { - format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id()) - }); + let frm_response = if cfg!(feature = "frm") { + db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone()) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable_lazy(|| { + format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_account.get_id()) + }) + .ok() + } else { + None + }; let profile_id = payment_intent .profile_id @@ -176,7 +180,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P multiple_capture_data: None, redirect_response: None, surcharge_details: None, - frm_message: frm_response.ok(), + frm_message: frm_response, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index d7ca01e6661..0508d0549e8 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -348,13 +348,17 @@ async fn get_tracker_for_sync< format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) })?; - let frm_response = db - .find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone()) - .await - .change_context(errors::ApiErrorResponse::PaymentNotFound) - .attach_printable_lazy(|| { - format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) - }); + let frm_response = if cfg!(feature = "frm") { + db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_account.get_id().clone()) + .await + .change_context(errors::ApiErrorResponse::PaymentNotFound) + .attach_printable_lazy(|| { + format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_account.get_id()) + }) + .ok() + } else { + None + }; let contains_encoded_data = payment_attempt.encoded_data.is_some(); @@ -472,7 +476,7 @@ async fn get_tracker_for_sync< redirect_response: None, payment_link_data: None, surcharge_details: None, - frm_message: frm_response.ok(), + frm_message: frm_response, incremental_authorization_details: None, authorizations, authentication,
2024-09-16T04:11:58Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Described in #5888 ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Ensures FRM DB queries are not executed if `frm` feature flag is not enabled. There are a couple of features disabled in HS production, and the DB migrations for such features have not been executed. This leads to unnecessary missing column logs in production - `ERROR: column fraud_check.last_step does not exist at character 443` Moving such DB queries behind the feature flag ensures they are not executed in the flow. ## How did you test it? <details> <summary>1. Create a txn</summary> cURL curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_4cUeectovRvg0seB0AhDXZ04342m045JeKncgz5XfwkkhJujY4gy7TzfTS9uvdiP' \ --data-raw '{ "amount": 10000, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "StripeCustomer", "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "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" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" } }, "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": "127.0.0.1" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' Response { "payment_id": "pay_vOR4HKlsgkvHTnZf4PjC", "merchant_id": "postman_merchant_GHAction_9205c2f8-ea92-4ceb-8d6e-182cf16425be", "status": "requires_payment_method", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD", "created": "2024-09-16T04:20:41.261Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": null, "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer", "created_at": 1726460441, "expires": 1726464041, "secret": "epk_51ac152969e5409fa03e13c462de5474" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_RSxpgp1DT0ak3TCybfa5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-16T04:35:41.261Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-16T04:20:41.283Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } </details> <details> <summary>2. Confirm the txn</summary> cURL curl --location 'http://localhost:8080/payments/pay_vOR4HKlsgkvHTnZf4PjC/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_8e7e083168464148bdc4aa4e18eb12ac' \ --data-raw '{ "client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD", "payment_method": "bank_debit", "payment_method_type": "ach", "payment_method_data": { "bank_debit": { "ach_bank_debit": { "account_number": "40308669", "routing_number": "121000358", "sort_code": "560036", "shopper_email": "example@gmail.com", "card_holder_name": "joseph Doe", "bank_name": "wells_fargo", "bank_account_holder_name": "David Archer", "billing_details": { "houseNumberOrName": "50", "street": "Test Street", "city": "Amsterdam", "stateOrProvince": "NY", "postalCode": "12010", "country": "US", "name": "A. Klaassen", "email": "example@gmail.com" }, "reference": "daslvcgbaieh" } } }, "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": "127.0.0.1" } }' Response { "payment_id": "pay_vOR4HKlsgkvHTnZf4PjC", "merchant_id": "postman_merchant_GHAction_9205c2f8-ea92-4ceb-8d6e-182cf16425be", "status": "succeeded", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": 10000, "connector": "adyen", "client_secret": "pay_vOR4HKlsgkvHTnZf4PjC_secret_pIfEyYXxJwmoBKAZnPcD", "created": "2024-09-16T04:20:41.261Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "abcdef123@gmail.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "ach": { "account_number": "****8669", "routing_number": "121***358", "card_holder_name": "joseph Doe", "bank_account_holder_name": "David Archer", "bank_name": "wells_fargo", "bank_type": null, "bank_holder_type": null } }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": null, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": null, "last_name": null }, "phone": null, "email": null }, "order_details": null, "email": "abcdef123@gmail.com", "name": "John Doe", "phone": "999999999", "return_url": "https://duck.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "ach", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "WMVPLJG2ZG47JFV5", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_vOR4HKlsgkvHTnZf4PjC_1", "payment_link": null, "profile_id": "pro_RSxpgp1DT0ak3TCybfa5", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_dQv2PlaakvcRdJ4XR04T", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-16T04:35:41.261Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-16T04:20:44.432Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } </details> <details> <summary>3. Look at the logs to see if fraud_check queries are present (should be present when `frm` is enabled and absent when `frm` feature is disabled. </summary> ![image](https://github.com/user-attachments/assets/39849bd2-9f02-41a3-91b0-21d47c964965) </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2aa215440e0531e315e61ee30bbbc5a5685481b3
juspay/hyperswitch
juspay__hyperswitch-6124
Bug: [CYPRESS]: Use the SDK to process a payment. --- ### **Title**: Verify Make and View a Test Payment --- ### **Description**: This task involves testing the "Make a test payment" feature from the homepage. The user will go through the checkout process, entering payment details and viewing the payment summary upon successful payment. --- ### **Test Case**: Make and View a Test Payment - **Pre-requisites**: None - **Steps**: 1. Go to the homepage. 2. Click on **"Try it out"** in the **"Make a test payment - Try our unified checkout"** message box. 3. Verify the user is redirected to the **test checkout page**. 4. Select the currency from the dropdown (e.g., **"EUR"**). 5. Enter the amount (**77**) in the text box. 6. Click on **"Show preview"**. 7. Verify that the **SDK preview** is rendered with the following elements: - **"Card number"** text box - **"Expiry"** text box - **"CVC"** text box - **"Save card details"** checkbox - **"Pay"** button with the currency and amount 8. Enter the test card details into the SDK: - **Card Number**: 4242 4242 4242 4242 - **Expiry**: 01/27 - **CVC**: 492 9. Verify that the card details are displayed correctly in the respective text boxes. 10. Click on the **"Pay"** button. 11. Verify that the **"Payment Successful"** message is displayed. 12. Click on **"Go to payment"**. 13. Verify that the user is redirected to the **payment details page**. - **Test Data**: - **Currency**: EUR - **Amount**: 77 - **Card Number**: 4242 4242 4242 4242 - **Expiry**: 01/27 - **CVC**: 492 - **Expected Results**: - The user is redirected to the **test checkout page** after clicking "Try it out." - The selected currency (**"EUR"**) should be reflected in the dropdown. - The amount (**77**) should be entered and displayed correctly in the text box. - After clicking **"Show preview,"** the SDK preview should be rendered with all necessary elements (card number, expiry, CVC, etc.). - Test card details should be entered correctly, and the payment form should reflect the correct input. - Upon clicking **"Pay,"** a **"Payment Successful"** message should be displayed. - The user should be redirected to the **payment details page** upon clicking **"Go to payment."** --- ### **Acceptance Criteria**: 1. The test checkout page is accessible from the homepage. 2. The currency and amount are correctly entered and reflected in the form. 3. The SDK preview renders with the appropriate fields. 4. Payment details are correctly submitted, and the payment is processed successfully. 5. The user can view the payment details page after successful payment. --- This structured format ensures that all steps, test data, and expected outcomes are clearly defined for testing the payment process.
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 2d4a539c1e9..453d1521226 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -9,6 +9,7 @@ use common_utils::{ use masking::{PeekInterface, Secret}; use router_derive::Setter; use time::PrimitiveDateTime; +use url::Url; use utoipa::ToSchema; use crate::{ @@ -177,7 +178,7 @@ pub struct PaymentsRequest { /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] - pub return_url: Option<url::Url>, + pub return_url: Option<Url>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, @@ -920,6 +921,8 @@ pub enum WalletData { SamsungPay(Box<SamsungPayWalletData>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), + /// The wallet data for WeChat Pay + WeChatPay(Box<WeChatPay>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -959,6 +962,9 @@ pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} +#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct WeChatPay {} + #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection {} @@ -1229,8 +1235,13 @@ pub enum NextActionData { DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, - /// contains third party sdk session token response + /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken> }, + /// Contains url for Qr code image, this qr code has to be shown in sdk + QrCodeInformation { + #[schema(value_type = String)] + image_data_url: Url, + }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -1242,6 +1253,11 @@ pub struct BankTransferNextStepsData { pub receiver: ReceiverDetails, } +#[derive(Clone, Debug, serde::Deserialize)] +pub struct QrCodeNextStepsInstruction { + pub image_data_url: Url, +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs index 52e9219103e..d592904434c 100644 --- a/crates/router/src/compatibility/stripe/payment_intents/types.rs +++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs @@ -687,6 +687,9 @@ pub enum StripeNextAction { ThirdPartySdkSessionToken { session_token: Option<payments::SessionToken>, }, + QrCodeInformation { + image_data_url: url::Url, + }, } pub(crate) fn into_stripe_next_action( @@ -710,5 +713,8 @@ pub(crate) fn into_stripe_next_action( payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } + payments::NextActionData::QrCodeInformation { image_data_url } => { + StripeNextAction::QrCodeInformation { image_data_url } + } }) } diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs index 0a013300aef..d4b6aac306b 100644 --- a/crates/router/src/compatibility/stripe/setup_intents/types.rs +++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs @@ -345,6 +345,9 @@ pub enum StripeNextAction { ThirdPartySdkSessionToken { session_token: Option<payments::SessionToken>, }, + QrCodeInformation { + image_data_url: url::Url, + }, } pub(crate) fn into_stripe_next_action( @@ -368,6 +371,9 @@ pub(crate) fn into_stripe_next_action( payments::NextActionData::ThirdPartySdkSessionToken { session_token } => { StripeNextAction::ThirdPartySdkSessionToken { session_token } } + payments::NextActionData::QrCodeInformation { image_data_url } => { + StripeNextAction::QrCodeInformation { image_data_url } + } }) } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 7a9c9ef4e27..acce44f4de4 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1060,8 +1060,7 @@ fn create_stripe_payment_method( StripePaymentMethodType::ApplePay, StripeBillingAddress::default(), )), - - payments::WalletData::WeChatPayRedirect(_) => Ok(( + payments::WalletData::WeChatPay(_) => Ok(( StripePaymentMethodData::Wallet(StripeWallet::WechatpayPayment(WechatpayPayment { client: WechatClient::Web, payment_method_types: StripePaymentMethodType::Wechatpay, @@ -1515,6 +1514,12 @@ pub struct SepaAndBacsBankTransferInstructions { pub receiver: SepaAndBacsReceiver, } +#[serde_with::skip_serializing_none] +#[derive(Clone, Debug, Serialize)] +pub struct WechatPayNextInstructions { + pub image_data_url: Url, +} + #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)] pub struct SepaAndBacsReceiver { pub amount_received: i64, @@ -1699,26 +1704,47 @@ pub fn get_connector_metadata( amount: i64, ) -> CustomResult<Option<serde_json::Value>, errors::ConnectorError> { let next_action_response = next_action - .and_then(|next_action_response| match next_action_response { - StripeNextActionResponse::DisplayBankTransferInstructions(response) => { - Some(SepaAndBacsBankTransferInstructions { - sepa_bank_instructions: response.financial_addresses[0].iban.to_owned(), - bacs_bank_instructions: response.financial_addresses[0] - .sort_code - .to_owned(), - receiver: SepaAndBacsReceiver { - amount_received: amount - response.amount_remaining, - amount_remaining: response.amount_remaining, - }, - }) - } - _ => None, - }).map(|response| { - common_utils::ext_traits::Encode::<SepaAndBacsBankTransferInstructions>::encode_to_value( - &response, - ) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - }).transpose()?; + .and_then(|next_action_response| match next_action_response { + StripeNextActionResponse::DisplayBankTransferInstructions(response) => { + let bank_instructions = response.financial_addresses.get(0); + let (sepa_bank_instructions, bacs_bank_instructions) = + bank_instructions.map_or((None, None), |financial_address| { + ( + financial_address.iban.to_owned(), + financial_address.sort_code.to_owned(), + ) + }); + + let bank_transfer_instructions = SepaAndBacsBankTransferInstructions { + sepa_bank_instructions, + bacs_bank_instructions, + receiver: SepaAndBacsReceiver { + amount_received: amount - response.amount_remaining, + amount_remaining: response.amount_remaining, + }, + }; + + Some(common_utils::ext_traits::Encode::< + SepaAndBacsBankTransferInstructions, + >::encode_to_value( + &bank_transfer_instructions + )) + } + StripeNextActionResponse::WechatPayDisplayQrCode(response) => { + let wechat_pay_instructions = WechatPayNextInstructions { + image_data_url: response.image_data_url.to_owned(), + }; + + Some( + common_utils::ext_traits::Encode::<WechatPayNextInstructions>::encode_to_value( + &wechat_pay_instructions, + ), + ) + } + _ => None, + }) + .transpose() + .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(next_action_response) } @@ -1848,7 +1874,7 @@ impl StripeNextActionResponse { Self::RedirectToUrl(redirect_to_url) | Self::AlipayHandleRedirect(redirect_to_url) => { Some(redirect_to_url.url.to_owned()) } - Self::WechatPayDisplayQrCode(redirect_to_url) => Some(redirect_to_url.data.to_owned()), + Self::WechatPayDisplayQrCode(_) => None, Self::VerifyWithMicrodeposits(verify_with_microdeposits) => { Some(verify_with_microdeposits.hosted_verification_url.to_owned()) } @@ -1885,7 +1911,11 @@ pub struct StripeRedirectToUrlResponse { #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] pub struct StripeRedirectToQr { + // This data contains url, it should be converted to QR code. + // Note: The url in this data is not redirection url data: Url, + // This is the image source, this image_data_url can directly be used by sdk to show the QR code + image_data_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize)] diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index c5a25b993e5..384a2230389 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -431,7 +431,8 @@ 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 + api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None, + api_models::payments::NextActionData::QrCodeInformation{..} => None }) .ok_or(errors::ApiErrorResponse::InternalServerError) .into_report() diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 64cb0bc5e21..f807fc6c820 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -322,6 +322,9 @@ where let bank_transfer_next_steps = bank_transfer_next_steps_check(payment_attempt.clone())?; + let next_action_containing_qr_code = + qr_code_next_steps_check(payment_attempt.clone())?; + if payment_intent.status == enums::IntentStatus::RequiresCustomerAction || bank_transfer_next_steps.is_some() { @@ -331,6 +334,11 @@ where bank_transfer_steps_and_charges_details: bank_transfer, } }) + .or(next_action_containing_qr_code.map(|qr_code_data| { + api_models::payments::NextActionData::QrCodeInformation { + image_data_url: qr_code_data.image_data_url, + } + })) .or(Some(api_models::payments::NextActionData::RedirectToUrl { redirect_to_url: helpers::create_startpay_url( server, @@ -554,6 +562,18 @@ where } } +pub fn qr_code_next_steps_check( + payment_attempt: storage::PaymentAttempt, +) -> RouterResult<Option<api_models::payments::QrCodeNextStepsInstruction>> { + let qr_code_steps: Option<Result<api_models::payments::QrCodeNextStepsInstruction, _>> = + payment_attempt + .connector_metadata + .map(|metadata| metadata.parse_value("QrCodeNextStepsInstruction")); + + let qr_code_instructions = qr_code_steps.transpose().ok().flatten(); + Ok(qr_code_instructions) +} + impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse { fn foreign_from(item: (storage::PaymentIntent, storage::PaymentAttempt)) -> Self { let pi = item.0; diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index a53c57bc05e..9d1473be928 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -233,6 +233,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::SdkNextAction, api_models::payments::NextActionCall, api_models::payments::SamsungPayWalletData, + api_models::payments::WeChatPay, api_models::payments::GpayTokenizationData, api_models::payments::GooglePayPaymentMethodInfo, api_models::payments::ApplePayWalletData, diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 53bc3c7c29a..650f6a4f5d9 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5530,7 +5530,7 @@ }, { "type": "object", - "description": "contains third party sdk session token response", + "description": "Contains third party sdk session token response", "required": [ "type" ], @@ -5550,6 +5550,25 @@ ] } } + }, + { + "type": "object", + "description": "Contains url for Qr code image, this qr code has to be shown in sdk", + "required": [ + "image_data_url", + "type" + ], + "properties": { + "image_data_url": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "qr_code_information" + ] + } + } } ], "discriminator": { @@ -8548,9 +8567,23 @@ "$ref": "#/components/schemas/WeChatPayRedirection" } } + }, + { + "type": "object", + "required": [ + "we_chat_pay" + ], + "properties": { + "we_chat_pay": { + "$ref": "#/components/schemas/WeChatPay" + } + } } ] }, + "WeChatPay": { + "type": "object" + }, "WeChatPayRedirection": { "type": "object" },
2023-06-27T14:05:27Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] New feature ## Description <!-- Describe your changes in detail --> Add support for WeChat Pay, we chat pay in stripe doesn't follow redirection.Qr code url is given in the next action, this qr code has to be shown in sdk. API contract for WeChat Pay: ``` "payment_method": "wallet", "payment_method_type": "we_chat_pay", "payment_method_data": { "wallet": { "we_chat_pay": {} } }, ``` ### Additional Changes - [x] This PR modifies the API contract <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug or documentation fix that will have little conversation). --> Add support for WeChat Pay payment method ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Manual Qr code url in next action <img width="1264" alt="Screen Shot 2023-06-27 at 6 16 14 PM" src="https://github.com/juspay/hyperswitch/assets/59434228/eef065bd-f0ef-47b4-899d-89c42545a52c"> Qr code <img width="1545" alt="Screen Shot 2023-06-27 at 6 15 53 PM" src="https://github.com/juspay/hyperswitch/assets/59434228/9c084396-8220-430e-a2e8-b2844c09416d"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed submitted code
ca4e242d206dc69a10a1fbf51805a4cf4885a35e
juspay/hyperswitch
juspay__hyperswitch-5886
Bug: [FEATURE] Add Cell ID in config ### Feature Description Add global cell id information in config for v2 ### Possible Implementation Will need to add in settings ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index 1f32481fec7..cf6703f43d4 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -734,6 +734,9 @@ connector_list = "" [recipient_emails] recon = "test@example.com" +[cell_information] +id = "12345" # Default CellID for Global Cell Information + [network_tokenization_supported_card_networks] card_networks = "Visa, AmericanExpress, Mastercard" # Supported card networks for network tokenization diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 319cdafed1d..db43cac979b 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -302,6 +302,9 @@ public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "p [user_auth_methods] encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table +[cell_information] +id = "12345" # Default CellID for Global Cell Information + [network_tokenization_service] # Network Tokenization Service Configuration generate_token_url= "" # base url to generate token fetch_token_url= "" # base url to fetch token diff --git a/config/development.toml b/config/development.toml index 6e56d5bb14d..29beed992f6 100644 --- a/config/development.toml +++ b/config/development.toml @@ -735,6 +735,9 @@ encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC69 [locker_based_open_banking_connectors] connector_list = "" +[cell_information] +id = "12345" + [network_tokenization_supported_card_networks] card_networks = "Visa, AmericanExpress, Mastercard" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 15038da0125..77a735aa757 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -137,8 +137,8 @@ ebanx.base_url = "https://sandbox.ebanxpay.com/" fiserv.base_url = "https://cert.api.fiservapps.com/" fiservemea.base_url = "https://prod.emea.api.fiservapps.com/sandbox" fiuu.base_url = "https://sandbox.merchant.razer.com/" -fiuu.secondary_base_url="https://sandbox.merchant.razer.com/" -fiuu.third_base_url="https://api.merchant.razer.com/" +fiuu.secondary_base_url = "https://sandbox.merchant.razer.com/" +fiuu.third_base_url = "https://api.merchant.razer.com/" forte.base_url = "https://sandbox.forte.net/api/v3" globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/" globepay.base_url = "https://pay.globepay.co/" @@ -380,7 +380,7 @@ open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,M upi_collect = { country = "IN", currency = "INR" } [pm_filters.plaid] -open_banking_pis = {currency = "EUR,GBP"} +open_banking_pis = { currency = "EUR,GBP" } [pm_filters.zen] credit = { not_available_flows = { capture_method = "manual" } } @@ -552,7 +552,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [multitenancy.tenants] public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } @@ -592,6 +592,9 @@ ach = { country = "US", currency = "USD" } [locker_based_open_banking_connectors] connector_list = "" +[cell_information] +id = "12345" + [network_tokenization_supported_card_networks] card_networks = "Visa, AmericanExpress, Mastercard" diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs index 5ed23a177b6..c0b6384abc6 100644 --- a/crates/common_utils/src/id_type/global_id.rs +++ b/crates/common_utils/src/id_type/global_id.rs @@ -63,27 +63,29 @@ impl From<AlphaNumericIdError> for CellIdError { impl CellId { /// Create a new cell id from a string - fn from_str(cell_id_string: &str) -> Result<Self, CellIdError> { - let trimmed_input_string = cell_id_string.trim().to_string(); + pub fn from_str(cell_id_string: impl AsRef<str>) -> Result<Self, CellIdError> { + let trimmed_input_string = cell_id_string.as_ref().trim().to_string(); let alphanumeric_id = AlphaNumericId::from(trimmed_input_string.into())?; let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?; Ok(Self(length_id)) } - pub fn from_string(input_string: String) -> error_stack::Result<Self, errors::ValidationError> { - Self::from_str(&input_string).change_context( - errors::ValidationError::IncorrectValueProvided { - field_name: "cell_id", - }, - ) - } - /// Get the string representation of the cell id fn get_string_repr(&self) -> &str { &self.0 .0 .0 } } +impl<'de> serde::Deserialize<'de> for CellId { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + let deserialized_string = String::deserialize(deserializer)?; + Self::from_str(deserialized_string.as_str()).map_err(serde::de::Error::custom) + } +} + /// Error generated from violation of constraints for MerchantReferenceId #[derive(Debug, Error, PartialEq, Eq)] pub(crate) enum GlobalIdError { diff --git a/crates/common_utils/src/id_type/global_id/payment_methods.rs b/crates/common_utils/src/id_type/global_id/payment_methods.rs index 5ccb774f6ea..3929efd09b5 100644 --- a/crates/common_utils/src/id_type/global_id/payment_methods.rs +++ b/crates/common_utils/src/id_type/global_id/payment_methods.rs @@ -28,8 +28,10 @@ pub enum GlobalPaymentMethodIdError { impl GlobalPaymentMethodId { /// Create a new GlobalPaymentMethodId from celll id information - pub fn generate(cell_id: &str) -> error_stack::Result<Self, errors::ValidationError> { - let cell_id = CellId::from_string(cell_id.to_string())?; + pub fn generate(cell_id: &str) -> error_stack::Result<Self, GlobalPaymentMethodIdError> { + let cell_id = CellId::from_str(cell_id) + .change_context(GlobalPaymentMethodIdError::ConstructionError) + .attach_printable("Failed to construct CellId from str")?; let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod); Ok(Self(global_id)) } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 442561c2ca3..83d159f6d29 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,7 +33,7 @@ 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"] +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"] 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"] diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 8c893b88319..e1b68efc446 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -498,6 +498,8 @@ pub(crate) async fn fetch_raw_secrets( decision: conf.decision, locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, grpc_client: conf.grpc_client, + #[cfg(feature = "v2")] + cell_information: conf.cell_information, network_tokenization_supported_card_networks: conf .network_tokenization_supported_card_networks, network_tokenization_service, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 675b8c44e2a..0a7defc4063 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -122,6 +122,8 @@ pub struct Settings<S: SecretState> { pub decision: Option<DecisionConfig>, pub locker_based_open_banking_connectors: LockerBasedRecipientConnectorList, pub grpc_client: GrpcClientSettings, + #[cfg(feature = "v2")] + pub cell_information: CellInformation, pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks, pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>, pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, @@ -854,6 +856,8 @@ impl Settings<SecuredSecret> { self.generic_link.payment_method_collect.validate()?; self.generic_link.payout_link.validate()?; + #[cfg(feature = "v2")] + self.cell_information.validate()?; self.network_tokenization_service .as_ref() .map(|x| x.get_inner().validate()) @@ -940,6 +944,26 @@ pub struct ServerTls { pub certificate: PathBuf, } +#[cfg(feature = "v2")] +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct CellInformation { + pub id: common_utils::id_type::CellId, +} + +#[cfg(feature = "v2")] +impl Default for CellInformation { + fn default() -> Self { + // We provide a static default cell id for constructing application settings. + // This will only panic at application startup if we're unable to construct the default, + // around the time of deserializing application settings. + // And a panic at application startup is considered acceptable. + #[allow(clippy::expect_used)] + let cell_id = common_utils::id_type::CellId::from_str("defid") + .expect("Failed to create a default for Cell Id"); + Self { id: cell_id } + } +} + fn deserialize_hashmap_inner<K, V>( value: HashMap<String, String>, ) -> Result<HashMap<K, HashSet<V>>, String> diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 67db7b1266c..7736d7b3f37 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -193,6 +193,19 @@ impl super::settings::GenericLinkEnvConfig { } } +#[cfg(feature = "v2")] +impl super::settings::CellInformation { + pub fn validate(&self) -> Result<(), ApplicationError> { + use common_utils::{fp_utils::when, id_type}; + + when(self == &super::settings::CellInformation::default(), || { + Err(ApplicationError::InvalidConfigurationValueError( + "CellId cannot be set to a default".into(), + )) + }) + } +} + impl super::settings::NetworkTokenizationService { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when;
2024-09-13T15:00:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added Cell Id in SessionState config The strategy is use check the value of Cell id at application start and panic if it equals the default value. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Cannot be tested, as setting the cell id as default in config will cause the application to panic. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
c0cac8d9135b14945ce5763327ec16b1578ca2a2
juspay/hyperswitch
juspay__hyperswitch-5891
Bug: [FEATURE] Open banking SDK fixes ### Feature Description SDK would send headers in order to identify the client platform, we need to consume in the backend and process accordingly. ### Possible Implementation Need to consume headers in specific flows. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 20f1205e14b..c50b1fb1d05 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -793,6 +793,8 @@ pub struct HeaderPayload { pub x_client_platform: Option<api_enums::ClientPlatform>, pub x_merchant_domain: Option<String>, pub locale: Option<String>, + pub x_app_id: Option<String>, + pub x_redirect_uri: Option<String>, } impl HeaderPayload { diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs index 8ed52907da8..443a4c30394 100644 --- a/crates/api_models/src/pm_auth.rs +++ b/crates/api_models/src/pm_auth.rs @@ -4,6 +4,8 @@ use common_utils::{ id_type, impl_api_event_type, }; +use crate::enums as api_enums; + #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct LinkTokenCreateRequest { @@ -12,6 +14,9 @@ pub struct LinkTokenCreateRequest { pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector + pub client_platform: api_enums::ClientPlatform, // Client Platform to perform platform based processing + pub android_package_name: Option<String>, // Android Package name to be sent for Android platform + pub redirect_uri: Option<String>, // Merchant redirect_uri to be sent in case of IOS platform } #[derive(Debug, Clone, serde::Serialize)] diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 653275bd560..9136ee35c7d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2479,6 +2479,7 @@ pub enum ClientPlatform { #[default] Web, Ios, + Android, #[serde(other)] Unknown, } diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index df0b63833d9..dde38561b44 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -80,6 +80,10 @@ pub struct RouterData<Flow, Request, Response> { pub minor_amount_captured: Option<MinorUnit>, pub integrity_check: Result<(), IntegrityCheckError>, + + pub additional_merchant_data: Option<api_models::admin::AdditionalMerchantData>, + + pub header_payload: Option<api_models::payments::HeaderPayload>, } // Different patterns of authentication. diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index ec182056f6c..93ace230f19 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -346,6 +346,8 @@ pub struct PaymentsPostProcessingData { pub customer_id: Option<id_type::CustomerId>, pub connector_transaction_id: Option<String>, pub country: Option<common_enums::CountryAlpha2>, + pub connector_meta_data: Option<pii::SecretSerdeValue>, + pub header_payload: Option<api_models::payments::HeaderPayload>, } impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>> @@ -371,6 +373,8 @@ impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsRes .get_payment_billing() .and_then(|bl| bl.address.as_ref()) .and_then(|address| address.country), + connector_meta_data: data.connector_meta_data.clone(), + header_payload: data.header_payload, }) } } diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index 109cc5a5c15..af0c26a5b85 100644 --- a/crates/pm_auth/src/connector/plaid/transformers.rs +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -15,6 +15,8 @@ pub struct PlaidLinkTokenRequest { language: String, products: Vec<String>, user: User, + android_package_name: Option<String>, + redirect_uri: Option<String>, } #[derive(Debug, Serialize, Eq, PartialEq)] @@ -42,6 +44,30 @@ impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest { }, )?, }, + android_package_name: match item.request.client_platform { + api_models::enums::ClientPlatform::Android => { + Some(item.request.android_package_name.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "android_package_name", + }, + )?) + } + api_models::enums::ClientPlatform::Ios + | api_models::enums::ClientPlatform::Web + | api_models::enums::ClientPlatform::Unknown => None, + }, + redirect_uri: match item.request.client_platform { + api_models::enums::ClientPlatform::Ios => { + Some(item.request.redirect_uri.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_uri", + }, + )?) + } + api_models::enums::ClientPlatform::Android + | api_models::enums::ClientPlatform::Web + | api_models::enums::ClientPlatform::Unknown => None, + }, }) } } diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs index 4c20e879d8b..878043afe50 100644 --- a/crates/pm_auth/src/types.rs +++ b/crates/pm_auth/src/types.rs @@ -3,6 +3,7 @@ pub mod api; use std::marker::PhantomData; use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate}; +use api_models::enums as api_enums; use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType}; use common_utils::{id_type, types}; use masking::Secret; @@ -24,6 +25,9 @@ pub struct LinkTokenRequest { pub country_codes: Option<Vec<String>>, pub language: Option<String>, pub user_info: Option<id_type::CustomerId>, + pub client_platform: api_enums::ClientPlatform, + pub android_package_name: Option<String>, + pub redirect_uri: Option<String>, } #[derive(Debug, Clone)] diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs index cf9c91afd0c..c4eb5a7a035 100644 --- a/crates/router/src/connector/plaid/transformers.rs +++ b/crates/router/src/connector/plaid/transformers.rs @@ -1,6 +1,5 @@ use common_enums::Currency; use common_utils::types::FloatMajorUnit; -use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -73,6 +72,8 @@ pub struct PlaidLinkTokenRequest { products: Vec<String>, user: User, payment_initiation: PlaidPaymentInitiation, + redirect_uri: Option<String>, + android_package_name: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize)] @@ -105,21 +106,21 @@ impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPay .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "payment_id", })?; - let recipient_val = item + let recipient_type = item .router_data - .connector_meta_data + .additional_merchant_data .as_ref() + .map(|merchant_data| match merchant_data { + api_models::admin::AdditionalMerchantData::OpenBankingRecipientData( + data, + ) => data.clone(), + }) .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "connector_customer", - })? - .peek() - .clone(); - - let recipient_type = - serde_json::from_value::<types::MerchantRecipientData>(recipient_val) - .change_context(errors::ConnectorError::ParsingFailed)?; + field_name: "additional_merchant_data", + })?; + let recipient_id = match recipient_type { - types::MerchantRecipientData::ConnectorRecipientId(id) => { + api_models::admin::MerchantRecipientData::ConnectorRecipientId(id) => { Ok(id.peek().to_string()) } _ => Err(errors::ConnectorError::MissingRequiredField { @@ -159,35 +160,73 @@ impl TryFrom<&types::PaymentsSyncRouterData> for PlaidSyncRequest { impl TryFrom<&types::PaymentsPostProcessingRouterData> for PlaidLinkTokenRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsPostProcessingRouterData) -> Result<Self, Self::Error> { - match item.request.payment_method_data.clone() { + match item.request.payment_method_data { domain::PaymentMethodData::OpenBanking(ref data) => match data { - domain::OpenBankingData::OpenBankingPIS { .. } => Ok(Self { - client_name: "Hyperswitch".to_string(), - country_codes: item - .request - .country - .map(|code| vec![code.to_string()]) - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "billing.address.country", - })?, - language: "en".to_string(), - products: vec!["payment_initiation".to_string()], - user: User { - client_user_id: item - .request - .customer_id - .clone() - .map(|id| id.get_string_repr().to_string()) - .unwrap_or("default cust".to_string()), - }, - payment_initiation: PlaidPaymentInitiation { - payment_id: item + domain::OpenBankingData::OpenBankingPIS { .. } => { + let headers = item.header_payload.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "header_payload", + }, + )?; + + let platform = headers.x_client_platform.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "x_client_platform", + }, + )?; + + let (is_android, is_ios) = match platform { + common_enums::ClientPlatform::Android => (true, false), + common_enums::ClientPlatform::Ios => (false, true), + _ => (false, false), + }; + + Ok(Self { + client_name: "Hyperswitch".to_string(), + country_codes: item .request - .connector_transaction_id - .clone() - .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, - }, - }), + .country + .map(|code| vec![code.to_string()]) + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "billing.address.country", + })?, + language: "en".to_string(), + products: vec!["payment_initiation".to_string()], + user: User { + client_user_id: item + .request + .customer_id + .clone() + .map(|id| id.get_string_repr().to_string()) + .unwrap_or("default cust".to_string()), + }, + payment_initiation: PlaidPaymentInitiation { + payment_id: item + .request + .connector_transaction_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?, + }, + android_package_name: if is_android { + Some(headers.x_app_id.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "x-app-id", + }, + )?) + } else { + None + }, + redirect_uri: if is_ios { + Some(headers.x_redirect_uri.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "x_redirect_uri", + }, + )?) + } else { + None + }, + }) + } }, _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs index f77296d7bc1..5b512bdd2b6 100644 --- a/crates/router/src/core/authentication.rs +++ b/crates/router/src/core/authentication.rs @@ -61,8 +61,12 @@ pub async fn perform_authentication( webhook_url, three_ds_requestor_url, )?; - let response = - utils::do_auth_connector_call(state, authentication_connector.clone(), router_data).await?; + let response = Box::pin(utils::do_auth_connector_call( + state, + authentication_connector.clone(), + router_data, + )) + .await?; let authentication = utils::update_trackers(state, response.clone(), authentication_data, None).await?; response diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs index 4a1298bb7bf..bbbbf9a2514 100644 --- a/crates/router/src/core/authentication/transformers.rs +++ b/crates/router/src/core/authentication/transformers.rs @@ -182,6 +182,8 @@ pub fn construct_router_data<F: Clone, Req, Res>( payment_method_status: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }) } diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 90c36ba9aa8..72a75661984 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -93,6 +93,7 @@ where customer, &merchant_connector_account, None, + None, ) .await?; diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs index 74606eb5917..92dc2a99e8a 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -39,6 +39,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC _customer: &Option<domain::Customer>, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + _header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>> { todo!() @@ -54,6 +55,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -151,6 +153,8 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs index f3eab2dd8d1..5ca790d4813 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -108,6 +108,8 @@ pub async fn construct_fulfillment_router_data<'a>( dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs index 6603f09cad3..e4d002931ec 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -36,6 +36,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh _customer: &Option<domain::Customer>, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + _header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>> { todo!() @@ -51,6 +52,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -120,6 +122,8 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs index 70006f555fe..56f6545cfd7 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp _customer: &Option<domain::Customer>, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + _header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> { todo!() } @@ -48,6 +49,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> { let status = storage_enums::AttemptStatus::Pending; @@ -128,6 +130,8 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload, }; Ok(router_data) diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs index ad62541155f..ebd967e7515 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -39,6 +39,7 @@ impl _customer: &Option<domain::Customer>, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + _header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult< RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>, > { @@ -55,6 +56,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult< RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>, > { @@ -134,6 +136,8 @@ impl dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload, }; Ok(router_data) diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index de4b0b77feb..544f9ea756e 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -78,6 +78,8 @@ pub async fn construct_mandate_revoke_router_data( dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 0ec14bd69ed..420757048f7 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -374,6 +374,7 @@ where &connector, &mut payment_data, op_ref, + Some(header_payload.clone()), ) .await?; } @@ -498,6 +499,7 @@ where &connector_data, &mut payment_data, op_ref, + Some(header_payload.clone()), ) .await?; } @@ -1625,6 +1627,7 @@ where customer, &merchant_connector_account, merchant_recipient_data, + None, ) .await?; @@ -1958,6 +1961,7 @@ where customer, &merchant_connector_account, None, + None, ) .await?; @@ -2103,6 +2107,7 @@ where customer, merchant_connector_account, None, + None, ) .await?; @@ -2287,6 +2292,7 @@ async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>( connector: &api::ConnectorData, payment_data: &mut D, _operation: &BoxedOperation<'_, F, Q, D>, + header_payload: Option<HeaderPayload>, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -2307,6 +2313,7 @@ where customer, merchant_conn_account, None, + header_payload, ) .await?; diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 1dec8911d31..e82af808b55 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -38,6 +38,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> { customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, Req, Res>>; #[cfg(all(feature = "v2", feature = "customer_v2"))] @@ -50,6 +51,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> { _customer: &Option<domain::Customer>, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<types::MerchantRecipientData>, + _header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, Req, Res>>; async fn get_merchant_recipient_data<'a>( diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs index e425abce336..aba38a40cb2 100644 --- a/crates/router/src/core/payments/flows/approve_flow.rs +++ b/crates/router/src/core/payments/flows/approve_flow.rs @@ -25,6 +25,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsApproveRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Approve, @@ -38,6 +39,7 @@ impl customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 0a55cefb427..ca01f377de7 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -37,6 +37,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult< types::RouterData< api::Authorize, @@ -56,6 +57,7 @@ impl customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index a56c49611a6..144bea32592 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -25,6 +25,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsCancelRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Void, @@ -38,6 +39,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index cb37a75813b..196466d208d 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -25,6 +25,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsCaptureRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Capture, @@ -38,6 +39,7 @@ impl customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } 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 212fb4bc240..1335e44b660 100644 --- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs +++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs @@ -29,6 +29,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult< types::RouterData< api::CompleteAuthorize, @@ -48,6 +49,7 @@ impl customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs index 226852e4a3c..76141537351 100644 --- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs +++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs @@ -28,6 +28,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> { Box::pin(transformers::construct_payment_router_data::< api::IncrementalAuthorization, @@ -41,6 +42,7 @@ impl customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index 428d170633e..ac205bcb7c8 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -26,6 +26,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult< types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, > { @@ -41,6 +42,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs index d2e65c8a638..f66bdfe3dfd 100644 --- a/crates/router/src/core/payments/flows/reject_flow.rs +++ b/crates/router/src/core/payments/flows/reject_flow.rs @@ -24,6 +24,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsRejectRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Reject, @@ -37,6 +38,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 54d8dc230c7..c4037a1a5b6 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -40,6 +40,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::PaymentsSessionRouterData> { Box::pin(transformers::construct_payment_router_data::< api::Session, @@ -53,6 +54,7 @@ impl customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/flows/session_update_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rs index c12667e19a2..682c20b725d 100644 --- a/crates/router/src/core/payments/flows/session_update_flow.rs +++ b/crates/router/src/core/payments/flows/session_update_flow.rs @@ -28,6 +28,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<types::MerchantRecipientData>, + _header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::SdkSessionUpdateRouterData> { Box::pin( transformers::construct_router_data_to_update_calculated_tax::< diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs index c412fd2b37f..293371024c9 100644 --- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs +++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs @@ -32,6 +32,7 @@ impl customer: &Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::SetupMandateRouterData> { Box::pin(transformers::construct_payment_router_data::< api::SetupMandate, @@ -45,6 +46,7 @@ impl customer, merchant_connector_account, merchant_recipient_data, + header_payload, )) .await } diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 2af3c52d758..9be4b02cbbd 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3634,6 +3634,8 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( connector_response: router_data.connector_response, integrity_check: Ok(()), connector_wallets_details: router_data.connector_wallets_details, + additional_merchant_data: router_data.additional_merchant_data, + header_payload: router_data.header_payload, } } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 93fa3ed44b8..de48f7e700a 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -151,6 +151,8 @@ where dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } @@ -167,6 +169,7 @@ pub async fn construct_payment_router_data<'a, F, T>( _customer: &'a Option<domain::Customer>, _merchant_connector_account: &helpers::MerchantConnectorAccountType, _merchant_recipient_data: Option<types::MerchantRecipientData>, + _header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, @@ -190,6 +193,7 @@ pub async fn construct_payment_router_data<'a, F, T>( customer: &'a Option<domain::Customer>, merchant_connector_account: &helpers::MerchantConnectorAccountType, merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, ) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>> where T: TryFrom<PaymentAdditionalData<'a, F>>, @@ -318,14 +322,7 @@ where .payment_attempt .authentication_type .unwrap_or_default(), - connector_meta_data: if let Some(data) = merchant_recipient_data { - let val = serde_json::to_value(data) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed while encoding MerchantRecipientData")?; - Some(Secret::new(val)) - } else { - merchant_connector_account.get_metadata() - }, + connector_meta_data: merchant_connector_account.get_metadata(), connector_wallets_details: merchant_connector_account.get_connector_wallets_details(), request: T::try_from(additional_data)?, response, @@ -364,6 +361,12 @@ where dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: merchant_recipient_data.map(|data| { + api_models::admin::AdditionalMerchantData::foreign_from( + types::AdditionalMerchantData::OpenBankingRecipientData(data), + ) + }), + header_payload, }; Ok(router_data) diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 85d5b78521f..6c8ad32234c 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -717,13 +717,13 @@ pub async fn payouts_fulfill_core( .await? .get_required_value("payout_method_data")?, ); - fulfill_payout( + Box::pin(fulfill_payout( &state, &merchant_account, &key_store, &connector_data, &mut payout_data, - ) + )) .await .attach_printable("Payout fulfillment failed for given Payout request")?; @@ -1121,13 +1121,13 @@ pub async fn call_connector_payout( // Auto fulfillment flow let status = payout_data.payout_attempt.status; if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment { - fulfill_payout( + Box::pin(fulfill_payout( state, merchant_account, key_store, connector_data, payout_data, - ) + )) .await .attach_printable("Payout fulfillment failed for given Payout request")?; } diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index f948d7faaf9..78b06a421af 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -165,6 +165,9 @@ pub async fn create_link_token( )?]), language: payload.language, user_info: payment_intent.and_then(|pi| pi.customer_id), + client_platform: payload.client_platform, + android_package_name: payload.android_package_name, + redirect_uri: payload.redirect_uri, }, response: Ok(pm_auth_types::LinkTokenResponse { link_token: "".to_string(), diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 0f7abf44b14..a45b3be8a3c 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1185,7 +1185,7 @@ pub async fn schedule_refund_execution( Ok(refund) } api_models::refunds::RefundType::Instant => { - let update_refund = trigger_refund_to_gateway( + let update_refund = Box::pin(trigger_refund_to_gateway( state, &refund, merchant_account, @@ -1194,7 +1194,7 @@ pub async fn schedule_refund_execution( payment_intent, creds_identifier, charges, - ) + )) .await; match update_refund { @@ -1438,7 +1438,7 @@ pub async fn trigger_refund_execute_workflow( }; //trigger refund request to gateway - let updated_refund = trigger_refund_to_gateway( + let updated_refund = Box::pin(trigger_refund_to_gateway( state, &refund, &merchant_account, @@ -1447,7 +1447,7 @@ pub async fn trigger_refund_execute_workflow( &payment_intent, None, charges, - ) + )) .await?; add_refund_sync_task( db, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 0e8b21f3a8a..8e86fb86967 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -215,6 +215,8 @@ pub async fn construct_payout_router_data<'a, F>( dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) @@ -370,6 +372,8 @@ pub async fn construct_refund_router_data<'a, F>( dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) @@ -677,6 +681,8 @@ pub async fn construct_accept_dispute_router_data<'a>( refund_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } @@ -769,6 +775,8 @@ pub async fn construct_submit_evidence_router_data<'a>( dispute_id: Some(dispute.dispute_id.clone()), connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } @@ -867,6 +875,8 @@ pub async fn construct_upload_file_router_data<'a>( dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } @@ -974,6 +984,8 @@ pub async fn construct_payments_dynamic_tax_calculation_router_data<'a, F: Clone payment_method_status: None, minor_amount_captured: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } @@ -1069,6 +1081,8 @@ pub async fn construct_defend_dispute_router_data<'a>( dispute_id: Some(dispute.dispute_id.clone()), connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } @@ -1159,6 +1173,8 @@ pub async fn construct_retrieve_file_router_data<'a>( dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 8987a9384df..8680e43eff3 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -120,6 +120,8 @@ pub async fn construct_webhook_router_data<'a>( dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, }; Ok(router_data) } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index caa96826937..b18c9ff4e80 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -83,6 +83,8 @@ pub mod headers { 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 const X_APP_ID: &str = "x-app-id"; + pub const X_REDIRECT_URI: &str = "x-redirect-uri"; pub const X_TENANT_ID: &str = "x-tenant-id"; } diff --git a/crates/router/src/services/conversion_impls.rs b/crates/router/src/services/conversion_impls.rs index f1aec19bd30..22930916093 100644 --- a/crates/router/src/services/conversion_impls.rs +++ b/crates/router/src/services/conversion_impls.rs @@ -74,6 +74,8 @@ fn get_default_router_data<F, Req, Resp>( payment_method_status: None, minor_amount_captured: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 16a8ed1ccc4..27fa1e1ced0 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -906,6 +906,8 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2) refund_id: data.refund_id.clone(), connector_response: data.connector_response.clone(), integrity_check: Ok(()), + additional_merchant_data: data.additional_merchant_data.clone(), + header_payload: data.header_payload.clone(), } } } @@ -968,6 +970,8 @@ impl<F1, F2> dispute_id: None, connector_response: data.connector_response.clone(), integrity_check: Ok(()), + additional_merchant_data: data.additional_merchant_data.clone(), + header_payload: data.header_payload.clone(), } } } diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 1b3162a3549..6c92b1b801a 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -113,6 +113,8 @@ impl VerifyConnectorData { dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, } } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 46210d4dd09..3df2299a2ae 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -21,8 +21,8 @@ use super::domain; use crate::{ core::errors, headers::{ - ACCEPT_LANGUAGE, BROWSER_NAME, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, X_CLIENT_VERSION, - X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, + ACCEPT_LANGUAGE, BROWSER_NAME, X_APP_ID, X_CLIENT_PLATFORM, X_CLIENT_SOURCE, + X_CLIENT_VERSION, X_MERCHANT_DOMAIN, X_PAYMENT_CONFIRM_SOURCE, X_REDIRECT_URI, }, services::authentication::get_header_value_by_key, types::{ @@ -1420,6 +1420,12 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { let x_merchant_domain = get_header_value_by_key(X_MERCHANT_DOMAIN.into(), headers)?.map(|val| val.to_string()); + let x_app_id = + get_header_value_by_key(X_APP_ID.into(), headers)?.map(|val| val.to_string()); + + let x_redirect_uri = + get_header_value_by_key(X_REDIRECT_URI.into(), headers)?.map(|val| val.to_string()); + Ok(Self { payment_confirm_source, client_source, @@ -1429,6 +1435,8 @@ impl ForeignTryFrom<&HeaderMap> for payments::HeaderPayload { x_client_platform, x_merchant_domain, locale, + x_app_id, + x_redirect_uri, }) } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index f3ff1a60361..5d48a0188ff 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -126,6 +126,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { refund_id: None, dispute_id: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, } } @@ -193,6 +195,8 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { refund_id: None, dispute_id: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, } } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index ea12d463fbd..582c212c241 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -544,6 +544,8 @@ pub trait ConnectorActions: Connector { dispute_id: None, connector_response: None, integrity_check: Ok(()), + additional_merchant_data: None, + header_payload: None, } }
2024-09-13T13:40:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Refactored RouterData to use HeaderPayload for Android/IOS Platform specific flows. - Refactored Open banking flows to consume and process the header information to take decisions based on client platform. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Payments create - ``` curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uFcNSTN14N27NiyGdgkK8eN2fBmPWHHhbPZh6RMkBUxoByMfAdPlBItplwGctI6P' \ --data-raw '{ "amount": 6500, "currency": "EUR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://google.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "GB", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response ``` { "payment_id": "pay_qrNjDvodTni9SiSVeukh", "merchant_id": "merchant_1726386502", "status": "requires_payment_method", "amount": 6500, "net_amount": 6500, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI", "created": "2024-09-15T07:50:42.333Z", "currency": "EUR", "customer_id": null, "customer": { "id": null, "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_72r0N5WGBqazqsPQluK8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-15T08:05:42.333Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-15T07:50:42.348Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` 2. PML - ``` curl --location --request GET 'http://localhost:8080/account/payment_methods?client_secret=pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_18865dbf242d48158d05eb8b49a55251' ``` Response - ``` { "redirect_url": "https://google.com/success", "currency": "EUR", "payment_methods": [ { "payment_method": "open_banking", "payment_method_types": [ { "payment_method_type": "open_banking_pis", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "plaid" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "Sarthak1", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` 3. Payments confirm - ``` curl --location --request POST 'http://localhost:8080/payments/pay_qrNjDvodTni9SiSVeukh/confirm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-client-platform: android' \ --header 'x-app-id: io.hyperswitch' \ --header 'api-key: pk_dev_18865dbf242d48158d05eb8b49a55251' \ --data-raw '{ "client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI", "payment_method": "open_banking", "payment_method_type": "open_banking_pis", "payment_method_data": { "open_banking": { "open_banking_pis": {} } } }' ``` Response - ``` { "payment_id": "pay_qrNjDvodTni9SiSVeukh", "merchant_id": "merchant_1726386502", "status": "requires_customer_action", "amount": 6500, "net_amount": 6500, "amount_capturable": 6500, "amount_received": null, "connector": "plaid", "client_secret": "pay_qrNjDvodTni9SiSVeukh_secret_Y14Mk7PkltuhrpuVCqAI", "created": "2024-09-15T07:50:42.333Z", "currency": "EUR", "customer_id": null, "customer": { "id": null, "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+1" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "open_banking", "payment_method_data": { "open_banking": { "open_banking_pis": {} }, "billing": null }, "payment_token": null, "shipping": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594430", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "GB", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "john", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": null, "name": null, "phone": null, "return_url": "https://google.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "third_party_sdk_session_token", "session_token": { "wallet_name": "open_banking", "open_banking_session_token": "link-sandbox-9e376cad-8ab2-40f7-b0a0-4744d06a003b" } }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "open_banking_pis", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": null, "connector_transaction_id": "payment-id-sandbox-adcf53a4-c1ff-46d9-81c2-8e8bfa0d6db2", "frm_message": null, "metadata": { "udf1": "value1", "login_date": "2019-09-10T10:11:12Z", "new_customer": "true" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "payment-id-sandbox-adcf53a4-c1ff-46d9-81c2-8e8bfa0d6db2", "payment_link": null, "profile_id": "pro_72r0N5WGBqazqsPQluK8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_jp7RozkyIQV4e9zTXjyf", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-15T08:05:42.333Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-15T07:51:02.510Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
fbd2cda763f0d8d2757d734578babd73a8613cb8
juspay/hyperswitch
juspay__hyperswitch-5862
Bug: [REFACTOR] unify locker api function call Create a single method using which locker api can be called and deserialised to the given type. Also send tenant-id in headers
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 996224d7bea..e2c2dbb48ce 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -4486,7 +4486,7 @@ async fn locker_recipient_create_call( ttl: state.conf.locker.ttl_for_storage_in_secs, }); - let store_resp = cards::call_to_locker_hs( + let store_resp = cards::add_card_to_hs_locker( state, &payload, &cust_id, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index c22465c3a32..7fc3e9a9559 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -124,6 +124,8 @@ pub enum VaultError { SaveCardFailed, #[error("Failed to fetch card details from card vault")] FetchCardFailed, + #[error("Failed to delete card in card vault")] + DeleteCardFailed, #[error("Failed to encode card vault request")] RequestEncodingFailed, #[error("Failed to deserialize card vault response")] @@ -146,6 +148,8 @@ pub enum VaultError { SavePaymentMethodFailed, #[error("Failed to generate fingerprint")] GenerateFingerprintFailed, + #[error("Failed while calling locker API")] + ApiError, } #[derive(Debug, thiserror::Error)] diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index ccd64f066df..376faeb6464 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -28,8 +28,10 @@ use common_utils::{ consts, crypto::{self, Encryptable}, encryption::Encryption, - ext_traits::{AsyncExt, Encode, StringExt, ValueExt}, - generate_id, id_type, type_name, + ext_traits::{AsyncExt, BytesExt, Encode, StringExt, ValueExt}, + generate_id, id_type, + request::Request, + type_name, types::{ keymanager::{Identifier, KeyManagerState}, MinorUnit, @@ -93,7 +95,7 @@ use crate::{ storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, transformers::ForeignTryFrom, }, - utils::{ConnectorResponseExt, OptionExt}, + utils::OptionExt, }; #[cfg(all( any(feature = "v1", feature = "v2"), @@ -1876,7 +1878,7 @@ pub async fn add_bank_to_locker( enc_data, ttl: state.conf.locker.ttl_for_storage_in_secs, }); - let store_resp = call_to_locker_hs( + let store_resp = add_card_to_hs_locker( state, &payload, customer_id, @@ -1920,7 +1922,7 @@ pub async fn add_card_to_locker( card_reference, ) .await - .inspect_err(|error| { + .inspect_err(|_| { metrics::CARD_LOCKER_FAILURES.add( &metrics::CONTEXT, 1, @@ -1929,7 +1931,6 @@ pub async fn add_card_to_locker( router_env::opentelemetry::KeyValue::new("operation", "add"), ], ); - logger::error!(?error, "Failed to add card in locker"); }) }, &metrics::CARD_ADD_TIME, @@ -1962,7 +1963,7 @@ pub async fn get_card_from_locker( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed while getting card from hyperswitch card vault") - .inspect_err(|error| { + .inspect_err(|_| { metrics::CARD_LOCKER_FAILURES.add( &metrics::CONTEXT, 1, @@ -1971,7 +1972,6 @@ pub async fn get_card_from_locker( router_env::opentelemetry::KeyValue::new("operation", "get"), ], ); - logger::error!(?error, "Failed to retrieve card from locker"); }) }, &metrics::CARD_GET_TIME, @@ -1996,9 +1996,15 @@ pub async fn delete_card_from_locker( async move { delete_card_from_hs_locker(state, customer_id, merchant_id, card_reference) .await - .inspect_err(|error| { - metrics::CARD_LOCKER_FAILURES.add(&metrics::CONTEXT, 1, &[]); - logger::error!(?error, "Failed to delete card from locker"); + .inspect_err(|_| { + metrics::CARD_LOCKER_FAILURES.add( + &metrics::CONTEXT, + 1, + &[ + router_env::opentelemetry::KeyValue::new("locker", "rust"), + router_env::opentelemetry::KeyValue::new("operation", "delete"), + ], + ); }) }, &metrics::CARD_DELETE_TIME, @@ -2006,6 +2012,8 @@ pub async fn delete_card_from_locker( &[], ) .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed while deleting card from locker") } #[cfg(all(feature = "v2", feature = "customer_v2"))] @@ -2049,7 +2057,8 @@ pub async fn add_card_hs( ttl: state.conf.locker.ttl_for_storage_in_secs, }); - let store_card_payload = call_to_locker_hs(state, &payload, customer_id, locker_choice).await?; + let store_card_payload = + add_card_to_hs_locker(state, &payload, customer_id, locker_choice).await?; let payment_method_resp = payment_methods::mk_add_card_response_hs( card.clone(), @@ -2111,30 +2120,22 @@ pub async fn get_payment_method_from_hs_locker<'a>( merchant_id, payment_method_reference, locker_choice, + state.tenant.name.clone(), + state.request_id, ) .await .change_context(errors::VaultError::FetchPaymentMethodFailed) .attach_printable("Making get payment method request failed")?; - let response = services::call_connector_api(state, request, "add_card_to_locker") - .await - .change_context(errors::VaultError::FetchPaymentMethodFailed) - .attach_printable("Failed while executing call_connector_api for get_card"); - 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, + + let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>( + state, + request, + "get_pm_from_locker", locker_choice, - locker.decryption_scheme.clone(), ) .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) - .attach_printable("Failed to parse struct to RetrieveCardResp")?; + .change_context(errors::VaultError::FetchPaymentMethodFailed)?; + let retrieve_card_resp = get_card_resp .payload .get_required_value("RetrieveCardRespPayload") @@ -2158,7 +2159,7 @@ pub async fn get_payment_method_from_hs_locker<'a>( } #[instrument(skip_all)] -pub async fn call_to_locker_hs( +pub async fn add_card_to_hs_locker( state: &routes::SessionState, payload: &payment_methods::StoreLockerReq, customer_id: &id_type::CustomerId, @@ -2168,30 +2169,23 @@ pub async fn call_to_locker_hs( let jwekey = state.conf.jwekey.get_inner(); let db = &*state.store; let stored_card_response = if !locker.mock_locker { - let request = - payment_methods::mk_add_locker_request_hs(jwekey, locker, payload, locker_choice) - .await?; - let response = services::call_connector_api(state, request, "add_card_to_hs_locker") - .await - .change_context(errors::VaultError::SaveCardFailed); - - let jwe_body: services::JweBody = response - .get_response_inner("JweBody") - .change_context(errors::VaultError::FetchCardFailed)?; - - let decrypted_payload = payment_methods::get_decrypted_response_payload( + let request = payment_methods::mk_add_locker_request_hs( jwekey, - jwe_body, + locker, + payload, + locker_choice, + state.tenant.name.clone(), + state.request_id, + ) + .await?; + call_locker_api::<payment_methods::StoreCardResp>( + state, + request, + "add_card_to_hs_locker", Some(locker_choice), - locker.decryption_scheme.clone(), ) .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)?; - stored_card_resp + .change_context(errors::VaultError::SaveCardFailed)? } else { let card_id = generate_id(consts::ID_LENGTH, "card"); mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await? @@ -2204,6 +2198,61 @@ pub async fn call_to_locker_hs( Ok(stored_card) } +#[instrument(skip_all)] +pub async fn call_locker_api<T>( + state: &routes::SessionState, + request: Request, + flow_name: &str, + locker_choice: Option<api_enums::LockerChoice>, +) -> errors::CustomResult<T, errors::VaultError> +where + T: serde::de::DeserializeOwned, +{ + let locker = &state.conf.locker; + let jwekey = state.conf.jwekey.get_inner(); + let response_type_name = type_name!(T); + + let response = services::call_connector_api(state, request, flow_name) + .await + .change_context(errors::VaultError::ApiError)?; + + let is_locker_call_succeeded = response.is_ok(); + + let jwe_body = response + .unwrap_or_else(|err| err) + .response + .parse_struct::<services::JweBody>("JweBody") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed while parsing locker response into JweBody")?; + + let decrypted_payload = payment_methods::get_decrypted_response_payload( + jwekey, + jwe_body, + locker_choice, + locker.decryption_scheme.clone(), + ) + .await + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed while decrypting locker payload response")?; + + // Irrespective of locker's response status, payload is JWE + JWS decrypted. But based on locker's status, + // if Ok, deserialize the decrypted payload into given type T + // if Err, raise an error including locker error message too + if is_locker_call_succeeded { + let stored_card_resp: Result<T, error_stack::Report<errors::VaultError>> = + decrypted_payload + .parse_struct(response_type_name) + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable_lazy(|| { + format!("Failed while parsing locker response into {response_type_name}") + }); + stored_card_resp + } else { + Err::<T, error_stack::Report<errors::VaultError>>((errors::VaultError::ApiError).into()) + .attach_printable_lazy(|| format!("Locker error response: {decrypted_payload:?}")) + } +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -2322,29 +2371,21 @@ pub async fn get_card_from_hs_locker<'a>( merchant_id, card_reference, Some(locker_choice), + state.tenant.name.clone(), + state.request_id, ) .await .change_context(errors::VaultError::FetchCardFailed) .attach_printable("Making get card request failed")?; - let response = services::call_connector_api(state, request, "get_card_from_locker") - .await - .change_context(errors::VaultError::FetchCardFailed) - .attach_printable("Failed while executing call_connector_api for get_card"); - 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, + let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>( + state, + request, + "get_card_from_locker", Some(locker_choice), - locker.decryption_scheme.clone(), ) .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)?; + .change_context(errors::VaultError::FetchCardFailed)?; + let retrieve_card_resp = get_card_resp .payload .get_required_value("RetrieveCardRespPayload") @@ -2366,7 +2407,7 @@ pub async fn delete_card_from_hs_locker<'a>( customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &'a str, -) -> errors::RouterResult<payment_methods::DeleteCardResp> { +) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> { let locker = &state.conf.locker; let jwekey = &state.conf.jwekey.get_inner(); @@ -2376,35 +2417,26 @@ pub async fn delete_card_from_hs_locker<'a>( customer_id, merchant_id, card_reference, + state.tenant.name.clone(), + state.request_id, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) + .change_context(errors::VaultError::DeleteCardFailed) .attach_printable("Making delete card request failed")?; if !locker.mock_locker { - let response = services::call_connector_api(state, request, "delete_card_from_locker") - .await - .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, + call_locker_api::<payment_methods::DeleteCardResp>( + state, + request, + "delete_card_from_locker", Some(api_enums::LockerChoice::HyperswitchCardVault), - locker.decryption_scheme.clone(), ) .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)?; - Ok(delete_card_resp) + .change_context(errors::VaultError::DeleteCardFailed) } else { Ok(mock_delete_card_hs(&*state.store, card_reference) .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("card_delete_failure_message")?) + .change_context(errors::VaultError::DeleteCardFailed)?) } } @@ -4871,6 +4903,10 @@ pub async fn list_customer_payment_method( let mut filtered_saved_payment_methods_ctx = Vec::new(); for pm in saved_payment_methods.into_iter() { + logger::debug!( + "Fetching payment method from locker for payment_method_id: {}", + pm.id + ); let payment_method = pm.payment_method.get_required_value("payment_method")?; let parent_payment_method_token = is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token")); diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index f594feb5954..f01ecffbbb3 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -10,6 +10,7 @@ use common_utils::{ }; use error_stack::ResultExt; use josekit::jwe; +use router_env::tracing_actix_web::RequestId; use serde::{Deserialize, Serialize}; use crate::{ @@ -301,6 +302,8 @@ pub async fn mk_add_locker_request_hs( locker: &settings::Locker, payload: &StoreLockerReq, locker_choice: api_enums::LockerChoice, + tenant_id: String, + request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let payload = payload .encode_to_vec() @@ -319,6 +322,13 @@ pub async fn mk_add_locker_request_hs( url.push_str("/cards/add"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header(headers::X_TENANT_ID, tenant_id.into()); + if let Some(req_id) = request_id { + request.add_header( + headers::X_REQUEST_ID, + req_id.as_hyphenated().to_string().into(), + ); + } request.set_body(RequestContent::Json(Box::new(jwe_payload))); Ok(request) } @@ -425,6 +435,7 @@ pub fn mk_add_card_response_hs( todo!() } +#[allow(clippy::too_many_arguments)] pub async fn mk_get_card_request_hs( jwekey: &settings::Jwekey, locker: &settings::Locker, @@ -432,6 +443,8 @@ pub async fn mk_get_card_request_hs( merchant_id: &id_type::MerchantId, card_reference: &str, locker_choice: Option<api_enums::LockerChoice>, + tenant_id: String, + request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = customer_id.to_owned(); let card_req_body = CardReqBody { @@ -458,6 +471,14 @@ pub async fn mk_get_card_request_hs( url.push_str("/cards/retrieve"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header(headers::X_TENANT_ID, tenant_id.into()); + if let Some(req_id) = request_id { + request.add_header( + headers::X_REQUEST_ID, + req_id.as_hyphenated().to_string().into(), + ); + } + request.set_body(RequestContent::Json(Box::new(jwe_payload))); Ok(request) } @@ -503,6 +524,8 @@ pub async fn mk_delete_card_request_hs( customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, + tenant_id: String, + request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = customer_id.to_owned(); let card_req_body = CardReqBody { @@ -527,6 +550,14 @@ pub async fn mk_delete_card_request_hs( url.push_str("/cards/delete"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header(headers::X_TENANT_ID, tenant_id.into()); + if let Some(req_id) = request_id { + request.add_header( + headers::X_REQUEST_ID, + req_id.as_hyphenated().to_string().into(), + ); + } + request.set_body(RequestContent::Json(Box::new(jwe_payload))); Ok(request) } @@ -539,6 +570,8 @@ pub async fn mk_delete_card_request_hs_by_id( id: &String, merchant_id: &id_type::MerchantId, card_reference: &str, + tenant_id: String, + request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = id.to_owned(); let card_req_body = CardReqBodyV2 { @@ -563,6 +596,14 @@ pub async fn mk_delete_card_request_hs_by_id( url.push_str("/cards/delete"); let mut request = services::Request::new(services::Method::Post, &url); request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header(headers::X_TENANT_ID, tenant_id.into()); + if let Some(req_id) = request_id { + request.add_header( + headers::X_REQUEST_ID, + req_id.as_hyphenated().to_string().into(), + ); + } + request.set_body(RequestContent::Json(Box::new(jwe_payload))); Ok(request) } @@ -641,12 +682,22 @@ pub fn mk_crud_locker_request( locker: &settings::Locker, path: &str, req: api::TokenizePayloadEncrypted, + tenant_id: String, + request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let mut url = locker.basilisk_host.to_owned(); url.push_str(path); let mut request = services::Request::new(services::Method::Post, &url); request.add_default_headers(); request.add_header(headers::CONTENT_TYPE, "application/json".into()); + request.add_header(headers::X_TENANT_ID, tenant_id.into()); + if let Some(req_id) = request_id { + request.add_header( + headers::X_REQUEST_ID, + req_id.as_hyphenated().to_string().into(), + ); + } + request.set_body(RequestContent::Json(Box::new(req))); Ok(request) } diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 11cb0c11761..035c5c139a8 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -307,7 +307,7 @@ pub async fn save_payout_data_to_locker( }; // Store payout method in locker - let stored_resp = cards::call_to_locker_hs( + let stored_resp = cards::add_card_to_hs_locker( state, &locker_req, customer_id, @@ -559,6 +559,7 @@ pub async fn save_payout_data_to_locker( card_reference, ) .await + .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to delete PMD from locker as a part of metadata update operation", )?; @@ -566,7 +567,7 @@ pub async fn save_payout_data_to_locker( locker_req.update_requestor_card_reference(Some(card_reference.to_string())); // Store in locker - let stored_resp = cards::call_to_locker_hs( + let stored_resp = cards::add_card_to_hs_locker( state, &locker_req, customer_id, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index ac452233e0f..caa96826937 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -83,6 +83,7 @@ pub mod headers { 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 const X_TENANT_ID: &str = "x-tenant-id"; } pub mod pii {
2024-09-11T14:08:08Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR performs below changes - * Creates a single method using which locker api can be called and deserialised to the given type. * Currently, if locker returns an Err, the error response is not JWE+JWS decrypted. Instead its logged directly. This new method calls the api and irrespective of whether locker responds with an OK response or Err response, JWE+JWS decryption happens on the locker response. * Sends `x-tenant-id` in the headers to locker ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> To test, I failed the locker on purpose and received below error report in Hyperswitch which also includes JWE+JWS decrypted error message. ![image](https://github.com/user-attachments/assets/e2c5374d-529d-4184-8353-5b485d4180f8) Sandbox testing - Basic sanity tests which also involves saving card in locker would suffice ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
10ac08944986a1fd101f8f05263e92ed7ebbba94
juspay/hyperswitch
juspay__hyperswitch-5860
Bug: refactor(users): Populate optional fields in the user APIs Currently - list users in lineage - get user role details - list invitations APIs send `null` for role_name, entity_name etc... These fields should be populated with proper data.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 7bb8409993d..7b22387b3c3 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -188,6 +188,7 @@ pub struct GetUserRoleDetailsResponseV2 { pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, pub status: UserStatus, pub entity_type: EntityType, + pub role_name: String, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 22aa80a459a..828dfeb20f8 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -63,5 +63,5 @@ pub enum RoleCheckType { #[derive(Debug, serde::Serialize, Clone)] pub struct MinimalRoleInfo { pub role_id: String, - pub role_name: Option<String>, + pub role_name: String, } diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs index 0a3c0e6d42f..065a5b6e114 100644 --- a/crates/diesel_models/src/query/role.rs +++ b/crates/diesel_models/src/query/role.rs @@ -43,6 +43,20 @@ impl Role { .await } + pub async fn find_by_role_id_in_org_scope( + conn: &PgPooledConn, + role_id: &str, + org_id: &id_type::OrganizationId, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::role_id + .eq(role_id.to_owned()) + .and(dsl::org_id.eq(org_id.to_owned())), + ) + .await + } + pub async fn update_by_role_id( conn: &PgPooledConn, role_id: &str, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index c9b0a956dbc..a0b6606c227 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1829,11 +1829,15 @@ pub mod routes { json_payload.into_inner(), |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; - let role_info = - RoleInfo::from_role_id(&state, &role_id, &auth.merchant_id, &auth.org_id) - .await - .change_context(UserErrors::InternalServerError) - .change_context(OpenSearchError::UnknownError)?; + let role_info = RoleInfo::from_role_id_in_merchant_scope( + &state, + &role_id, + &auth.merchant_id, + &auth.org_id, + ) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; let permissions = role_info.get_permissions_set(); let accessible_indexes: Vec<_> = OPENSEARCH_INDEX_PERMISSIONS .iter() @@ -1885,11 +1889,15 @@ pub mod routes { indexed_req, |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; - let role_info = - RoleInfo::from_role_id(&state, &role_id, &auth.merchant_id, &auth.org_id) - .await - .change_context(UserErrors::InternalServerError) - .change_context(OpenSearchError::UnknownError)?; + let role_info = RoleInfo::from_role_id_in_merchant_scope( + &state, + &role_id, + &auth.merchant_id, + &auth.org_id, + ) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; let permissions = role_info.get_permissions_set(); let _ = OPENSEARCH_INDEX_PERMISSIONS .iter() diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 31ab0e8ff22..45e9065d263 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -100,7 +100,7 @@ pub async fn get_user_details( ) -> UserResponse<user_api::GetUserDetailsResponse> { let user = user_from_token.get_user_from_db(&state).await?; let verification_days_left = utils::user::get_verification_days_left(&state, &user)?; - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -539,7 +539,7 @@ async fn handle_invitation( .into()); } - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( state, &request.role_id, &user_from_token.merchant_id, @@ -1154,7 +1154,7 @@ pub async fn switch_merchant_id( let user = user_from_token.get_user_from_db(&state).await?; let key_manager_state = &(&state).into(); - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -1328,10 +1328,15 @@ pub async fn list_merchants_for_user( return Err(report!(UserErrors::InternalServerError) .attach_printable("org_id not found in user_role")); }; - roles::RoleInfo::from_role_id(&state, &user_role.role_id, merchant_id, org_id) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Unable to find role info for user role") + roles::RoleInfo::from_role_id_in_merchant_scope( + &state, + &user_role.role_id, + merchant_id, + org_id, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to find role info for user role") })) .await? .into_iter() @@ -1394,7 +1399,7 @@ pub async fn get_user_details_in_merchant_account( .to_not_found_response(UserErrors::InvalidRoleOperation) .attach_printable("User not found in the merchant account")?; - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &required_user_role.role_id, &user_from_token.merchant_id, @@ -1428,7 +1433,7 @@ pub async fn list_user_roles_details( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; - let requestor_role_info = roles::RoleInfo::from_role_id( + let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -1438,7 +1443,7 @@ pub async fn list_user_roles_details( .to_not_found_response(UserErrors::InternalServerError) .attach_printable("Failed to fetch role info")?; - let user_roles_set: HashSet<_> = state + let user_roles_set = state .store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: required_user.get_user_id(), @@ -1459,7 +1464,7 @@ pub async fn list_user_roles_details( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to fetch user roles")? .into_iter() - .collect(); + .collect::<HashSet<_>>(); let org_name = state .store @@ -1477,11 +1482,11 @@ pub async fn list_user_roles_details( let (merchant_ids, merchant_profile_ids) = user_roles_set.iter().try_fold( (Vec::new(), Vec::new()), |(mut merchant, mut merchant_profile), user_role| { - let entity_type = user_role + let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError) - .attach_printable("Failed to fetch entity id and type")? - .1; + .attach_printable("Failed to compute entity id and type")?; + match entity_type { EntityType::Merchant => { let merchant_id = user_role @@ -1525,7 +1530,7 @@ pub async fn list_user_roles_details( }, )?; - let merchant_map: HashMap<_, _> = state + let merchant_map = state .store .list_multiple_merchant_accounts(&(&state).into(), merchant_ids) .await @@ -1538,50 +1543,71 @@ pub async fn list_user_roles_details( merchant_account.merchant_name.clone(), ) }) - .collect(); + .collect::<HashMap<_, _>>(); let key_manager_state = &(&state).into(); - let profile_map: HashMap<_, _> = - futures::future::try_join_all(merchant_profile_ids.iter().map( - |merchant_profile_id| async { - let merchant_key_store = state - .store - .get_merchant_key_store_by_merchant_id( - key_manager_state, - &merchant_profile_id.0, - &state.store.get_master_key().to_vec().into(), - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to retrieve merchant key store by merchant_id")?; + let profile_map = futures::future::try_join_all(merchant_profile_ids.iter().map( + |merchant_profile_id| async { + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_profile_id.0, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve merchant key store by merchant_id")?; - state - .store - .find_business_profile_by_profile_id( - key_manager_state, - &merchant_key_store, - &merchant_profile_id.1, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to retrieve business profile") - }, - )) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to construct proifle map")? - .into_iter() - .map(|profile| (profile.get_id().to_owned(), profile.profile_name)) - .collect(); + state + .store + .find_business_profile_by_profile_id( + key_manager_state, + &merchant_key_store, + &merchant_profile_id.1, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve business profile") + }, + )) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to construct proifle map")? + .into_iter() + .map(|profile| (profile.get_id().to_owned(), profile.profile_name)) + .collect::<HashMap<_, _>>(); + + let role_name_map = futures::future::try_join_all( + user_roles_set + .iter() + .map(|user_role| user_role.role_id.clone()) + .collect::<HashSet<_>>() + .into_iter() + .map(|role_id| async { + let role_info = roles::RoleInfo::from_role_id_in_org_scope( + &state, + &role_id, + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok::<_, error_stack::Report<_>>((role_id, role_info.get_role_name().to_string())) + }), + ) + .await? + .into_iter() + .collect::<HashMap<_, _>>(); let role_details_list: Vec<_> = user_roles_set .iter() .map(|user_role| { - let entity_type = user_role + let (_, entity_type) = user_role .get_entity_id_and_type() - .ok_or(UserErrors::InternalServerError)? - .1; + .ok_or(UserErrors::InternalServerError)?; + let (merchant, profile) = match entity_type { EntityType::Internal => { return Err(UserErrors::InvalidRoleOperationWithMessage( @@ -1642,6 +1668,10 @@ pub async fn list_user_roles_details( profile, status: user_role.status.foreign_into(), entity_type, + role_name: role_name_map + .get(&user_role.role_id) + .ok_or(UserErrors::InternalServerError) + .cloned()?, }) }) .collect::<Result<Vec<_>, UserErrors>>()?; @@ -1684,7 +1714,7 @@ pub async fn list_users_for_merchant_account( let users_user_roles_and_roles = futures::future::try_join_all(users_and_user_roles.into_iter().map( |(user, user_role)| async { - roles::RoleInfo::from_role_id( + roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_role.role_id.clone(), user_role @@ -2586,7 +2616,7 @@ pub async fn list_orgs_for_user( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> { - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -2640,7 +2670,7 @@ pub async fn list_merchants_for_user_in_org( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::ListMerchantsForUserInOrgResponse>> { - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -2707,7 +2737,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_api::ListProfilesForUserInOrgAndMerchantAccountResponse>> { - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -2796,7 +2826,7 @@ pub async fn switch_org_for_user( .into()); } - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -2875,7 +2905,7 @@ pub async fn switch_merchant_for_user_in_org( } let key_manager_state = &(&state).into(); - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -3084,7 +3114,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( } let key_manager_state = &(&state).into(); - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 369ee97a02a..868d2e65a24 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -3,9 +3,11 @@ use std::collections::{HashMap, HashSet}; use api_models::{user as user_api, user_role as user_role_api}; use diesel_models::{ enums::{UserRoleVersion, UserStatus}, + organization::OrganizationBridge, user_role::UserRoleUpdate, }; use error_stack::{report, ResultExt}; +use masking::Secret; use once_cell::sync::Lazy; use crate::{ @@ -75,7 +77,7 @@ pub async fn update_user_role( req: user_role_api::UpdateUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &req.role_id, &user_from_token.merchant_id, @@ -100,7 +102,7 @@ pub async fn update_user_role( .attach_printable("User Changing their own role"); } - let updator_role = roles::RoleInfo::from_role_id( + let updator_role = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -133,7 +135,7 @@ pub async fn update_user_role( }; if let Some(user_role) = v2_user_role_to_be_updated { - let role_to_be_updated = roles::RoleInfo::from_role_id( + let role_to_be_updated = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_role.role_id, &user_from_token.merchant_id, @@ -198,7 +200,7 @@ pub async fn update_user_role( }; if let Some(user_role) = v1_user_role_to_be_updated { - let role_to_be_updated = roles::RoleInfo::from_role_id( + let role_to_be_updated = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_role.role_id, &user_from_token.merchant_id, @@ -501,7 +503,7 @@ pub async fn delete_user_role( .attach_printable("User deleting himself"); } - let deletion_requestor_role_info = roles::RoleInfo::from_role_id( + let deletion_requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -535,7 +537,7 @@ pub async fn delete_user_role( }; if let Some(role_to_be_deleted) = user_role_v2 { - let target_role_info = roles::RoleInfo::from_role_id( + let target_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, @@ -597,7 +599,7 @@ pub async fn delete_user_role( }; if let Some(role_to_be_deleted) = user_role_v1 { - let target_role_info = roles::RoleInfo::from_role_id( + let target_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, @@ -672,7 +674,7 @@ pub async fn list_users_in_lineage( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> { - let requestor_role_info = roles::RoleInfo::from_role_id( + let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &user_from_token.role_id, &user_from_token.merchant_id, @@ -744,6 +746,29 @@ pub async fn list_users_in_lineage( .map(|user| (user.user_id.clone(), user.email)) .collect::<HashMap<_, _>>(); + let role_info_map = + futures::future::try_join_all(user_roles_set.iter().map(|user_role| async { + roles::RoleInfo::from_role_id_in_org_scope( + &state, + &user_role.role_id, + &user_from_token.org_id, + ) + .await + .map(|role_info| { + ( + user_role.role_id.clone(), + user_role_api::role::MinimalRoleInfo { + role_id: user_role.role_id.clone(), + role_name: role_info.get_role_name().to_string(), + }, + ) + }) + })) + .await + .change_context(UserErrors::InternalServerError)? + .into_iter() + .collect::<HashMap<_, _>>(); + let user_role_map = user_roles_set .into_iter() .fold(HashMap::new(), |mut map, user_role| { @@ -763,11 +788,13 @@ pub async fn list_users_in_lineage( .ok_or(UserErrors::InternalServerError)?, roles: role_id_vec .into_iter() - .map(|role_id| user_role_api::role::MinimalRoleInfo { - role_id, - role_name: None, + .map(|role_id| { + role_info_map + .get(&role_id) + .cloned() + .ok_or(UserErrors::InternalServerError) }) - .collect(), + .collect::<Result<Vec<_>, _>>()?, }) }) .collect::<Result<Vec<_>, _>>()?, @@ -778,7 +805,7 @@ pub async fn list_invitations_for_user( state: SessionState, user_from_token: auth::UserIdFromAuth, ) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> { - let invitations = state + let user_roles = state .store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, @@ -794,18 +821,143 @@ pub async fn list_invitations_for_user( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to list user roles by user id and invitation sent")? .into_iter() - .collect::<HashSet<_>>() + .collect::<HashSet<_>>(); + + let (org_ids, merchant_ids, profile_ids_with_merchant_ids) = user_roles.iter().try_fold( + (Vec::new(), Vec::new(), Vec::new()), + |(mut org_ids, mut merchant_ids, mut profile_ids_with_merchant_ids), user_role| { + let (_, entity_type) = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError) + .attach_printable("Failed to compute entity id and type")?; + + match entity_type { + EntityType::Organization => org_ids.push( + user_role + .org_id + .clone() + .ok_or(UserErrors::InternalServerError)?, + ), + EntityType::Merchant => merchant_ids.push( + user_role + .merchant_id + .clone() + .ok_or(UserErrors::InternalServerError)?, + ), + EntityType::Profile => profile_ids_with_merchant_ids.push(( + user_role + .profile_id + .clone() + .ok_or(UserErrors::InternalServerError)?, + user_role + .merchant_id + .clone() + .ok_or(UserErrors::InternalServerError)?, + )), + EntityType::Internal => return Err(report!(UserErrors::InternalServerError)), + } + + Ok((org_ids, merchant_ids, profile_ids_with_merchant_ids)) + }, + )?; + + let org_name_map = futures::future::try_join_all(org_ids.into_iter().map(|org_id| async { + let org_name = state + .store + .find_organization_by_org_id(&org_id) + .await + .change_context(UserErrors::InternalServerError)? + .get_organization_name() + .map(Secret::new); + + Ok::<_, error_stack::Report<UserErrors>>((org_id, org_name)) + })) + .await? + .into_iter() + .collect::<HashMap<_, _>>(); + + let key_manager_state = &(&state).into(); + + let merchant_name_map = state + .store + .list_multiple_merchant_accounts(key_manager_state, merchant_ids) + .await + .change_context(UserErrors::InternalServerError)? + .into_iter() + .map(|merchant| { + ( + merchant.get_id().clone(), + merchant + .merchant_name + .map(|encryptable_name| encryptable_name.into_inner()), + ) + }) + .collect::<HashMap<_, _>>(); + + let master_key = &state.store.get_master_key().to_vec().into(); + + let profile_name_map = futures::future::try_join_all(profile_ids_with_merchant_ids.iter().map( + |(profile_id, merchant_id)| async { + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id(key_manager_state, merchant_id, master_key) + .await + .change_context(UserErrors::InternalServerError)?; + + let business_profile = state + .store + .find_business_profile_by_profile_id( + key_manager_state, + &merchant_key_store, + profile_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok::<_, error_stack::Report<UserErrors>>(( + profile_id.clone(), + Secret::new(business_profile.profile_name), + )) + }, + )) + .await? + .into_iter() + .collect::<HashMap<_, _>>(); + + user_roles .into_iter() - .filter_map(|user_role| { - let (entity_id, entity_type) = user_role.get_entity_id_and_type()?; - Some(user_role_api::ListInvitationForUserResponse { + .map(|user_role| { + let (entity_id, entity_type) = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError) + .attach_printable("Failed to compute entity id and type")?; + + let entity_name = match entity_type { + EntityType::Organization => user_role + .org_id + .as_ref() + .and_then(|org_id| org_name_map.get(org_id).cloned()) + .ok_or(UserErrors::InternalServerError)?, + EntityType::Merchant => user_role + .merchant_id + .as_ref() + .and_then(|merchant_id| merchant_name_map.get(merchant_id).cloned()) + .ok_or(UserErrors::InternalServerError)?, + EntityType::Profile => user_role + .profile_id + .as_ref() + .map(|profile_id| profile_name_map.get(profile_id).cloned()) + .ok_or(UserErrors::InternalServerError)?, + EntityType::Internal => return Err(report!(UserErrors::InternalServerError)), + }; + + Ok(user_role_api::ListInvitationForUserResponse { entity_id, entity_type, - entity_name: None, + entity_name, role_id: user_role.role_id, }) }) - .collect(); - - Ok(ApplicationResponse::Json(invitations)) + .collect::<Result<Vec<_>, _>>() + .map(ApplicationResponse::Json) } diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 8c9cd1da0ab..571ae7f995d 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -127,7 +127,7 @@ pub async fn get_role_with_groups( user_from_token: UserFromToken, role: role_api::GetRoleRequest, ) -> UserResponse<role_api::RoleInfoWithGroupsResponse> { - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, &role.role_id, &user_from_token.merchant_id, @@ -172,7 +172,7 @@ pub async fn update_role( utils::user_role::validate_role_groups(groups)?; } - let role_info = roles::RoleInfo::from_role_id( + let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( &state, role_id, &user_from_token.merchant_id, @@ -348,7 +348,7 @@ pub async fn list_roles_at_entity_level( if check_type && role_info.get_entity_type() == req.entity_type { Some(role_api::MinimalRoleInfo { role_id: role_info.get_role_id().to_string(), - role_name: Some(role_info.get_role_name().to_string()), + role_name: role_info.get_role_name().to_string(), }) } else { None diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 76111afc6bd..42cd71c280d 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3341,6 +3341,16 @@ impl RoleInterface for KafkaStore { .await } + async fn find_role_by_role_id_in_org_scope( + &self, + role_id: &str, + org_id: &id_type::OrganizationId, + ) -> CustomResult<storage::Role, errors::StorageError> { + self.diesel_store + .find_role_by_role_id_in_org_scope(role_id, org_id) + .await + } + async fn update_role_by_role_id( &self, role_id: &str, diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index ddcb24dc254..20a4922d165 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -30,6 +30,12 @@ pub trait RoleInterface { org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Role, errors::StorageError>; + async fn find_role_by_role_id_in_org_scope( + &self, + role_id: &str, + org_id: &id_type::OrganizationId, + ) -> CustomResult<storage::Role, errors::StorageError>; + async fn update_role_by_role_id( &self, role_id: &str, @@ -93,6 +99,18 @@ impl RoleInterface for Store { .map_err(|error| report!(errors::StorageError::from(error))) } + #[instrument(skip_all)] + async fn find_role_by_role_id_in_org_scope( + &self, + role_id: &str, + org_id: &id_type::OrganizationId, + ) -> CustomResult<storage::Role, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + storage::Role::find_by_role_id_in_org_scope(&conn, role_id, org_id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + #[instrument(skip_all)] async fn update_role_by_role_id( &self, @@ -223,6 +241,24 @@ impl RoleInterface for MockDb { ) } + async fn find_role_by_role_id_in_org_scope( + &self, + role_id: &str, + org_id: &id_type::OrganizationId, + ) -> CustomResult<storage::Role, errors::StorageError> { + let roles = self.roles.lock().await; + roles + .iter() + .find(|role| role.role_id == role_id && role.org_id == *org_id) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No role available in org scope for role_id = {role_id} and org_id = {org_id:?}" + )) + .into(), + ) + } + async fn update_role_by_role_id( &self, role_id: &str, diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index c498a33614e..19383f010f2 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -71,7 +71,7 @@ impl RoleInfo { .any(|group| get_permissions_vec(group).contains(required_permission)) } - pub async fn from_role_id( + pub async fn from_role_id_in_merchant_scope( state: &SessionState, role_id: &str, merchant_id: &id_type::MerchantId, @@ -87,6 +87,22 @@ impl RoleInfo { .map(Self::from) } } + + pub async fn from_role_id_in_org_scope( + state: &SessionState, + role_id: &str, + org_id: &id_type::OrganizationId, + ) -> CustomResult<Self, errors::StorageError> { + if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { + Ok(role.clone()) + } else { + state + .store + .find_role_by_role_id_in_org_scope(role_id, org_id) + .await + .map(Self::from) + } + } } impl From<diesel_models::role::Role> for RoleInfo { diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 3da24f2be7d..22edf6768c8 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -75,9 +75,14 @@ impl UserFromToken { } pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> { - RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id) - .await - .change_context(UserErrors::InternalServerError) + RoleInfo::from_role_id_in_merchant_scope( + state, + &self.role_id, + &self.merchant_id, + &self.org_id, + ) + .await + .change_context(UserErrors::InternalServerError) } } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 68bee0f022d..2d700ffe505 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -152,10 +152,11 @@ pub async fn set_role_permissions_in_cache_if_required( return Ok(()); } - let role_info = roles::RoleInfo::from_role_id(state, role_id, merchant_id, org_id) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Error getting role_info from role_id")?; + let role_info = + roles::RoleInfo::from_role_id_in_merchant_scope(state, role_id, merchant_id, org_id) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error getting role_info from role_id")?; authz::set_role_info_in_cache( state,
2024-09-11T12:21:48Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Populate entity name in list invitations API. - Add role name in the response of get user role details API. - Populate role name in list users in lineage API. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5860. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. List invitations ``` curl 'http://localhost:8080/user/list/invitation' \ -H 'authorization: Bearer SPT with accept invite purpose' \ ``` ```json [ { "entity_id": "merchant_1726053750", "entity_type": "merchant", "entity_name": "First Merchant", "role_id": "role_66NmyEPLz3vHvN67Wdz1" }, { "entity_id": "merchant_1726053866", "entity_type": "merchant", "entity_name": "Second merchant", "role_id": "role_pit0nT2xUJsZPCPUqOJD" } ] ``` Entity name should be populated. 2. List lineage ``` curl 'http://localhost:8080/user/user/v2/list' \ -H 'authorization: Bearer JWT' \ ``` ```json [ { "email": "mani.dchandra+secmer@juspay.in", "roles": [ { "role_id": "role_pit0nT2xUJsZPCPUqOJD", "role_name": "role_in_second_merchant" }, { "role_id": "role_66NmyEPLz3vHvN67Wdz1", "role_name": "role_in_first_merchant" } ] }, { "email": "mani.dchandra+firmer@juspay.in", "roles": [ { "role_id": "role_66NmyEPLz3vHvN67Wdz1", "role_name": "role_in_first_merchant" } ] }, { "email": "mani.dchandra@juspay.in", "roles": [ { "role_id": "org_admin", "role_name": "organization_admin" } ] } ] ``` Role name should be populated. 3. Get user role details ``` curl 'http://localhost:8080/user/user/v2' \ -H 'authorization: Bearer JWT' \ --data-raw '{"email":"email"}' ``` ``` [ { "role_id": "role_pit0nT2xUJsZPCPUqOJD", "org": { "name": null, "id": "org_UQ9eMA5oT6GjJMONxPtZ" }, "merchant": { "name": "Second merchant", "id": "merchant_1726053866" }, "profile": null, "status": "Active", "entity_type": "merchant", "role_name": "role_in_second_merchant" }, { "role_id": "role_66NmyEPLz3vHvN67Wdz1", "org": { "name": null, "id": "org_UQ9eMA5oT6GjJMONxPtZ" }, "merchant": { "name": "First Profile", "id": "merchant_1726053750" }, "profile": null, "status": "Active", "entity_type": "merchant", "role_name": "role_in_first_merchant" } ] ``` `role_name` should be present and populated. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
246fdc84064367885596b33f5e0e66af78a97a3c
juspay/hyperswitch
juspay__hyperswitch-5855
Bug: fix merchant payment method list 1. `collect_billing_details_from_wallets` field should be made true if either of `always_collect_billing_details_from_wallet_connector` ` collect_billing_details_from_wallet_connector` 2. `collect_shipping_details_from_wallets` field should be made true if either of `always_collect_shipping_details_from_wallet_connector` ` collect_shipping_details_from_wallet_connector`
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index c553840347d..8ab3bf50147 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3656,23 +3656,29 @@ pub async fn list_payment_methods( api_surcharge_decision_configs::MerchantSurchargeConfigs::default() }; - let collect_shipping_details_from_wallets = business_profile - .as_ref() - .and_then(|business_profile| { - business_profile.always_collect_shipping_details_from_wallet_connector - }) - .or(business_profile.as_ref().and_then(|business_profile| { - business_profile.collect_shipping_details_from_wallet_connector - })); + let collect_shipping_details_from_wallets = + business_profile.as_ref().and_then(|business_profile| { + if business_profile + .always_collect_shipping_details_from_wallet_connector + .unwrap_or(false) + { + business_profile.always_collect_shipping_details_from_wallet_connector + } else { + business_profile.collect_shipping_details_from_wallet_connector + } + }); - let collect_billing_details_from_wallets = business_profile - .as_ref() - .and_then(|business_profile| { - business_profile.always_collect_billing_details_from_wallet_connector - }) - .or(business_profile.as_ref().and_then(|business_profile| { - business_profile.collect_billing_details_from_wallet_connector - })); + let collect_billing_details_from_wallets = + business_profile.as_ref().and_then(|business_profile| { + if business_profile + .always_collect_billing_details_from_wallet_connector + .unwrap_or(false) + { + business_profile.always_collect_billing_details_from_wallet_connector + } else { + business_profile.collect_billing_details_from_wallet_connector + } + }); let is_tax_connector_enabled = business_profile.as_ref().map_or(false, |business_profile| { business_profile.get_is_tax_connector_enabled()
2024-09-11T08:13:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> 1. `collect_billing_details_from_wallets` field should be made true if either of `always_collect_billing_details_from_wallet_connector` ` collect_billing_details_from_wallet_connector` is true 2. `collect_shipping_details_from_wallets` field should be made true if either of `always_collect_shipping_details_from_wallet_connector` ` collect_shipping_details_from_wallet_connector` is true So that the sdk gets to know that the address details needs to be collected from apple pay and not from the customers ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create a merchant account and mca -> Set the below config in the business profile ``` curl --location 'http://localhost:8080/account/merchant_1726040867/business_profile/pro_a6nz5AzJNeeczSAq4bjx' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_billing_details_from_wallet_connector": true, "collect_shipping_details_from_wallet_connector": true, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": true }' ``` -> Do merchant payment methods list ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_TmMtZnKNBJ9k42xukGoq_secret_xMznqubrJIb6UDS16dAC' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_cfcaee79a88d488c8bc71a50d39010ef' ``` ``` { "redirect_url": "https://google.com/success", "currency": "EUR", "payment_methods": [ { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] }, { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "DinersClub", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": true, "collect_billing_details_from_wallets": true, "is_tax_calculation_enabled": false } ``` In the above response `"collect_shipping_details_from_wallets": true, "collect_billing_details_from_wallets": true,` even though the ` "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false,` is set to false. -> When all the configs are false ``` curl --location 'http://localhost:8080/account/merchant_1726047949/business_profile/pro_TAHURhBV24jEzIvGiIiQ' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "collect_billing_details_from_wallet_connector": false, "collect_shipping_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, }' ``` -> merchant pml ``` { "redirect_url": "https://google.com/success", "currency": "EUR", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] }, { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "DinersClub", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "email": { "required_field": "email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false } ``` -> When ` "always_collect_shipping_details_from_wallet_connector": true, "always_collect_billing_details_from_wallet_connector": true,` ``` { "redirect_url": "https://google.com/success", "currency": "EUR", "payment_methods": [ { "payment_method": "pay_later", "payment_method_types": [ { "payment_method_type": "klarna", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] }, { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null }, "billing.address.line2": { "required_field": "payment_method_data.billing.address.line2", "display_name": "line2", "field_type": "user_address_line2", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "shipping.address.zip": { "required_field": "shipping.address.zip", "display_name": "zip", "field_type": "user_shipping_address_pincode", "value": null }, "shipping.address.line1": { "required_field": "shipping.address.line1", "display_name": "line1", "field_type": "user_shipping_address_line1", "value": null }, "shipping.address.last_name": { "required_field": "shipping.address.last_name", "display_name": "shipping_last_name", "field_type": "user_shipping_name", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "shipping.address.first_name": { "required_field": "shipping.address.first_name", "display_name": "shipping_first_name", "field_type": "user_shipping_name", "value": null }, "shipping.address.state": { "required_field": "shipping.address.state", "display_name": "state", "field_type": "user_shipping_address_state", "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "shipping.address.city": { "required_field": "shipping.address.city", "display_name": "city", "field_type": "user_shipping_address_city", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "shipping.address.country": { "required_field": "shipping.address.country", "display_name": "country", "field_type": { "user_shipping_address_country": { "options": [ "ALL" ] } }, "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "apple_pay", "payment_experience": [ { "payment_experience_type": "invoke_sdk_client", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "shipping.address.city": { "required_field": "shipping.address.city", "display_name": "city", "field_type": "user_shipping_address_city", "value": null }, "shipping.address.last_name": { "required_field": "shipping.address.last_name", "display_name": "shipping_last_name", "field_type": "user_shipping_name", "value": null }, "shipping.address.first_name": { "required_field": "shipping.address.first_name", "display_name": "shipping_first_name", "field_type": "user_shipping_name", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": null }, "shipping.address.line1": { "required_field": "shipping.address.line1", "display_name": "line1", "field_type": "user_shipping_address_line1", "value": null }, "shipping.address.state": { "required_field": "shipping.address.state", "display_name": "state", "field_type": "user_shipping_address_state", "value": null }, "shipping.address.country": { "required_field": "shipping.address.country", "display_name": "country", "field_type": { "user_shipping_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "shipping.address.zip": { "required_field": "shipping.address.zip", "display_name": "zip", "field_type": "user_shipping_address_pincode", "value": null }, "billing.address.line2": { "required_field": "payment_method_data.billing.address.line2", "display_name": "line2", "field_type": "user_address_line2", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "paypal", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "cybersource" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Discover", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "DinersClub", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "cybersource" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "payment_method_data.card.card_exp_year": { "required_field": "payment_method_data.card.card_exp_year", "display_name": "card_exp_year", "field_type": "user_card_expiry_year", "value": null }, "payment_method_data.card.card_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "payment_method_data.card.card_exp_month": { "required_field": "payment_method_data.card.card_exp_month", "display_name": "card_exp_month", "field_type": "user_card_expiry_month", "value": null }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": null }, "payment_method_data.card.card_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": null }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": null } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "normal", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": true, "collect_billing_details_from_wallets": true, "is_tax_calculation_enabled": false } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
be346e5d963925ecbe1bbb77aa024f7eed66019e
juspay/hyperswitch
juspay__hyperswitch-5858
Bug: [FEATURE] [DEUTSCHEBANK] Integrate SEPA Payments ### Feature Description Integrate SEPA Payments for connector Deutsche Bank ### Possible Implementation https://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html#chap_sdd ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index bda5fab29c0..acff517e107 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -4979,6 +4979,7 @@ "cryptopay", "cybersource", "datatrans", + "deutschebank", "dlocal", "ebanx", "fiserv", @@ -17213,6 +17214,7 @@ "cryptopay", "cybersource", "datatrans", + "deutschebank", "dlocal", "ebanx", "fiserv", diff --git a/config/config.example.toml b/config/config.example.toml index 4c543fbdec3..7059626f8cf 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -201,7 +201,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" -deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" +deutschebank.base_url = "https://testmerch.directpos.de/rest-api" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -411,6 +411,7 @@ bankofamerica = { payment_method = "card" } cybersource = { payment_method = "card" } nmi = { payment_method = "card" } payme = { payment_method = "card" } +deutschebank = { payment_method = "bank_debit" } [dummy_connector] enabled = true # Whether dummy connector is enabled or not diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 4f109fc612c..90d29a6992d 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -43,7 +43,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" -deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" +deutschebank.base_url = "https://testmerch.directpos.de/rest-api" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -346,6 +346,7 @@ bankofamerica = { payment_method = "card" } cybersource = { payment_method = "card" } nmi.payment_method = "card" payme.payment_method = "card" +deutschebank = { payment_method = "bank_debit" } #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 9c387aa10af..0443d191542 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -48,7 +48,7 @@ cryptopay.base_url = "https://business.cryptopay.me/" cybersource.base_url = "https://api.cybersource.com/" datatrans.base_url = "https://api.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" -deutschebank.base_url = "https://merch.directpos.de/rest-api/services/v2.1" +deutschebank.base_url = "https://merch.directpos.de/rest-api" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" fiserv.base_url = "https://cert.api.fiservapps.com/" @@ -359,6 +359,7 @@ bankofamerica = { payment_method = "card" } cybersource = { payment_method = "card" } nmi.payment_method = "card" payme.payment_method = "card" +deutschebank = { payment_method = "bank_debit" } #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 706bcb6e1b9..8c679241729 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -48,7 +48,7 @@ cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" -deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" +deutschebank.base_url = "https://testmerch.directpos.de/rest-api" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" fiserv.base_url = "https://cert.api.fiservapps.com/" @@ -363,6 +363,7 @@ bankofamerica = { payment_method = "card" } cybersource = { payment_method = "card" } nmi.payment_method = "card" payme.payment_method = "card" +deutschebank = { payment_method = "bank_debit" } #tokenization configuration which describe token lifetime and payment method for specific connector [tokenization] diff --git a/config/development.toml b/config/development.toml index 0b6c1c76909..1c6a4a827f3 100644 --- a/config/development.toml +++ b/config/development.toml @@ -210,7 +210,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" -deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" +deutschebank.base_url = "https://testmerch.directpos.de/rest-api" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -538,6 +538,7 @@ bankofamerica = { payment_method = "card" } cybersource = { payment_method = "card" } nmi = { payment_method = "card" } payme = { payment_method = "card" } +deutschebank = { payment_method = "bank_debit" } [connector_customer] connector_list = "gocardless,stax,stripe" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index bc1be36f82c..704acdfee14 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -130,7 +130,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" -deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" +deutschebank.base_url = "https://testmerch.directpos.de/rest-api" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -317,6 +317,7 @@ bankofamerica = { payment_method = "card" } cybersource = { payment_method = "card" } nmi = { payment_method = "card" } payme = { payment_method = "card" } +deutschebank = { payment_method = "bank_debit" } [dummy_connector] enabled = true diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 2826608b639..64af2349f7c 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -94,7 +94,7 @@ pub enum Connector { Cryptopay, Cybersource, Datatrans, - // Deutschebank, + Deutschebank, Dlocal, Ebanx, Fiserv, @@ -187,6 +187,7 @@ impl Connector { matches!( (self, payment_method), (Self::Airwallex, _) + | (Self::Deutschebank, _) | (Self::Globalpay, _) | (Self::Paypal, _) | (Self::Payu, _) @@ -231,7 +232,7 @@ impl Connector { | Self::Cashtocode | Self::Coinbase | Self::Cryptopay - // | Self::Deutschebank + | Self::Deutschebank | Self::Dlocal | Self::Ebanx | Self::Fiserv diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index b6500d79b84..10c9dae2cc1 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -208,7 +208,7 @@ pub enum RoutableConnectors { Cryptopay, Cybersource, Datatrans, - // Deutschebank, + Deutschebank, Dlocal, Ebanx, Fiserv, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index fb4d92581ed..3ead246702c 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -171,6 +171,7 @@ pub struct ConnectorConfig { pub opennode: Option<ConnectorTomlConfig>, pub bambora: Option<ConnectorTomlConfig>, pub datatrans: Option<ConnectorTomlConfig>, + pub deutschebank: Option<ConnectorTomlConfig>, pub dlocal: Option<ConnectorTomlConfig>, pub ebanx_payout: Option<ConnectorTomlConfig>, pub fiserv: Option<ConnectorTomlConfig>, @@ -322,6 +323,7 @@ impl ConnectorConfig { Connector::Opennode => Ok(connector_data.opennode), Connector::Bambora => Ok(connector_data.bambora), Connector::Datatrans => Ok(connector_data.datatrans), + Connector::Deutschebank => Ok(connector_data.deutschebank), Connector::Dlocal => Ok(connector_data.dlocal), Connector::Ebanx => Ok(connector_data.ebanx_payout), Connector::Fiserv => Ok(connector_data.fiserv), diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index ef2cf56f31b..41bcb52704a 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1353,6 +1353,14 @@ api_key="Key" key1="Merchant ID" api_secret="Shared Secret" +[deutschebank] +[[deutschebank.bank_debit]] + payment_method_type = "sepa" +[deutschebank.connector_auth.SignatureKey] +api_key="Client ID" +key1="Merchant ID" +api_secret="Client Key" + [dlocal] [[dlocal.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index c7e55ca7a79..8d6d2d3a5c6 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1125,6 +1125,14 @@ placeholder="Enter Acquirer Country Code" required=false type="Text" +[deutschebank] +[[deutschebank.bank_debit]] + payment_method_type = "sepa" +[deutschebank.connector_auth.SignatureKey] +api_key="Client ID" +key1="Merchant ID" +api_secret="Client Key" + [dlocal] [[dlocal.credit]] payment_method_type = "Mastercard" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index 9d44f76970f..165682b7501 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1352,6 +1352,14 @@ api_key="Key" key1="Merchant ID" api_secret="Shared Secret" +[deutschebank] +[[deutschebank.bank_debit]] + payment_method_type = "sepa" +[deutschebank.connector_auth.SignatureKey] +api_key="Client ID" +key1="Merchant ID" +api_secret="Client Key" + [dlocal] [[dlocal.credit]] payment_method_type = "Mastercard" diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs index 3d7e55c3a90..30e67babe89 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -1,27 +1,36 @@ pub mod transformers; +use std::time::SystemTime; + +use actix_web::http::header::Date; +use base64::Engine; +use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, - types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, + types::{AmountConvertor, MinorUnit, MinorUnitForConnector}, }; 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}, + payments::{ + Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, Session, + SetupMandate, Void, + }, refunds::{Execute, RSync}, }, router_request_types::{ - AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, - RefundsData, SetupMandateRequestData, + AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData, + PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, + PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{PaymentsResponseData, RefundsResponseData}, types::{ - PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, }, }; @@ -33,20 +42,26 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; +use masking::{ExposeInterface, Mask, Secret}; +use rand::distributions::{Alphanumeric, DistString}; +use ring::hmac; use transformers as deutschebank; -use crate::{constants::headers, types::ResponseRouterData, utils}; +use crate::{ + constants::headers, + types::ResponseRouterData, + utils::{self, PaymentsCompleteAuthorizeRequestData, RefundsRequestData}, +}; #[derive(Clone)] pub struct Deutschebank { - amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), + amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync), } impl Deutschebank { pub fn new() -> &'static Self { &Self { - amount_converter: &StringMinorUnitForConnector, + amount_converter: &MinorUnitForConnector, } } } @@ -56,6 +71,7 @@ impl api::PaymentSession for Deutschebank {} impl api::ConnectorAccessToken for Deutschebank {} impl api::MandateSetup for Deutschebank {} impl api::PaymentAuthorize for Deutschebank {} +impl api::PaymentsCompleteAuthorize for Deutschebank {} impl api::PaymentSync for Deutschebank {} impl api::PaymentCapture for Deutschebank {} impl api::PaymentVoid for Deutschebank {} @@ -79,10 +95,20 @@ where 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 access_token = req + .access_token + .clone() + .ok_or(errors::ConnectorError::FailedToObtainAuthType)?; + let mut header = vec![ + ( + headers::CONTENT_TYPE.to_string(), + self.get_content_type().to_string().into(), + ), + ( + headers::AUTHORIZATION.to_string(), + format!("Bearer {}", access_token.token.expose()).into_masked(), + ), + ]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) @@ -96,9 +122,6 @@ impl ConnectorCommon for Deutschebank { fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base - // TODO! Check connector documentation, on which unit they are processing the currency. - // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, - // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { @@ -116,8 +139,8 @@ impl ConnectorCommon for Deutschebank { let auth = deutschebank::DeutschebankAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), + headers::MERCHANT_ID.to_string(), + auth.merchant_id.expose().into_masked(), )]) } @@ -136,9 +159,9 @@ impl ConnectorCommon for Deutschebank { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.rc, + message: response.message.clone(), + reason: Some(response.message), attempt_status: None, connector_transaction_id: None, }) @@ -146,20 +169,124 @@ impl ConnectorCommon for Deutschebank { } impl ConnectorValidation for Deutschebank { - //TODO: implement functions when support enabled + fn validate_capture_method( + &self, + capture_method: Option<enums::CaptureMethod>, + _pmt: Option<enums::PaymentMethodType>, + ) -> CustomResult<(), errors::ConnectorError> { + let capture_method = capture_method.unwrap_or_default(); + match capture_method { + enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual => Ok(()), + enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err( + utils::construct_not_implemented_error_report(capture_method, self.id()), + ), + } + } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Deutschebank { //TODO: implement sessions flow } -impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Deutschebank {} - impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Deutschebank { } +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Deutschebank { + fn get_url( + &self, + _req: &RefreshTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}/security/v1/token", self.base_url(connectors))) + } + + fn get_content_type(&self) -> &'static str { + "application/x-www-form-urlencoded" + } + + fn build_request( + &self, + req: &RefreshTokenRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + let auth = deutschebank::DeutschebankAuthType::try_from(&req.connector_auth_type)?; + let client_id = auth.client_id.expose(); + let date = Date(SystemTime::now().into()).to_string(); + let random_string = Alphanumeric.sample_string(&mut rand::thread_rng(), 50); + + let string_to_sign = client_id.clone() + &date + &random_string; + let key = hmac::Key::new(hmac::HMAC_SHA256, auth.client_key.expose().as_bytes()); + let client_secret = format!( + "V1:{}", + common_utils::consts::BASE64_ENGINE + .encode(hmac::sign(&key, string_to_sign.as_bytes()).as_ref()) + ); + + let headers = vec![ + ( + headers::X_RANDOM_VALUE.to_string(), + random_string.into_masked(), + ), + (headers::X_REQUEST_DATE.to_string(), date.into_masked()), + ( + headers::CONTENT_TYPE.to_string(), + types::RefreshTokenType::get_content_type(self) + .to_string() + .into(), + ), + ]; + + let connector_req = deutschebank::DeutschebankAccessTokenRequest { + client_id: Secret::from(client_id), + client_secret: Secret::from(client_secret), + grant_type: "client_credentials".to_string(), + scope: "ftx".to_string(), + }; + let body = RequestContent::FormUrlEncoded(Box::new(connector_req)); + + let req = Some( + RequestBuilder::new() + .method(Method::Post) + .headers(headers) + .url(&types::RefreshTokenType::get_url(self, req, connectors)?) + .set_body(body) + .build(), + ); + Ok(req) + } + + fn handle_response( + &self, + data: &RefreshTokenRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { + let response: deutschebank::DeutschebankAccessTokenResponse = res + .response + .parse_struct("Paypal PaypalAuthUpdateResponse") + .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<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Deutschebank { fn get_headers( &self, @@ -176,9 +303,12 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, _req: &PaymentsAuthorizeRouterData, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!( + "{}/services/v2.1/managedmandate", + self.base_url(connectors) + )) } fn get_request_body( @@ -226,7 +356,7 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: deutschebank::DeutschebankPaymentsResponse = res + let response: deutschebank::DeutschebankMandatePostResponse = res .response .parse_struct("Deutschebank PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -248,6 +378,105 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData } } +impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> + for Deutschebank +{ + fn get_headers( + &self, + req: &PaymentsCompleteAuthorizeRouterData, + 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: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let event_id = req.connector_request_reference_id.clone(); + let tx_action = if req.request.is_auto_capture()? { + "authorization" + } else { + "preauthorization" + }; + Ok(format!( + "{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}", + self.base_url(connectors) + )) + } + + fn get_request_body( + &self, + req: &PaymentsCompleteAuthorizeRouterData, + _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 = deutschebank::DeutschebankRouterData::from((amount, req)); + let connector_req = + deutschebank::DeutschebankDirectDebitRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsCompleteAuthorizeRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsCompleteAuthorizeType::get_url( + self, req, connectors, + )?) + .attach_default_headers() + .headers(types::PaymentsCompleteAuthorizeType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCompleteAuthorizeRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { + let response: deutschebank::DeutschebankPaymentsResponse = res + .response + .parse_struct("Deutschebank PaymentsCompleteAuthorizeResponse") + .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 Deutschebank { fn get_headers( &self, @@ -263,10 +492,18 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Deu fn get_url( &self, - _req: &PaymentsSyncRouterData, - _connectors: &Connectors, + req: &PaymentsSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let tx_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}/services/v2.1/payment/tx/{tx_id}", + self.base_url(connectors) + )) } fn build_request( @@ -292,7 +529,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Deu ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: deutschebank::DeutschebankPaymentsResponse = res .response - .parse_struct("deutschebank PaymentsSyncResponse") + .parse_struct("DeutschebankPaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -327,18 +564,32 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo fn get_url( &self, - _req: &PaymentsCaptureRouterData, - _connectors: &Connectors, + req: &PaymentsCaptureRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let event_id = req.connector_request_reference_id.clone(); + let tx_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/capture", + self.base_url(connectors) + )) } fn get_request_body( &self, - _req: &PaymentsCaptureRouterData, + req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) + let amount = utils::convert_amount( + self.amount_converter, + req.request.minor_amount_to_capture, + req.request.currency, + )?; + + let connector_router_data = deutschebank::DeutschebankRouterData::from((amount, req)); + let connector_req = + deutschebank::DeutschebankCaptureRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( @@ -389,7 +640,86 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo } } -impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Deutschebank {} +impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Deutschebank { + fn get_headers( + &self, + req: &PaymentsCancelRouterData, + 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: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + let event_id = req.connector_request_reference_id.clone(); + let tx_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/reversal", + self.base_url(connectors) + )) + } + + fn get_request_body( + &self, + req: &PaymentsCancelRouterData, + _connectors: &Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let connector_req = deutschebank::DeutschebankReversalRequest::try_from(req)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &PaymentsCancelRouterData, + connectors: &Connectors, + ) -> CustomResult<Option<Request>, errors::ConnectorError> { + Ok(Some( + RequestBuilder::new() + .method(Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(types::PaymentsVoidType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn handle_response( + &self, + data: &PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { + let response: deutschebank::DeutschebankPaymentsResponse = res + .response + .parse_struct("Deutschebank PaymentsCancelResponse") + .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<Execute, RefundsData, RefundsResponseData> for Deutschebank { fn get_headers( @@ -406,10 +736,15 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Deutsch fn get_url( &self, - _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + req: &RefundsRouterData<Execute>, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let event_id = req.attempt_id.clone(); + let tx_id = req.request.connector_transaction_id.clone(); + Ok(format!( + "{}/services/v2.1/payment/event/{event_id}/tx/{tx_id}/refund", + self.base_url(connectors) + )) } fn get_request_body( @@ -455,9 +790,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Deutsch event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: deutschebank::RefundResponse = res + let response: deutschebank::DeutschebankPaymentsResponse = res .response - .parse_struct("deutschebank RefundResponse") + .parse_struct("DeutschebankPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -492,10 +827,14 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Deutscheb fn get_url( &self, - _req: &RefundSyncRouterData, - _connectors: &Connectors, + req: &RefundSyncRouterData, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + let tx_id = req.request.get_connector_refund_id()?; + Ok(format!( + "{}/services/v2.1/payment/tx/{tx_id}", + self.base_url(connectors) + )) } fn build_request( @@ -522,9 +861,9 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Deutscheb event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: deutschebank::RefundResponse = res + let response: deutschebank::DeutschebankPaymentsResponse = res .response - .parse_struct("deutschebank RefundSyncResponse") + .parse_struct("DeutschebankPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index aca2bd497b6..dc146dc38d4 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -1,31 +1,43 @@ +use std::collections::HashMap; + use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_utils::{pii::Email, types::MinorUnit}; 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}, + payment_method_data::{BankDebitData, PaymentMethodData}, + router_data::{AccessToken, ConnectorAuthType, RouterData}, + router_flow_types::{ + payments::{Authorize, Capture, CompleteAuthorize, PSync}, + refunds::{Execute, RSync}, + }, + router_request_types::{ + CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, + ResponseId, + }, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, + types::{ + PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, + PaymentsCompleteAuthorizeRouterData, RefundsRouterData, + }, }; use hyperswitch_interfaces::errors; -use masking::Secret; +use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ - types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, + utils::{ + AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + RefundsRequestData, RouterData as OtherRouterData, + }, }; -//TODO: Fill the struct with respective fields pub struct DeutschebankRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: MinorUnit, pub router_data: T, } -impl<T> From<(StringMinorUnit, T)> for DeutschebankRouterData<T> { - fn from((amount, item): (StringMinorUnit, T)) -> Self { - //Todo : use utils to convert the amount to the type of amount that a connector accepts +impl<T> From<(MinorUnit, T)> for DeutschebankRouterData<T> { + fn from((amount, item): (MinorUnit, T)) -> Self { Self { amount, router_data: item, @@ -33,20 +45,80 @@ impl<T> From<(StringMinorUnit, T)> for DeutschebankRouterData<T> { } } -//TODO: Fill the struct with respective fields +pub struct DeutschebankAuthType { + pub(super) client_id: Secret<String>, + pub(super) merchant_id: Secret<String>, + pub(super) client_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { + match auth_type { + ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } => Ok(Self { + client_id: api_key.to_owned(), + merchant_id: key1.to_owned(), + client_key: api_secret.to_owned(), + }), + _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), + } + } +} + #[derive(Default, Debug, Serialize, PartialEq)] -pub struct DeutschebankPaymentsRequest { - amount: StringMinorUnit, - card: DeutschebankCard, +pub struct DeutschebankAccessTokenRequest { + pub grant_type: String, + pub client_id: Secret<String>, + pub client_secret: Secret<String>, + pub scope: String, } -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct DeutschebankCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, +#[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] +pub struct DeutschebankAccessTokenResponse { + pub access_token: Secret<String>, + pub expires_in: i64, + pub expires_on: i64, + pub scope: String, + pub token_type: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>> + for RouterData<F, T, AccessToken> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, DeutschebankAccessTokenResponse, T, AccessToken>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(AccessToken { + token: item.response.access_token, + expires: item.response.expires_in, + }), + ..item.data + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum DeutschebankSEPAApproval { + Click, + Email, + Sms, + Dynamic, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct DeutschebankPaymentsRequest { + approval_by: DeutschebankSEPAApproval, + email_address: Email, + iban: Secret<String>, + first_name: Secret<String>, + last_name: Secret<String>, } impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> @@ -56,81 +128,315 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> fn try_from( item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { + let billing_address = item.router_data.get_billing_address()?; match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = DeutschebankCard { - 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, - }) - } + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => Ok(Self { + approval_by: DeutschebankSEPAApproval::Click, + email_address: item.router_data.request.get_email()?, + iban, + first_name: billing_address.get_first_name()?.clone(), + last_name: billing_address.get_last_name()?.clone(), + }), _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } -//TODO: Fill the struct with respective fields -// Auth Struct -pub struct DeutschebankAuthType { - pub(super) api_key: Secret<String>, +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum DeutschebankSEPAMandateStatus { + Created, + PendingApproval, + PendingSecondaryApproval, + PendingReview, + PendingSubmission, + Submitted, + Active, + Failed, + Discarded, + Expired, + Replaced, } -impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType { +impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus { + fn from(item: DeutschebankSEPAMandateStatus) -> Self { + match item { + DeutschebankSEPAMandateStatus::Active + | DeutschebankSEPAMandateStatus::Created + | DeutschebankSEPAMandateStatus::PendingApproval + | DeutschebankSEPAMandateStatus::PendingSecondaryApproval + | DeutschebankSEPAMandateStatus::PendingReview + | DeutschebankSEPAMandateStatus::PendingSubmission + | DeutschebankSEPAMandateStatus::Submitted => Self::AuthenticationPending, + DeutschebankSEPAMandateStatus::Failed + | DeutschebankSEPAMandateStatus::Discarded + | DeutschebankSEPAMandateStatus::Expired + | DeutschebankSEPAMandateStatus::Replaced => Self::Failure, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankMandatePostResponse { + rc: String, + message: String, + mandate_id: Option<String>, + reference: Option<String>, + approval_date: Option<String>, + language: Option<String>, + approval_by: Option<DeutschebankSEPAApproval>, + state: Option<DeutschebankSEPAMandateStatus>, +} + +impl + TryFrom< + ResponseRouterData< + Authorize, + DeutschebankMandatePostResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> +{ 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(), + fn try_from( + item: ResponseRouterData< + Authorize, + DeutschebankMandatePostResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let signed_on = match item.response.approval_date { + Some(date) => date.chars().take(10).collect(), + None => time::OffsetDateTime::now_utc().date().to_string(), + }; + match item.response.reference { + Some(reference) => Ok(Self { + status: if item.response.rc == "0" { + match item.response.state { + Some(state) => common_enums::AttemptStatus::from(state), + None => common_enums::AttemptStatus::Failure, + } + } else { + common_enums::AttemptStatus::Failure + }, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Some(RedirectForm::Form { + endpoint: item.data.request.get_complete_authorize_url()?, + method: common_utils::request::Method::Get, + form_fields: HashMap::from([ + ("reference".to_string(), reference), + ("signed_on".to_string(), signed_on), + ]), + }), + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }), + None => Ok(Self { + status: common_enums::AttemptStatus::Failure, + ..item.data }), - _ => 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 DeutschebankPaymentStatus { - Succeeded, - Failed, - #[default] - Processing, + +#[derive(Debug, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankAmount { + amount: MinorUnit, + currency: api_models::enums::Currency, } -impl From<DeutschebankPaymentStatus> for common_enums::AttemptStatus { - fn from(item: DeutschebankPaymentStatus) -> Self { - match item { - DeutschebankPaymentStatus::Succeeded => Self::Charged, - DeutschebankPaymentStatus::Failed => Self::Failure, - DeutschebankPaymentStatus::Processing => Self::Authorizing, +#[derive(Debug, Serialize, PartialEq)] +pub struct DeutschebankMeansOfPayment { + bank_account: DeutschebankBankAccount, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct DeutschebankBankAccount { + account_holder: Secret<String>, + iban: Secret<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct DeutschebankMandate { + reference: Secret<String>, + signed_on: Secret<String>, +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct DeutschebankDirectDebitRequest { + amount_total: DeutschebankAmount, + means_of_payment: DeutschebankMeansOfPayment, + mandate: DeutschebankMandate, +} + +impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> + for DeutschebankDirectDebitRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + let account_holder = item.router_data.get_billing_address()?.get_full_name()?; + let redirect_response = item.router_data.request.redirect_response.clone().ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "redirect_response", + }, + )?; + let queries_params = redirect_response + .params + .map(|param| { + let mut queries = HashMap::<String, String>::new(); + let values = param.peek().split('&').collect::<Vec<&str>>(); + for value in values { + let pair = value.split('=').collect::<Vec<&str>>(); + queries.insert( + pair.first() + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)? + .to_string(), + pair.get(1) + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)? + .to_string(), + ); + } + Ok::<_, errors::ConnectorError>(queries) + }) + .transpose()? + .ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + let reference = Secret::from( + queries_params + .get("reference") + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "reference", + })? + .to_owned(), + ); + let signed_on = Secret::from( + queries_params + .get("signed_on") + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "signed_on", + })? + .to_owned(), + ); + + match item.router_data.request.payment_method_data.clone() { + Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. })) => { + Ok(Self { + amount_total: DeutschebankAmount { + amount: item.amount, + currency: item.router_data.request.currency, + }, + means_of_payment: DeutschebankMeansOfPayment { + bank_account: DeutschebankBankAccount { + account_holder, + iban, + }, + }, + mandate: { + DeutschebankMandate { + reference, + signed_on, + } + }, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum DeutschebankTXAction { + Authorization, + Capture, + Credit, + Preauthorization, + Refund, + Reversal, + RiskCheck, + #[serde(rename = "verify-mop")] + VerifyMop, + Payment, + AccountInformation, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq)] +pub struct BankAccount { + account_holder: Option<Secret<String>>, + bank_name: Option<Secret<String>>, + bic: Option<Secret<String>>, + iban: Option<Secret<String>>, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq)] +pub struct TransactionBankAccountInfo { + bank_account: Option<BankAccount>, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq)] +pub struct DeutschebankTransactionInfo { + back_state: Option<String>, + ip_address: Option<Secret<String>>, + #[serde(rename = "type")] + pm_type: Option<String>, + transaction_bankaccount_info: Option<TransactionBankAccountInfo>, +} + +#[derive(Debug, Deserialize, Serialize, PartialEq)] pub struct DeutschebankPaymentsResponse { - status: DeutschebankPaymentStatus, - id: String, + rc: String, + message: String, + timestamp: String, + back_ext_id: Option<String>, + back_rc: Option<String>, + event_id: Option<String>, + kind: Option<String>, + tx_action: Option<DeutschebankTXAction>, + tx_id: String, + amount_total: Option<DeutschebankAmount>, + transaction_info: Option<DeutschebankTransactionInfo>, } -impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankPaymentsResponse, T, PaymentsResponseData>> - for RouterData<F, T, PaymentsResponseData> +impl + TryFrom< + ResponseRouterData< + CompleteAuthorize, + DeutschebankPaymentsResponse, + CompleteAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, DeutschebankPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData< + CompleteAuthorize, + DeutschebankPaymentsResponse, + CompleteAuthorizeData, + PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), + status: if item.response.rc == "0" { + match item.data.request.is_auto_capture()? { + true => common_enums::AttemptStatus::Charged, + false => common_enums::AttemptStatus::Authorized, + } + } else { + common_enums::AttemptStatus::Failure + }, response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), + resource_id: ResponseId::ConnectorTransactionId(item.response.tx_id), redirection_data: None, mandate_reference: None, connector_metadata: None, @@ -144,87 +450,230 @@ impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankPaymentsResponse, T, Paymen } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] -pub struct DeutschebankRefundRequest { - pub amount: StringMinorUnit, +#[derive(Debug, Serialize, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum DeutschebankTransactionKind { + Directdebit, } -impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest { +#[derive(Debug, Serialize, PartialEq)] +pub struct DeutschebankCaptureRequest { + changed_amount: MinorUnit, + kind: DeutschebankTransactionKind, +} + +impl TryFrom<&DeutschebankRouterData<&PaymentsCaptureRouterData>> for DeutschebankCaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + fn try_from( + item: &DeutschebankRouterData<&PaymentsCaptureRouterData>, + ) -> Result<Self, Self::Error> { Ok(Self { - amount: item.amount.to_owned(), + changed_amount: item.amount, + kind: DeutschebankTransactionKind::Directdebit, }) } } -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, - #[default] - Processing, +impl + TryFrom< + ResponseRouterData< + Capture, + DeutschebankPaymentsResponse, + PaymentsCaptureData, + PaymentsResponseData, + >, + > for RouterData<Capture, PaymentsCaptureData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + Capture, + DeutschebankPaymentsResponse, + PaymentsCaptureData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.tx_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, + }), + status: if item.response.rc == "0" { + common_enums::AttemptStatus::Charged + } else { + common_enums::AttemptStatus::Failure + }, + ..item.data + }) + } } -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 +impl + TryFrom< + ResponseRouterData< + PSync, + DeutschebankPaymentsResponse, + PaymentsSyncData, + PaymentsResponseData, + >, + > for RouterData<PSync, PaymentsSyncData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + PSync, + DeutschebankPaymentsResponse, + PaymentsSyncData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let status = if item.response.rc == "0" { + item.response + .tx_action + .and_then(|tx_action| match tx_action { + DeutschebankTXAction::Preauthorization => { + Some(common_enums::AttemptStatus::Authorized) + } + DeutschebankTXAction::Authorization | DeutschebankTXAction::Capture => { + Some(common_enums::AttemptStatus::Charged) + } + DeutschebankTXAction::Credit + | DeutschebankTXAction::Refund + | DeutschebankTXAction::Reversal + | DeutschebankTXAction::RiskCheck + | DeutschebankTXAction::VerifyMop + | DeutschebankTXAction::Payment + | DeutschebankTXAction::AccountInformation => None, + }) + } else { + Some(common_enums::AttemptStatus::Failure) + }; + match status { + Some(status) => Ok(Self { + status, + ..item.data + }), + None => Ok(Self { ..item.data }), } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +#[derive(Debug, Serialize)] +pub struct DeutschebankReversalRequest { + kind: DeutschebankTransactionKind, +} + +impl TryFrom<&PaymentsCancelRouterData> for DeutschebankReversalRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(_item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { + Ok(Self { + kind: DeutschebankTransactionKind::Directdebit, + }) + } } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { +impl TryFrom<PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>> + for PaymentsCancelRouterData +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: PaymentsCancelResponseRouterData<DeutschebankPaymentsResponse>, ) -> 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), - }), + status: if item.response.rc == "0" { + common_enums::AttemptStatus::Voided + } else { + common_enums::AttemptStatus::VoidFailed + }, ..item.data }) } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +#[derive(Debug, Serialize)] +pub struct DeutschebankRefundRequest { + changed_amount: MinorUnit, + kind: DeutschebankTransactionKind, +} + +impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &DeutschebankRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + Ok(Self { + changed_amount: item.amount.to_owned(), + kind: DeutschebankTransactionKind::Directdebit, + }) + } +} + +impl TryFrom<RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>> + for RefundsRouterData<Execute> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<Execute, DeutschebankPaymentsResponse>, ) -> 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), + connector_refund_id: item.response.tx_id, + refund_status: if item.response.rc == "0" { + enums::RefundStatus::Success + } else { + enums::RefundStatus::Failure + }, }), ..item.data }) } } -//TODO: Fill the struct with respective fields +impl TryFrom<RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>> + for RefundsRouterData<RSync> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: RefundsResponseRouterData<RSync, DeutschebankPaymentsResponse>, + ) -> Result<Self, Self::Error> { + let status = if item.response.rc == "0" { + item.response + .tx_action + .and_then(|tx_action| match tx_action { + DeutschebankTXAction::Credit | DeutschebankTXAction::Refund => { + Some(enums::RefundStatus::Success) + } + DeutschebankTXAction::Preauthorization + | DeutschebankTXAction::Authorization + | DeutschebankTXAction::Capture + | DeutschebankTXAction::Reversal + | DeutschebankTXAction::RiskCheck + | DeutschebankTXAction::VerifyMop + | DeutschebankTXAction::Payment + | DeutschebankTXAction::AccountInformation => None, + }) + } else { + Some(enums::RefundStatus::Failure) + }; + match status { + Some(refund_status) => Ok(Self { + response: Ok(RefundsResponseData { + refund_status, + connector_refund_id: item.data.request.get_connector_refund_id()?, + }), + ..item.data + }), + None => Ok(Self { ..item.data }), + } + } +} + #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct DeutschebankErrorResponse { - pub status_code: u16, - pub code: String, + pub rc: String, pub message: String, - pub reason: Option<String>, } diff --git a/crates/hyperswitch_connectors/src/constants.rs b/crates/hyperswitch_connectors/src/constants.rs index 86d6144b1f1..c5ca6512a34 100644 --- a/crates/hyperswitch_connectors/src/constants.rs +++ b/crates/hyperswitch_connectors/src/constants.rs @@ -7,7 +7,10 @@ pub(crate) mod headers { pub(crate) const DATE: &str = "Date"; pub(crate) const IDEMPOTENCY_KEY: &str = "Idempotency-Key"; pub(crate) const MESSAGE_SIGNATURE: &str = "Message-Signature"; + pub(crate) const MERCHANT_ID: &str = "Merchant-ID"; pub(crate) const TIMESTAMP: &str = "Timestamp"; pub(crate) const X_ACCEPT_VERSION: &str = "X-Accept-Version"; pub(crate) const X_NN_ACCESS_KEY: &str = "X-NN-Access-Key"; + pub(crate) const X_RANDOM_VALUE: &str = "X-RandomValue"; + pub(crate) const X_REQUEST_DATE: &str = "X-RequestDate"; } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 1f50150c08d..b9ae736e435 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -190,7 +190,6 @@ macro_rules! default_imp_for_complete_authorize { default_imp_for_complete_authorize!( connectors::Bitpay, - connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index f714dfac86c..b64c745eec0 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -1308,6 +1308,16 @@ pub struct TokenizedBankRedirectValue2 { pub customer_id: Option<id_type::CustomerId>, } +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct TokenizedBankDebitValue2 { + pub customer_id: Option<id_type::CustomerId>, +} + +#[derive(Debug, serde::Serialize, serde::Deserialize)] +pub struct TokenizedBankDebitValue1 { + pub data: BankDebitData, +} + pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index d27c7974092..3d47afb9b82 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -1,13 +1,14 @@ use crate::{ - router_data::RouterData, + router_data::{AccessToken, RouterData}, router_flow_types::{ - Authorize, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, PSync, - PaymentMethodToken, RSync, SetupMandate, Void, + AccessTokenAuth, Authorize, CalculateTax, Capture, CompleteAuthorize, + CreateConnectorCustomer, PSync, PaymentMethodToken, RSync, SetupMandate, Void, }, router_request_types::{ - CompleteAuthorizeData, ConnectorCustomerData, PaymentMethodTokenizationData, - PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSyncData, - PaymentsTaxCalculationData, RefundsData, SetupMandateRequestData, + AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData, + PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, + PaymentsCaptureData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, + SetupMandateRequestData, }, router_response_types::{ PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, @@ -31,3 +32,4 @@ pub type PaymentsCompleteAuthorizeRouterData = RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>; pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; +pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index acffafa6c32..659c94423d4 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -11209,8 +11209,43 @@ impl Default for super::settings::RequiredFields { } ) ]), - }) - ]), + } + ), + ( + enums::Connector::Deutschebank, + 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.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, + } + ) + ]), + } + ) + ]), }, ), ( diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 996224d7bea..75b8d922f82 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1300,6 +1300,10 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> { datatrans::transformers::DatatransAuthType::try_from(self.auth_type)?; Ok(()) } + api_enums::Connector::Deutschebank => { + deutschebank::transformers::DeutschebankAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Dlocal => { dlocal::transformers::DlocalAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 0061eb4fbc0..9a39a3c341b 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -79,9 +79,22 @@ pub async fn retrieve_payment_method( Ok((pm_opt.to_owned(), payment_token)) } + pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => { + let payment_token = helpers::store_payment_method_data_in_vault( + state, + payment_attempt, + payment_intent, + enums::PaymentMethod::BankDebit, + pm, + merchant_key_store, + business_profile, + ) + .await?; + + Ok((pm_opt.to_owned(), payment_token)) + } pm @ Some(domain::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)), - pm @ Some(domain::PaymentMethodData::BankDebit(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)), pm @ Some(domain::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)), diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 54da4308bfb..75278010ceb 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -279,6 +279,58 @@ impl Vaultable for domain::BankRedirectData { } } +impl Vaultable for domain::BankDebitData { + fn get_value1( + &self, + _customer_id: Option<id_type::CustomerId>, + ) -> CustomResult<String, errors::VaultError> { + let value1 = domain::TokenizedBankDebitValue1 { + data: self.to_owned(), + }; + + value1 + .encode_to_string_of_json() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode bank debit data") + } + + fn get_value2( + &self, + customer_id: Option<id_type::CustomerId>, + ) -> CustomResult<String, errors::VaultError> { + let value2 = domain::TokenizedBankDebitValue2 { customer_id }; + + value2 + .encode_to_string_of_json() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode bank debit supplementary data") + } + + fn from_values( + value1: String, + value2: String, + ) -> CustomResult<(Self, SupplementaryVaultData), errors::VaultError> { + let value1: domain::TokenizedBankDebitValue1 = value1 + .parse_struct("TokenizedBankDebitValue1") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Could not deserialize into bank debit data")?; + + let value2: domain::TokenizedBankDebitValue2 = value2 + .parse_struct("TokenizedBankDebitValue2") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Could not deserialize into supplementary bank debit data")?; + + let bank_transfer_data = value1.data; + + let supp_data = SupplementaryVaultData { + customer_id: value2.customer_id, + payment_method_id: None, + }; + + Ok((bank_transfer_data, supp_data)) + } +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "value", rename_all = "snake_case")] pub enum VaultPaymentMethod { @@ -286,6 +338,7 @@ pub enum VaultPaymentMethod { Wallet(String), BankTransfer(String), BankRedirect(String), + BankDebit(String), } impl Vaultable for domain::PaymentMethodData { @@ -302,6 +355,9 @@ impl Vaultable for domain::PaymentMethodData { Self::BankRedirect(bank_redirect) => { VaultPaymentMethod::BankRedirect(bank_redirect.get_value1(customer_id)?) } + Self::BankDebit(bank_debit) => { + VaultPaymentMethod::BankDebit(bank_debit.get_value1(customer_id)?) + } _ => Err(errors::VaultError::PaymentMethodNotSupported) .attach_printable("Payment method not supported")?, }; @@ -325,6 +381,9 @@ impl Vaultable for domain::PaymentMethodData { Self::BankRedirect(bank_redirect) => { VaultPaymentMethod::BankRedirect(bank_redirect.get_value2(customer_id)?) } + Self::BankDebit(bank_debit) => { + VaultPaymentMethod::BankDebit(bank_debit.get_value2(customer_id)?) + } _ => Err(errors::VaultError::PaymentMethodNotSupported) .attach_printable("Payment method not supported")?, }; @@ -374,6 +433,10 @@ impl Vaultable for domain::PaymentMethodData { domain::BankRedirectData::from_values(mvalue1, mvalue2)?; Ok((Self::BankRedirect(bank_redirect), supp_data)) } + (VaultPaymentMethod::BankDebit(mvalue1), VaultPaymentMethod::BankDebit(mvalue2)) => { + let (bank_debit, supp_data) = domain::BankDebitData::from_values(mvalue1, mvalue2)?; + Ok((Self::BankDebit(bank_debit), supp_data)) + } _ => Err(errors::VaultError::PaymentMethodNotSupported) .attach_printable("Payment method not supported"), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 5f9c1a7be0b..6cb4532d617 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1770,6 +1770,10 @@ pub async fn retrieve_payment_method_with_temporary_token( Some((the_pm, enums::PaymentMethod::BankRedirect)) } + Some(the_pm @ domain::PaymentMethodData::BankDebit(_)) => { + Some((the_pm, enums::PaymentMethod::BankDebit)) + } + Some(_) => Err(errors::ApiErrorResponse::InternalServerError) .attach_printable("Payment method received from locker is unsupported by locker")?, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ca86003f4b4..34dea537b2d 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -359,9 +359,9 @@ impl ConnectorData { enums::Connector::Datatrans => { Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) } - // enums::Connector::Deutschebank => { - // Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new()))) - // } + enums::Connector::Deutschebank => { + Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new()))) + } enums::Connector::Dlocal => Ok(ConnectorEnum::Old(Box::new(&connector::Dlocal))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new( diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs index 1cf36bc4428..bfd7b54f556 100644 --- a/crates/router/src/types/domain/payments.rs +++ b/crates/router/src/types/domain/payments.rs @@ -6,8 +6,9 @@ pub use hyperswitch_domain_models::payment_method_data::{ GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, MbWayRedirection, MifinityData, OpenBankingData, PayLaterData, PaymentMethodData, RealTimePaymentData, SamsungPayWalletData, SepaAndBacsBillingDetails, - SwishQrData, TokenizedBankRedirectValue1, TokenizedBankRedirectValue2, - TokenizedBankTransferValue1, TokenizedBankTransferValue2, TokenizedCardValue1, - TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, TouchNGoRedirection, - UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData, WeChatPayQr, + SwishQrData, TokenizedBankDebitValue1, TokenizedBankDebitValue2, TokenizedBankRedirectValue1, + TokenizedBankRedirectValue2, TokenizedBankTransferValue1, TokenizedBankTransferValue2, + TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2, + TouchNGoRedirection, UpiCollectData, UpiData, UpiIntentData, VoucherData, WalletData, + WeChatPayQr, }; diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index f883d1d4c50..46210d4dd09 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -274,7 +274,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Cryptopay => Self::Cryptopay, api_enums::Connector::Cybersource => Self::Cybersource, api_enums::Connector::Datatrans => Self::Datatrans, - // api_enums::Connector::Deutschebank => Self::Deutschebank, + api_enums::Connector::Deutschebank => Self::Deutschebank, api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Fiserv => Self::Fiserv, diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 6ed9bd7103d..f61770a5bde 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -276,7 +276,9 @@ api_key = "API Key" api_key="API Key" [deutschebank] -api_key="API Key" +api_key = "Client ID" +key1 = "Merchant ID" +api_secret = "Client Key" [thunes] -api_key="API Key" \ No newline at end of file +api_key="API Key" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 68895e5876e..a0fed3c003a 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -31,7 +31,7 @@ pub struct ConnectorAuthentication { pub cryptopay: Option<BodyKey>, pub cybersource: Option<SignatureKey>, pub datatrans: Option<HeaderKey>, - pub deutschebank: Option<HeaderKey>, + pub deutschebank: Option<SignatureKey>, pub dlocal: Option<SignatureKey>, #[cfg(feature = "dummy_connector")] pub dummyconnector: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index b1f74f57feb..ed15e8893bd 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -96,7 +96,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" -deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" +deutschebank.base_url = "https://testmerch.directpos.de/rest-api" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/"
2024-09-06T10:29:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Integrate SEPA Payments for connector Deutsche Bank https://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html#chap_sdd ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/5858 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Authorize: Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data '{ "amount": 9000, "currency": "EUR", "confirm": true, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "customer_id": "customer123", "payment_method": "bank_debit", "payment_method_type": "sepa", "payment_method_data": { "bank_debit": { "sepa_bank_debit": { "iban": "DE87123456781234567890" } } }, "billing": { "address": { "first_name": "joseph", "last_name": "Doe" } }, }' ``` Response: ``` { "payment_id": "pay_9SIimBI1UXiGdsR4XCmH", "merchant_id": "merchant_1725539597", "status": "requires_customer_action", "amount": 9000, "net_amount": 9000, "amount_capturable": 9000, "amount_received": null, "connector": "deutschebank", "client_secret": "pay_9SIimBI1UXiGdsR4XCmH_secret_s0dXk9MNEsKru7clJoNK", "created": "2024-09-12T10:41:39.816Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "DE871************67890", "bank_account_holder_name": null } }, "billing": null }, "payment_token": "token_IORpLx2lNN9VK64COwy0", "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "customer@gmail.com", "name": "John Doe", "phone": "9999999999", "return_url": "https://example.com/", "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_9SIimBI1UXiGdsR4XCmH/merchant_1725539597/pay_9SIimBI1UXiGdsR4XCmH_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "customer123", "created_at": 1726137699, "expires": 1726141299, "secret": "epk_a677e949924b417cb73e1badf1ac05f8" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-12T10:56:39.816Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-12T10:41:42.563Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` Then do redirection 2. PSYNC: Request: ``` curl --location 'http://localhost:8080/payments/pay_aCYBEjtBmw7l7u4jQWhM' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' ``` Response: ``` { "payment_id": "pay_aCYBEjtBmw7l7u4jQWhM", "merchant_id": "merchant_1725539597", "status": "succeeded", "amount": 9000, "net_amount": 9000, "amount_capturable": 0, "amount_received": 9000, "connector": "deutschebank", "client_secret": "pay_aCYBEjtBmw7l7u4jQWhM_secret_4TLRv0W2zGPEaN5hxwOC", "created": "2024-09-12T10:32:33.053Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": null, "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "DE871************67890", "bank_account_holder_name": null } }, "billing": null }, "payment_token": "token_1gP6ixqxxYORXgW6mAxq", "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "customer@gmail.com", "name": "John Doe", "phone": "9999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "fNo3C3goIky4BNzSU7ys9n", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-12T10:47:33.053Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-12T10:40:37.356Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` 3. Capture: Request: ``` curl --location 'http://localhost:8080/payments/pay_zwqrtx6EMgaV2gkK7WdS/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data '{}' ``` Response: ``` { "payment_id": "pay_zwqrtx6EMgaV2gkK7WdS", "merchant_id": "merchant_1725539597", "status": "succeeded", "amount": 9000, "net_amount": 9000, "amount_capturable": 0, "amount_received": 9000, "connector": "deutschebank", "client_secret": "pay_zwqrtx6EMgaV2gkK7WdS_secret_Br19bUUvGCMLAiG1Fusv", "created": "2024-09-12T10:42:41.662Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "DE871************67890", "bank_account_holder_name": null } }, "billing": null }, "payment_token": "token_RzJMp7J8sp2wWoRnBYPA", "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "customer@gmail.com", "name": "John Doe", "phone": "9999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "8v739jbpsaKxnsCB52QmeF", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-12T10:57:41.662Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-12T10:42:57.446Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` 4. Void: Request: ``` curl --location 'http://localhost:8080/payments/pay_sH3vFdwGOoPjobg4sud9/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data '{}' ``` Response: ``` { "payment_id": "pay_sH3vFdwGOoPjobg4sud9", "merchant_id": "merchant_1725539597", "status": "cancelled", "amount": 9000, "net_amount": 9000, "amount_capturable": 0, "amount_received": null, "connector": "deutschebank", "client_secret": "pay_sH3vFdwGOoPjobg4sud9_secret_jlUGjGn6ADDu02Ql8O4K", "created": "2024-09-12T10:44:13.912Z", "currency": "EUR", "customer_id": "customer123", "customer": { "id": "customer123", "name": "John Doe", "email": "customer@gmail.com", "phone": "9999999999", "phone_country_code": "+1" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": null, "off_session": null, "capture_on": null, "capture_method": "manual", "payment_method": "bank_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "DE871************67890", "bank_account_holder_name": null } }, "billing": null }, "payment_token": "token_2Mq0WwprhovjSGXcJmZa", "shipping": null, "billing": { "address": { "city": null, "country": null, "line1": null, "line2": null, "line3": null, "zip": null, "state": null, "first_name": "joseph", "last_name": "Doe" }, "phone": null, "email": null }, "order_details": null, "email": "customer@gmail.com", "name": "John Doe", "phone": "9999999999", "return_url": null, "authentication_type": "no_three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "sepa", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "9VFMneA8NhYUj7xoG0bmMA", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-12T10:59:13.912Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-12T10:44:39.083Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` 5. Refunds: Request: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' \ --data '{ "payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv", "refund_type": "instant" }' ``` Response: ``` { "refund_id": "ref_UDEk9Xks0pRZI5GdY1BJ", "payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv", "amount": 9000, "currency": "EUR", "status": "succeeded", "reason": null, "metadata": null, "error_message": null, "error_code": null, "created_at": "2024-09-16T07:57:15.637Z", "updated_at": "2024-09-16T07:57:18.072Z", "connector": "deutschebank", "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "charges": null } ``` 6. RSYNC: Request: ``` curl --location 'http://localhost:8080/refunds/ref_UDEk9Xks0pRZI5GdY1BJ' \ --header 'Accept: application/json' \ --header 'api-key: dev_2QpEeK0ByPRkb2DPBxHfad4i1WxQO3hZSuVzlFcg9mTrLFUHRpGfE0SCuQwZjGEb' ``` Response: ``` { "refund_id": "ref_UDEk9Xks0pRZI5GdY1BJ", "payment_id": "pay_bBC3GTsRPYVPQ8v1XdVv", "amount": 9000, "currency": "EUR", "status": "succeeded", "reason": null, "metadata": null, "error_message": null, "error_code": null, "created_at": "2024-09-16T07:57:15.637Z", "updated_at": "2024-09-16T07:58:34.252Z", "connector": "deutschebank", "profile_id": "pro_EuXuxP2KVO0m1tlDWSau", "merchant_connector_id": "mca_MZAsrTowXuzpeXl4DMj2", "charges": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
10ac08944986a1fd101f8f05263e92ed7ebbba94
juspay/hyperswitch
juspay__hyperswitch-5852
Bug: Adding information about decimal and non decimal currencies There is lack of information about decimal and non decimal currencies in the documentation.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index ac4f3fe7b46..ac7f5dfd2cc 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -11596,7 +11596,7 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency", + "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", "example": 6540, "nullable": true, "minimum": 0 @@ -11960,7 +11960,7 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency", + "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", "minimum": 0 }, "currency": { @@ -12938,7 +12938,7 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency", + "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", "example": 6540, "nullable": true, "minimum": 0 @@ -14048,7 +14048,7 @@ "amount": { "type": "integer", "format": "int64", - "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency", + "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", "example": 6540, "nullable": true, "minimum": 0 diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cd32c045f18..eac7c9888aa 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -278,7 +278,7 @@ pub struct CustomerDetailsResponse { #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { - /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency + /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)]
2024-09-11T06:20:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [X] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5852. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [ ] I formatted the code `cargo +nightly fmt --all` - [ ] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
034f736ea6e25ae2c75e74dedc12ac54f5979d68
juspay/hyperswitch
juspay__hyperswitch-5846
Bug: feat(payments): add support for profile aggregates Show count of aggregate payments status in the given time range for a particular profile
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index e5b0e8b9120..62fb06fd522 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -71,6 +71,7 @@ pub trait PaymentIntentInterface { async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, + profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: &api_models::payments::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError>; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f94a5a4633b..4eedb52c99d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3234,11 +3234,12 @@ pub async fn get_payment_filters( pub async fn get_aggregates_for_payments( state: SessionState, merchant: domain::MerchantAccount, + profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: api::TimeRange, ) -> RouterResponse<api::PaymentsAggregateResponse> { let db = state.store.as_ref(); let intent_status_with_count = db - .get_intent_status_with_count(merchant.get_id(), &time_range) + .get_intent_status_with_count(merchant.get_id(), profile_id_list, &time_range) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 2088177754e..76111afc6bd 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1640,10 +1640,11 @@ impl PaymentIntentInterface for KafkaStore { async fn get_intent_status_with_count( &self, merchant_id: &id_type::MerchantId, + profile_id_list: Option<Vec<id_type::ProfileId>>, time_range: &api_models::payments::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::DataStorageError> { self.diesel_store - .get_intent_status_with_count(merchant_id, time_range) + .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4f8e269dff9..210ded9c25d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -547,6 +547,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("/aggregate").route(web::get().to(get_payments_aggregates))) + .service( + web::resource("/profile/aggregate") + .route(web::get().to(get_payments_aggregates_profile)), + ) .service( web::resource("/v2/profile/filter") .route(web::get().to(get_payment_filters_profile)), diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 18460d6329e..8f3ee3dd4bc 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1341,7 +1341,7 @@ pub async fn get_payments_aggregates( &req, payload, |state, auth: auth::AuthenticationData, req, _| { - payments::get_aggregates_for_payments(state, auth.merchant_account, req) + payments::get_aggregates_for_payments(state, auth.merchant_account, None, req) }, &auth::JWTAuth { permission: Permission::PaymentRead, @@ -2074,3 +2074,34 @@ impl GetLockingInput for payment_types::PaymentsManualUpdateRequest { } } } + +#[instrument(skip_all, fields(flow = ?Flow::PaymentsAggregate))] +#[cfg(feature = "olap")] +pub async fn get_payments_aggregates_profile( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + payload: web::Query<payment_types::TimeRange>, +) -> impl Responder { + let flow = Flow::PaymentsAggregate; + let payload = payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, req, _| { + payments::get_aggregates_for_payments( + state, + auth.merchant_account, + auth.profile_id.map(|profile_id| vec![profile_id]), + req, + ) + }, + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Profile, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index f5db60da3fa..e296c88b3ac 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -44,6 +44,7 @@ impl PaymentIntentInterface for MockDb { async fn get_intent_status_with_count( &self, _merchant_id: &common_utils::id_type::MerchantId, + _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _time_range: &api_models::payments::TimeRange, ) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> { // [#172]: Implement function for `MockDb` diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index f69c26e6409..90395e15dac 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -350,10 +350,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &api_models::payments::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { self.router_store - .get_intent_status_with_count(merchant_id, time_range) + .get_intent_status_with_count(merchant_id, profile_id_list, time_range) .await } @@ -670,6 +671,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { async fn get_intent_status_with_count( &self, merchant_id: &common_utils::id_type::MerchantId, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: &api_models::payments::TimeRange, ) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> { let conn = connection::pg_connection_read(self).await.switch()?; @@ -681,6 +683,10 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .into_boxed(); + if let Some(profile_id) = profile_id_list { + query = query.filter(pi_dsl::profile_id.eq_any(profile_id)); + } + query = query.filter(pi_dsl::created_at.ge(time_range.start_time)); query = match time_range.end_time {
2024-09-10T07:40:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Add support for profile level aggregates in payments. - For now it will have list of intent status along with the their count for a given time range. ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #[#5846](https://github.com/juspay/hyperswitch/issues/5846) ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Request : ``` curl --location 'http://localhost:8080/payments/profile/aggregate?start_time=2022-08-10T18%3A30%3A00Z' \ --header 'Authorization: Bearer JWT token' \ --data '' ``` Response : ``` { "status_with_count": { "failed": 5, "cancelled": 0, "processing": 0, "requires_capture": 0, "partially_captured_and_capturable": 0, "requires_merchant_action": 0, "requires_payment_method": 0, "requires_customer_action": 0, "requires_confirmation": 0, "succeeded": 40, "partially_captured": 0 } } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
296ca311c96cc032aaa9ad846299db24bacaeb56
juspay/hyperswitch
juspay__hyperswitch-5876
Bug: [BUG] Nix build is broken ### Bug Description `nix build` is broken as you can see from the CI failure of https://github.com/juspay/hyperswitch/pull/5017 ### Expected Behavior All outputs of `flake.nix` should build. ### Actual Behavior Some outputs (eg: router) do not build ### Steps To Reproduce `nix --accept-flake-config github:juspay/omnix ci run github:juspay/hyperswitch` ### Context For The Bug _No response_ ### Environment Both on NixOS and macOS ### Have you spent some time checking if this bug has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/Cargo.nix b/Cargo.nix deleted file mode 100644 index 1c3c3a086f5..00000000000 --- a/Cargo.nix +++ /dev/null @@ -1,5948 +0,0 @@ -# This file was @generated by cargo2nix 0.11.0. -# It is not intended to be manually edited. - -args@{ - release ? true, - rootFeatures ? [ - "api_models/default" - "common_utils/default" - "masking/default" - "router_env/default" - "router_derive/default" - "drainer/default" - "redis_interface/default" - "diesel_models/default" - "router/default" - ], - rustPackages, - buildRustPackages, - hostPlatform, - hostPlatformCpu ? null, - hostPlatformFeatures ? [], - target ? null, - codegenOpts ? null, - profileOpts ? null, - rustcLinkFlags ? null, - rustcBuildFlags ? null, - mkRustCrate, - rustLib, - lib, - workspaceSrc, -}: -let - workspaceSrc = if args.workspaceSrc == null then ./. else args.workspaceSrc; -in let - inherit (rustLib) fetchCratesIo fetchCrateLocal fetchCrateGit fetchCrateAlternativeRegistry expandFeatures decideProfile genDrvsByProfile; - profilesByName = { - release = builtins.fromTOML "codegen-units = 1\nlto = true\nstrip = true\n"; - }; - rootFeatures' = expandFeatures rootFeatures; - overridableMkRustCrate = f: - let - drvs = genDrvsByProfile profilesByName ({ profile, profileName }: mkRustCrate ({ inherit release profile hostPlatformCpu hostPlatformFeatures target profileOpts codegenOpts rustcLinkFlags rustcBuildFlags; } // (f profileName))); - in { compileMode ? null, profileName ? decideProfile compileMode release }: - let drv = drvs.${profileName}; in if compileMode == null then drv else drv.override { inherit compileMode; }; -in -{ - cargo2nixVersion = "0.11.0"; - workspace = { - api_models = rustPackages.unknown.api_models."0.1.0"; - common_utils = rustPackages.unknown.common_utils."0.1.0"; - masking = rustPackages.unknown.masking."0.1.0"; - router_env = rustPackages.unknown.router_env."0.1.0"; - router_derive = rustPackages.unknown.router_derive."0.1.0"; - drainer = rustPackages.unknown.drainer."0.1.0"; - redis_interface = rustPackages.unknown.redis_interface."0.1.0"; - diesel_models = rustPackages.unknown.diesel_models."0.1.0"; - router = rustPackages.unknown.router."0.2.0"; - }; - "registry+https://github.com/rust-lang/crates.io-index".actix."0.13.0" = overridableMkRustCrate (profileName: rec { - name = "actix"; - version = "0.13.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f728064aca1c318585bf4bb04ffcfac9e75e508ab4e8b1bd9ba5dfe04e2cbed5"; }; - features = builtins.concatLists [ - [ "actix_derive" ] - [ "default" ] - [ "macros" ] - ]; - dependencies = { - actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; }; - actix_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix_derive."0.6.0" { profileName = "__noProfile"; }; - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - crossbeam_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" = overridableMkRustCrate (profileName: rec { - name = "actix-codec"; - version = "0.5.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "57a7559404a7f3573127aab53c08ce37a6c6a315c374a31070f3c91cd1b4a7fe"; }; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-cors."0.6.4" = overridableMkRustCrate (profileName: rec { - name = "actix-cors"; - version = "0.6.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b340e9cfa5b08690aae90fb61beb44e9b06f44fe3d0f93781aaa58cfba86245e"; }; - dependencies = { - actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; }; - actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; }; - derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" = overridableMkRustCrate (profileName: rec { - name = "actix-http"; - version = "3.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0070905b2c4a98d184c4e81025253cb192aa8a73827553f38e9410801ceb35bb"; }; - features = builtins.concatLists [ - [ "__compress" ] - [ "base64" ] - [ "brotli" ] - [ "compress-brotli" ] - [ "compress-gzip" ] - [ "compress-zstd" ] - [ "default" ] - [ "flate2" ] - [ "h2" ] - [ "http2" ] - [ "local-channel" ] - [ "rand" ] - [ "sha1" ] - [ "ws" ] - [ "zstd" ] - ]; - dependencies = { - actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; }; - actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; }; - actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; }; - actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; }; - ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; }; - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; }; - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - brotli = rustPackages."registry+https://github.com/rust-lang/crates.io-index".brotli."3.3.4" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - bytestring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" { inherit profileName; }; - derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; }; - encoding_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; }; - flate2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - httparse = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httparse."1.8.0" { inherit profileName; }; - httpdate = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httpdate."1.0.2" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - language_tags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".language-tags."0.3.2" { inherit profileName; }; - local_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".local-channel."0.1.3" { inherit profileName; }; - mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - sha1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sha1."0.10.5" { inherit profileName; }; - smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - zstd = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd."0.12.2+zstd.1.5.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-macros."0.2.3" = overridableMkRustCrate (profileName: rec { - name = "actix-macros"; - version = "0.2.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "465a6172cf69b960917811022d8f29bc0b7fa1398bc4f78b3c466673db1213b6"; }; - dependencies = { - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-router."0.5.1" = overridableMkRustCrate (profileName: rec { - name = "actix-router"; - version = "0.5.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d66ff4d247d2b160861fa2866457e85706833527840e4133f8f49aa423a38799"; }; - features = builtins.concatLists [ - [ "default" ] - [ "http" ] - ]; - dependencies = { - bytestring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" = overridableMkRustCrate (profileName: rec { - name = "actix-rt"; - version = "2.8.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "15265b6b8e2347670eb363c47fc8c75208b4a4994b27192f345fcbe707804f3e"; }; - features = builtins.concatLists [ - [ "actix-macros" ] - [ "default" ] - [ "macros" ] - ]; - dependencies = { - actix_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-macros."0.2.3" { profileName = "__noProfile"; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-server."2.1.1" = overridableMkRustCrate (profileName: rec { - name = "actix-server"; - version = "2.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0da34f8e659ea1b077bb4637948b815cd3768ad5a188fdcd74ff4d84240cd824"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; }; - actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; }; - actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - mio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mio."0.8.5" { inherit profileName; }; - num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; }; - socket2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" = overridableMkRustCrate (profileName: rec { - name = "actix-service"; - version = "2.0.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3b894941f818cfdc7ccc4b9e60fa7e53b5042a2e8567270f9147d5591893373a"; }; - dependencies = { - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - paste = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".paste."1.0.11" { profileName = "__noProfile"; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-tls."3.0.3" = overridableMkRustCrate (profileName: rec { - name = "actix-tls"; - version = "3.0.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9fde0cf292f7cdc7f070803cb9a0d45c018441321a78b1042ffbbb81ec333297"; }; - features = builtins.concatLists [ - [ "accept" ] - [ "connect" ] - [ "default" ] - [ "http" ] - [ "rustls" ] - [ "tokio-rustls" ] - [ "uri" ] - [ "webpki-roots" ] - ]; - dependencies = { - actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; }; - actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; }; - actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; }; - actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio_rustls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - webpki_roots = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki-roots."0.22.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" = overridableMkRustCrate (profileName: rec { - name = "actix-utils"; - version = "3.0.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "88a1dcdff1466e3c2488e1cb5c36a71822750ad43839937f85d2f4d9f8b705d8"; }; - dependencies = { - local_waker = rustPackages."registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" = overridableMkRustCrate (profileName: rec { - name = "actix-web"; - version = "4.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "464e0fddc668ede5f26ec1f9557a8d44eda948732f40c6b0ad79126930eb775f"; }; - features = builtins.concatLists [ - [ "__compress" ] - [ "actix-macros" ] - [ "actix-web-codegen" ] - [ "compress-brotli" ] - [ "compress-gzip" ] - [ "compress-zstd" ] - [ "cookie" ] - [ "cookies" ] - [ "default" ] - [ "macros" ] - ]; - dependencies = { - actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; }; - actix_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" { inherit profileName; }; - actix_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-macros."0.2.3" { profileName = "__noProfile"; }; - actix_router = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-router."0.5.1" { inherit profileName; }; - actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; }; - actix_server = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-server."2.1.1" { inherit profileName; }; - actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; }; - actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; }; - actix_web_codegen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web-codegen."4.1.0" { profileName = "__noProfile"; }; - ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - bytestring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" { inherit profileName; }; - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - cookie = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cookie."0.16.2" { inherit profileName; }; - derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; }; - encoding_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - language_tags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".language-tags."0.3.2" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; }; - smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; - socket2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix-web-codegen."4.1.0" = overridableMkRustCrate (profileName: rec { - name = "actix-web-codegen"; - version = "4.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1fa9362663c8643d67b2d5eafba49e4cb2c8a053a29ed00a0bea121f17c76b13"; }; - dependencies = { - actix_router = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-router."0.5.1" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".actix_derive."0.6.0" = overridableMkRustCrate (profileName: rec { - name = "actix_derive"; - version = "0.6.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6d44b8fee1ced9671ba043476deddef739dd0959bf77030b26b738cc591737a7"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".adler."1.0.2" = overridableMkRustCrate (profileName: rec { - name = "adler"; - version = "1.0.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" = overridableMkRustCrate (profileName: rec { - name = "ahash"; - version = "0.7.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - ${ if hostPlatform.parsed.kernel.name == "linux" || hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" || hostPlatform.parsed.kernel.name == "freebsd" || hostPlatform.parsed.kernel.name == "openbsd" || hostPlatform.parsed.kernel.name == "netbsd" || hostPlatform.parsed.kernel.name == "dragonfly" || hostPlatform.parsed.kernel.name == "solaris" || hostPlatform.parsed.kernel.name == "illumos" || hostPlatform.parsed.kernel.name == "fuchsia" || hostPlatform.parsed.kernel.name == "redox" || hostPlatform.parsed.kernel.name == "cloudabi" || hostPlatform.parsed.kernel.name == "haiku" || hostPlatform.parsed.kernel.name == "vxworks" || hostPlatform.parsed.kernel.name == "emscripten" || hostPlatform.parsed.kernel.name == "wasi" then "getrandom" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" { inherit profileName; }; - ${ if !((hostPlatform.parsed.cpu.name == "armv6l" || hostPlatform.parsed.cpu.name == "armv7l") && hostPlatform.parsed.kernel.name == "none") then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - }; - buildDependencies = { - version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aho-corasick."0.7.20" = overridableMkRustCrate (profileName: rec { - name = "aho-corasick"; - version = "0.7.20"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" = overridableMkRustCrate (profileName: rec { - name = "alloc-no-stdlib"; - version = "2.0.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" = overridableMkRustCrate (profileName: rec { - name = "alloc-stdlib"; - version = "0.2.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"; }; - dependencies = { - alloc_no_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" = overridableMkRustCrate (profileName: rec { - name = "anyhow"; - version = "1.0.68"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2cb2f989d18dd141ab8ae82f64d1a8cdd37e0840f73a406896cf5e99502fab61"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "unknown".api_models."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "api_models"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/api_models"); - dependencies = { - actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; }; - common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; }; - error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; }; - frunk = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" { inherit profileName; }; - frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; }; - masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; }; - mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - reqwest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".reqwest."0.11.14" { inherit profileName; }; - router_derive = buildRustPackages."unknown".router_derive."0.1.0" { profileName = "__noProfile"; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - utoipa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".arc-swap."1.6.0" = overridableMkRustCrate (profileName: rec { - name = "arc-swap"; - version = "1.6.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".arcstr."1.1.5" = overridableMkRustCrate (profileName: rec { - name = "arcstr"; - version = "1.1.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3f907281554a3d0312bb7aab855a8e0ef6cbf1614d06de54105039ca8b34460e"; }; - features = builtins.concatLists [ - [ "default" ] - [ "substr" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".arrayref."0.3.6" = overridableMkRustCrate (profileName: rec { - name = "arrayref"; - version = "0.3.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".arrayvec."0.7.2" = overridableMkRustCrate (profileName: rec { - name = "arrayvec"; - version = "0.7.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".assert-json-diff."2.0.2" = overridableMkRustCrate (profileName: rec { - name = "assert-json-diff"; - version = "2.0.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"; }; - dependencies = { - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - }; - }); - "git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "async-bb8-diesel"; - version = "0.1.0"; - registry = "git+https://github.com/juspay/async-bb8-diesel"; - src = fetchCrateGit { - url = https://github.com/juspay/async-bb8-diesel; - name = "async-bb8-diesel"; - version = "0.1.0"; - rev = "9a71d142726dbc33f41c1fd935ddaa79841c7be5";}; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - bb8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" { inherit profileName; }; - diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".async-channel."1.8.0" = overridableMkRustCrate (profileName: rec { - name = "async-channel"; - version = "1.8.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "cf46fee83e5ccffc220104713af3292ff9bc7c64c7de289f66dae8e38d826833"; }; - dependencies = { - concurrent_queue = rustPackages."registry+https://github.com/rust-lang/crates.io-index".concurrent-queue."2.1.0" { inherit profileName; }; - event_listener = rustPackages."registry+https://github.com/rust-lang/crates.io-index".event-listener."2.5.3" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".async-compression."0.3.15" = overridableMkRustCrate (profileName: rec { - name = "async-compression"; - version = "0.3.15"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "942c7cd7ae39e91bde4820d74132e9862e62c2f386c3aa90ccf55949f5bad63a"; }; - features = builtins.concatLists [ - [ "flate2" ] - [ "gzip" ] - [ "tokio" ] - ]; - dependencies = { - flate2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".async-stream."0.3.3" = overridableMkRustCrate (profileName: rec { - name = "async-stream"; - version = "0.3.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "dad5c83079eae9969be7fadefe640a1c566901f05ff91ab221de4b6f68d9507e"; }; - dependencies = { - async_stream_impl = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-stream-impl."0.3.3" { profileName = "__noProfile"; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".async-stream-impl."0.3.3" = overridableMkRustCrate (profileName: rec { - name = "async-stream-impl"; - version = "0.3.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "10f203db73a71dfa2fb6dd22763990fa26f3d2625a6da2da900d23b87d26be27"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" = overridableMkRustCrate (profileName: rec { - name = "async-trait"; - version = "0.1.63"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "eff18d764974428cf3a9328e23fc5c986f5fbed46e6cd4cdf42544df5d297ec1"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".atty."0.2.14" = overridableMkRustCrate (profileName: rec { - name = "atty"; - version = "0.2.14"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"; }; - dependencies = { - ${ if hostPlatform.parsed.kernel.name == "hermit" then "hermit_abi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.1.19" { inherit profileName; }; - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" = overridableMkRustCrate (profileName: rec { - name = "autocfg"; - version = "1.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".awc."3.1.0" = overridableMkRustCrate (profileName: rec { - name = "awc"; - version = "3.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0dff3fc64a176e0d4398c71b0f2c2679ff4a723c6ed8fcc68dfe5baa00665388"; }; - features = builtins.concatLists [ - [ "__compress" ] - [ "compress-brotli" ] - [ "compress-gzip" ] - [ "compress-zstd" ] - [ "cookie" ] - [ "cookies" ] - [ "default" ] - [ "rustls" ] - [ "tls-rustls" ] - ]; - dependencies = { - actix_codec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" { inherit profileName; }; - actix_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" { inherit profileName; }; - actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; }; - actix_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" { inherit profileName; }; - actix_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-tls."3.0.3" { inherit profileName; }; - actix_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" { inherit profileName; }; - ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; }; - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - cookie = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cookie."0.16.2" { inherit profileName; }; - derive_more = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" { profileName = "__noProfile"; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - tls_rustls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-config."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-config"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3c3d1e2a1f1ab3ac6c4b884e37413eaa03eb9d901e4fc68ee8f5c1d49721680e"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "client-hyper") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sdk_sso" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sso."0.24.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sdk_sts" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sts."0.24.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "ring" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "zeroize" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-credential-types"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bb0696a0523a39a19087747e4dafda0362dc867531e3d72a3f195564c84e5e08"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "zeroize" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-endpoint"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "80a4f935ab6a1919fbfd6102a80c4fccd9ff5f47f94ba154074afe1051903261"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-http"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "82976ca4e426ee9ca3ffcf919d9b2c8d14d0cd80d43cc02173737a8f07f28d4d"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "lazy_static" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-kms."0.24.0" = overridableMkRustCrate (profileName: rec { - name = "aws-sdk-kms"; - version = "0.24.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "434d7097fc824eee1d94cf6c5e3a30714da15b81a5b99618f8feb67f8eb2f70a"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio") - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_endpoint" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sig_auth" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_stream" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sso."0.24.0" = overridableMkRustCrate (profileName: rec { - name = "aws-sdk-sso"; - version = "0.24.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ca0119bacf0c42f587506769390983223ba834e605f049babe514b2bd646dbb2"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_endpoint" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sig_auth" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_stream" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sts."0.24.0" = overridableMkRustCrate (profileName: rec { - name = "aws-sdk-sts"; - version = "0.24.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "270b6a33969ebfcb193512fbd5e8ee5306888ad6c6d5d775cdbfb2d50d94de26"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_endpoint" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sig_auth" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_query" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-query."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_xml" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-xml."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-sig-auth"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "660a02a98ab1af83bd8d714afbab2d502ba9b18c49e7e4cddd6bf8837ff778cb"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sigv4" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sigv4."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sigv4."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-sigv4"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "cdaf11005b7444e6cd66f600d09861a3aeb6eb89a0f003c7c9820dbab2d15297"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "form_urlencoded") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "http") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "percent-encoding") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "sign-http") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "form_urlencoded" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hmac" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hmac."0.12.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "sha2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-async"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "075d87b46420b28b64140f2ba88fa6b158c2877466a2acdbeaf396c25e4b9b33"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "futures_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_stream" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-client"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "17d44078855a64d757e5c1727df29ffa6679022c38cfc4ba4e63ee9567133141"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "client-hyper") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "hyper") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "hyper-rustls") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "lazy_static") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http_tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "fastrand" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper_rustls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper-rustls."0.23.2" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "lazy_static" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-http"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b5bd86f48d7e36fb24ee922d04d79c8353e01724b1c38757ed92593179223aa7"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rt-tokio") - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tokio") - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tokio-util") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes_utils" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "futures_core" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_utils" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-utils."0.1.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-http-tower"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c8972d1b4ae3aba1a10e7106fed53a5a36bc8ef86170a84f6ddd33d36fac12ad"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-json"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "18973f12721e27b54891386497a57e1ba09975df1c6cfeccafaf541198962aef"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-query."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-query"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2881effde104a2b0619badaad9f30ae67805e86fbbdb99e5fcc176e8bfbc1a85"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "urlencoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".urlencoding."2.1.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-types"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "da7e499c4b15bab8eb6b234df31833cc83a1bdaa691ba72d5d81efc109d9d705"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "base64_simd" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64-simd."0.7.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "itoa" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "num_integer" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-integer."0.1.45" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "ryu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-xml."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-smithy-xml"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9a73082f023f4a361fe811954da0061076709198792a3d2ad3a7498e10b606a0"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "xmlparser" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".xmlparser."0.13.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" = overridableMkRustCrate (profileName: rec { - name = "aws-types"; - version = "0.54.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f8f15b34253b68cde08e39b0627cc6101bcca64351229484b4743392c035d057"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_credential_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_async" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_client" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - buildDependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustc_version" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".axum."0.6.2" = overridableMkRustCrate (profileName: rec { - name = "axum"; - version = "0.6.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1304eab461cf02bd70b083ed8273388f9724c549b316ba3d1e213ce0e9e7fb7e"; }; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - axum_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".axum-core."0.3.1" { inherit profileName; }; - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - matchit = rustPackages."registry+https://github.com/rust-lang/crates.io-index".matchit."0.7.0" { inherit profileName; }; - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - sync_wrapper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sync_wrapper."0.1.1" { inherit profileName; }; - tower = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - tower_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-http."0.3.5" { inherit profileName; }; - tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; }; - tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; - }; - buildDependencies = { - rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".axum-core."0.3.1" = overridableMkRustCrate (profileName: rec { - name = "axum-core"; - version = "0.3.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f487e40dc9daee24d8a1779df88522f159a54a980f99cfbe43db0be0bd3444a8"; }; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; }; - tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; - }; - buildDependencies = { - rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" = overridableMkRustCrate (profileName: rec { - name = "base64"; - version = "0.13.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" = overridableMkRustCrate (profileName: rec { - name = "base64"; - version = "0.21.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a4a4ddaa51a5bc52a6948f74c06d20aaaddb71924eab79b8c97a8c556e942d6a"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".base64-simd."0.7.0" = overridableMkRustCrate (profileName: rec { - name = "base64-simd"; - version = "0.7.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "781dd20c3aff0bd194fe7d2a977dd92f21c173891f3a03b677359e5fa457e5d5"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "alloc") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "detect") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "simd_abstraction" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".simd-abstraction."0.7.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" = overridableMkRustCrate (profileName: rec { - name = "bb8"; - version = "0.8.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1627eccf3aa91405435ba240be23513eeca466b5dc33866422672264de061582"; }; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".bit-set."0.5.3" = overridableMkRustCrate (profileName: rec { - name = "bit-set"; - version = "0.5.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - bit_vec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bit-vec."0.6.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".bit-vec."0.6.3" = overridableMkRustCrate (profileName: rec { - name = "bit-vec"; - version = "0.6.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" = overridableMkRustCrate (profileName: rec { - name = "bitflags"; - version = "1.3.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".blake3."1.3.3" = overridableMkRustCrate (profileName: rec { - name = "blake3"; - version = "1.3.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef"; }; - features = builtins.concatLists [ - [ "default" ] - [ "digest" ] - [ "std" ] - ]; - dependencies = { - arrayref = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arrayref."0.3.6" { inherit profileName; }; - arrayvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arrayvec."0.7.2" { inherit profileName; }; - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - constant_time_eq = rustPackages."registry+https://github.com/rust-lang/crates.io-index".constant_time_eq."0.2.4" { inherit profileName; }; - digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; }; - }; - buildDependencies = { - cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.9.0" = overridableMkRustCrate (profileName: rec { - name = "block-buffer"; - version = "0.9.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"; }; - dependencies = { - generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.10.3" = overridableMkRustCrate (profileName: rec { - name = "block-buffer"; - version = "0.10.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"; }; - dependencies = { - generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".brotli."3.3.4" = overridableMkRustCrate (profileName: rec { - name = "brotli"; - version = "3.3.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68"; }; - features = builtins.concatLists [ - [ "alloc-stdlib" ] - [ "default" ] - [ "ffi-api" ] - [ "std" ] - ]; - dependencies = { - alloc_no_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" { inherit profileName; }; - alloc_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" { inherit profileName; }; - brotli_decompressor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".brotli-decompressor."2.3.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".brotli-decompressor."2.3.4" = overridableMkRustCrate (profileName: rec { - name = "brotli-decompressor"; - version = "2.3.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744"; }; - features = builtins.concatLists [ - [ "alloc-stdlib" ] - [ "std" ] - ]; - dependencies = { - alloc_no_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" { inherit profileName; }; - alloc_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".bumpalo."3.12.0" = overridableMkRustCrate (profileName: rec { - name = "bumpalo"; - version = "3.12.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".byteorder."1.4.3" = overridableMkRustCrate (profileName: rec { - name = "byteorder"; - version = "1.4.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" = overridableMkRustCrate (profileName: rec { - name = "bytes"; - version = "1.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" = overridableMkRustCrate (profileName: rec { - name = "bytes-utils"; - version = "0.1.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e47d3a8076e283f3acd27400535992edb3ba4b5bb72f8891ad8fbe7932a7d4b9"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - either = rustPackages."registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" = overridableMkRustCrate (profileName: rec { - name = "bytestring"; - version = "1.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f7f83e57d9154148e355404702e2694463241880b939570d7c97c014da7a69a1"; }; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" = overridableMkRustCrate (profileName: rec { - name = "cc"; - version = "1.0.78"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d"; }; - features = builtins.concatLists [ - [ "jobserver" ] - [ "parallel" ] - ]; - dependencies = { - jobserver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".jobserver."0.1.25" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" = overridableMkRustCrate (profileName: rec { - name = "cfg-if"; - version = "1.0.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".clap."4.1.4" = overridableMkRustCrate (profileName: rec { - name = "clap"; - version = "4.1.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f13b9c79b5d1dd500d20ef541215a6423c75829ef43117e1b4d17fd8af0b5d76"; }; - features = builtins.concatLists [ - [ "derive" ] - [ "help" ] - [ "std" ] - [ "usage" ] - ]; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - clap_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".clap_derive."4.1.0" { profileName = "__noProfile"; }; - clap_lex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".clap_lex."0.3.1" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".clap_derive."4.1.0" = overridableMkRustCrate (profileName: rec { - name = "clap_derive"; - version = "4.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "684a277d672e91966334af371f1a7b5833f9aa00b07c84e92fbce95e00208ce8"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - heck = rustPackages."registry+https://github.com/rust-lang/crates.io-index".heck."0.4.0" { inherit profileName; }; - proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".clap_lex."0.3.1" = overridableMkRustCrate (profileName: rec { - name = "clap_lex"; - version = "0.3.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "783fe232adfca04f90f56201b26d79682d4cd2625e0bc7290b95123afe558ade"; }; - dependencies = { - os_str_bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".os_str_bytes."6.4.1" { inherit profileName; }; - }; - }); - "unknown".common_utils."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "common_utils"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/common_utils"); - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; }; - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; }; - masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; }; - nanoid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nanoid."0.4.0" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; }; - router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; }; - signal_hook = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" { inherit profileName; }; - signal_hook_tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-tokio."0.3.1" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - devDependencies = { - fake = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fake."2.5.0" { inherit profileName; }; - proptest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proptest."1.1.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".concurrent-queue."2.1.0" = overridableMkRustCrate (profileName: rec { - name = "concurrent-queue"; - version = "2.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c278839b831783b70278b14df4d45e1beb1aad306c07bb796637de9a0e323e8e"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - crossbeam_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" = overridableMkRustCrate (profileName: rec { - name = "config"; - version = "0.13.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d379af7f68bfc21714c6c7dea883544201741d2ce8274bb12fa54f89507f52a7"; }; - features = builtins.concatLists [ - [ "default" ] - [ "ini" ] - [ "json" ] - [ "json5" ] - [ "json5_rs" ] - [ "ron" ] - [ "rust-ini" ] - [ "serde_json" ] - [ "toml" ] - [ "yaml" ] - [ "yaml-rust" ] - ]; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - json5_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".json5."0.4.1" { inherit profileName; }; - lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - nom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" { inherit profileName; }; - pathdiff = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pathdiff."0.2.1" { inherit profileName; }; - ron = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ron."0.7.1" { inherit profileName; }; - ini = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rust-ini."0.18.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - toml = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml."0.5.11" { inherit profileName; }; - yaml_rust = rustPackages."registry+https://github.com/rust-lang/crates.io-index".yaml-rust."0.4.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".constant_time_eq."0.2.4" = overridableMkRustCrate (profileName: rec { - name = "constant_time_eq"; - version = "0.2.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f3ad85c1f65dc7b37604eb0e89748faf0b9653065f2a8ef69f96a687ec1e9279"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".convert_case."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "convert_case"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".cookie."0.16.2" = overridableMkRustCrate (profileName: rec { - name = "cookie"; - version = "0.16.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb"; }; - features = builtins.concatLists [ - [ "percent-encode" ] - [ "percent-encoding" ] - ]; - dependencies = { - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - }; - buildDependencies = { - version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".cookie-factory."0.3.2" = overridableMkRustCrate (profileName: rec { - name = "cookie-factory"; - version = "0.3.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "396de984970346b0d9e93d1415082923c679e5ae5c3ee3dcbd104f5610af126b"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".core-foundation."0.9.3" = overridableMkRustCrate (profileName: rec { - name = "core-foundation"; - version = "0.9.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146"; }; - dependencies = { - core_foundation_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" { inherit profileName; }; - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" = overridableMkRustCrate (profileName: rec { - name = "core-foundation-sys"; - version = "0.8.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" = overridableMkRustCrate (profileName: rec { - name = "cpufeatures"; - version = "0.2.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"; }; - dependencies = { - ${ if hostPlatform.config == "aarch64-apple-darwin" || hostPlatform.config == "aarch64-linux-android" || hostPlatform.parsed.cpu.name == "aarch64" && hostPlatform.parsed.kernel.name == "linux" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".crc16."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "crc16"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".crc32fast."1.3.2" = overridableMkRustCrate (profileName: rec { - name = "crc32fast"; - version = "1.3.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" = overridableMkRustCrate (profileName: rec { - name = "crossbeam-channel"; - version = "0.5.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c2dd04ddaf88237dc3b8d8f9a3c1004b506b54b3313403944054d23c0870c521"; }; - features = builtins.concatLists [ - [ "crossbeam-utils" ] - [ "default" ] - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - crossbeam_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" = overridableMkRustCrate (profileName: rec { - name = "crossbeam-utils"; - version = "0.8.14"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4fb766fa798726286dbbb842f174001dab8abc7b627a1dd86e0b7222a95d929f"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".crypto-common."0.1.6" = overridableMkRustCrate (profileName: rec { - name = "crypto-common"; - version = "0.1.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; }; - typenum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".dashmap."5.4.0" = overridableMkRustCrate (profileName: rec { - name = "dashmap"; - version = "5.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc"; }; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - hashbrown = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" { inherit profileName; }; - lock_api = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".deadpool."0.9.5" = overridableMkRustCrate (profileName: rec { - name = "deadpool"; - version = "0.9.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "421fe0f90f2ab22016f32a9881be5134fdd71c65298917084b0c7477cbc3856e"; }; - features = builtins.concatLists [ - [ "async-trait" ] - [ "default" ] - [ "managed" ] - [ "unmanaged" ] - ]; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - deadpool_runtime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".deadpool-runtime."0.1.2" { inherit profileName; }; - num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; }; - retain_mut = rustPackages."registry+https://github.com/rust-lang/crates.io-index".retain_mut."0.1.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".deadpool-runtime."0.1.2" = overridableMkRustCrate (profileName: rec { - name = "deadpool-runtime"; - version = "0.1.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".derive_deref."1.1.1" = overridableMkRustCrate (profileName: rec { - name = "derive_deref"; - version = "1.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "dcdbcee2d9941369faba772587a565f4f534e42cb8d17e5295871de730163b2b"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" = overridableMkRustCrate (profileName: rec { - name = "derive_more"; - version = "0.99.17"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321"; }; - features = builtins.concatLists [ - [ "add" ] - [ "add_assign" ] - [ "as_mut" ] - [ "as_ref" ] - [ "constructor" ] - [ "convert_case" ] - [ "default" ] - [ "deref" ] - [ "deref_mut" ] - [ "display" ] - [ "error" ] - [ "from" ] - [ "from_str" ] - [ "index" ] - [ "index_mut" ] - [ "into" ] - [ "into_iterator" ] - [ "is_variant" ] - [ "iterator" ] - [ "mul" ] - [ "mul_assign" ] - [ "not" ] - [ "rustc_version" ] - [ "sum" ] - [ "try_into" ] - [ "unwrap" ] - ]; - dependencies = { - convert_case = rustPackages."registry+https://github.com/rust-lang/crates.io-index".convert_case."0.4.0" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - buildDependencies = { - rustc_version = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" = overridableMkRustCrate (profileName: rec { - name = "diesel"; - version = "2.0.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4391a22b19c916e50bec4d6140f29bdda3e3bb187223fe6e3ea0b6e4d1021c04"; }; - features = builtins.concatLists [ - [ "32-column-tables" ] - [ "bitflags" ] - [ "byteorder" ] - [ "default" ] - [ "itoa" ] - [ "postgres" ] - [ "postgres_backend" ] - [ "pq-sys" ] - [ "r2d2" ] - [ "serde_json" ] - [ "time" ] - [ "with-deprecated" ] - ]; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - byteorder = rustPackages."registry+https://github.com/rust-lang/crates.io-index".byteorder."1.4.3" { inherit profileName; }; - diesel_derives = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel_derives."2.0.1" { profileName = "__noProfile"; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - pq_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pq-sys."0.4.7" { inherit profileName; }; - r2d2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".r2d2."0.8.10" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".diesel_derives."2.0.1" = overridableMkRustCrate (profileName: rec { - name = "diesel_derives"; - version = "2.0.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "143b758c91dbc3fe1fdcb0dba5bd13276c6a66422f2ef5795b58488248a310aa"; }; - features = builtins.concatLists [ - [ "32-column-tables" ] - [ "default" ] - [ "postgres" ] - [ "with-deprecated" ] - ]; - dependencies = { - proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".digest."0.9.0" = overridableMkRustCrate (profileName: rec { - name = "digest"; - version = "0.9.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "std" ] - ]; - dependencies = { - generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" = overridableMkRustCrate (profileName: rec { - name = "digest"; - version = "0.10.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "block-buffer" ] - [ "core-api" ] - [ "default" ] - [ "mac" ] - [ "std" ] - [ "subtle" ] - ]; - dependencies = { - block_buffer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.10.3" { inherit profileName; }; - crypto_common = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crypto-common."0.1.6" { inherit profileName; }; - subtle = rustPackages."registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".dlv-list."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "dlv-list"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257"; }; - }); - "unknown".drainer."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "drainer"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/drainer"); - dependencies = { - async_bb8_diesel = rustPackages."git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" { inherit profileName; }; - bb8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" { inherit profileName; }; - clap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".clap."4.1.4" { inherit profileName; }; - common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; }; - config = rustPackages."registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" { inherit profileName; }; - diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; }; - error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - redis_interface = rustPackages."unknown".redis_interface."0.1.0" { inherit profileName; }; - router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_path_to_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" { inherit profileName; }; - diesel_models = rustPackages."unknown".diesel_models."0.1.0" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - buildDependencies = { - router_env = buildRustPackages."unknown".router_env."0.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".dyn-clone."1.0.10" = overridableMkRustCrate (profileName: rec { - name = "dyn-clone"; - version = "1.0.10"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c9b0705efd4599c15a38151f4721f7bc388306f61084d3bfd50bd07fbca5cb60"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" = overridableMkRustCrate (profileName: rec { - name = "either"; - version = "1.8.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "90e5c1c8368803113bf0c9584fc495a58b86dc8a29edbf8fe877d21d9507e797"; }; - features = builtins.concatLists [ - [ "default" ] - [ "use_std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" = overridableMkRustCrate (profileName: rec { - name = "encoding_rs"; - version = "0.8.31"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".env_logger."0.7.1" = overridableMkRustCrate (profileName: rec { - name = "env_logger"; - version = "0.7.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36"; }; - features = builtins.concatLists [ - [ "atty" ] - [ "default" ] - [ "humantime" ] - [ "regex" ] - [ "termcolor" ] - ]; - dependencies = { - atty = rustPackages."registry+https://github.com/rust-lang/crates.io-index".atty."0.2.14" { inherit profileName; }; - humantime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".humantime."1.3.0" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - termcolor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".termcolor."1.2.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" = overridableMkRustCrate (profileName: rec { - name = "error-stack"; - version = "0.2.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "859d224e04b2d93d974c08e375dac9b8d1a513846e44c6666450a57b1ed963f9"; }; - features = builtins.concatLists [ - [ "default" ] - [ "pretty-print" ] - [ "std" ] - ]; - dependencies = { - anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; }; - owo_colors = rustPackages."registry+https://github.com/rust-lang/crates.io-index".owo-colors."3.5.0" { inherit profileName; }; - }; - buildDependencies = { - rustc_version = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".event-listener."2.5.3" = overridableMkRustCrate (profileName: rec { - name = "event-listener"; - version = "2.5.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".fake."2.5.0" = overridableMkRustCrate (profileName: rec { - name = "fake"; - version = "2.5.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4d68f517805463f3a896a9d29c1d6ff09d3579ded64a7201b4069f8f9c0d52fd"; }; - dependencies = { - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" = overridableMkRustCrate (profileName: rec { - name = "fastrand"; - version = "1.8.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a7a407cfaa3385c4ae6b23e84623d48c2798d06e3e6a1878f7f59f17b3f86499"; }; - dependencies = { - ${ if hostPlatform.parsed.cpu.name == "wasm32" then "instant" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" = overridableMkRustCrate (profileName: rec { - name = "flate2"; - version = "1.0.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841"; }; - features = builtins.concatLists [ - [ "default" ] - [ "miniz_oxide" ] - [ "rust_backend" ] - ]; - dependencies = { - crc32fast = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crc32fast."1.3.2" { inherit profileName; }; - miniz_oxide = rustPackages."registry+https://github.com/rust-lang/crates.io-index".miniz_oxide."0.6.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".float-cmp."0.8.0" = overridableMkRustCrate (profileName: rec { - name = "float-cmp"; - version = "0.8.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e1267f4ac4f343772758f7b1bdcbe767c218bbab93bb432acbf5162bbf85a6c4"; }; - features = builtins.concatLists [ - [ "default" ] - [ "num-traits" ] - [ "ratio" ] - ]; - dependencies = { - num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" = overridableMkRustCrate (profileName: rec { - name = "fnv"; - version = "1.0.7"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".foreign-types."0.3.2" = overridableMkRustCrate (profileName: rec { - name = "foreign-types"; - version = "0.3.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"; }; - dependencies = { - foreign_types_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".foreign-types-shared."0.1.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".foreign-types-shared."0.1.1" = overridableMkRustCrate (profileName: rec { - name = "foreign-types-shared"; - version = "0.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" = overridableMkRustCrate (profileName: rec { - name = "form_urlencoded"; - version = "1.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8"; }; - dependencies = { - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".fred."5.2.0" = overridableMkRustCrate (profileName: rec { - name = "fred"; - version = "5.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6be0137d9045288f9c0a0659da3b74c196ad0263d2eafa0f5a73785a907bad14"; }; - features = builtins.concatLists [ - [ "default" ] - [ "enable-tls" ] - [ "ignore-auth-error" ] - [ "metrics" ] - [ "native-tls" ] - [ "partial-tracing" ] - [ "pool-prefer-active" ] - [ "tokio-native-tls" ] - [ "tracing" ] - [ "tracing-futures" ] - ]; - dependencies = { - arc_swap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arc-swap."1.6.0" { inherit profileName; }; - arcstr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".arcstr."1.1.5" { inherit profileName; }; - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - bytes_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" { inherit profileName; }; - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - float_cmp = rustPackages."registry+https://github.com/rust-lang/crates.io-index".float-cmp."0.8.0" { inherit profileName; }; - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; }; - parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.11.2" { inherit profileName; }; - pretty_env_logger = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pretty_env_logger."0.4.0" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - redis_protocol = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redis-protocol."4.1.0" { inherit profileName; }; - semver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" { inherit profileName; }; - sha1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sha-1."0.9.8" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" { inherit profileName; }; - tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.6.10" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - tracing_futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" { inherit profileName; }; - url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" = overridableMkRustCrate (profileName: rec { - name = "frunk"; - version = "0.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0"; }; - features = builtins.concatLists [ - [ "default" ] - [ "frunk_proc_macros" ] - [ "proc-macros" ] - [ "std" ] - [ "validated" ] - ]; - dependencies = { - frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; }; - frunk_derives = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_derives."0.4.1" { profileName = "__noProfile"; }; - frunk_proc_macros = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros."0.1.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" = overridableMkRustCrate (profileName: rec { - name = "frunk_core"; - version = "0.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_derives."0.4.1" = overridableMkRustCrate (profileName: rec { - name = "frunk_derives"; - version = "0.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173"; }; - dependencies = { - frunk_proc_macro_helpers = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macro_helpers."0.1.1" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macro_helpers."0.1.1" = overridableMkRustCrate (profileName: rec { - name = "frunk_proc_macro_helpers"; - version = "0.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50"; }; - dependencies = { - frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros."0.1.1" = overridableMkRustCrate (profileName: rec { - name = "frunk_proc_macros"; - version = "0.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0"; }; - dependencies = { - frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; }; - frunk_proc_macros_impl = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros_impl."0.1.1" { profileName = "__noProfile"; }; - proc_macro_hack = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros_impl."0.1.1" = overridableMkRustCrate (profileName: rec { - name = "frunk_proc_macros_impl"; - version = "0.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653"; }; - dependencies = { - frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; }; - frunk_proc_macro_helpers = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macro_helpers."0.1.1" { inherit profileName; }; - proc_macro_hack = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" { profileName = "__noProfile"; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "38390104763dc37a5145a53c29c63c1290b5d316d6086ec32c293f6736051bb0"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "async-await" ] - [ "default" ] - [ "executor" ] - [ "futures-executor" ] - [ "std" ] - ]; - dependencies = { - futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_executor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-executor."0.3.25" { inherit profileName; }; - futures_io = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-channel"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "52ba265a92256105f45b719605a571ffe2d1f0fea3807304b522c1d778f79eed"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "futures-sink" ] - [ "sink" ] - [ "std" ] - ]; - dependencies = { - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-core"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-executor."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-executor"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7acc85df6714c176ab5edf386123fafe217be88c0840ec11f199441134a074e2"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-io"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "00f5fb52a06bdcadeb54e8d3671f8888a39697dcb0b81b23b55174030427f4eb"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-lite."1.12.0" = overridableMkRustCrate (profileName: rec { - name = "futures-lite"; - version = "1.12.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7694489acd39452c77daa48516b894c153f192c3578d5a839b62c58099fcbf48"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "fastrand" ] - [ "futures-io" ] - [ "memchr" ] - [ "parking" ] - [ "std" ] - [ "waker-fn" ] - ]; - dependencies = { - fastrand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_io = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" { inherit profileName; }; - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - parking = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking."2.0.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - waker_fn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".waker-fn."1.1.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-macro."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-macro"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bdfb8ce053d86b91919aad980c220b1fb8401a9394410e1c289ed7e66b61835d"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-sink"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-task"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-timer."3.0.2" = overridableMkRustCrate (profileName: rec { - name = "futures-timer"; - version = "3.0.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" = overridableMkRustCrate (profileName: rec { - name = "futures-util"; - version = "0.3.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "async-await" ] - [ "async-await-macro" ] - [ "channel" ] - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - [ "futures-channel" ] - [ "futures-io" ] - [ "futures-macro" ] - [ "futures-sink" ] - [ "io" ] - [ "memchr" ] - [ "sink" ] - [ "slab" ] - [ "std" ] - ]; - dependencies = { - futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_io = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" { inherit profileName; }; - futures_macro = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-macro."0.3.25" { profileName = "__noProfile"; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - futures_task = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" { inherit profileName; }; - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - pin_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-utils."0.1.0" { inherit profileName; }; - slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" = overridableMkRustCrate (profileName: rec { - name = "generic-array"; - version = "0.14.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"; }; - features = builtins.concatLists [ - [ "more_lengths" ] - ]; - dependencies = { - typenum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" { inherit profileName; }; - }; - buildDependencies = { - version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".gethostname."0.4.1" = overridableMkRustCrate (profileName: rec { - name = "gethostname"; - version = "0.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8a329e22866dd78b35d2c639a4a23d7b950aeae300dfd79f4fb19f74055c2404"; }; - dependencies = { - ${ if !hostPlatform.isWindows then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.isWindows then "windows" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows."0.43.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" = overridableMkRustCrate (profileName: rec { - name = "getrandom"; - version = "0.1.16"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.9.0+wasi-snapshot-preview1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" = overridableMkRustCrate (profileName: rec { - name = "getrandom"; - version = "0.2.8"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".git2."0.16.1" = overridableMkRustCrate (profileName: rec { - name = "git2"; - version = "0.16.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ccf7f68c2995f392c49fffb4f95ae2c873297830eb25c6bc4c114ce8f4562acc"; }; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - libgit2_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libgit2-sys."0.14.2+1.5.1" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" = overridableMkRustCrate (profileName: rec { - name = "h2"; - version = "0.3.15"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4"; }; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; }; - slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" = overridableMkRustCrate (profileName: rec { - name = "hashbrown"; - version = "0.12.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"; }; - features = builtins.concatLists [ - [ "ahash" ] - [ "default" ] - [ "inline-more" ] - [ "raw" ] - ]; - dependencies = { - ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".heck."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "heck"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.1.19" = overridableMkRustCrate (profileName: rec { - name = "hermit-abi"; - version = "0.1.19"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.2.6" = overridableMkRustCrate (profileName: rec { - name = "hermit-abi"; - version = "0.2.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" = overridableMkRustCrate (profileName: rec { - name = "hex"; - version = "0.4.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".hmac."0.12.1" = overridableMkRustCrate (profileName: rec { - name = "hmac"; - version = "0.12.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "digest" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" = overridableMkRustCrate (profileName: rec { - name = "http"; - version = "0.2.8"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399"; }; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" = overridableMkRustCrate (profileName: rec { - name = "http-body"; - version = "0.4.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1"; }; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".http-range-header."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "http-range-header"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0bfe8eed0a9285ef776bb792479ea3834e8b94e13d615c2f66d03dd50a435a29"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".http-types."2.12.0" = overridableMkRustCrate (profileName: rec { - name = "http-types"; - version = "2.12.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6e9b187a72d63adbfba487f48095306ac823049cb504ee195541e91c7775f5ad"; }; - features = builtins.concatLists [ - [ "http" ] - [ "hyperium_http" ] - ]; - dependencies = { - anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; }; - async_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".async-channel."1.8.0" { inherit profileName; }; - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; - futures_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-lite."1.12.0" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - infer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".infer."0.2.3" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.7.3" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_qs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.8.5" { inherit profileName; }; - serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; }; - url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".httparse."1.8.0" = overridableMkRustCrate (profileName: rec { - name = "httparse"; - version = "1.8.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".httpdate."1.0.2" = overridableMkRustCrate (profileName: rec { - name = "httpdate"; - version = "1.0.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".humantime."1.3.0" = overridableMkRustCrate (profileName: rec { - name = "humantime"; - version = "1.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f"; }; - dependencies = { - quick_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" = overridableMkRustCrate (profileName: rec { - name = "hyper"; - version = "0.14.23"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "034711faac9d2166cb1baf1a2fb0b60b1f277f8492fd72176c17f3515e1abd3c"; }; - features = builtins.concatLists [ - [ "client" ] - [ "default" ] - [ "full" ] - [ "h2" ] - [ "http1" ] - [ "http2" ] - [ "runtime" ] - [ "server" ] - [ "socket2" ] - [ "stream" ] - [ "tcp" ] - ]; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - httparse = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httparse."1.8.0" { inherit profileName; }; - httpdate = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httpdate."1.0.2" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - socket2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - want = rustPackages."registry+https://github.com/rust-lang/crates.io-index".want."0.3.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".hyper-rustls."0.23.2" = overridableMkRustCrate (profileName: rec { - name = "hyper-rustls"; - version = "0.23.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "http1") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "http2") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "log") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "logging") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "native-tokio") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "rustls-native-certs") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tls12") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "tokio-runtime") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "http" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "log" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustls_native_certs" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls-native-certs."0.6.2" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_rustls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".hyper-timeout."0.4.1" = overridableMkRustCrate (profileName: rec { - name = "hyper-timeout"; - version = "0.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1"; }; - dependencies = { - hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_io_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-io-timeout."1.2.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".hyper-tls."0.5.0" = overridableMkRustCrate (profileName: rec { - name = "hyper-tls"; - version = "0.5.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905"; }; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".idna."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "idna"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6"; }; - dependencies = { - unicode_bidi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-bidi."0.3.8" { inherit profileName; }; - unicode_normalization = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-normalization."0.1.22" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" = overridableMkRustCrate (profileName: rec { - name = "indexmap"; - version = "1.9.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399"; }; - features = builtins.concatLists [ - [ "serde" ] - [ "std" ] - ]; - dependencies = { - hashbrown = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".infer."0.2.3" = overridableMkRustCrate (profileName: rec { - name = "infer"; - version = "0.2.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" = overridableMkRustCrate (profileName: rec { - name = "instant"; - version = "0.1.12"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"; }; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ipnet."2.7.1" = overridableMkRustCrate (profileName: rec { - name = "ipnet"; - version = "2.7.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "30e22bd8629359895450b59ea7a776c850561b96a3b1d31321c1949d9e6c9146"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".is_ci."1.1.1" = overridableMkRustCrate (profileName: rec { - name = "is_ci"; - version = "1.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "616cde7c720bb2bb5824a224687d8f77bfd38922027f01d825cd7453be5099fb"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".itertools."0.10.5" = overridableMkRustCrate (profileName: rec { - name = "itertools"; - version = "0.10.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"; }; - features = builtins.concatLists [ - [ "use_alloc" ] - ]; - dependencies = { - either = rustPackages."registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".itoa."0.4.8" = overridableMkRustCrate (profileName: rec { - name = "itoa"; - version = "0.4.8"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"; }; - features = builtins.concatLists [ - [ "i128" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" = overridableMkRustCrate (profileName: rec { - name = "itoa"; - version = "1.0.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".jobserver."0.1.25" = overridableMkRustCrate (profileName: rec { - name = "jobserver"; - version = "0.1.25"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "068b1ee6743e4d11fb9c6a1e6064b3693a1b600e7f5f5988047d98b3dc9fb90b"; }; - dependencies = { - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".josekit."0.8.1" = overridableMkRustCrate (profileName: rec { - name = "josekit"; - version = "0.8.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "dee6af62ad98bdf699ad2ecc8323479a1fdc7aa5faa6043d93119d83f6c5fca8"; }; - dependencies = { - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "anyhow" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "base64" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "flate2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "openssl" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl."0.10.45" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "regex" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "serde" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "serde_json" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "thiserror" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" = overridableMkRustCrate (profileName: rec { - name = "js-sys"; - version = "0.3.60"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47"; }; - dependencies = { - wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".json5."0.4.1" = overridableMkRustCrate (profileName: rec { - name = "json5"; - version = "0.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1"; }; - dependencies = { - pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; }; - pest_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pest_derive."2.5.3" { profileName = "__noProfile"; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".jsonwebtoken."8.2.0" = overridableMkRustCrate (profileName: rec { - name = "jsonwebtoken"; - version = "8.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "09f4f04699947111ec1733e71778d763555737579e44b85844cae8e1940a1828"; }; - features = builtins.concatLists [ - [ "default" ] - [ "pem" ] - [ "simple_asn1" ] - [ "use_pem" ] - ]; - dependencies = { - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; - pem = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pem."1.1.1" { inherit profileName; }; - ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - simple_asn1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".simple_asn1."0.6.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".language-tags."0.3.2" = overridableMkRustCrate (profileName: rec { - name = "language-tags"; - version = "0.3.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" = overridableMkRustCrate (profileName: rec { - name = "lazy_static"; - version = "1.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" = overridableMkRustCrate (profileName: rec { - name = "libc"; - version = "0.2.139"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".libgit2-sys."0.14.2+1.5.1" = overridableMkRustCrate (profileName: rec { - name = "libgit2-sys"; - version = "0.14.2+1.5.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7f3d95f6b51075fe9810a7ae22c7095f12b98005ab364d8544797a825ce946a4"; }; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - libz_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libz-sys."1.1.8" { inherit profileName; }; - }; - buildDependencies = { - cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; - pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".libm."0.2.6" = overridableMkRustCrate (profileName: rec { - name = "libm"; - version = "0.2.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "348108ab3fba42ec82ff6e9564fc4ca0247bdccdc68dd8af9764bbc79c3c8ffb"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".libmimalloc-sys."0.1.30" = overridableMkRustCrate (profileName: rec { - name = "libmimalloc-sys"; - version = "0.1.30"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "dd8c7cbf8b89019683667e347572e6d55a7df7ea36b0c4ce69961b0cde67b174"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/mimalloc") "secure") - ]; - dependencies = { - ${ if rootFeatures' ? "router/mimalloc" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - buildDependencies = { - ${ if rootFeatures' ? "router/mimalloc" then "cc" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".libz-sys."1.1.8" = overridableMkRustCrate (profileName: rec { - name = "libz-sys"; - version = "1.1.8"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9702761c3935f8cc2f101793272e202c72b99da8f4224a19ddcf1279a6450bbf"; }; - features = builtins.concatLists [ - [ "libc" ] - ]; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - buildDependencies = { - cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; - pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; }; - ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".linked-hash-map."0.5.6" = overridableMkRustCrate (profileName: rec { - name = "linked-hash-map"; - version = "0.5.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".literally."0.1.3" = overridableMkRustCrate (profileName: rec { - name = "literally"; - version = "0.1.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f0d2be3f5a0d4d5c983d1f8ecc2a87676a0875a14feb9eebf0675f7c3e2f3c35"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".local-channel."0.1.3" = overridableMkRustCrate (profileName: rec { - name = "local-channel"; - version = "0.1.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7f303ec0e94c6c54447f84f3b0ef7af769858a9c4ef56ef2a986d3dcd4c3fc9c"; }; - dependencies = { - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - local_waker = rustPackages."registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" = overridableMkRustCrate (profileName: rec { - name = "local-waker"; - version = "0.1.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e34f76eb3611940e0e7d53a9aaa4e6a3151f69541a282fd0dad5571420c53ff1"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" = overridableMkRustCrate (profileName: rec { - name = "lock_api"; - version = "0.4.9"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df"; }; - dependencies = { - scopeguard = rustPackages."registry+https://github.com/rust-lang/crates.io-index".scopeguard."1.1.0" { inherit profileName; }; - }; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" = overridableMkRustCrate (profileName: rec { - name = "log"; - version = "0.4.17"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - }; - }); - "unknown".masking."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "masking"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/masking"); - features = builtins.concatLists [ - [ "alloc" ] - (lib.optional (rootFeatures' ? "masking/bytes") "bytes") - [ "default" ] - [ "diesel" ] - [ "serde" ] - ]; - dependencies = { - ${ if rootFeatures' ? "masking/bytes" then "bytes" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - subtle = rustPackages."registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" { inherit profileName; }; - zeroize = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; }; - }; - devDependencies = { - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".matchers."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "matchers"; - version = "0.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"; }; - dependencies = { - regex_automata = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-automata."0.1.10" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".matchit."0.7.0" = overridableMkRustCrate (profileName: rec { - name = "matchit"; - version = "0.7.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b87248edafb776e59e6ee64a79086f65890d3510f2c656c000bf2a7e8a0aea40"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".maud."0.24.0" = overridableMkRustCrate (profileName: rec { - name = "maud"; - version = "0.24.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "19aff2cd19eb4b93df29efa602652513b0f731f1d3474f6e377f763fddf61e58"; }; - features = builtins.concatLists [ - [ "actix-web" ] - [ "actix-web-dep" ] - [ "default" ] - [ "futures-util" ] - ]; - dependencies = { - actix_web_dep = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."0.4.8" { inherit profileName; }; - maud_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".maud_macros."0.24.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".maud_macros."0.24.0" = overridableMkRustCrate (profileName: rec { - name = "maud_macros"; - version = "0.24.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e5c114f6f24b08fdd4a25d2fb87a8b140df56b577723247b382e8b04c583f2eb"; }; - dependencies = { - proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" = overridableMkRustCrate (profileName: rec { - name = "memchr"; - version = "2.5.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".mimalloc."0.1.34" = overridableMkRustCrate (profileName: rec { - name = "mimalloc"; - version = "0.1.34"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9dcb174b18635f7561a0c6c9fc2ce57218ac7523cf72c50af80e2d79ab8f3ba1"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/mimalloc") "default") - (lib.optional (rootFeatures' ? "router/mimalloc") "secure") - ]; - dependencies = { - ${ if rootFeatures' ? "router/mimalloc" then "libmimalloc_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libmimalloc-sys."0.1.30" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" = overridableMkRustCrate (profileName: rec { - name = "mime"; - version = "0.3.16"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".minimal-lexical."0.2.1" = overridableMkRustCrate (profileName: rec { - name = "minimal-lexical"; - version = "0.2.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".miniz_oxide."0.6.2" = overridableMkRustCrate (profileName: rec { - name = "miniz_oxide"; - version = "0.6.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa"; }; - features = builtins.concatLists [ - [ "with-alloc" ] - ]; - dependencies = { - adler = rustPackages."registry+https://github.com/rust-lang/crates.io-index".adler."1.0.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".mio."0.8.5" = overridableMkRustCrate (profileName: rec { - name = "mio"; - version = "0.8.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de"; }; - features = builtins.concatLists [ - [ "default" ] - [ "net" ] - [ "os-ext" ] - [ "os-poll" ] - ]; - dependencies = { - ${ if hostPlatform.isUnix || hostPlatform.parsed.kernel.name == "wasi" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" { inherit profileName; }; - ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".nanoid."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "nanoid"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"; }; - dependencies = { - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" = overridableMkRustCrate (profileName: rec { - name = "native-tls"; - version = "0.2.11"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e"; }; - dependencies = { - ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "lazy_static" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "log" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "openssl" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl."0.10.45" { inherit profileName; }; - ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "openssl_probe" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-probe."0.1.5" { inherit profileName; }; - ${ if !(hostPlatform.parsed.kernel.name == "windows" || hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios") then "openssl_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "windows" then "schannel" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".schannel."0.1.21" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "security_framework" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "security_framework_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "tempfile" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" = overridableMkRustCrate (profileName: rec { - name = "nom"; - version = "7.1.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "std" ] - ]; - dependencies = { - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - minimal_lexical = rustPackages."registry+https://github.com/rust-lang/crates.io-index".minimal-lexical."0.2.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".nom8."0.2.0" = overridableMkRustCrate (profileName: rec { - name = "nom8"; - version = "0.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ae01545c9c7fc4486ab7debaf2aad7003ac19431791868fb2e8066df97fad2f8"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "std" ] - ]; - dependencies = { - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".nu-ansi-term."0.46.0" = overridableMkRustCrate (profileName: rec { - name = "nu-ansi-term"; - version = "0.46.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"; }; - dependencies = { - overload = rustPackages."registry+https://github.com/rust-lang/crates.io-index".overload."0.1.1" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "windows" then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".num-bigint."0.4.3" = overridableMkRustCrate (profileName: rec { - name = "num-bigint"; - version = "0.4.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f"; }; - dependencies = { - num_integer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-integer."0.1.45" { inherit profileName; }; - num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; }; - }; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".num-integer."0.1.45" = overridableMkRustCrate (profileName: rec { - name = "num-integer"; - version = "0.1.45"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - [ "i128" ] - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std") - ]; - dependencies = { - num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; }; - }; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" = overridableMkRustCrate (profileName: rec { - name = "num-traits"; - version = "0.2.15"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd"; }; - features = builtins.concatLists [ - [ "i128" ] - [ "libm" ] - [ "std" ] - ]; - dependencies = { - libm = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libm."0.2.6" { inherit profileName; }; - }; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" = overridableMkRustCrate (profileName: rec { - name = "num_cpus"; - version = "1.15.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b"; }; - dependencies = { - ${ if (hostPlatform.parsed.cpu.name == "x86_64" || hostPlatform.parsed.cpu.name == "aarch64") && hostPlatform.parsed.kernel.name == "hermit" then "hermit_abi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.2.6" { inherit profileName; }; - ${ if !hostPlatform.isWindows then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" = overridableMkRustCrate (profileName: rec { - name = "once_cell"; - version = "1.17.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6f61fba1741ea2b3d6a1e3178721804bb716a68a6aeba1149b5d52e3d464ea66"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "race" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".opaque-debug."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "opaque-debug"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".openssl."0.10.45" = overridableMkRustCrate (profileName: rec { - name = "openssl"; - version = "0.10.45"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b102428fd03bc5edf97f62620f7298614c45cedf287c271e7ed450bbaf83f2e1"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - foreign_types = rustPackages."registry+https://github.com/rust-lang/crates.io-index".foreign-types."0.3.2" { inherit profileName; }; - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - openssl_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-macros."0.1.0" { profileName = "__noProfile"; }; - ffi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".openssl-macros."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "openssl-macros"; - version = "0.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".openssl-probe."0.1.5" = overridableMkRustCrate (profileName: rec { - name = "openssl-probe"; - version = "0.1.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" = overridableMkRustCrate (profileName: rec { - name = "openssl-sys"; - version = "0.9.80"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "23bbbf7854cd45b83958ebe919f0e8e516793727652e27fda10a8384cfc790b7"; }; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; - pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; }; - ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; }; - }; - }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" = overridableMkRustCrate (profileName: rec { - name = "opentelemetry"; - version = "0.18.0"; - registry = "git+https://github.com/open-telemetry/opentelemetry-rust"; - src = fetchCrateGit { - url = https://github.com/open-telemetry/opentelemetry-rust; - name = "opentelemetry"; - version = "0.18.0"; - rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";}; - features = builtins.concatLists [ - [ "default" ] - [ "metrics" ] - [ "rt-tokio-current-thread" ] - [ "trace" ] - ]; - dependencies = { - opentelemetry_api = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_api."0.18.0" { inherit profileName; }; - opentelemetry_sdk = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_sdk."0.18.0" { inherit profileName; }; - }; - }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-otlp."0.11.0" = overridableMkRustCrate (profileName: rec { - name = "opentelemetry-otlp"; - version = "0.11.0"; - registry = "git+https://github.com/open-telemetry/opentelemetry-rust"; - src = fetchCrateGit { - url = https://github.com/open-telemetry/opentelemetry-rust; - name = "opentelemetry-otlp"; - version = "0.11.0"; - rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";}; - features = builtins.concatLists [ - [ "default" ] - [ "grpc-tonic" ] - [ "http" ] - [ "metrics" ] - [ "prost" ] - [ "tokio" ] - [ "tonic" ] - [ "trace" ] - ]; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; }; - opentelemetry_proto = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-proto."0.1.0" { inherit profileName; }; - prost = rustPackages."registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tonic = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" { inherit profileName; }; - }; - }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-proto."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "opentelemetry-proto"; - version = "0.1.0"; - registry = "git+https://github.com/open-telemetry/opentelemetry-rust"; - src = fetchCrateGit { - url = https://github.com/open-telemetry/opentelemetry-rust; - name = "opentelemetry-proto"; - version = "0.1.0"; - rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";}; - features = builtins.concatLists [ - [ "gen-tonic" ] - [ "metrics" ] - [ "prost" ] - [ "tonic" ] - [ "traces" ] - ]; - dependencies = { - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; }; - prost = rustPackages."registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" { inherit profileName; }; - tonic = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" { inherit profileName; }; - }; - }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_api."0.18.0" = overridableMkRustCrate (profileName: rec { - name = "opentelemetry_api"; - version = "0.18.0"; - registry = "git+https://github.com/open-telemetry/opentelemetry-rust"; - src = fetchCrateGit { - url = https://github.com/open-telemetry/opentelemetry-rust; - name = "opentelemetry_api"; - version = "0.18.0"; - rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";}; - features = builtins.concatLists [ - [ "default" ] - [ "fnv" ] - [ "metrics" ] - [ "pin-project-lite" ] - [ "trace" ] - ]; - dependencies = { - fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; }; - futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "wasm32" then "js_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - }; - }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_sdk."0.18.0" = overridableMkRustCrate (profileName: rec { - name = "opentelemetry_sdk"; - version = "0.18.0"; - registry = "git+https://github.com/open-telemetry/opentelemetry-rust"; - src = fetchCrateGit { - url = https://github.com/open-telemetry/opentelemetry-rust; - name = "opentelemetry_sdk"; - version = "0.18.0"; - rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658";}; - features = builtins.concatLists [ - [ "async-trait" ] - [ "crossbeam-channel" ] - [ "dashmap" ] - [ "default" ] - [ "fnv" ] - [ "metrics" ] - [ "percent-encoding" ] - [ "rand" ] - [ "rt-tokio-current-thread" ] - [ "tokio" ] - [ "tokio-stream" ] - [ "trace" ] - ]; - dependencies = { - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - crossbeam_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" { inherit profileName; }; - dashmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dashmap."5.4.0" { inherit profileName; }; - fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; }; - futures_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" { inherit profileName; }; - futures_executor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-executor."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - opentelemetry_api = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_api."0.18.0" { inherit profileName; }; - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ordered-multimap."0.4.3" = overridableMkRustCrate (profileName: rec { - name = "ordered-multimap"; - version = "0.4.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a"; }; - dependencies = { - dlv_list = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dlv-list."0.3.0" { inherit profileName; }; - hashbrown = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".os_str_bytes."6.4.1" = overridableMkRustCrate (profileName: rec { - name = "os_str_bytes"; - version = "6.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee"; }; - features = builtins.concatLists [ - [ "raw_os_str" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".outref."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "outref"; - version = "0.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7f222829ae9293e33a9f5e9f440c6760a3d450a64affe1846486b140db81c1f4"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".overload."0.1.1" = overridableMkRustCrate (profileName: rec { - name = "overload"; - version = "0.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".owo-colors."3.5.0" = overridableMkRustCrate (profileName: rec { - name = "owo-colors"; - version = "3.5.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"; }; - features = builtins.concatLists [ - [ "supports-color" ] - [ "supports-colors" ] - ]; - dependencies = { - supports_color = rustPackages."registry+https://github.com/rust-lang/crates.io-index".supports-color."1.3.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".parking."2.0.0" = overridableMkRustCrate (profileName: rec { - name = "parking"; - version = "2.0.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.11.2" = overridableMkRustCrate (profileName: rec { - name = "parking_lot"; - version = "0.11.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - instant = rustPackages."registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" { inherit profileName; }; - lock_api = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" { inherit profileName; }; - parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.8.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" = overridableMkRustCrate (profileName: rec { - name = "parking_lot"; - version = "0.12.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - lock_api = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" { inherit profileName; }; - parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.8.6" = overridableMkRustCrate (profileName: rec { - name = "parking_lot_core"; - version = "0.8.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc"; }; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - instant = rustPackages."registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" { inherit profileName; }; - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "redox" then "syscall" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" { inherit profileName; }; - smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; - ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" = overridableMkRustCrate (profileName: rec { - name = "parking_lot_core"; - version = "0.9.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ba1ef8814b5c993410bb3adfad7a5ed269563e4a2f90c41f5d85be7fb47133bf"; }; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "redox" then "syscall" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" { inherit profileName; }; - smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; - ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".paste."1.0.11" = overridableMkRustCrate (profileName: rec { - name = "paste"; - version = "1.0.11"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d01a5bd0424d00070b0098dd17ebca6f961a959dead1dbcbbbc1d1cd8d3deeba"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pathdiff."0.2.1" = overridableMkRustCrate (profileName: rec { - name = "pathdiff"; - version = "0.2.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pem."1.1.1" = overridableMkRustCrate (profileName: rec { - name = "pem"; - version = "1.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a8835c273a76a90455d7344889b0964598e3316e2a79ede8e36f16bdcf2228b8"; }; - dependencies = { - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" = overridableMkRustCrate (profileName: rec { - name = "percent-encoding"; - version = "2.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" = overridableMkRustCrate (profileName: rec { - name = "pest"; - version = "2.5.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4257b4a04d91f7e9e6290be5d3da4804dd5784fafde3a497d73eb2b4a158c30a"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - [ "thiserror" ] - ]; - dependencies = { - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - ucd_trie = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ucd-trie."0.1.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pest_derive."2.5.3" = overridableMkRustCrate (profileName: rec { - name = "pest_derive"; - version = "2.5.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "241cda393b0cdd65e62e07e12454f1f25d57017dcc514b1514cd3c4645e3a0a6"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; }; - pest_generator = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest_generator."2.5.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pest_generator."2.5.3" = overridableMkRustCrate (profileName: rec { - name = "pest_generator"; - version = "2.5.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "46b53634d8c8196302953c74d5352f33d0c512a9499bd2ce468fc9f4128fa27c"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; }; - pest_meta = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest_meta."2.5.3" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pest_meta."2.5.3" = overridableMkRustCrate (profileName: rec { - name = "pest_meta"; - version = "2.5.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0ef4f1332a8d4678b41966bb4cc1d0676880e84183a1ecc3f4b69f03e99c7a51"; }; - dependencies = { - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - pest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" { inherit profileName; }; - }; - buildDependencies = { - sha2 = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" = overridableMkRustCrate (profileName: rec { - name = "pin-project"; - version = "1.0.12"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ad29a609b6bcd67fee905812e544992d216af9d755757c05ed2d0e15a74c6ecc"; }; - dependencies = { - pin_project_internal = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-internal."1.0.12" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pin-project-internal."1.0.12" = overridableMkRustCrate (profileName: rec { - name = "pin-project-internal"; - version = "1.0.12"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "069bdb1e05adc7a8990dce9cc75370895fbe4e3d58b9b73bf1aee56359344a55"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" = overridableMkRustCrate (profileName: rec { - name = "pin-project-lite"; - version = "0.2.9"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pin-utils."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "pin-utils"; - version = "0.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" = overridableMkRustCrate (profileName: rec { - name = "pkg-config"; - version = "0.3.26"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ppv-lite86."0.2.17" = overridableMkRustCrate (profileName: rec { - name = "ppv-lite86"; - version = "0.2.17"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"; }; - features = builtins.concatLists [ - [ "simd" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".pq-sys."0.4.7" = overridableMkRustCrate (profileName: rec { - name = "pq-sys"; - version = "0.4.7"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3b845d6d8ec554f972a2c5298aad68953fd64e7441e846075450b44656a016d1"; }; - buildDependencies = { - ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".pretty_env_logger."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "pretty_env_logger"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "926d36b9553851b8b0005f1275891b392ee4d2d833852c417ed025477350fb9d"; }; - dependencies = { - env_logger = rustPackages."registry+https://github.com/rust-lang/crates.io-index".env_logger."0.7.1" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" = overridableMkRustCrate (profileName: rec { - name = "proc-macro-error"; - version = "1.0.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"; }; - features = builtins.concatLists [ - [ "default" ] - [ "syn" ] - [ "syn-error" ] - ]; - dependencies = { - proc_macro_error_attr = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error-attr."1.0.4" { profileName = "__noProfile"; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - buildDependencies = { - version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro-error-attr."1.0.4" = overridableMkRustCrate (profileName: rec { - name = "proc-macro-error-attr"; - version = "1.0.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - }; - buildDependencies = { - version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" = overridableMkRustCrate (profileName: rec { - name = "proc-macro-hack"; - version = "0.5.20+deprecated"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" = overridableMkRustCrate (profileName: rec { - name = "proc-macro2"; - version = "1.0.50"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2"; }; - features = builtins.concatLists [ - [ "default" ] - [ "proc-macro" ] - ]; - dependencies = { - unicode_ident = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".proptest."1.1.0" = overridableMkRustCrate (profileName: rec { - name = "proptest"; - version = "1.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "29f1b898011ce9595050a68e60f90bad083ff2987a695a42357134c8381fba70"; }; - features = builtins.concatLists [ - [ "bit-set" ] - [ "break-dead-code" ] - [ "default" ] - [ "fork" ] - [ "lazy_static" ] - [ "quick-error" ] - [ "regex-syntax" ] - [ "rusty-fork" ] - [ "std" ] - [ "tempfile" ] - [ "timeout" ] - ]; - dependencies = { - bit_set = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bit-set."0.5.3" { inherit profileName; }; - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - byteorder = rustPackages."registry+https://github.com/rust-lang/crates.io-index".byteorder."1.4.3" { inherit profileName; }; - lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; }; - quick_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quick-error."2.0.1" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - rand_chacha = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.3.1" { inherit profileName; }; - rand_xorshift = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_xorshift."0.3.0" { inherit profileName; }; - regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; }; - rusty_fork = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rusty-fork."0.3.0" { inherit profileName; }; - tempfile = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" { inherit profileName; }; - unarray = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unarray."0.1.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" = overridableMkRustCrate (profileName: rec { - name = "prost"; - version = "0.11.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "21dc42e00223fc37204bd4aa177e69420c604ca4a183209a8f9de30c6d934698"; }; - features = builtins.concatLists [ - [ "default" ] - [ "prost-derive" ] - [ "std" ] - ]; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - prost_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" = overridableMkRustCrate (profileName: rec { - name = "prost-derive"; - version = "0.11.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8bda8c0881ea9f722eb9629376db3d0b903b462477c1aafcb0566610ac28ac5d"; }; - dependencies = { - anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; }; - itertools = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itertools."0.10.5" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" = overridableMkRustCrate (profileName: rec { - name = "quick-error"; - version = "1.2.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".quick-error."2.0.1" = overridableMkRustCrate (profileName: rec { - name = "quick-error"; - version = "2.0.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" = overridableMkRustCrate (profileName: rec { - name = "quote"; - version = "1.0.23"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b"; }; - features = builtins.concatLists [ - [ "default" ] - [ "proc-macro" ] - ]; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".r2d2."0.8.10" = overridableMkRustCrate (profileName: rec { - name = "r2d2"; - version = "0.8.10"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "51de85fb3fb6524929c8a2eb85e6b6d363de4e8c48f9e2c2eac4944abc181c93"; }; - dependencies = { - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; }; - scheduled_thread_pool = rustPackages."registry+https://github.com/rust-lang/crates.io-index".scheduled-thread-pool."0.2.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand."0.7.3" = overridableMkRustCrate (profileName: rec { - name = "rand"; - version = "0.7.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "getrandom" ] - [ "getrandom_package" ] - [ "libc" ] - [ "std" ] - ]; - dependencies = { - getrandom_package = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" { inherit profileName; }; - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if !(hostPlatform.parsed.kernel.name == "emscripten") then "rand_chacha" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.2.2" { inherit profileName; }; - rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "emscripten" then "rand_hc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_hc."0.2.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" = overridableMkRustCrate (profileName: rec { - name = "rand"; - version = "0.8.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "getrandom" ] - [ "libc" ] - [ "rand_chacha" ] - [ "small_rng" ] - [ "std" ] - [ "std_rng" ] - ]; - dependencies = { - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - rand_chacha = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.3.1" { inherit profileName; }; - rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.2.2" = overridableMkRustCrate (profileName: rec { - name = "rand_chacha"; - version = "0.2.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - ppv_lite86 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ppv-lite86."0.2.17" { inherit profileName; }; - rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.3.1" = overridableMkRustCrate (profileName: rec { - name = "rand_chacha"; - version = "0.3.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - dependencies = { - ppv_lite86 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ppv-lite86."0.2.17" { inherit profileName; }; - rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" = overridableMkRustCrate (profileName: rec { - name = "rand_core"; - version = "0.5.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "getrandom" ] - [ "std" ] - ]; - dependencies = { - getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" = overridableMkRustCrate (profileName: rec { - name = "rand_core"; - version = "0.6.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "getrandom" ] - [ "std" ] - ]; - dependencies = { - getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand_hc."0.2.0" = overridableMkRustCrate (profileName: rec { - name = "rand_hc"; - version = "0.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"; }; - dependencies = { - rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rand_xorshift."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "rand_xorshift"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d25bf25ec5ae4a3f1b92f929810509a2f53d7dca2f50b794ff57e3face536c8f"; }; - dependencies = { - rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".redis-protocol."4.1.0" = overridableMkRustCrate (profileName: rec { - name = "redis-protocol"; - version = "4.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9c31deddf734dc0a39d3112e73490e88b61a05e83e074d211f348404cee4d2c6"; }; - features = builtins.concatLists [ - [ "decode-mut" ] - [ "default" ] - ]; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - bytes_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" { inherit profileName; }; - cookie_factory = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cookie-factory."0.3.2" { inherit profileName; }; - crc16 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crc16."0.4.0" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - nom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" { inherit profileName; }; - }; - }); - "unknown".redis_interface."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "redis_interface"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/redis_interface"); - dependencies = { - common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; }; - error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; }; - fred = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fred."5.2.0" { inherit profileName; }; - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - }; - devDependencies = { - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" = overridableMkRustCrate (profileName: rec { - name = "redox_syscall"; - version = "0.2.16"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"; }; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" = overridableMkRustCrate (profileName: rec { - name = "regex"; - version = "1.7.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733"; }; - features = builtins.concatLists [ - [ "aho-corasick" ] - [ "default" ] - [ "memchr" ] - [ "perf" ] - [ "perf-cache" ] - [ "perf-dfa" ] - [ "perf-inline" ] - [ "perf-literal" ] - [ "std" ] - [ "unicode" ] - [ "unicode-age" ] - [ "unicode-bool" ] - [ "unicode-case" ] - [ "unicode-gencat" ] - [ "unicode-perl" ] - [ "unicode-script" ] - [ "unicode-segment" ] - ]; - dependencies = { - aho_corasick = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aho-corasick."0.7.20" { inherit profileName; }; - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".regex-automata."0.1.10" = overridableMkRustCrate (profileName: rec { - name = "regex-automata"; - version = "0.1.10"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"; }; - features = builtins.concatLists [ - [ "default" ] - [ "regex-syntax" ] - [ "std" ] - ]; - dependencies = { - regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" = overridableMkRustCrate (profileName: rec { - name = "regex-syntax"; - version = "0.6.28"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848"; }; - features = builtins.concatLists [ - [ "default" ] - [ "unicode" ] - [ "unicode-age" ] - [ "unicode-bool" ] - [ "unicode-case" ] - [ "unicode-gencat" ] - [ "unicode-perl" ] - [ "unicode-script" ] - [ "unicode-segment" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".remove_dir_all."0.5.3" = overridableMkRustCrate (profileName: rec { - name = "remove_dir_all"; - version = "0.5.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"; }; - dependencies = { - ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".reqwest."0.11.14" = overridableMkRustCrate (profileName: rec { - name = "reqwest"; - version = "0.11.14"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "21eed90ec8570952d53b772ecf8f206aa1ec9a3d76b2521c56c42973f2d91ee9"; }; - features = builtins.concatLists [ - [ "__tls" ] - [ "async-compression" ] - [ "default" ] - [ "default-tls" ] - [ "gzip" ] - [ "hyper-tls" ] - [ "json" ] - [ "native-tls" ] - [ "native-tls-crate" ] - [ "serde_json" ] - [ "tokio-native-tls" ] - [ "tokio-util" ] - ]; - dependencies = { - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "async_compression" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".async-compression."0.3.15" { inherit profileName; }; - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "encoding_rs" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "h2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "http_body" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "hyper" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "hyper_tls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper-tls."0.5.0" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "ipnet" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ipnet."2.7.1" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "wasm32" then "js_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "log" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "mime" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "native_tls_crate" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "pin_project_lite" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "tokio" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "tokio_native_tls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32") then "tokio_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; - url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "wasm32" then "wasm_bindgen" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "wasm32" then "wasm_bindgen_futures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-futures."0.4.33" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "wasm32" then "web_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" { inherit profileName; }; - ${ if hostPlatform.isWindows then "winreg" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winreg."0.10.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".retain_mut."0.1.9" = overridableMkRustCrate (profileName: rec { - name = "retain_mut"; - version = "0.1.9"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4389f1d5789befaf6029ebd9f7dac4af7f7e3d61b69d4f30e2ac02b57e7712b0"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" = overridableMkRustCrate (profileName: rec { - name = "ring"; - version = "0.16.20"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "dev_urandom_fallback" ] - [ "once_cell" ] - [ "std" ] - ]; - dependencies = { - ${ if hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "linux" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "linux" || hostPlatform.parsed.kernel.name == "dragonfly" || hostPlatform.parsed.kernel.name == "freebsd" || hostPlatform.parsed.kernel.name == "illumos" || hostPlatform.parsed.kernel.name == "netbsd" || hostPlatform.parsed.kernel.name == "openbsd" || hostPlatform.parsed.kernel.name == "solaris" then "once_cell" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "i686" || hostPlatform.parsed.cpu.name == "x86_64" || (hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "armv6l" || hostPlatform.parsed.cpu.name == "armv7l") && (hostPlatform.parsed.kernel.name == "android" || hostPlatform.parsed.kernel.name == "fuchsia" || hostPlatform.parsed.kernel.name == "linux") then "spin" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".spin."0.5.2" { inherit profileName; }; - untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "wasm32" && hostPlatform.parsed.vendor.name == "unknown" && hostPlatform.parsed.kernel.name == "unknown" && hostPlatform.parsed.abi.name == "" then "web_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "windows" then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - buildDependencies = { - cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ron."0.7.1" = overridableMkRustCrate (profileName: rec { - name = "ron"; - version = "0.7.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a"; }; - dependencies = { - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "unknown".router."0.2.0" = overridableMkRustCrate (profileName: rec { - name = "router"; - version = "0.2.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/router"); - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/accounts_cache" || rootFeatures' ? "router/default") "accounts_cache") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "aws-config") - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "aws-sdk-kms") - (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/sandbox") "basilisk") - (lib.optional (rootFeatures' ? "router/default") "default") - (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox") "josekit") - (lib.optional (rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "kms") - (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/kv_store") "kv_store") - (lib.optional (rootFeatures' ? "router/mimalloc") "mimalloc") - (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/olap" || rootFeatures' ? "router/openapi") "olap") - (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/oltp" || rootFeatures' ? "router/openapi") "oltp") - (lib.optional (rootFeatures' ? "router/openapi") "openapi") - (lib.optional (rootFeatures' ? "router/production") "production") - (lib.optional (rootFeatures' ? "router/sandbox") "sandbox") - (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe") "stripe") - ]; - dependencies = { - actix = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix."0.13.0" { inherit profileName; }; - actix_cors = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-cors."0.6.4" { inherit profileName; }; - actix_rt = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" { inherit profileName; }; - actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; }; - api_models = rustPackages."unknown".api_models."0.1.0" { inherit profileName; }; - async_bb8_diesel = rustPackages."git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" { inherit profileName; }; - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_config" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-config."0.54.1" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_sdk_kms" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-sdk-kms."0.24.0" { inherit profileName; }; - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; }; - bb8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" { inherit profileName; }; - blake3 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".blake3."1.3.3" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - clap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".clap."4.1.4" { inherit profileName; }; - common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; }; - config = rustPackages."registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" { inherit profileName; }; - crc32fast = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crc32fast."1.3.2" { inherit profileName; }; - diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; }; - dyn_clone = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dyn-clone."1.0.10" { inherit profileName; }; - encoding_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" { inherit profileName; }; - error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; }; - frunk = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" { inherit profileName; }; - frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; }; - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "josekit" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".josekit."0.8.1" { inherit profileName; }; - jsonwebtoken = rustPackages."registry+https://github.com/rust-lang/crates.io-index".jsonwebtoken."8.2.0" { inherit profileName; }; - literally = rustPackages."registry+https://github.com/rust-lang/crates.io-index".literally."0.1.3" { inherit profileName; }; - masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; }; - maud = rustPackages."registry+https://github.com/rust-lang/crates.io-index".maud."0.24.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/mimalloc" then "mimalloc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mimalloc."0.1.34" { inherit profileName; }; - mime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" { inherit profileName; }; - nanoid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nanoid."0.4.0" { inherit profileName; }; - num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - redis_interface = rustPackages."unknown".redis_interface."0.1.0" { inherit profileName; }; - regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - reqwest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".reqwest."0.11.14" { inherit profileName; }; - ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; }; - router_derive = buildRustPackages."unknown".router_derive."0.1.0" { profileName = "__noProfile"; }; - router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_path_to_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" { inherit profileName; }; - ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "serde_qs" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.11.0" { inherit profileName; }; - serde_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" { inherit profileName; }; - signal_hook = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" { inherit profileName; }; - signal_hook_tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-tokio."0.3.1" { inherit profileName; }; - diesel_models = rustPackages."unknown".diesel_models."0.1.0" { inherit profileName; }; - strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; - utoipa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" { inherit profileName; }; - uuid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" { inherit profileName; }; - }; - devDependencies = { - actix_http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" { inherit profileName; }; - awc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".awc."3.1.0" { inherit profileName; }; - derive_deref = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".derive_deref."1.1.1" { profileName = "__noProfile"; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - serial_test = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serial_test."1.0.0" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - toml = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml."0.7.2" { inherit profileName; }; - wiremock = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wiremock."0.5.17" { inherit profileName; }; - }; - buildDependencies = { - router_env = buildRustPackages."unknown".router_env."0.1.0" { profileName = "__noProfile"; }; - }; - }); - "unknown".router_derive."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "router_derive"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/router_derive"); - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - devDependencies = { - diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; }; - }; - }); - "unknown".router_env."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "router_env"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/router_env"); - features = builtins.concatLists [ - [ "actix_web" ] - [ "default" ] - [ "log_custom_entries_to_extra" ] - [ "log_extra_implicit_fields" ] - [ "tracing-actix-web" ] - [ "vergen" ] - ]; - dependencies = { - config = rustPackages."registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" { inherit profileName; }; - gethostname = rustPackages."registry+https://github.com/rust-lang/crates.io-index".gethostname."0.4.1" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; }; - opentelemetry_otlp = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-otlp."0.11.0" { inherit profileName; }; - rustc_hash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc-hash."1.1.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - serde_path_to_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" { inherit profileName; }; - strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - tracing_actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-actix-web."0.7.2" { inherit profileName; }; - tracing_appender = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-appender."0.2.2" { inherit profileName; }; - tracing_attributes = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-attributes."0.1.22" { profileName = "__noProfile"; }; - tracing_opentelemetry = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-opentelemetry."0.18.0" { inherit profileName; }; - tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; }; - vergen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" { inherit profileName; }; - }; - devDependencies = { - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - buildDependencies = { - vergen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rust-ini."0.18.0" = overridableMkRustCrate (profileName: rec { - name = "rust-ini"; - version = "0.18.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - ordered_multimap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ordered-multimap."0.4.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rustc-hash."1.1.0" = overridableMkRustCrate (profileName: rec { - name = "rustc-hash"; - version = "1.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "rustc_version"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"; }; - dependencies = { - semver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" = overridableMkRustCrate (profileName: rec { - name = "rustls"; - version = "0.20.8"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f"; }; - features = builtins.concatLists [ - [ "dangerous_configuration" ] - [ "default" ] - [ "log" ] - [ "logging" ] - [ "tls12" ] - ]; - dependencies = { - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; }; - sct = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sct."0.7.0" { inherit profileName; }; - webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rustls-native-certs."0.6.2" = overridableMkRustCrate (profileName: rec { - name = "rustls-native-certs"; - version = "0.6.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0167bac7a9f490495f3c33013e7722b53cb087ecbe082fb0c6387c96f634ea50"; }; - dependencies = { - ${ if (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") && hostPlatform.isUnix && !(hostPlatform.parsed.kernel.name == "darwin") then "openssl_probe" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-probe."0.1.5" { inherit profileName; }; - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustls_pemfile" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls-pemfile."1.0.2" { inherit profileName; }; - ${ if (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") && hostPlatform.isWindows then "schannel" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".schannel."0.1.21" { inherit profileName; }; - ${ if (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") && hostPlatform.parsed.kernel.name == "darwin" then "security_framework" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rustls-pemfile."1.0.2" = overridableMkRustCrate (profileName: rec { - name = "rustls-pemfile"; - version = "1.0.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"; }; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "base64" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" = overridableMkRustCrate (profileName: rec { - name = "rustversion"; - version = "1.0.11"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5583e89e108996506031660fe09baa5011b9dd0341b89029313006d1fb508d70"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".rusty-fork."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "rusty-fork"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "cb3dcc6e454c328bb824492db107ab7c0ae8fcffe4ad210136ef014458c1bc4f"; }; - features = builtins.concatLists [ - [ "timeout" ] - [ "wait-timeout" ] - ]; - dependencies = { - fnv = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" { inherit profileName; }; - quick_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" { inherit profileName; }; - tempfile = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" { inherit profileName; }; - wait_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wait-timeout."0.2.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" = overridableMkRustCrate (profileName: rec { - name = "ryu"; - version = "1.0.12"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".schannel."0.1.21" = overridableMkRustCrate (profileName: rec { - name = "schannel"; - version = "0.1.21"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3"; }; - dependencies = { - windows_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".scheduled-thread-pool."0.2.6" = overridableMkRustCrate (profileName: rec { - name = "scheduled-thread-pool"; - version = "0.2.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "977a7519bff143a44f842fd07e80ad1329295bd71686457f18e496736f4bf9bf"; }; - dependencies = { - parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".scopeguard."1.1.0" = overridableMkRustCrate (profileName: rec { - name = "scopeguard"; - version = "1.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".sct."0.7.0" = overridableMkRustCrate (profileName: rec { - name = "sct"; - version = "0.7.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4"; }; - dependencies = { - ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; }; - untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" = overridableMkRustCrate (profileName: rec { - name = "security-framework"; - version = "2.7.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2bc1bb97804af6631813c55739f771071e0f2ed33ee20b68c86ec505d906356c"; }; - features = builtins.concatLists [ - [ "OSX_10_9" ] - [ "default" ] - ]; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - core_foundation = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation."0.9.3" { inherit profileName; }; - core_foundation_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" { inherit profileName; }; - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - security_framework_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" = overridableMkRustCrate (profileName: rec { - name = "security-framework-sys"; - version = "2.6.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556"; }; - features = builtins.concatLists [ - [ "OSX_10_9" ] - [ "default" ] - ]; - dependencies = { - core_foundation_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" { inherit profileName; }; - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" = overridableMkRustCrate (profileName: rec { - name = "semver"; - version = "1.0.16"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "58bc9567378fc7690d6b2addae4e60ac2eeea07becb2c64b9f218b53865cba2a"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" = overridableMkRustCrate (profileName: rec { - name = "serde"; - version = "1.0.152"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bb7d1f0d3021d347a83e556fc4683dea2ea09d87bccdf88ff5c12545d89d5efb"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "derive" ] - [ "serde_derive" ] - [ "std" ] - ]; - dependencies = { - serde_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_derive."1.0.152" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde_derive."1.0.152" = overridableMkRustCrate (profileName: rec { - name = "serde_derive"; - version = "1.0.152"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "af487d118eecd09402d70a5d72551860e788df87b464af30e5ea6a38c75c541e"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" = overridableMkRustCrate (profileName: rec { - name = "serde_json"; - version = "1.0.91"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883"; }; - features = builtins.concatLists [ - [ "default" ] - (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox") "indexmap") - (lib.optional (rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox") "preserve_order") - [ "std" ] - ]; - dependencies = { - ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "indexmap" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - ryu = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" = overridableMkRustCrate (profileName: rec { - name = "serde_path_to_error"; - version = "0.1.9"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "26b04f22b563c91331a10074bda3dd5492e3cc39d56bd557e91c0af42b6c7341"; }; - dependencies = { - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.8.5" = overridableMkRustCrate (profileName: rec { - name = "serde_qs"; - version = "0.8.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c7715380eec75f029a4ef7de39a9200e0a63823176b759d055b613f5a87df6a6"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.11.0" = overridableMkRustCrate (profileName: rec { - name = "serde_qs"; - version = "0.11.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c679fa27b429f2bb57fd4710257e643e86c966e716037259f8baa33de594a1b6"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe") "default") - ]; - dependencies = { - ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "percent_encoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "serde" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "thiserror" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde_spanned."0.6.1" = overridableMkRustCrate (profileName: rec { - name = "serde_spanned"; - version = "0.6.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0efd8caf556a6cebd3b285caf480045fcc1ac04f6bd786b09a6f11af30c4fcf4"; }; - features = builtins.concatLists [ - [ "serde" ] - ]; - dependencies = { - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" = overridableMkRustCrate (profileName: rec { - name = "serde_urlencoded"; - version = "0.7.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"; }; - dependencies = { - form_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" { inherit profileName; }; - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - ryu = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serial_test."1.0.0" = overridableMkRustCrate (profileName: rec { - name = "serial_test"; - version = "1.0.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "538c30747ae860d6fb88330addbbd3e0ddbe46d662d032855596d8a8ca260611"; }; - features = builtins.concatLists [ - [ "async" ] - [ "default" ] - [ "futures" ] - [ "log" ] - [ "logging" ] - ]; - dependencies = { - dashmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".dashmap."5.4.0" { inherit profileName; }; - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; }; - serial_test_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".serial_test_derive."1.0.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".serial_test_derive."1.0.0" = overridableMkRustCrate (profileName: rec { - name = "serial_test_derive"; - version = "1.0.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "079a83df15f85d89a68d64ae1238f142f172b1fa915d0d76b26a7cba1b659a69"; }; - features = builtins.concatLists [ - [ "async" ] - ]; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".sha-1."0.9.8" = overridableMkRustCrate (profileName: rec { - name = "sha-1"; - version = "0.9.8"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "99cd6713db3cf16b6c84e06321e049a9b9f699826e16096d23bbcc44d15d51a6"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - block_buffer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.9.0" { inherit profileName; }; - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "i686" || hostPlatform.parsed.cpu.name == "x86_64" then "cpufeatures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" { inherit profileName; }; - digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.9.0" { inherit profileName; }; - opaque_debug = rustPackages."registry+https://github.com/rust-lang/crates.io-index".opaque-debug."0.3.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".sha1."0.10.5" = overridableMkRustCrate (profileName: rec { - name = "sha1"; - version = "0.10.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "i686" || hostPlatform.parsed.cpu.name == "x86_64" then "cpufeatures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" { inherit profileName; }; - digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" = overridableMkRustCrate (profileName: rec { - name = "sha2"; - version = "0.10.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std") - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - ${ if hostPlatform.parsed.cpu.name == "aarch64" || hostPlatform.parsed.cpu.name == "x86_64" || hostPlatform.parsed.cpu.name == "i686" then "cpufeatures" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" { inherit profileName; }; - digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".sharded-slab."0.1.4" = overridableMkRustCrate (profileName: rec { - name = "sharded-slab"; - version = "0.1.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31"; }; - dependencies = { - lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" = overridableMkRustCrate (profileName: rec { - name = "signal-hook"; - version = "0.3.14"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a253b5e89e2698464fc26b545c9edceb338e18a89effeeecfea192c3025be29d"; }; - features = builtins.concatLists [ - [ "channel" ] - [ "default" ] - [ "iterator" ] - ]; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - signal_hook_registry = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" = overridableMkRustCrate (profileName: rec { - name = "signal-hook-registry"; - version = "1.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"; }; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".signal-hook-tokio."0.3.1" = overridableMkRustCrate (profileName: rec { - name = "signal-hook-tokio"; - version = "0.3.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "213241f76fb1e37e27de3b6aa1b068a2c333233b59cca6634f634b80a27ecf1e"; }; - features = builtins.concatLists [ - [ "futures-core-0_3" ] - [ "futures-v0_3" ] - ]; - dependencies = { - futures_core_0_3 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - signal_hook = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".simd-abstraction."0.7.1" = overridableMkRustCrate (profileName: rec { - name = "simd-abstraction"; - version = "0.7.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9cadb29c57caadc51ff8346233b5cec1d240b68ce55cf1afc764818791876987"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "alloc") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "detect") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std") - ]; - dependencies = { - ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "outref" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".outref."0.1.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".simple_asn1."0.6.2" = overridableMkRustCrate (profileName: rec { - name = "simple_asn1"; - version = "0.6.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "adc4e5204eb1910f40f9cfa375f6f05b68c3abac4b6fd879c8ff5e7ae8a0a085"; }; - dependencies = { - num_bigint = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-bigint."0.4.3" { inherit profileName; }; - num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" = overridableMkRustCrate (profileName: rec { - name = "slab"; - version = "0.4.7"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" = overridableMkRustCrate (profileName: rec { - name = "smallvec"; - version = "1.10.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" = overridableMkRustCrate (profileName: rec { - name = "socket2"; - version = "0.4.7"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd"; }; - features = builtins.concatLists [ - [ "all" ] - ]; - dependencies = { - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".spin."0.5.2" = overridableMkRustCrate (profileName: rec { - name = "spin"; - version = "0.5.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"; }; - }); - "unknown".diesel_models."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "diesel_models"; - version = "0.1.0"; - registry = "unknown"; - src = fetchCrateLocal (workspaceSrc + "/crates/diesel_models"); - features = builtins.concatLists [ - [ "default" ] - [ "kv_store" ] - ]; - dependencies = { - async_bb8_diesel = rustPackages."git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" { inherit profileName; }; - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - common_utils = rustPackages."unknown".common_utils."0.1.0" { inherit profileName; }; - diesel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" { inherit profileName; }; - error_stack = rustPackages."registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" { inherit profileName; }; - frunk = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" { inherit profileName; }; - frunk_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" { inherit profileName; }; - hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; }; - masking = rustPackages."unknown".masking."0.1.0" { inherit profileName; }; - router_derive = buildRustPackages."unknown".router_derive."0.1.0" { profileName = "__noProfile"; }; - router_env = rustPackages."unknown".router_env."0.1.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; }; - thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" = overridableMkRustCrate (profileName: rec { - name = "strum"; - version = "0.24.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f"; }; - features = builtins.concatLists [ - [ "default" ] - [ "derive" ] - [ "std" ] - [ "strum_macros" ] - ]; - dependencies = { - strum_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".strum_macros."0.24.3" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".strum_macros."0.24.3" = overridableMkRustCrate (profileName: rec { - name = "strum_macros"; - version = "0.24.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59"; }; - dependencies = { - heck = rustPackages."registry+https://github.com/rust-lang/crates.io-index".heck."0.4.0" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" = overridableMkRustCrate (profileName: rec { - name = "subtle"; - version = "2.4.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601"; }; - features = builtins.concatLists [ - [ "default" ] - [ "i128" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".supports-color."1.3.1" = overridableMkRustCrate (profileName: rec { - name = "supports-color"; - version = "1.3.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8ba6faf2ca7ee42fdd458f4347ae0a9bd6bcc445ad7cb57ad82b383f18870d6f"; }; - dependencies = { - atty = rustPackages."registry+https://github.com/rust-lang/crates.io-index".atty."0.2.14" { inherit profileName; }; - is_ci = rustPackages."registry+https://github.com/rust-lang/crates.io-index".is_ci."1.1.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" = overridableMkRustCrate (profileName: rec { - name = "syn"; - version = "1.0.107"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5"; }; - features = builtins.concatLists [ - [ "clone-impls" ] - [ "default" ] - [ "derive" ] - [ "extra-traits" ] - [ "fold" ] - [ "full" ] - [ "parsing" ] - [ "printing" ] - [ "proc-macro" ] - [ "quote" ] - [ "visit" ] - [ "visit-mut" ] - ]; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - unicode_ident = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".sync_wrapper."0.1.1" = overridableMkRustCrate (profileName: rec { - name = "sync_wrapper"; - version = "0.1.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "20518fe4a4c9acf048008599e464deb21beeae3d3578418951a189c235a7a9a8"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" = overridableMkRustCrate (profileName: rec { - name = "tempfile"; - version = "3.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4"; }; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - fastrand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" { inherit profileName; }; - ${ if hostPlatform.isUnix || hostPlatform.parsed.kernel.name == "wasi" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - ${ if hostPlatform.parsed.kernel.name == "redox" then "syscall" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" { inherit profileName; }; - remove_dir_all = rustPackages."registry+https://github.com/rust-lang/crates.io-index".remove_dir_all."0.5.3" { inherit profileName; }; - ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".termcolor."1.2.0" = overridableMkRustCrate (profileName: rec { - name = "termcolor"; - version = "1.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"; }; - dependencies = { - ${ if hostPlatform.isWindows then "winapi_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-util."0.1.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" = overridableMkRustCrate (profileName: rec { - name = "thiserror"; - version = "1.0.38"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0"; }; - dependencies = { - thiserror_impl = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror-impl."1.0.38" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".thiserror-impl."1.0.38" = overridableMkRustCrate (profileName: rec { - name = "thiserror-impl"; - version = "1.0.38"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".thread_local."1.1.4" = overridableMkRustCrate (profileName: rec { - name = "thread_local"; - version = "1.1.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180"; }; - dependencies = { - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" = overridableMkRustCrate (profileName: rec { - name = "time"; - version = "0.3.17"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "formatting" ] - [ "macros" ] - [ "parsing" ] - [ "serde" ] - [ "serde-well-known" ] - [ "std" ] - ]; - dependencies = { - itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - time_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" { inherit profileName; }; - time_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".time-macros."0.2.6" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "time-core"; - version = "0.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".time-macros."0.2.6" = overridableMkRustCrate (profileName: rec { - name = "time-macros"; - version = "0.2.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2"; }; - features = builtins.concatLists [ - [ "formatting" ] - [ "parsing" ] - [ "serde" ] - ]; - dependencies = { - time_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tinyvec."1.6.0" = overridableMkRustCrate (profileName: rec { - name = "tinyvec"; - version = "1.6.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "default" ] - [ "tinyvec_macros" ] - ]; - dependencies = { - tinyvec_macros = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tinyvec_macros."0.1.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tinyvec_macros."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "tinyvec_macros"; - version = "0.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" = overridableMkRustCrate (profileName: rec { - name = "tokio"; - version = "1.25.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c8e00990ebabbe4c14c08aca901caed183ecd5c09562a12c824bb53d3c3fd3af"; }; - features = builtins.concatLists [ - [ "bytes" ] - [ "default" ] - (lib.optional (rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "fs") - [ "io-std" ] - [ "io-util" ] - [ "libc" ] - [ "macros" ] - [ "memchr" ] - [ "mio" ] - [ "net" ] - [ "num_cpus" ] - [ "parking_lot" ] - [ "rt" ] - [ "rt-multi-thread" ] - [ "signal" ] - [ "signal-hook-registry" ] - [ "socket2" ] - [ "sync" ] - [ "time" ] - [ "tokio-macros" ] - [ "windows-sys" ] - ]; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; - mio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".mio."0.8.5" { inherit profileName; }; - num_cpus = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" { inherit profileName; }; - parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - ${ if hostPlatform.isUnix then "signal_hook_registry" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" { inherit profileName; }; - ${ if !(hostPlatform.parsed.cpu.name == "wasm32" || hostPlatform.parsed.cpu.name == "wasm64") then "socket2" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" { inherit profileName; }; - tokio_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-macros."1.8.2" { profileName = "__noProfile"; }; - ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; }; - }; - buildDependencies = { - autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-io-timeout."1.2.0" = overridableMkRustCrate (profileName: rec { - name = "tokio-io-timeout"; - version = "1.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "30b74022ada614a1b4834de765f9bb43877f910cc8ce4be40e89042c9223a8bf"; }; - dependencies = { - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-macros."1.8.2" = overridableMkRustCrate (profileName: rec { - name = "tokio-macros"; - version = "1.8.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "tokio-native-tls"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b"; }; - dependencies = { - native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" = overridableMkRustCrate (profileName: rec { - name = "tokio-rustls"; - version = "0.23.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59"; }; - features = builtins.concatLists [ - [ "default" ] - [ "logging" ] - [ "tls12" ] - ]; - dependencies = { - rustls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" = overridableMkRustCrate (profileName: rec { - name = "tokio-stream"; - version = "0.1.11"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "d660770404473ccd7bc9f8b28494a811bc18542b915c0855c51e8f419d5223ce"; }; - features = builtins.concatLists [ - [ "default" ] - [ "time" ] - ]; - dependencies = { - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.6.10" = overridableMkRustCrate (profileName: rec { - name = "tokio-util"; - version = "0.6.10"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507"; }; - features = builtins.concatLists [ - [ "codec" ] - [ "default" ] - ]; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" = overridableMkRustCrate (profileName: rec { - name = "tokio-util"; - version = "0.7.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740"; }; - features = builtins.concatLists [ - [ "codec" ] - [ "default" ] - [ "io" ] - [ "tracing" ] - ]; - dependencies = { - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".toml."0.5.11" = overridableMkRustCrate (profileName: rec { - name = "toml"; - version = "0.5.11"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"; }; - features = builtins.concatLists [ - [ "default" ] - ]; - dependencies = { - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".toml."0.7.2" = overridableMkRustCrate (profileName: rec { - name = "toml"; - version = "0.7.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f7afcae9e3f0fe2c370fd4657108972cbb2fa9db1b9f84849cefd80741b01cb6"; }; - features = builtins.concatLists [ - [ "default" ] - [ "display" ] - [ "parse" ] - ]; - dependencies = { - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_spanned = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_spanned."0.6.1" { inherit profileName; }; - toml_datetime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" { inherit profileName; }; - toml_edit = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_edit."0.19.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" = overridableMkRustCrate (profileName: rec { - name = "toml_datetime"; - version = "0.6.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3ab8ed2edee10b50132aed5f331333428b011c99402b5a534154ed15746f9622"; }; - features = builtins.concatLists [ - [ "serde" ] - ]; - dependencies = { - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".toml_edit."0.19.3" = overridableMkRustCrate (profileName: rec { - name = "toml_edit"; - version = "0.19.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5e6a7712b49e1775fb9a7b998de6635b299237f48b404dde71704f2e0e7f37e5"; }; - features = builtins.concatLists [ - [ "default" ] - [ "serde" ] - ]; - dependencies = { - indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; }; - nom8 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nom8."0.2.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_spanned = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_spanned."0.6.1" { inherit profileName; }; - toml_datetime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" = overridableMkRustCrate (profileName: rec { - name = "tonic"; - version = "0.8.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8f219fad3b929bef19b1f86fbc0358d35daed8f2cac972037ac0dc10bbb8d5fb"; }; - features = builtins.concatLists [ - [ "async-trait" ] - [ "axum" ] - [ "channel" ] - [ "codegen" ] - [ "default" ] - [ "h2" ] - [ "hyper" ] - [ "hyper-timeout" ] - [ "prost" ] - [ "prost-derive" ] - [ "prost1" ] - [ "tokio" ] - [ "tower" ] - [ "tracing-futures" ] - [ "transport" ] - ]; - dependencies = { - async_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".async-stream."0.3.3" { inherit profileName; }; - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - axum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".axum."0.6.2" { inherit profileName; }; - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - h2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - hyper_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper-timeout."0.4.1" { inherit profileName; }; - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; }; - prost1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" { inherit profileName; }; - prost_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" { profileName = "__noProfile"; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - tower = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; }; - tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - tracing_futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" = overridableMkRustCrate (profileName: rec { - name = "tower"; - version = "0.4.13"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"; }; - features = builtins.concatLists [ - [ "__common" ] - [ "balance" ] - [ "buffer" ] - [ "default" ] - [ "discover" ] - [ "futures-core" ] - [ "futures-util" ] - [ "indexmap" ] - [ "limit" ] - [ "load" ] - [ "log" ] - [ "make" ] - [ "pin-project" ] - [ "pin-project-lite" ] - [ "rand" ] - [ "ready-cache" ] - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "retry") - [ "slab" ] - [ "timeout" ] - [ "tokio" ] - [ "tokio-util" ] - [ "tracing" ] - [ "util" ] - ]; - dependencies = { - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; }; - pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; - slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; - tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; }; - tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tower-http."0.3.5" = overridableMkRustCrate (profileName: rec { - name = "tower-http"; - version = "0.3.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f873044bf02dd1e8239e9c1293ea39dad76dc594ec16185d0a1bf31d8dc8d858"; }; - features = builtins.concatLists [ - [ "default" ] - [ "map-response-body" ] - [ "tower" ] - [ "util" ] - ]; - dependencies = { - bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; - bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; - futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; - futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; - http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" { inherit profileName; }; - http_body = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" { inherit profileName; }; - http_range_header = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-range-header."0.3.0" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tower = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; - tower_layer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" { inherit profileName; }; - tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" = overridableMkRustCrate (profileName: rec { - name = "tower-layer"; - version = "0.3.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" = overridableMkRustCrate (profileName: rec { - name = "tower-service"; - version = "0.3.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" = overridableMkRustCrate (profileName: rec { - name = "tracing"; - version = "0.1.36"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "2fce9567bd60a67d08a16488756721ba392f24f29006402881e43b19aac64307"; }; - features = builtins.concatLists [ - [ "attributes" ] - [ "default" ] - [ "log" ] - [ "std" ] - [ "tracing-attributes" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; - tracing_attributes = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-attributes."0.1.22" { profileName = "__noProfile"; }; - tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-actix-web."0.7.2" = overridableMkRustCrate (profileName: rec { - name = "tracing-actix-web"; - version = "0.7.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4082e4d81173e0b7ad3cfb71e9eaef0dd0cbb7b139fdb56394f488a3b0760b23"; }; - features = builtins.concatLists [ - [ "default" ] - [ "emit_event_on_error" ] - [ "opentelemetry_0_18" ] - [ "opentelemetry_0_18_pkg" ] - [ "tracing-opentelemetry_0_18_pkg" ] - ]; - dependencies = { - actix_web = rustPackages."registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" { inherit profileName; }; - opentelemetry_0_18_pkg = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; }; - pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - tracing_opentelemetry_0_18_pkg = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-opentelemetry."0.18.0" { inherit profileName; }; - uuid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-appender."0.2.2" = overridableMkRustCrate (profileName: rec { - name = "tracing-appender"; - version = "0.2.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e"; }; - dependencies = { - crossbeam_channel = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-attributes."0.1.22" = overridableMkRustCrate (profileName: rec { - name = "tracing-attributes"; - version = "0.1.22"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "11c75893af559bc8e10716548bdef5cb2b983f8e637db9d0e15126b61b484ee2"; }; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" = overridableMkRustCrate (profileName: rec { - name = "tracing-core"; - version = "0.1.30"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a"; }; - features = builtins.concatLists [ - [ "default" ] - [ "once_cell" ] - [ "std" ] - [ "valuable" ] - ]; - dependencies = { - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - ${ if false then "valuable" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".valuable."0.1.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" = overridableMkRustCrate (profileName: rec { - name = "tracing-futures"; - version = "0.2.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2"; }; - features = builtins.concatLists [ - [ "default" ] - [ "pin-project" ] - [ "std" ] - [ "std-future" ] - ]; - dependencies = { - pin_project = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-log."0.1.3" = overridableMkRustCrate (profileName: rec { - name = "tracing-log"; - version = "0.1.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922"; }; - features = builtins.concatLists [ - [ "log-tracer" ] - [ "std" ] - ]; - dependencies = { - lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-opentelemetry."0.18.0" = overridableMkRustCrate (profileName: rec { - name = "tracing-opentelemetry"; - version = "0.18.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "21ebb87a95ea13271332df069020513ab70bdb5637ca42d6e492dc3bbbad48de"; }; - features = builtins.concatLists [ - [ "default" ] - [ "metrics" ] - [ "tracing-log" ] - ]; - dependencies = { - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - opentelemetry = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; - tracing_log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-log."0.1.3" { inherit profileName; }; - tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-serde."0.1.3" = overridableMkRustCrate (profileName: rec { - name = "tracing-serde"; - version = "0.1.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bc6b213177105856957181934e4920de57730fc69bf42c37ee5bb664d406d9e1"; }; - dependencies = { - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" = overridableMkRustCrate (profileName: rec { - name = "tracing-subscriber"; - version = "0.3.16"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a6176eae26dd70d0c919749377897b54a9276bd7061339665dd68777926b5a70"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "ansi" ] - [ "default" ] - [ "env-filter" ] - [ "fmt" ] - [ "json" ] - [ "matchers" ] - [ "nu-ansi-term" ] - [ "once_cell" ] - [ "regex" ] - [ "registry" ] - [ "serde" ] - [ "serde_json" ] - [ "sharded-slab" ] - [ "smallvec" ] - [ "std" ] - [ "thread_local" ] - [ "tracing" ] - [ "tracing-log" ] - [ "tracing-serde" ] - ]; - dependencies = { - matchers = rustPackages."registry+https://github.com/rust-lang/crates.io-index".matchers."0.1.0" { inherit profileName; }; - nu_ansi_term = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nu-ansi-term."0.46.0" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - sharded_slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".sharded-slab."0.1.4" { inherit profileName; }; - smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; - thread_local = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thread_local."1.1.4" { inherit profileName; }; - tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; - tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; - tracing_log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-log."0.1.3" { inherit profileName; }; - tracing_serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-serde."0.1.3" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".try-lock."0.2.4" = overridableMkRustCrate (profileName: rec { - name = "try-lock"; - version = "0.2.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" = overridableMkRustCrate (profileName: rec { - name = "typenum"; - version = "1.16.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".ucd-trie."0.1.5" = overridableMkRustCrate (profileName: rec { - name = "ucd-trie"; - version = "0.1.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81"; }; - features = builtins.concatLists [ - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".unarray."0.1.4" = overridableMkRustCrate (profileName: rec { - name = "unarray"; - version = "0.1.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".unicode-bidi."0.3.8" = overridableMkRustCrate (profileName: rec { - name = "unicode-bidi"; - version = "0.3.8"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992"; }; - features = builtins.concatLists [ - [ "default" ] - [ "hardcoded-data" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" = overridableMkRustCrate (profileName: rec { - name = "unicode-ident"; - version = "1.0.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".unicode-normalization."0.1.22" = overridableMkRustCrate (profileName: rec { - name = "unicode-normalization"; - version = "0.1.22"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - dependencies = { - tinyvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tinyvec."1.6.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" = overridableMkRustCrate (profileName: rec { - name = "untrusted"; - version = "0.7.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" = overridableMkRustCrate (profileName: rec { - name = "url"; - version = "2.3.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643"; }; - features = builtins.concatLists [ - [ "default" ] - [ "serde" ] - ]; - dependencies = { - form_urlencoded = rustPackages."registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" { inherit profileName; }; - idna = rustPackages."registry+https://github.com/rust-lang/crates.io-index".idna."0.3.0" { inherit profileName; }; - percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".urlencoding."2.1.2" = overridableMkRustCrate (profileName: rec { - name = "urlencoding"; - version = "2.1.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" = overridableMkRustCrate (profileName: rec { - name = "utoipa"; - version = "3.0.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "3920fa753064b1be7842bea26175ffa0dfc4a8f30bcb52b8ff03fddf8889914c"; }; - features = builtins.concatLists [ - [ "default" ] - [ "preserve_order" ] - [ "time" ] - ]; - dependencies = { - indexmap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - utoipa_gen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa-gen."3.0.1" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".utoipa-gen."3.0.1" = overridableMkRustCrate (profileName: rec { - name = "utoipa-gen"; - version = "3.0.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "720298fac6efca20df9e457e67a1eab41a20d1c3101380b5c4dca1ca60ae0062"; }; - features = builtins.concatLists [ - [ "time" ] - ]; - dependencies = { - proc_macro_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" = overridableMkRustCrate (profileName: rec { - name = "uuid"; - version = "1.2.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "422ee0de9031b5b948b97a8fc04e3aa35230001a722ddd27943e0be31564ce4c"; }; - features = builtins.concatLists [ - [ "default" ] - [ "getrandom" ] - [ "rng" ] - [ "serde" ] - [ "std" ] - [ "v4" ] - ]; - dependencies = { - getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".valuable."0.1.0" = overridableMkRustCrate (profileName: rec { - name = "valuable"; - version = "0.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" = overridableMkRustCrate (profileName: rec { - name = "vcpkg"; - version = "0.2.15"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" = overridableMkRustCrate (profileName: rec { - name = "vergen"; - version = "8.0.0-beta.3"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "7ddc80f045ae4afcbb388b085240e773f6728dfbbacff007dd91fc9e2f686fc7"; }; - features = builtins.concatLists [ - [ "cargo" ] - [ "default" ] - [ "git" ] - [ "git2" ] - [ "git2-rs" ] - [ "rustc" ] - [ "rustc_version" ] - [ "time" ] - ]; - dependencies = { - anyhow = rustPackages."registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" { inherit profileName; }; - git2_rs = rustPackages."registry+https://github.com/rust-lang/crates.io-index".git2."0.16.1" { inherit profileName; }; - rustc_version = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { inherit profileName; }; - time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; - }; - buildDependencies = { - rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" = overridableMkRustCrate (profileName: rec { - name = "version_check"; - version = "0.9.4"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wait-timeout."0.2.0" = overridableMkRustCrate (profileName: rec { - name = "wait-timeout"; - version = "0.2.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6"; }; - dependencies = { - ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".waker-fn."1.1.0" = overridableMkRustCrate (profileName: rec { - name = "waker-fn"; - version = "1.1.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".want."0.3.0" = overridableMkRustCrate (profileName: rec { - name = "want"; - version = "0.3.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0"; }; - dependencies = { - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - try_lock = rustPackages."registry+https://github.com/rust-lang/crates.io-index".try-lock."0.2.4" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasi."0.9.0+wasi-snapshot-preview1" = overridableMkRustCrate (profileName: rec { - name = "wasi"; - version = "0.9.0+wasi-snapshot-preview1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" = overridableMkRustCrate (profileName: rec { - name = "wasi"; - version = "0.11.0+wasi-snapshot-preview1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"; }; - features = builtins.concatLists [ - [ "default" ] - [ "std" ] - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" = overridableMkRustCrate (profileName: rec { - name = "wasm-bindgen"; - version = "0.2.83"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268"; }; - features = builtins.concatLists [ - [ "default" ] - [ "spans" ] - [ "std" ] - ]; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - wasm_bindgen_macro = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro."0.2.83" { profileName = "__noProfile"; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-backend."0.2.83" = overridableMkRustCrate (profileName: rec { - name = "wasm-bindgen-backend"; - version = "0.2.83"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142"; }; - features = builtins.concatLists [ - [ "spans" ] - ]; - dependencies = { - bumpalo = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bumpalo."3.12.0" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - wasm_bindgen_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-futures."0.4.33" = overridableMkRustCrate (profileName: rec { - name = "wasm-bindgen-futures"; - version = "0.4.33"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "23639446165ca5a5de86ae1d8896b737ae80319560fbaa4c2887b7da6e7ebd7d"; }; - dependencies = { - cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; - js_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; }; - wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; }; - ${ if builtins.elem "atomics" hostPlatformFeatures then "web_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro."0.2.83" = overridableMkRustCrate (profileName: rec { - name = "wasm-bindgen-macro"; - version = "0.2.83"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810"; }; - features = builtins.concatLists [ - [ "spans" ] - ]; - dependencies = { - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - wasm_bindgen_macro_support = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro-support."0.2.83" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro-support."0.2.83" = overridableMkRustCrate (profileName: rec { - name = "wasm-bindgen-macro-support"; - version = "0.2.83"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c"; }; - features = builtins.concatLists [ - [ "spans" ] - ]; - dependencies = { - proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; - quote = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" { inherit profileName; }; - syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; - wasm_bindgen_backend = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-backend."0.2.83" { inherit profileName; }; - wasm_bindgen_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" = overridableMkRustCrate (profileName: rec { - name = "wasm-bindgen-shared"; - version = "0.2.83"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" = overridableMkRustCrate (profileName: rec { - name = "web-sys"; - version = "0.3.60"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f"; }; - features = builtins.concatLists [ - [ "Blob" ] - [ "BlobPropertyBag" ] - [ "Crypto" ] - [ "Event" ] - [ "EventTarget" ] - [ "File" ] - [ "FormData" ] - [ "Headers" ] - [ "MessageEvent" ] - [ "ReadableStream" ] - [ "Request" ] - [ "RequestCredentials" ] - [ "RequestInit" ] - [ "RequestMode" ] - [ "Response" ] - [ "ServiceWorkerGlobalScope" ] - [ "Window" ] - [ "Worker" ] - [ "WorkerGlobalScope" ] - ]; - dependencies = { - js_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" { inherit profileName; }; - wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" = overridableMkRustCrate (profileName: rec { - name = "webpki"; - version = "0.22.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"; }; - features = builtins.concatLists [ - [ "alloc" ] - [ "std" ] - ]; - dependencies = { - ring = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" { inherit profileName; }; - untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".webpki-roots."0.22.6" = overridableMkRustCrate (profileName: rec { - name = "webpki-roots"; - version = "0.22.6"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "b6c71e40d7d2c34a5106301fb632274ca37242cd0c9d3e64dbece371a40a2d87"; }; - dependencies = { - webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" = overridableMkRustCrate (profileName: rec { - name = "winapi"; - version = "0.3.9"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"; }; - features = builtins.concatLists [ - [ "consoleapi" ] - [ "errhandlingapi" ] - [ "fileapi" ] - [ "handleapi" ] - [ "impl-debug" ] - [ "impl-default" ] - [ "minwinbase" ] - [ "minwindef" ] - [ "ntsecapi" ] - [ "ntstatus" ] - [ "processenv" ] - [ "std" ] - [ "timezoneapi" ] - [ "winbase" ] - [ "wincon" ] - [ "winerror" ] - [ "winnt" ] - [ "winreg" ] - [ "ws2ipdef" ] - [ "ws2tcpip" ] - [ "wtypesbase" ] - ]; - dependencies = { - ${ if hostPlatform.config == "i686-pc-windows-gnu" then "winapi_i686_pc_windows_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-i686-pc-windows-gnu."0.4.0" { inherit profileName; }; - ${ if hostPlatform.config == "x86_64-pc-windows-gnu" then "winapi_x86_64_pc_windows_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-x86_64-pc-windows-gnu."0.4.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".winapi-i686-pc-windows-gnu."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "winapi-i686-pc-windows-gnu"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".winapi-util."0.1.5" = overridableMkRustCrate (profileName: rec { - name = "winapi-util"; - version = "0.1.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"; }; - dependencies = { - ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".winapi-x86_64-pc-windows-gnu."0.4.0" = overridableMkRustCrate (profileName: rec { - name = "winapi-x86_64-pc-windows-gnu"; - version = "0.4.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows."0.43.0" = overridableMkRustCrate (profileName: rec { - name = "windows"; - version = "0.43.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244"; }; - features = builtins.concatLists [ - [ "Win32" ] - [ "Win32_Foundation" ] - [ "Win32_System" ] - [ "Win32_System_SystemInformation" ] - [ "default" ] - ]; - dependencies = { - ${ if hostPlatform.config == "aarch64-pc-windows-gnullvm" then "windows_aarch64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_gnullvm."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "aarch64-pc-windows-msvc" || hostPlatform.config == "aarch64-uwp-windows-msvc" then "windows_aarch64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_msvc."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "i686-pc-windows-gnu" || hostPlatform.config == "i686-uwp-windows-gnu" then "windows_i686_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_gnu."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "i686-pc-windows-msvc" || hostPlatform.config == "i686-uwp-windows-msvc" then "windows_i686_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_msvc."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "x86_64-pc-windows-gnu" || hostPlatform.config == "x86_64-uwp-windows-gnu" then "windows_x86_64_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnu."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "x86_64-pc-windows-gnullvm" then "windows_x86_64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnullvm."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "x86_64-pc-windows-msvc" || hostPlatform.config == "x86_64-uwp-windows-msvc" then "windows_x86_64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" = overridableMkRustCrate (profileName: rec { - name = "windows-sys"; - version = "0.42.0"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"; }; - features = builtins.concatLists [ - [ "Win32" ] - [ "Win32_Foundation" ] - [ "Win32_Networking" ] - [ "Win32_Networking_WinSock" ] - [ "Win32_Security" ] - [ "Win32_Security_Authentication" ] - [ "Win32_Security_Authentication_Identity" ] - [ "Win32_Security_Authorization" ] - [ "Win32_Security_Credentials" ] - [ "Win32_Security_Cryptography" ] - [ "Win32_Storage" ] - [ "Win32_Storage_FileSystem" ] - [ "Win32_System" ] - [ "Win32_System_Console" ] - [ "Win32_System_IO" ] - [ "Win32_System_LibraryLoader" ] - [ "Win32_System_Memory" ] - [ "Win32_System_Pipes" ] - [ "Win32_System_SystemServices" ] - [ "Win32_System_WindowsProgramming" ] - [ "default" ] - ]; - dependencies = { - ${ if hostPlatform.config == "aarch64-pc-windows-gnullvm" then "windows_aarch64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_gnullvm."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "aarch64-pc-windows-msvc" || hostPlatform.config == "aarch64-uwp-windows-msvc" then "windows_aarch64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_msvc."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "i686-pc-windows-gnu" || hostPlatform.config == "i686-uwp-windows-gnu" then "windows_i686_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_gnu."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "i686-pc-windows-msvc" || hostPlatform.config == "i686-uwp-windows-msvc" then "windows_i686_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_i686_msvc."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "x86_64-pc-windows-gnu" || hostPlatform.config == "x86_64-uwp-windows-gnu" then "windows_x86_64_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnu."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "x86_64-pc-windows-gnullvm" then "windows_x86_64_gnullvm" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnullvm."0.42.1" { inherit profileName; }; - ${ if hostPlatform.config == "x86_64-pc-windows-msvc" || hostPlatform.config == "x86_64-uwp-windows-msvc" then "windows_x86_64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_gnullvm."0.42.1" = overridableMkRustCrate (profileName: rec { - name = "windows_aarch64_gnullvm"; - version = "0.42.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_msvc."0.42.1" = overridableMkRustCrate (profileName: rec { - name = "windows_aarch64_msvc"; - version = "0.42.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows_i686_gnu."0.42.1" = overridableMkRustCrate (profileName: rec { - name = "windows_i686_gnu"; - version = "0.42.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows_i686_msvc."0.42.1" = overridableMkRustCrate (profileName: rec { - name = "windows_i686_msvc"; - version = "0.42.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnu."0.42.1" = overridableMkRustCrate (profileName: rec { - name = "windows_x86_64_gnu"; - version = "0.42.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnullvm."0.42.1" = overridableMkRustCrate (profileName: rec { - name = "windows_x86_64_gnullvm"; - version = "0.42.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" = overridableMkRustCrate (profileName: rec { - name = "windows_x86_64_msvc"; - version = "0.42.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"; }; - }); - "registry+https://github.com/rust-lang/crates.io-index".winreg."0.10.1" = overridableMkRustCrate (profileName: rec { - name = "winreg"; - version = "0.10.1"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"; }; - dependencies = { - winapi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".wiremock."0.5.17" = overridableMkRustCrate (profileName: rec { - name = "wiremock"; - version = "0.5.17"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "12316b50eb725e22b2f6b9c4cbede5b7b89984274d113a7440c86e5c3fc6f99b"; }; - dependencies = { - assert_json_diff = rustPackages."registry+https://github.com/rust-lang/crates.io-index".assert-json-diff."2.0.2" { inherit profileName; }; - async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" { profileName = "__noProfile"; }; - base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; - deadpool = rustPackages."registry+https://github.com/rust-lang/crates.io-index".deadpool."0.9.5" { inherit profileName; }; - futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" { inherit profileName; }; - futures_timer = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-timer."3.0.2" { inherit profileName; }; - http_types = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-types."2.12.0" { inherit profileName; }; - hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" { inherit profileName; }; - log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; - once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; - regex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" { inherit profileName; }; - serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; - serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; - tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".xmlparser."0.13.5" = overridableMkRustCrate (profileName: rec { - name = "xmlparser"; - version = "0.13.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "4d25c75bf9ea12c4040a97f829154768bbbce366287e2dc044af160cd79a13fd"; }; - features = builtins.concatLists [ - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std") - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".yaml-rust."0.4.5" = overridableMkRustCrate (profileName: rec { - name = "yaml-rust"; - version = "0.4.5"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"; }; - dependencies = { - linked_hash_map = rustPackages."registry+https://github.com/rust-lang/crates.io-index".linked-hash-map."0.5.6" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" = overridableMkRustCrate (profileName: rec { - name = "zeroize"; - version = "1.5.7"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f"; }; - features = builtins.concatLists [ - [ "alloc" ] - (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") - ]; - }); - "registry+https://github.com/rust-lang/crates.io-index".zstd."0.12.2+zstd.1.5.2" = overridableMkRustCrate (profileName: rec { - name = "zstd"; - version = "0.12.2+zstd.1.5.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "e9262a83dc741c0b0ffec209881b45dbc232c21b02a2b9cb1adb93266e41303d"; }; - features = builtins.concatLists [ - [ "arrays" ] - [ "default" ] - [ "legacy" ] - [ "zdict_builder" ] - ]; - dependencies = { - zstd_safe = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd-safe."6.0.2+zstd.1.5.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".zstd-safe."6.0.2+zstd.1.5.2" = overridableMkRustCrate (profileName: rec { - name = "zstd-safe"; - version = "6.0.2+zstd.1.5.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "a6cf39f730b440bab43da8fb5faf5f254574462f73f260f85f7987f32154ff17"; }; - features = builtins.concatLists [ - [ "arrays" ] - [ "legacy" ] - [ "std" ] - [ "zdict_builder" ] - ]; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - zstd_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd-sys."2.0.5+zstd.1.5.2" { inherit profileName; }; - }; - }); - "registry+https://github.com/rust-lang/crates.io-index".zstd-sys."2.0.5+zstd.1.5.2" = overridableMkRustCrate (profileName: rec { - name = "zstd-sys"; - version = "2.0.5+zstd.1.5.2"; - registry = "registry+https://github.com/rust-lang/crates.io-index"; - src = fetchCratesIo { inherit name version; sha256 = "edc50ffce891ad571e9f9afe5039c4837bede781ac4bb13052ed7ae695518596"; }; - features = builtins.concatLists [ - [ "legacy" ] - [ "std" ] - [ "zdict_builder" ] - ]; - dependencies = { - libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; - }; - buildDependencies = { - cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; - pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; }; - }; - }); -} \ No newline at end of file diff --git a/flake.lock b/flake.lock index 1c0c93e34bd..6f955108475 100644 --- a/flake.lock +++ b/flake.lock @@ -71,21 +71,6 @@ "type": "github" } }, - "flake-utils_2": { - "locked": { - "lastModified": 1659877975, - "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", - "owner": "numtide", - "repo": "flake-utils", - "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", - "type": "github" - }, - "original": { - "owner": "numtide", - "repo": "flake-utils", - "type": "github" - } - }, "nixpkgs": { "locked": { "lastModified": 1654275867, @@ -138,11 +123,11 @@ }, "nixpkgs_3": { "locked": { - "lastModified": 1665296151, - "narHash": "sha256-uOB0oxqxN9K7XGF1hcnY+PQnlQJ+3bP2vCn/+Ru/bbc=", + "lastModified": 1718428119, + "narHash": "sha256-WdWDpNaq6u1IPtxtYHHWpl5BmabtpmLnMAx0RdJ/vo8=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "14ccaaedd95a488dd7ae142757884d8e125b3363", + "rev": "e6cea36f83499eb4e9cd184c8a8e823296b50ad5", "type": "github" }, "original": { @@ -187,15 +172,14 @@ }, "rust-overlay_2": { "inputs": { - "flake-utils": "flake-utils_2", "nixpkgs": "nixpkgs_3" }, "locked": { - "lastModified": 1676601131, - "narHash": "sha256-iwCg6NimjD4euquhicmSo0wuyP56xUVJUMe0yqUyQms=", + "lastModified": 1726626348, + "narHash": "sha256-sYV7e1B1yLcxo8/h+/hTwzZYmaju2oObNiy5iRI0C30=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "d0dc81ffe8ea09dbf3c07db62a1a057f5319e3ce", + "rev": "6fd52ad8bd88f39efb2c999cc971921c2fb9f3a2", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index bd651e042c1..ad3de7e660b 100644 --- a/flake.nix +++ b/flake.nix @@ -2,48 +2,41 @@ description = "hyperswitch"; inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-parts.url = "github:hercules-ci/flake-parts"; + + # TODO: Move away from these to https://github.com/juspay/rust-flake cargo2nix.url = "github:cargo2nix/cargo2nix/release-0.11.0"; rust-overlay.url = "github:oxalica/rust-overlay"; - flake-parts.url = "github:hercules-ci/flake-parts"; - nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; }; - outputs = inputs@{ self, nixpkgs, flake-parts, ... }: - flake-parts.lib.mkFlake { inherit inputs; } { - systems = nixpkgs.lib.systems.flakeExposed; - perSystem = { self', pkgs, system, ... }: + outputs = inputs: + inputs.flake-parts.lib.mkFlake { inherit inputs; } { + systems = inputs.nixpkgs.lib.systems.flakeExposed; + perSystem = { self', pkgs, lib, system, ... }: let - rustVersion = "1.65.0"; - rustPkgs = pkgs.rustBuilder.makePackageSet { - inherit rustVersion; - packageFun = import ./Cargo.nix; - }; + cargoToml = lib.importTOML ./Cargo.toml; + rustVersion = cargoToml.workspace.package.rust-version; frameworks = pkgs.darwin.apple_sdk.frameworks; in { - _module.args.pkgs = import nixpkgs { + _module.args.pkgs = import inputs.nixpkgs { inherit system; overlays = [ inputs.cargo2nix.overlays.default (import inputs.rust-overlay) ]; }; - packages = rec { - router = (rustPkgs.workspace.router { }).bin; - default = router; - }; - apps = { - router-scheduler = { - type = "app"; - program = "${self'.packages.router}/bin/scheduler"; - }; - }; devShells.default = pkgs.mkShell { - buildInputs = with pkgs; [ + name = "hyperswitch-shell"; + packages = with pkgs; [ openssl pkg-config exa fd rust-bin.stable.${rustVersion}.default - ] ++ lib.optionals stdenv.isDarwin [ frameworks.CoreServices frameworks.Foundation ]; # arch might have issue finding these libs. - + ] ++ lib.optionals stdenv.isDarwin [ + # arch might have issue finding these libs. + frameworks.CoreServices + frameworks.Foundation + ]; }; }; };
2024-09-11T19:50:00Z
Resolves #5876 This PR makes sure that `flake.nix` builds, and checks it in CI (uses self-hosted runners) going forward. It removes no longer used Nix code (they don't build). - [x] Add github workflow action to build flake outputs - [x] Remove packages that no longer build (see #5017)
3ddfe53838c6b039dc5f669ccd23d3035521d691
juspay/hyperswitch
juspay__hyperswitch-5838
Bug: [REFACTOR] update auth data for recon APIs ### Refactor Description Refactor the code to - pass only the required authentication data to recon APIs (remove UserFromToken which contains different resource IDs) - remove existing impls for fetching user from DB ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index fa9944ee8ee..2c2dfc9c9f0 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -17,11 +17,10 @@ use crate::{ pub async fn send_recon_request( state: SessionState, - user_with_auth_data: authentication::UserFromTokenWithAuthData, + auth_data: authentication::AuthenticationDataWithUser, ) -> RouterResponse<recon_api::ReconStatusResponse> { - let user = user_with_auth_data.0; - let user_in_db = &user_with_auth_data.1.user; - let merchant_id = user.merchant_id; + let user_in_db = &auth_data.user; + let merchant_id = auth_data.merchant_account.get_id().clone(); let user_email = user_in_db.email.clone(); let email_contents = email_types::ProFeatureRequest { @@ -55,7 +54,6 @@ pub async fn send_recon_request( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]") .async_and_then(|_| async { - let auth = user_with_auth_data.1; let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate { recon_status: enums::ReconStatus::Requested, }; @@ -65,9 +63,9 @@ pub async fn send_recon_request( let response = db .update_merchant( key_manager_state, - auth.merchant_account, + auth_data.merchant_account, updated_merchant_account, - &auth.key_store, + &auth_data.key_store, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 31ab0e8ff22..09d7ef8458c 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1823,11 +1823,9 @@ pub async fn verify_token( state: SessionState, user: auth::UserFromToken, ) -> UserResponse<user_api::VerifyTokenResponse> { - let user_in_db = state - .global_store - .find_user_by_id(&user.user_id) + let user_in_db = user + .get_user_from_db(&state) .await - .change_context(UserErrors::InternalServerError) .attach_printable_lazy(|| { format!( "Failed to fetch the user from DB for user_id - {}", @@ -1837,7 +1835,7 @@ pub async fn verify_token( Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse { merchant_id: user.merchant_id.to_owned(), - user_email: user_in_db.email, + user_email: user_in_db.0.email, })) } diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 34097b6bac6..e112d543960 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -575,7 +575,10 @@ pub async fn verify_recon_token(state: web::Data<AppState>, http_req: HttpReques &http_req, (), |state, user, _req, _| user_core::verify_token(state, user), - &auth::DashboardNoPermissionAuth, + &auth::JWTAuth { + permission: Permission::ReconAdmin, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 5f9fc798d89..d8318ce9517 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -1984,13 +1984,9 @@ where default_auth } -#[derive(Clone)] -#[cfg(feature = "recon")] -pub struct UserFromTokenWithAuthData(pub UserFromToken, pub AuthenticationDataWithUser); - #[cfg(feature = "recon")] #[async_trait] -impl<A> AuthenticateAndFetch<UserFromTokenWithAuthData, A> for JWTAuth +impl<A> AuthenticateAndFetch<AuthenticationDataWithUser, A> for JWTAuth where A: SessionStateInfo + Sync, { @@ -1998,7 +1994,7 @@ where &self, request_headers: &HeaderMap, state: &A, - ) -> RouterResult<(UserFromTokenWithAuthData, AuthenticationType)> { + ) -> RouterResult<(AuthenticationDataWithUser, 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()); @@ -2049,17 +2045,9 @@ where let auth_type = AuthenticationType::MerchantJwt { merchant_id: auth.merchant_account.get_id().clone(), - user_id: Some(user_id.clone()), - }; - - let user = UserFromToken { - user_id, - merchant_id: payload.merchant_id.clone(), - org_id: payload.org_id, - role_id: payload.role_id, - profile_id: payload.profile_id, + user_id: Some(user_id), }; - Ok((UserFromTokenWithAuthData(user, auth), auth_type)) + Ok((auth, auth_type)) } }
2024-09-06T13:53:29Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Described in #5838 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Helps removing redundant code. ## How did you test it? <details> <summary>1. Request a new JWT token for recon dashboard</summary> cURL Request curl --location 'http://localhost:8080/recon/token' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTcwNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.aepFkZLGZUYHGY0R0dSNsvevrZodDtfwfEDyriBiti0' \ --data '' Response { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTczNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.U8agaqNLLk-NdCE5WdqYOFa5IUHXAW3TCa4Gb7IcYfs" } </details> <details> <summary>2. Verify this recon token</summary> cURL Request curl --location 'http://localhost:8080/recon/verify_token' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNTg4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTczNywib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19ER3FOSkhMYlRWSk9uejBIcDJYQyJ9.U8agaqNLLk-NdCE5WdqYOFa5IUHXAW3TCa4Gb7IcYfs' \ --data '' Response { "merchant_id": "merchant_1725560588", "user_email": "example@example.com" } </details> <details> <summary>3. Switch the merchant on dashboard from the same user and request a new JWT token for recon dashboard</summary> cURL Request curl --location 'http://localhost:8080/recon/token' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgyNSwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.nZtXfvFWUC7FfAbNQ_IouE5zjWxYd8fahXhzR4bs_oQ' \ --data '' Response { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgzOCwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.kcgt6zaH5o8qVBvSWLopTMaUQEI5SwltGAnlWB7OSXk" } </details> <details> <summary>4. Verify this token (it should have switched merchant's ID)</summary> cURL Request curl --location 'http://localhost:8080/recon/verify_token' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWZmNzcxNmItNzBlMi00MjdiLWE1NzctMzNkOTZiNWM5YzM4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI1NTYwNzU0Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNjA0MTgzOCwib3JnX2lkIjoib3JnX2dMZjA1Ykc4bEVVMFE5T2NPeFNNIiwicHJvZmlsZV9pZCI6InByb19kcWxvUTR4bzRVbG9Lb0swMVpoTiJ9.kcgt6zaH5o8qVBvSWLopTMaUQEI5SwltGAnlWB7OSXk' \ --data '' Response { "merchant_id": "merchant_1725560754", "user_email": "example@example.com" } </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
aa2f5d147561f6e996228d269e6a54c5d1f53a60
juspay/hyperswitch
juspay__hyperswitch-5842
Bug: feat(roles): New roles for profile level Create new roles for profile level roles. - profile_admin - profile_view_only - profile_operator - profile_developer - profile_iam
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 879db9a5a67..1fcfbdb5df9 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -419,7 +419,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Organization, }, api_locking::LockAction::NotApplicable, )) @@ -465,7 +465,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -545,7 +545,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Organization, }, api_locking::LockAction::NotApplicable, )) @@ -591,7 +591,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -671,7 +671,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Organization, }, api_locking::LockAction::NotApplicable, )) @@ -717,7 +717,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -931,7 +931,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Organization, }, api_locking::LockAction::NotApplicable, )) @@ -967,7 +967,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1056,7 +1056,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Organization, }, api_locking::LockAction::NotApplicable, )) @@ -1092,7 +1092,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1179,7 +1179,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1213,7 +1213,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1245,7 +1245,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1776,7 +1776,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1808,7 +1808,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1851,7 +1851,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1894,7 +1894,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1961,7 +1961,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -1990,7 +1990,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Organization, }, api_locking::LockAction::NotApplicable, )) @@ -2077,7 +2077,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -2116,7 +2116,7 @@ pub mod routes { }, &auth::JWTAuth { permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Organization, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/consts/user_role.rs b/crates/router/src/consts/user_role.rs index fbabec67291..3cc2cb26886 100644 --- a/crates/router/src/consts/user_role.rs +++ b/crates/router/src/consts/user_role.rs @@ -5,6 +5,13 @@ pub const ROLE_ID_MERCHANT_IAM_ADMIN: &str = "merchant_iam_admin"; pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer"; pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator"; pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support"; + +pub const ROLE_ID_PROFILE_ADMIN: &str = "profile_admin"; +pub const ROLE_ID_PROFILE_VIEW_ONLY: &str = "profile_view_only"; +pub const ROLE_ID_PROFILE_IAM_ADMIN: &str = "profile_iam_admin"; +pub const ROLE_ID_PROFILE_DEVELOPER: &str = "profile_developer"; +pub const ROLE_ID_PROFILE_OPERATOR: &str = "profile_operator"; pub const ROLE_ID_PROFILE_CUSTOMER_SUPPORT: &str = "profile_customer_support"; + pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000"; pub const MAX_ROLE_NAME_LENGTH: usize = 64; diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 8c42e8df353..e423f861078 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -2652,6 +2652,7 @@ pub async fn create_connector( state: SessionState, req: api::MerchantConnectorCreate, merchant_account: domain::MerchantAccount, + auth_profile_id: Option<id_type::ProfileId>, key_store: domain::MerchantKeyStore, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); @@ -2683,6 +2684,8 @@ pub async fn create_connector( .validate_and_get_business_profile(&merchant_account, store, key_manager_state, &key_store) .await?; + core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?; + let pm_auth_config_validation = PMAuthConfigValidation { connector_type: &req.connector_type, pm_auth_config: &req.pm_auth_config, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index ae92360b13e..0dc34aa4245 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -226,14 +226,20 @@ pub async fn connector_create( &req, payload, |state, auth_data, req, _| { - create_connector(state, req, auth_data.merchant_account, auth_data.key_store) + create_connector( + state, + req, + auth_data.merchant_account, + auth_data.profile_id, + auth_data.key_store, + ) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromRoute(merchant_id.clone()), &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -259,7 +265,13 @@ pub async fn connector_create( &req, payload, |state, auth_data, req, _| { - create_connector(state, req, auth_data.merchant_account, auth_data.key_store) + create_connector( + state, + req, + auth_data.merchant_account, + None, + auth_data.key_store, + ) }, auth::auth_type( &auth::AdminApiAuthWithMerchantIdFromHeader, @@ -526,7 +538,7 @@ pub async fn connector_update( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -889,8 +901,8 @@ pub async fn business_profile_update( &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), - minimum_entity_level: EntityType::Merchant, required_permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index e4d7337ef72..e2cb50b0aa7 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -666,14 +666,14 @@ pub async fn list_countries_currencies_for_connector_payment_method( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::MerchantConnectorAccountWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 8533c9ddea9..b1831068991 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -45,14 +45,14 @@ pub async fn routing_create_config( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -88,14 +88,14 @@ pub async fn routing_link_config( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -352,14 +352,14 @@ pub async fn routing_unlink_config( &auth::HeaderAuth(auth::ApiKeyAuth), &auth::JWTAuth { permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -478,7 +478,7 @@ pub async fn routing_retrieve_default_config( &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -486,7 +486,7 @@ pub async fn routing_retrieve_default_config( &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::RoutingRead, - minimum_entity_level: EntityType::Profile, + minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) @@ -963,7 +963,7 @@ pub async fn routing_update_default_config_for_profile( &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -971,7 +971,7 @@ pub async fn routing_update_default_config_for_profile( &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::RoutingWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 34097b6bac6..62af1d4374c 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -177,7 +177,7 @@ pub async fn set_dashboard_metadata( user_core::dashboard_metadata::set_metadata, &auth::JWTAuth { permission: Permission::MerchantAccountWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -365,7 +365,7 @@ pub async fn list_user_roles_details( user_core::list_user_roles_details, &auth::JWTAuth { permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -468,7 +468,7 @@ pub async fn invite_multiple_user( }, &auth::JWTAuth { permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -494,7 +494,7 @@ pub async fn resend_invite( }, &auth::JWTAuth { permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 00b289b0b80..b1260b5d7ad 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -114,7 +114,7 @@ pub async fn get_role( }, &auth::JWTAuth { permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -160,7 +160,7 @@ pub async fn update_user_role( user_role_core::update_user_role, &auth::JWTAuth { permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -261,7 +261,7 @@ pub async fn delete_user_role( user_role_core::delete_user_role, &auth::JWTAuth { permission: Permission::UsersWrite, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -282,9 +282,10 @@ pub async fn get_role_information( |_, _: (), _, _| async move { user_role_core::get_authorization_info_with_group_tag().await }, - &auth::JWTAuth{ + &auth::JWTAuth { permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant}, + minimum_entity_level: EntityType::Profile + }, api_locking::LockAction::NotApplicable, )) .await @@ -318,7 +319,7 @@ pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest) |state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token), &auth::JWTAuth { permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -347,7 +348,7 @@ pub async fn list_invitable_roles_at_entity_level( }, &auth::JWTAuth { permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -376,7 +377,7 @@ pub async fn list_updatable_roles_at_entity_level( }, &auth::JWTAuth { permission: Permission::UsersRead, - minimum_entity_level: EntityType::Merchant, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index 8bac297e7c2..df42d412989 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -8,6 +8,8 @@ use crate::consts; pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|| { let mut roles = HashMap::new(); + + // Internal Roles roles.insert( common_utils::consts::ROLE_ID_INTERNAL_ADMIN, RoleInfo { @@ -58,6 +60,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| }, ); + // Merchant Roles roles.insert( common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN, RoleInfo { @@ -106,7 +109,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::ReconOps, ], role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(), - role_name: "admin".to_string(), + role_name: "merchant_admin".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, @@ -127,7 +130,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(), - role_name: "view_only".to_string(), + role_name: "merchant_view_only".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, @@ -147,7 +150,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(), - role_name: "iam".to_string(), + role_name: "merchant_iam".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, @@ -168,7 +171,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsManage, ], role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(), - role_name: "developer".to_string(), + role_name: "merchant_developer".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, @@ -190,7 +193,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(), - role_name: "operator".to_string(), + role_name: "merchant_operator".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Merchant, is_invitable: true, @@ -218,17 +221,129 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| is_internal: false, }, ); + + // Profile Roles roles.insert( - consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT, + consts::user_role::ROLE_ID_PROFILE_ADMIN, RoleInfo { groups: vec![ PermissionGroup::OperationsView, PermissionGroup::OperationsManage, PermissionGroup::ConnectorsView, + PermissionGroup::ConnectorsManage, + PermissionGroup::WorkflowsView, + PermissionGroup::WorkflowsManage, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + ], + role_id: consts::user_role::ROLE_ID_PROFILE_ADMIN.to_string(), + role_name: "profile_admin".to_string(), + scope: RoleScope::Organization, + entity_type: EntityType::Profile, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY.to_string(), + role_name: "profile_view_only".to_string(), + scope: RoleScope::Organization, + entity_type: EntityType::Profile, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::UsersManage, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN.to_string(), + role_name: "profile_iam".to_string(), + scope: RoleScope::Organization, + entity_type: EntityType::Profile, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_PROFILE_DEVELOPER, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::ConnectorsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + PermissionGroup::MerchantDetailsManage, + ], + role_id: consts::user_role::ROLE_ID_PROFILE_DEVELOPER.to_string(), + role_name: "profile_developer".to_string(), + scope: RoleScope::Organization, + entity_type: EntityType::Profile, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_PROFILE_OPERATOR, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, + ], + role_id: consts::user_role::ROLE_ID_PROFILE_OPERATOR.to_string(), + role_name: "profile_operator".to_string(), + scope: RoleScope::Organization, + entity_type: EntityType::Profile, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); + roles.insert( + consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::AnalyticsView, + PermissionGroup::UsersView, + PermissionGroup::MerchantDetailsView, ], role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(), - role_name: "profile_support".to_string(), + role_name: "profile_customer_support".to_string(), scope: RoleScope::Organization, entity_type: EntityType::Profile, is_invitable: true,
2024-09-09T13:52:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - Make merchant account create profile level. - Create new roles for profile users. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5842. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Invite user at any of the following roles: - profile_admin - profile_view_only - profile_iam_admin - profile_developer - profile_operator Dashboard features should work without 401s. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
bf1797fe7cf769eb6e89f75b132a35a6cd9003df
juspay/hyperswitch
juspay__hyperswitch-5831
Bug: chore: address Rust 1.81.0 clippy lints Address the clippy lints occurring due to new rust version 1.81.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs index 10514108991..946489513b4 100644 --- a/crates/drainer/src/health_check.rs +++ b/crates/drainer/src/health_check.rs @@ -170,7 +170,7 @@ impl HealthCheckInterface for Store { logger::debug!("Redis set_key was successful"); redis_conn - .get_key("test_key") + .get_key::<()>("test_key") .await .change_context(HealthCheckRedisError::GetFailed)?; diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index 7d5553bb25c..2707ef4b6f2 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -1017,11 +1017,12 @@ impl api::IncomingWebhook for Globalpay { &self, request: &api::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - let details = std::str::from_utf8(request.body) - .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; - Ok(Box::new(serde_json::from_str(details).change_context( - errors::ConnectorError::WebhookResourceObjectNotFound, - )?)) + Ok(Box::new( + request + .body + .parse_struct::<GlobalpayPaymentsResponse>("GlobalpayPaymentsResponse") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?, + )) } } diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index 6092ac8bbb9..83faee677d4 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -52,7 +52,7 @@ impl HealthCheckInterface for app::SessionState { logger::debug!("Redis set_key was successful"); redis_conn - .get_key("test_key") + .get_key::<()>("test_key") .await .change_context(errors::HealthCheckRedisError::GetFailed)?; 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 477f025c785..4ea4b60d67d 100644 --- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs +++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs @@ -88,11 +88,10 @@ impl SurchargeSource { ) }) .transpose()? - .map(|surcharge_details| { + .inspect(|surcharge_details| { let (surcharge_metadata, surcharge_key) = surcharge_metadata_and_key; surcharge_metadata .insert_surcharge_details(surcharge_key, surcharge_details.clone()); - surcharge_details })) } Self::Predetermined(request_surcharge_details) => Ok(Some( diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f71bf9b94ab..6b231717563 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -145,7 +145,7 @@ where .to_validate_request()? .validate_request(&req, &merchant_account)?; - tracing::Span::current().record("payment_id", &format!("{}", validate_result.payment_id)); + tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id)); let operations::GetTrackerResponse { operation, diff --git a/crates/router_env/tests/env.rs b/crates/router_env/tests/env.rs index e4609a48838..cff2ae45f12 100644 --- a/crates/router_env/tests/env.rs +++ b/crates/router_env/tests/env.rs @@ -25,7 +25,7 @@ async fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { #[cfg(feature = "vergen")] #[tokio::test] -async fn env_macro() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { +async fn env_macro() { println!("version : {:?}", env::version!()); println!("build : {:?}", env::build!()); println!("commit : {:?}", env::commit!()); @@ -35,6 +35,4 @@ async fn env_macro() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { assert!(!env::build!().is_empty()); assert!(!env::commit!().is_empty()); // assert!(env::platform!().len() > 0); - - Ok(()) } diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 8511702baa2..74b1526fe8e 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -259,12 +259,11 @@ where result .await - .map(|result| { + .inspect(|_| { logger::debug!(kv_operation= %operation, status="success"); let keyvalue = router_env::opentelemetry::KeyValue::new("operation", operation.clone()); metrics::KV_OPERATION_SUCCESSFUL.add(&metrics::CONTEXT, 1, &[keyvalue]); - result }) .inspect_err(|err| { logger::error!(kv_operation = %operation, status="error", error = ?err); diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index 8f24b62fcaf..7d7557a7f5f 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -30,7 +30,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { self.subscriber.manage_subscriptions(); self.subscriber - .subscribe(channel) + .subscribe::<(), &str>(channel) .await .change_context(redis_errors::RedisError::SubscribeError)?;
2024-09-07T05:19:45Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [x] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR addresses the clippy lints occurring due to new rust version 1.81.0 ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> This PR addresses clippy lint due to new rust version. So basic sanity testing should suffice. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d9485a5f360f78f308f4e70c361f33873c63b686
juspay/hyperswitch
juspay__hyperswitch-5822
Bug: feat(analytics): Revert api_event metrics and filters back to merchant_id authentication `api_event_metrics` and `api_event_filters` APIs were modified to authenticate through AuthInfo where there are MerchantLevel, ProfileLevel and OrgLevel authentication. (https://github.com/juspay/hyperswitch/pull/5729) But ApiEvents table is not yet populated with organization_id and profile_id, hence should be reverted back.
diff --git a/crates/analytics/src/api_event/core.rs b/crates/analytics/src/api_event/core.rs index f3a7b154b90..305de7e69c8 100644 --- a/crates/analytics/src/api_event/core.rs +++ b/crates/analytics/src/api_event/core.rs @@ -21,7 +21,6 @@ use super::{ metrics::ApiEventMetricRow, }; use crate::{ - enums::AuthInfo, errors::{AnalyticsError, AnalyticsResult}, metrics, types::FiltersError, @@ -52,7 +51,7 @@ pub async fn api_events_core( pub async fn get_filters( pool: &AnalyticsProvider, req: GetApiEventFiltersRequest, - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, ) -> AnalyticsResult<ApiEventFiltersResponse> { use api_models::analytics::{api_event::ApiEventDimensions, ApiEventFilterValue}; @@ -69,7 +68,8 @@ pub async fn get_filters( AnalyticsProvider::Clickhouse(ckh_pool) | AnalyticsProvider::CombinedSqlx(_, ckh_pool) | AnalyticsProvider::CombinedCkh(_, ckh_pool) => { - get_api_event_filter_for_dimension(dim, auth, &req.time_range, ckh_pool).await + get_api_event_filter_for_dimension(dim, merchant_id, &req.time_range, ckh_pool) + .await } } .switch()? @@ -92,7 +92,7 @@ pub async fn get_filters( #[instrument(skip_all)] pub async fn get_api_event_metrics( pool: &AnalyticsProvider, - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, req: GetApiEventMetricRequest, ) -> AnalyticsResult<MetricsResponse<ApiMetricsBucketResponse>> { let mut metrics_accumulator: HashMap<ApiEventMetricsBucketIdentifier, ApiEventMetricRow> = @@ -109,14 +109,14 @@ pub async fn get_api_event_metrics( // TODO: lifetime issues with joinset, // can be optimized away if joinset lifetime requirements are relaxed - let auth_scoped = auth.to_owned(); + let merchant_id_scoped = merchant_id.to_owned(); set.spawn( async move { let data = pool .get_api_event_metrics( &metric_type, &req.group_by_names.clone(), - &auth_scoped, + &merchant_id_scoped, &req.filters, &req.time_series.map(|t| t.granularity), &req.time_range, diff --git a/crates/analytics/src/api_event/filters.rs b/crates/analytics/src/api_event/filters.rs index 5c8136805c9..62fd8789018 100644 --- a/crates/analytics/src/api_event/filters.rs +++ b/crates/analytics/src/api_event/filters.rs @@ -4,7 +4,6 @@ use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::{ - enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, }; @@ -13,7 +12,7 @@ pub trait ApiEventFilterAnalytics: LoadRow<ApiEventFilter> {} pub async fn get_api_event_filter_for_dimension<T>( dimension: ApiEventDimensions, - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<ApiEventFilter>> @@ -33,7 +32,9 @@ where .attach_printable("Error filtering time range") .switch()?; - auth.set_filter_clause(&mut query_builder).switch()?; + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; query_builder.set_distinct(); diff --git a/crates/analytics/src/api_event/metrics.rs b/crates/analytics/src/api_event/metrics.rs index 48e95b6b5cd..ac29ec15169 100644 --- a/crates/analytics/src/api_event/metrics.rs +++ b/crates/analytics/src/api_event/metrics.rs @@ -7,7 +7,6 @@ use api_models::analytics::{ use time::PrimitiveDateTime; use crate::{ - enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult}, }; @@ -44,7 +43,7 @@ where async fn load_metrics( &self, dimensions: &[ApiEventDimensions], - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, @@ -65,7 +64,7 @@ where async fn load_metrics( &self, dimensions: &[ApiEventDimensions], - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, @@ -74,17 +73,38 @@ where match self { Self::Latency => { MaxLatency - .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) .await } Self::ApiCount => { ApiCount - .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) .await } Self::StatusCodeCount => { StatusCodeCount - .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + pool, + ) .await } } diff --git a/crates/analytics/src/api_event/metrics/api_count.rs b/crates/analytics/src/api_event/metrics/api_count.rs index 3973870a455..f00c01bbf38 100644 --- a/crates/analytics/src/api_event/metrics/api_count.rs +++ b/crates/analytics/src/api_event/metrics/api_count.rs @@ -10,7 +10,6 @@ use time::PrimitiveDateTime; use super::ApiEventMetricRow; use crate::{ - enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -31,7 +30,7 @@ where async fn load_metrics( &self, _dimensions: &[ApiEventDimensions], - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, @@ -70,7 +69,9 @@ where .switch()?; } - auth.set_filter_clause(&mut query_builder).switch()?; + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; time_range .set_filter_clause(&mut query_builder) diff --git a/crates/analytics/src/api_event/metrics/latency.rs b/crates/analytics/src/api_event/metrics/latency.rs index c9a62abe676..5d71da2a0aa 100644 --- a/crates/analytics/src/api_event/metrics/latency.rs +++ b/crates/analytics/src/api_event/metrics/latency.rs @@ -10,7 +10,6 @@ use time::PrimitiveDateTime; use super::ApiEventMetricRow; use crate::{ - enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, @@ -34,7 +33,7 @@ where async fn load_metrics( &self, _dimensions: &[ApiEventDimensions], - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, @@ -77,7 +76,9 @@ where filters.set_filter_clause(&mut query_builder).switch()?; - auth.set_filter_clause(&mut query_builder).switch()?; + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; time_range .set_filter_clause(&mut query_builder) diff --git a/crates/analytics/src/api_event/metrics/status_code_count.rs b/crates/analytics/src/api_event/metrics/status_code_count.rs index 190f38999c9..b4fff367b62 100644 --- a/crates/analytics/src/api_event/metrics/status_code_count.rs +++ b/crates/analytics/src/api_event/metrics/status_code_count.rs @@ -10,7 +10,6 @@ use time::PrimitiveDateTime; use super::ApiEventMetricRow; use crate::{ - enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; @@ -31,7 +30,7 @@ where async fn load_metrics( &self, _dimensions: &[ApiEventDimensions], - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, @@ -48,7 +47,9 @@ where filters.set_filter_clause(&mut query_builder).switch()?; - auth.set_filter_clause(&mut query_builder).switch()?; + query_builder + .add_filter_clause("merchant_id", merchant_id) + .switch()?; time_range .set_filter_clause(&mut query_builder) diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 66005a61b75..d5cb3c718df 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -828,7 +828,7 @@ impl AnalyticsProvider { &self, metric: &ApiEventMetrics, dimensions: &[ApiEventDimensions], - auth: &AuthInfo, + merchant_id: &common_utils::id_type::MerchantId, filters: &ApiEventFilters, granularity: &Option<Granularity>, time_range: &TimeRange, @@ -840,7 +840,14 @@ impl AnalyticsProvider { | Self::CombinedSqlx(_, ckh_pool) => { // Since API events are ckh only use ckh here metric - .load_metrics(dimensions, auth, filters, granularity, time_range, ckh_pool) + .load_metrics( + dimensions, + merchant_id, + filters, + granularity, + time_range, + ckh_pool, + ) .await } } diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 7c4d1acc6bf..879db9a5a67 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -215,14 +215,6 @@ pub mod routes { web::resource("filters/disputes") .route(web::post().to(get_org_dispute_filters)), ) - .service( - web::resource("filters/api_events") - .route(web::post().to(get_org_api_event_filters)), - ) - .service( - web::resource("metrics/api_events") - .route(web::post().to(get_org_api_events_metrics)), - ) .service( web::resource("report/dispute") .route(web::post().to(generate_org_dispute_report)), @@ -257,14 +249,6 @@ pub mod routes { web::resource("filters/refunds") .route(web::post().to(get_profile_refund_filters)), ) - .service( - web::resource("metrics/api_events") - .route(web::post().to(get_profile_api_events_metrics)), - ) - .service( - web::resource("filters/api_events") - .route(web::post().to(get_profile_api_event_filters)), - ) .service( web::resource("metrics/disputes") .route(web::post().to(get_profile_dispute_metrics)), @@ -1757,100 +1741,13 @@ pub mod routes { &req, payload, |state, auth: AuthenticationData, req, _| async move { - let org_id = auth.merchant_account.get_org_id(); - let merchant_id = auth.merchant_account.get_id(); - let auth: AuthInfo = AuthInfo::MerchantLevel { - org_id: org_id.clone(), - merchant_ids: vec![merchant_id.clone()], - }; - analytics::api_event::get_api_event_metrics(&state.pool, &auth, req) - .await - .map(ApplicationResponse::Json) - }, - &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, - }, - api_locking::LockAction::NotApplicable, - )) - .await - } - - /// # Panics - /// - /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element. - pub async fn get_org_api_events_metrics( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<[GetApiEventMetricRequest; 1]>, - ) -> impl Responder { - // safety: This shouldn't panic owing to the data type - #[allow(clippy::expect_used)] - let payload = json_payload - .into_inner() - .to_vec() - .pop() - .expect("Couldn't get GetApiEventMetricRequest"); - let flow = AnalyticsFlow::GetApiEventMetrics; - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - payload, - |state, auth: AuthenticationData, req, _| async move { - let org_id = auth.merchant_account.get_org_id(); - let auth: AuthInfo = AuthInfo::OrgLevel { - org_id: org_id.clone(), - }; - analytics::api_event::get_api_event_metrics(&state.pool, &auth, req) - .await - .map(ApplicationResponse::Json) - }, - &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, - }, - api_locking::LockAction::NotApplicable, - )) - .await - } - - /// # Panics - /// - /// Panics if `json_payload` array does not contain one `GetApiEventMetricRequest` element. - pub async fn get_profile_api_events_metrics( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<[GetApiEventMetricRequest; 1]>, - ) -> impl Responder { - // safety: This shouldn't panic owing to the data type - #[allow(clippy::expect_used)] - let payload = json_payload - .into_inner() - .to_vec() - .pop() - .expect("Couldn't get GetApiEventMetricRequest"); - let flow = AnalyticsFlow::GetApiEventMetrics; - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - payload, - |state, auth: AuthenticationData, req, _| async move { - let org_id = auth.merchant_account.get_org_id(); - let merchant_id = auth.merchant_account.get_id(); - let profile_id = auth - .profile_id - .ok_or(report!(UserErrors::JwtProfileIdMissing)) - .change_context(AnalyticsError::AccessForbiddenError)?; - let auth: AuthInfo = AuthInfo::ProfileLevel { - org_id: org_id.clone(), - merchant_id: merchant_id.clone(), - profile_ids: vec![profile_id.clone()], - }; - analytics::api_event::get_api_event_metrics(&state.pool, &auth, req) - .await - .map(ApplicationResponse::Json) + analytics::api_event::get_api_event_metrics( + &state.pool, + auth.merchant_account.get_id(), + req, + ) + .await + .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::Analytics, @@ -1873,78 +1770,7 @@ pub mod routes { &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { - let org_id = auth.merchant_account.get_org_id(); - let merchant_id = auth.merchant_account.get_id(); - let auth: AuthInfo = AuthInfo::MerchantLevel { - org_id: org_id.clone(), - merchant_ids: vec![merchant_id.clone()], - }; - analytics::api_event::get_filters(&state.pool, req, &auth) - .await - .map(ApplicationResponse::Json) - }, - &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, - }, - api_locking::LockAction::NotApplicable, - )) - .await - } - - pub async fn get_org_api_event_filters( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<GetApiEventFiltersRequest>, - ) -> impl Responder { - let flow = AnalyticsFlow::GetApiEventFilters; - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - json_payload.into_inner(), - |state, auth: AuthenticationData, req, _| async move { - let org_id = auth.merchant_account.get_org_id(); - let auth: AuthInfo = AuthInfo::OrgLevel { - org_id: org_id.clone(), - }; - analytics::api_event::get_filters(&state.pool, req, &auth) - .await - .map(ApplicationResponse::Json) - }, - &auth::JWTAuth { - permission: Permission::Analytics, - minimum_entity_level: EntityType::Merchant, - }, - api_locking::LockAction::NotApplicable, - )) - .await - } - - pub async fn get_profile_api_event_filters( - state: web::Data<AppState>, - req: actix_web::HttpRequest, - json_payload: web::Json<GetApiEventFiltersRequest>, - ) -> impl Responder { - let flow = AnalyticsFlow::GetApiEventFilters; - Box::pin(api::server_wrap( - flow, - state.clone(), - &req, - json_payload.into_inner(), - |state, auth: AuthenticationData, req, _| async move { - let org_id = auth.merchant_account.get_org_id(); - let merchant_id = auth.merchant_account.get_id(); - let profile_id = auth - .profile_id - .ok_or(report!(UserErrors::JwtProfileIdMissing)) - .change_context(AnalyticsError::AccessForbiddenError)?; - let auth: AuthInfo = AuthInfo::ProfileLevel { - org_id: org_id.clone(), - merchant_id: merchant_id.clone(), - profile_ids: vec![profile_id.clone()], - }; - analytics::api_event::get_filters(&state.pool, req, &auth) + analytics::api_event::get_filters(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) },
2024-09-06T05:59:52Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Previously modified api_event_metrics and api_event_filters to authenticate through AuthInfo where there are MerchantLevel, ProfileLevel and OrgLevel authentication. ([https://github.com/juspay/hyperswitch/pull/5729](https://github.com/juspay/hyperswitch/pull/5729)) But ApiEvents table is not populated with `organization_id` and `profile_id`, hence reverting back. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Fix the issues on sandbox analytics related to api_events. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Spoke with dashboard team and removed the following api endpoints: - /analytics/v1/profile/metrics/api_events - /analytics/v1/profile/filters/api_events - /analytics/v1/org/metrics/api_events - /analytics/v1/org/filters/api_events ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d3a1703bf59afc06e87e94433bc10a01e413259b
juspay/hyperswitch
juspay__hyperswitch-5847
Bug: [FEATURE] add translation to unified error messages in API response and payout link ### Feature Description Connector can fail due to numerous reasons and usually returns an error code along with an error message. These error messages are specific to the underlying connectors. However, these errors can be logically categorised under a single error code + message combination. This ensures the errors are better understood across different connectors. Once these errors are unified, they can be translated as well based on the requested locale for both payout APIs and payout links. ### Possible Implementation 1. Obtain a list of all the errors across different payout connectors 2. Form unified codes and messages (push them in GSM table) 3. Form translated messages (push them in GSM table) 4. Whenever an error occurs, `unified_code` and `unified_message` is updated in the payout entry (based on DB lookup in GSM) 5. Whenever the payout is requested, the unified error code and message is translated (based on DB lookup in GSM) for the requested locale and attached in the response / link ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index acff517e107..e7dbbcdabe6 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -15207,13 +15207,17 @@ }, "unified_code": { "type": "string", - "description": "error code unified across the connectors is received here if there was an error while calling connector", - "nullable": true + "description": "(This field is not live yet)\nError code unified across the connectors is received here in case of errors while calling the underlying connector", + "example": "UE_000", + "nullable": true, + "maxLength": 255 }, "unified_message": { "type": "string", - "description": "error message unified across the connectors is received here if there was an error while calling connector", - "nullable": true + "description": "(This field is not live yet)\nError message unified across the connectors is received here in case of errors while calling the underlying connector", + "example": "Invalid card details", + "nullable": true, + "maxLength": 1024 } } }, @@ -15727,6 +15731,20 @@ "example": "+1", "nullable": true, "maxLength": 255 + }, + "unified_code": { + "type": "string", + "description": "(This field is not live yet)\nError code unified across the connectors is received here in case of errors while calling the underlying connector", + "example": "UE_000", + "nullable": true, + "maxLength": 255 + }, + "unified_message": { + "type": "string", + "description": "(This field is not live yet)\nError message unified across the connectors is received here in case of errors while calling the underlying connector", + "example": "Invalid card details", + "nullable": true, + "maxLength": 1024 } }, "additionalProperties": false diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 01bb63642be..10771df4ccd 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -5,6 +5,7 @@ use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, pii::{self, Email}, + types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; use router_derive::FlatStruct; @@ -383,7 +384,7 @@ pub struct Venmo { pub telephone_number: Option<Secret<String>>, } -#[derive(Debug, ToSchema, Clone, Serialize)] +#[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts @@ -535,6 +536,18 @@ pub struct PayoutCreateResponse { /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, + + /// (This field is not live yet) + /// Error code unified across the connectors is received here in case of errors while calling the underlying connector + #[remove_in(PayoutCreateResponse)] + #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] + pub unified_code: Option<UnifiedCode>, + + /// (This field is not live yet) + /// Error message unified across the connectors is received here in case of errors while calling the underlying connector + #[remove_in(PayoutCreateResponse)] + #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] + pub unified_message: Option<UnifiedMessage>, } #[derive( @@ -568,10 +581,16 @@ pub struct PayoutAttemptResponse { pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: 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>, + /// (This field is not live yet) + /// Error code unified across the connectors is received here in case of errors while calling the underlying connector + #[remove_in(PayoutAttemptResponse)] + #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] + pub unified_code: Option<UnifiedCode>, + /// (This field is not live yet) + /// Error message unified across the connectors is received here in case of errors while calling the underlying connector + #[remove_in(PayoutAttemptResponse)] + #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] + pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] @@ -819,8 +838,8 @@ pub struct PayoutLinkStatusDetails { pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, - pub error_code: Option<String>, - pub error_message: Option<String>, + pub error_code: Option<UnifiedCode>, + pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 299e70dc4c9..70f00ad9b3f 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -146,3 +146,6 @@ pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin"; pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only"; /// Role ID for Internal Admin pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin"; + +/// Payout flow identifier used for performing GSM operations +pub const PAYOUT_FLOW_STR: &str = "payout_flow"; diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 7f2f844b03f..6acf5000ced 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -32,7 +32,7 @@ use utoipa::ToSchema; use crate::{ consts, - errors::{CustomResult, ParsingError, PercentageError}, + errors::{CustomResult, ParsingError, PercentageError, ValidationError}, }; /// Represents Percentage Value between 0 and 100 both inclusive #[derive(Clone, Default, Debug, PartialEq, Serialize)] @@ -767,3 +767,107 @@ where self.0.to_sql(out) } } + +/// Domain type for unified code +#[derive( + Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression, +)] +#[diesel(sql_type = sql_types::Text)] +pub struct UnifiedCode(pub String); + +impl TryFrom<String> for UnifiedCode { + type Error = error_stack::Report<ValidationError>; + fn try_from(src: String) -> Result<Self, Self::Error> { + if src.len() > 255 { + Err(report!(ValidationError::InvalidValue { + message: "unified_code's length should not exceed 255 characters".to_string() + })) + } else { + Ok(Self(src)) + } + } +} + +impl<DB> Queryable<sql_types::Text, DB> for UnifiedCode +where + DB: Backend, + Self: FromSql<sql_types::Text, DB>, +{ + type Row = Self; + + fn build(row: Self::Row) -> deserialize::Result<Self> { + Ok(row) + } +} +impl<DB> FromSql<sql_types::Text, DB> for UnifiedCode +where + DB: Backend, + String: FromSql<sql_types::Text, DB>, +{ + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { + let val = String::from_sql(bytes)?; + Ok(Self::try_from(val)?) + } +} + +impl<DB> ToSql<sql_types::Text, DB> for UnifiedCode +where + DB: Backend, + String: ToSql<sql_types::Text, DB>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { + self.0.to_sql(out) + } +} + +/// Domain type for unified messages +#[derive( + Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression, +)] +#[diesel(sql_type = sql_types::Text)] +pub struct UnifiedMessage(pub String); + +impl TryFrom<String> for UnifiedMessage { + type Error = error_stack::Report<ValidationError>; + fn try_from(src: String) -> Result<Self, Self::Error> { + if src.len() > 1024 { + Err(report!(ValidationError::InvalidValue { + message: "unified_message's length should not exceed 1024 characters".to_string() + })) + } else { + Ok(Self(src)) + } + } +} + +impl<DB> Queryable<sql_types::Text, DB> for UnifiedMessage +where + DB: Backend, + Self: FromSql<sql_types::Text, DB>, +{ + type Row = Self; + + fn build(row: Self::Row) -> deserialize::Result<Self> { + Ok(row) + } +} +impl<DB> FromSql<sql_types::Text, DB> for UnifiedMessage +where + DB: Backend, + String: FromSql<sql_types::Text, DB>, +{ + fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> { + let val = String::from_sql(bytes)?; + Ok(Self::try_from(val)?) + } +} + +impl<DB> ToSql<sql_types::Text, DB> for UnifiedMessage +where + DB: Backend, + String: ToSql<sql_types::Text, DB>, +{ + fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result { + self.0.to_sql(out) + } +} diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rs index 619e694f411..edb60bc1f44 100644 --- a/crates/diesel_models/src/payout_attempt.rs +++ b/crates/diesel_models/src/payout_attempt.rs @@ -1,3 +1,4 @@ +use common_utils::types::{UnifiedCode, UnifiedMessage}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{self, Deserialize, Serialize}; use time::PrimitiveDateTime; @@ -30,6 +31,8 @@ pub struct PayoutAttempt { pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, + pub unified_code: Option<UnifiedCode>, + pub unified_message: Option<UnifiedMessage>, } #[derive( @@ -66,6 +69,8 @@ pub struct PayoutAttemptNew { pub profile_id: common_utils::id_type::ProfileId, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, + pub unified_code: Option<UnifiedCode>, + pub unified_message: Option<UnifiedMessage>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -76,6 +81,8 @@ pub enum PayoutAttemptUpdate { error_message: Option<String>, error_code: Option<String>, is_eligible: Option<bool>, + unified_code: Option<UnifiedCode>, + unified_message: Option<UnifiedMessage>, }, PayoutTokenUpdate { payout_token: String, @@ -110,6 +117,8 @@ pub struct PayoutAttemptUpdateInternal { pub address_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, + pub unified_code: Option<UnifiedCode>, + pub unified_message: Option<UnifiedMessage>, } impl Default for PayoutAttemptUpdateInternal { @@ -129,6 +138,8 @@ impl Default for PayoutAttemptUpdateInternal { last_modified_at: common_utils::date_time::now(), address_id: None, customer_id: None, + unified_code: None, + unified_message: None, } } } @@ -146,12 +157,16 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { error_message, error_code, is_eligible, + unified_code, + unified_message, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, + unified_code, + unified_message, ..Default::default() }, PayoutAttemptUpdate::BusinessUpdate { @@ -197,6 +212,8 @@ impl PayoutAttemptUpdate { address_id, customer_id, merchant_connector_id, + unified_code, + unified_message, } = self.into(); PayoutAttempt { payout_token: payout_token.or(source.payout_token), @@ -213,6 +230,8 @@ impl PayoutAttemptUpdate { address_id: address_id.or(source.address_id), customer_id: customer_id.or(source.customer_id), merchant_connector_id: merchant_connector_id.or(source.merchant_connector_id), + unified_code: unified_code.or(source.unified_code), + unified_message: unified_message.or(source.unified_message), ..source } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 6e8918f02a4..b98b19abb46 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1047,6 +1047,10 @@ diesel::table! { #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, + #[max_length = 255] + unified_code -> Nullable<Varchar>, + #[max_length = 1024] + unified_message -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index bd64c4bb002..2e007a14840 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1003,6 +1003,10 @@ diesel::table! { #[max_length = 32] merchant_connector_id -> Nullable<Varchar>, routing_info -> Nullable<Jsonb>, + #[max_length = 255] + unified_code -> Nullable<Varchar>, + #[max_length = 1024] + unified_message -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs index f747eb96c4a..9c516142844 100644 --- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs @@ -1,6 +1,9 @@ use api_models::enums::PayoutConnectors; use common_enums as storage_enums; -use common_utils::id_type; +use common_utils::{ + id_type, + types::{UnifiedCode, UnifiedMessage}, +}; use serde::{Deserialize, Serialize}; use storage_enums::MerchantStorageScheme; use time::PrimitiveDateTime; @@ -78,6 +81,8 @@ pub struct PayoutAttempt { pub profile_id: id_type::ProfileId, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, + pub unified_code: Option<UnifiedCode>, + pub unified_message: Option<UnifiedMessage>, } #[derive(Clone, Debug, PartialEq)] @@ -101,6 +106,8 @@ pub struct PayoutAttemptNew { pub profile_id: id_type::ProfileId, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub routing_info: Option<serde_json::Value>, + pub unified_code: Option<UnifiedCode>, + pub unified_message: Option<UnifiedMessage>, } #[derive(Debug, Clone)] @@ -111,6 +118,9 @@ pub enum PayoutAttemptUpdate { error_message: Option<String>, error_code: Option<String>, is_eligible: Option<bool>, + + unified_code: Option<UnifiedCode>, + unified_message: Option<UnifiedMessage>, }, PayoutTokenUpdate { payout_token: String, @@ -143,6 +153,8 @@ pub struct PayoutAttemptUpdateInternal { pub address_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + pub unified_code: Option<UnifiedCode>, + pub unified_message: Option<UnifiedMessage>, } impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { @@ -158,12 +170,16 @@ impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal { error_message, error_code, is_eligible, + unified_code, + unified_message, } => Self { connector_payout_id, status: Some(status), error_message, error_code, is_eligible, + unified_code, + unified_message, ..Default::default() }, PayoutAttemptUpdate::BusinessUpdate { diff --git a/crates/router/src/connector/adyenplatform/transformers/payouts.rs b/crates/router/src/connector/adyenplatform/transformers/payouts.rs index e0ec8f9e18b..09772fc87de 100644 --- a/crates/router/src/connector/adyenplatform/transformers/payouts.rs +++ b/crates/router/src/connector/adyenplatform/transformers/payouts.rs @@ -270,14 +270,20 @@ impl<F> TryFrom<types::PayoutsResponseRouterData<F, AdyenTransferResponse>> item: types::PayoutsResponseRouterData<F, AdyenTransferResponse>, ) -> Result<Self, Self::Error> { let response: AdyenTransferResponse = item.response; + let status = enums::PayoutStatus::from(response.status); + + let error_code = match status { + enums::PayoutStatus::Ineligible => Some(response.reason), + _ => None, + }; Ok(Self { response: Ok(types::PayoutsResponseData { - status: Some(enums::PayoutStatus::from(response.status)), + status: Some(status), connector_payout_id: Some(response.id), payout_eligible: None, should_add_next_step_to_process_tracker: false, - error_code: None, + error_code, error_message: None, }), ..item.data diff --git a/crates/router/src/core/generic_link/payout_link/status/script.js b/crates/router/src/core/generic_link/payout_link/status/script.js index 473af49b2e7..819d7e63c37 100644 --- a/crates/router/src/core/generic_link/payout_link/status/script.js +++ b/crates/router/src/core/generic_link/payout_link/status/script.js @@ -121,10 +121,10 @@ function renderStatusDetails(payoutDetails) { "{{i18n_ref_id_text}}": payoutDetails.payout_id, }; if (typeof payoutDetails.error_code === "string") { - // resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code; + resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code; } if (typeof payoutDetails.error_message === "string") { - // resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message; + resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message; } var resourceNode = document.createElement("div"); resourceNode.id = "resource-info-container"; diff --git a/crates/router/src/core/generic_link/payout_link/status/styles.css b/crates/router/src/core/generic_link/payout_link/status/styles.css index a10bfe7e3c0..11c6e68dc41 100644 --- a/crates/router/src/core/generic_link/payout_link/status/styles.css +++ b/crates/router/src/core/generic_link/payout_link/status/styles.css @@ -80,11 +80,12 @@ body { #resource-info-container { width: 100%; border-top: 1px solid rgb(231, 234, 241); - padding: 20px 10px; + padding: 20px 0; } #resource-info { display: flex; align-items: center; + margin: 0 2.5rem; } #info-key { text-align: right; diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index a153d071088..b175c8b7c03 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -17,7 +17,10 @@ use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use super::errors::{RouterResponse, StorageErrorExt}; use crate::{ configs::settings::{PaymentMethodFilterKey, PaymentMethodFilters}, - core::{payments::helpers, payouts::validator}, + core::{ + payments::helpers as payment_helpers, + payouts::{helpers as payout_helpers, validator}, + }, errors, routes::{app::StorageInterface, SessionState}, services, @@ -271,6 +274,14 @@ pub async fn initiate_payout_link( // Send back status page (_, link_utils::PayoutLinkStatus::Submitted) => { + let translated_unified_message = + payout_helpers::get_translated_unified_code_and_message( + &state, + payout_attempt.unified_code.as_ref(), + payout_attempt.unified_message.as_ref(), + &locale, + ) + .await?; let js_data = payouts::PayoutLinkStatusDetails { payout_link_id: payout_link.link_id, payout_id: payout_link.primary_reference, @@ -284,8 +295,8 @@ pub async fn initiate_payout_link( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to parse payout status link's return URL")?, status: payout.status, - error_code: payout_attempt.error_code, - error_message: payout_attempt.error_message, + error_code: payout_attempt.unified_code, + error_message: translated_unified_message, ui_config: ui_config_data, test_mode: link_data.test_mode.unwrap_or(false), }; @@ -338,7 +349,7 @@ pub async fn filter_payout_methods( .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; // Filter MCAs based on profile_id and connector_type - let filtered_mcas = helpers::filter_mca_based_on_profile_and_connector_type( + let filtered_mcas = payment_helpers::filter_mca_based_on_profile_and_connector_type( all_mcas, &payout.profile_id, common_enums::ConnectorType::PayoutProcessor, diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 85d5b78521f..d0c0b2d3cde 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -16,7 +16,7 @@ use common_utils::{ ext_traits::{AsyncExt, ValueExt}, id_type::CustomerId, link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus}, - types::MinorUnit, + types::{MinorUnit, UnifiedCode, UnifiedMessage}, }; use diesel_models::{ enums as storage_enums, @@ -71,6 +71,7 @@ pub struct PayoutData { pub profile_id: common_utils::id_type::ProfileId, pub should_terminate: bool, pub payout_link: Option<PayoutLink>, + pub current_locale: String, } // ********************************************** CORE FLOWS ********************************************** @@ -358,7 +359,7 @@ pub async fn payouts_create_core( .await? }; - response_handler(&merchant_account, &payout_data).await + response_handler(&state, &merchant_account, &payout_data).await } #[instrument(skip_all)] @@ -367,6 +368,7 @@ pub async fn payouts_confirm_core( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutCreateRequest, + locale: &str, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, @@ -374,6 +376,7 @@ pub async fn payouts_confirm_core( None, &key_store, &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), + locale, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); @@ -429,7 +432,7 @@ pub async fn payouts_confirm_core( ) .await?; - response_handler(&merchant_account, &payout_data).await + response_handler(&state, &merchant_account, &payout_data).await } pub async fn payouts_update_core( @@ -437,6 +440,7 @@ pub async fn payouts_update_core( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutCreateRequest, + locale: &str, ) -> RouterResponse<payouts::PayoutCreateResponse> { let payout_id = req.payout_id.clone().get_required_value("payout_id")?; let mut payout_data = make_payout_data( @@ -445,6 +449,7 @@ pub async fn payouts_update_core( None, &key_store, &payouts::PayoutRequest::PayoutCreateRequest(req.to_owned()), + locale, ) .await?; @@ -509,7 +514,7 @@ pub async fn payouts_update_core( .await?; } - response_handler(&merchant_account, &payout_data).await + response_handler(&state, &merchant_account, &payout_data).await } #[instrument(skip_all)] @@ -519,6 +524,7 @@ pub async fn payouts_retrieve_core( profile_id: Option<common_utils::id_type::ProfileId>, key_store: domain::MerchantKeyStore, req: payouts::PayoutRetrieveRequest, + locale: &str, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, @@ -526,6 +532,7 @@ pub async fn payouts_retrieve_core( profile_id, &key_store, &payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()), + locale, ) .await?; let payout_attempt = payout_data.payout_attempt.to_owned(); @@ -553,7 +560,7 @@ pub async fn payouts_retrieve_core( .await?; } - response_handler(&merchant_account, &payout_data).await + response_handler(&state, &merchant_account, &payout_data).await } #[instrument(skip_all)] @@ -562,6 +569,7 @@ pub async fn payouts_cancel_core( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutActionRequest, + locale: &str, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, @@ -569,6 +577,7 @@ pub async fn payouts_cancel_core( None, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), + locale, ) .await?; @@ -593,6 +602,8 @@ pub async fn payouts_cancel_core( error_message: Some("Cancelled by user".to_string()), error_code: None, is_eligible: None, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = state .store @@ -643,7 +654,7 @@ pub async fn payouts_cancel_core( .attach_printable("Payout cancellation failed for given Payout request")?; } - response_handler(&merchant_account, &payout_data).await + response_handler(&state, &merchant_account, &payout_data).await } #[instrument(skip_all)] @@ -652,6 +663,7 @@ pub async fn payouts_fulfill_core( merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: payouts::PayoutActionRequest, + locale: &str, ) -> RouterResponse<payouts::PayoutCreateResponse> { let mut payout_data = make_payout_data( &state, @@ -659,6 +671,7 @@ pub async fn payouts_fulfill_core( None, &key_store, &payouts::PayoutRequest::PayoutActionRequest(req.to_owned()), + locale, ) .await?; @@ -735,7 +748,7 @@ pub async fn payouts_fulfill_core( })); } - response_handler(&merchant_account, &payout_data).await + response_handler(&state, &merchant_account, &payout_data).await } #[cfg(all(feature = "olap", feature = "v2", feature = "customer_v2"))] @@ -745,6 +758,7 @@ pub async fn payouts_list_core( _profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, _key_store: domain::MerchantKeyStore, _constraints: payouts::PayoutListConstraints, + _locale: &str, ) -> RouterResponse<payouts::PayoutListResponse> { todo!() } @@ -760,6 +774,7 @@ pub async fn payouts_list_core( profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, key_store: domain::MerchantKeyStore, constraints: payouts::PayoutListConstraints, + _locale: &str, ) -> RouterResponse<payouts::PayoutListResponse> { validator::validate_payout_list_request(&constraints)?; let merchant_id = merchant_account.get_id(); @@ -878,6 +893,7 @@ pub async fn payouts_filtered_list_core( profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, key_store: domain::MerchantKeyStore, filters: payouts::PayoutListFilterConstraints, + _locale: &str, ) -> RouterResponse<payouts::PayoutListResponse> { let limit = &filters.limit; validator::validate_payout_list_request_for_joins(*limit)?; @@ -981,6 +997,7 @@ pub async fn payouts_list_available_filters_core( merchant_account: domain::MerchantAccount, profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: api::TimeRange, + _locale: &str, ) -> RouterResponse<api::PayoutListFilters> { let db = state.store.as_ref(); let payouts = db @@ -1293,6 +1310,8 @@ pub async fn create_recipient( error_code: None, error_message: None, is_eligible: recipient_create_data.payout_eligible, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1406,6 +1425,8 @@ pub async fn check_payout_eligibility( error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1437,12 +1458,34 @@ pub async fn check_payout_eligibility( } Err(err) => { let status = storage_enums::PayoutStatus::Failed; + let (error_code, error_message) = (Some(err.code), Some(err.message)); + let (unified_code, unified_message) = helpers::get_gsm_record( + state, + error_code.clone(), + error_message.clone(), + payout_data.payout_attempt.connector.clone(), + consts::PAYOUT_FLOW_STR, + ) + .await + .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, - error_code: Some(err.code), - error_message: Some(err.message), + error_code, + error_message, is_eligible: Some(false), + unified_code: unified_code + .map(UnifiedCode::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_code", + })?, + unified_message: unified_message + .map(UnifiedMessage::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })?, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1497,6 +1540,8 @@ pub async fn complete_create_payout( error_code: None, error_message: None, is_eligible: None, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1591,6 +1636,8 @@ pub async fn create_payout( error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1622,12 +1669,34 @@ pub async fn create_payout( } Err(err) => { let status = storage_enums::PayoutStatus::Failed; + let (error_code, error_message) = (Some(err.code), Some(err.message)); + let (unified_code, unified_message) = helpers::get_gsm_record( + state, + error_code.clone(), + error_message.clone(), + payout_data.payout_attempt.connector.clone(), + consts::PAYOUT_FLOW_STR, + ) + .await + .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, - error_code: Some(err.code), - error_message: Some(err.message), + error_code, + error_message, is_eligible: None, + unified_code: unified_code + .map(UnifiedCode::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_code", + })?, + unified_message: unified_message + .map(UnifiedMessage::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })?, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1774,12 +1843,37 @@ pub async fn update_retrieve_payout_tracker<F, T>( .unwrap_or(payout_attempt.status.to_owned()); let updated_payout_attempt = if helpers::is_payout_err_state(status) { + let (error_code, error_message) = ( + payout_response_data.error_code.clone(), + payout_response_data.error_message.clone(), + ); + let (unified_code, unified_message) = helpers::get_gsm_record( + state, + error_code.clone(), + error_message.clone(), + payout_data.payout_attempt.connector.clone(), + consts::PAYOUT_FLOW_STR, + ) + .await + .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_response_data.connector_payout_id.clone(), status, - error_code: payout_response_data.error_code.clone(), - error_message: payout_response_data.error_message.clone(), + error_code, + error_message, is_eligible: payout_response_data.payout_eligible, + unified_code: unified_code + .map(UnifiedCode::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_code", + })?, + unified_message: unified_message + .map(UnifiedMessage::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })?, } } else { storage::PayoutAttemptUpdate::StatusUpdate { @@ -1788,6 +1882,8 @@ pub async fn update_retrieve_payout_tracker<F, T>( error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, + unified_code: None, + unified_message: None, } }; @@ -1886,6 +1982,8 @@ pub async fn create_recipient_disburse_account( error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1899,12 +1997,34 @@ pub async fn create_recipient_disburse_account( .attach_printable("Error updating payout_attempt in db")?; } Err(err) => { + let (error_code, error_message) = (Some(err.code), Some(err.message)); + let (unified_code, unified_message) = helpers::get_gsm_record( + state, + error_code.clone(), + error_message.clone(), + payout_data.payout_attempt.connector.clone(), + consts::PAYOUT_FLOW_STR, + ) + .await + .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status: storage_enums::PayoutStatus::Failed, - error_code: Some(err.code), - error_message: Some(err.message), + error_code, + error_message, is_eligible: None, + unified_code: unified_code + .map(UnifiedCode::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_code", + })?, + unified_message: unified_message + .map(UnifiedMessage::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })?, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1964,6 +2084,8 @@ pub async fn cancel_payout( error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -1988,12 +2110,34 @@ pub async fn cancel_payout( } Err(err) => { let status = storage_enums::PayoutStatus::Failed; + let (error_code, error_message) = (Some(err.code), Some(err.message)); + let (unified_code, unified_message) = helpers::get_gsm_record( + state, + error_code.clone(), + error_message.clone(), + payout_data.payout_attempt.connector.clone(), + consts::PAYOUT_FLOW_STR, + ) + .await + .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, - error_code: Some(err.code), - error_message: Some(err.message), + error_code, + error_message, is_eligible: None, + unified_code: unified_code + .map(UnifiedCode::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_code", + })?, + unified_message: unified_message + .map(UnifiedMessage::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })?, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -2075,6 +2219,8 @@ pub async fn fulfill_payout( error_code: None, error_message: None, is_eligible: payout_response_data.payout_eligible, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -2131,12 +2277,34 @@ pub async fn fulfill_payout( } Err(err) => { let status = storage_enums::PayoutStatus::Failed; + let (error_code, error_message) = (Some(err.code), Some(err.message)); + let (unified_code, unified_message) = helpers::get_gsm_record( + state, + error_code.clone(), + error_message.clone(), + payout_data.payout_attempt.connector.clone(), + consts::PAYOUT_FLOW_STR, + ) + .await + .map_or((None, None), |gsm| (gsm.unified_code, gsm.unified_message)); let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate { connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(), status, - error_code: Some(err.code), - error_message: Some(err.message), + error_code, + error_message, is_eligible: None, + unified_code: unified_code + .map(UnifiedCode::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_code", + })?, + unified_message: unified_message + .map(UnifiedMessage::try_from) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })?, }; payout_data.payout_attempt = db .update_payout_attempt( @@ -2165,6 +2333,7 @@ pub async fn fulfill_payout( } pub async fn response_handler( + state: &SessionState, merchant_account: &domain::MerchantAccount, payout_data: &PayoutData, ) -> RouterResponse<payouts::PayoutCreateResponse> { @@ -2176,12 +2345,20 @@ pub async fn response_handler( let customer_id = payouts.customer_id; let billing = billing_address.as_ref().map(From::from); + let translated_unified_message = helpers::get_translated_unified_code_and_message( + state, + payout_attempt.unified_code.as_ref(), + payout_attempt.unified_message.as_ref(), + &payout_data.current_locale, + ) + .await?; + let response = api::PayoutCreateResponse { payout_id: payouts.payout_id.to_owned(), merchant_id: merchant_account.get_id().to_owned(), amount: payouts.amount, currency: payouts.destination_currency.to_owned(), - connector: payout_attempt.connector.to_owned(), + connector: payout_attempt.connector, payout_type: payouts.payout_type.to_owned(), billing, auto_fulfill: payouts.auto_fulfill, @@ -2212,6 +2389,8 @@ pub async fn response_handler( connector_transaction_id: payout_attempt.connector_payout_id, priority: payouts.priority, attempts: None, + unified_code: payout_attempt.unified_code, + unified_message: translated_unified_message, payout_link: payout_link .map(|payout_link| { url::Url::parse(payout_link.url.peek()).map(|link| PayoutLinkResponse { @@ -2389,6 +2568,8 @@ pub async fn payout_create_db_entries( last_modified_at: common_utils::date_time::now(), merchant_connector_id: None, routing_info: None, + unified_code: None, + unified_message: None, }; let payout_attempt = db .insert_payout_attempt( @@ -2418,6 +2599,7 @@ pub async fn payout_create_db_entries( should_terminate: false, profile_id: profile_id.to_owned(), payout_link, + current_locale: locale.to_string(), }) } @@ -2428,6 +2610,7 @@ pub async fn make_payout_data( _auth_profile_id: Option<common_utils::id_type::ProfileId>, _key_store: &domain::MerchantKeyStore, _req: &payouts::PayoutRequest, + locale: &str, ) -> RouterResult<PayoutData> { todo!() } @@ -2439,6 +2622,7 @@ pub async fn make_payout_data( auth_profile_id: Option<common_utils::id_type::ProfileId>, key_store: &domain::MerchantKeyStore, req: &payouts::PayoutRequest, + locale: &str, ) -> RouterResult<PayoutData> { let db = &*state.store; let merchant_id = merchant_account.get_id(); @@ -2594,6 +2778,7 @@ pub async fn make_payout_data( should_terminate: false, profile_id, payout_link, + current_locale: locale.to_string(), }) } diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 11cb0c11761..b6f685ee2a1 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -8,7 +8,7 @@ use common_utils::{ fp_utils, id_type, type_name, types::{ keymanager::{Identifier, KeyManagerState}, - MinorUnit, + MinorUnit, UnifiedCode, UnifiedMessage, }, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] @@ -944,12 +944,13 @@ pub async fn get_gsm_record( error_code: Option<String>, error_message: Option<String>, connector_name: Option<String>, - flow: String, + flow: &str, ) -> Option<storage::gsm::GatewayStatusMap> { + let connector_name = connector_name.unwrap_or_default(); let get_gsm = || async { state.store.find_gsm_rule( - connector_name.clone().unwrap_or_default(), - flow.clone(), + connector_name.clone(), + flow.to_string(), "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(), @@ -959,7 +960,7 @@ pub async fn get_gsm_record( if err.current_context().is_db_not_found() { logger::warn!( "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}", - connector_name.unwrap_or_default(), + connector_name, flow, error_code, error_message @@ -1265,3 +1266,29 @@ pub(super) fn get_customer_details_from_request( phone_country_code: customer_phone_code, } } + +pub async fn get_translated_unified_code_and_message( + state: &SessionState, + unified_code: Option<&UnifiedCode>, + unified_message: Option<&UnifiedMessage>, + locale: &str, +) -> CustomResult<Option<UnifiedMessage>, errors::ApiErrorResponse> { + Ok(unified_code + .zip(unified_message) + .async_and_then(|(code, message)| async { + payment_helpers::get_unified_translation( + state, + code.0.clone(), + message.0.clone(), + locale.to_string(), + ) + .await + .map(UnifiedMessage::try_from) + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "unified_message", + })? + .or_else(|| unified_message.cloned())) +} diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs index e190e627bdf..00c25b0d67e 100644 --- a/crates/router/src/core/payouts/retry.rs +++ b/crates/router/src/core/payouts/retry.rs @@ -190,12 +190,15 @@ pub async fn get_gsm( let error_code = payout_data.payout_attempt.error_code.to_owned(); let error_message = payout_data.payout_attempt.error_message.to_owned(); let connector_name = Some(original_connector_data.connector_name.to_string()); - let flow = "payout_flow".to_string(); - Ok( - payouts::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow) - .await, + Ok(payouts::helpers::get_gsm_record( + state, + error_code, + error_message, + connector_name, + common_utils::consts::PAYOUT_FLOW_STR, ) + .await) } #[instrument(skip_all)] @@ -295,6 +298,8 @@ pub async fn modify_trackers( last_modified_at: common_utils::date_time::now(), merchant_connector_id: None, routing_info: None, + unified_code: None, + unified_message: None, }; payout_data.payout_attempt = db .insert_payout_attempt( diff --git a/crates/router/src/core/payouts/transformers.rs b/crates/router/src/core/payouts/transformers.rs index ed17eb71afa..080cf775b24 100644 --- a/crates/router/src/core/payouts/transformers.rs +++ b/crates/router/src/core/payouts/transformers.rs @@ -98,10 +98,12 @@ impl created: Some(payout.created_at), connector_transaction_id: attempt.connector_transaction_id.clone(), priority: payout.priority, - attempts: Some(vec![attempt]), billing: address, client_secret: None, payout_link: None, + unified_code: attempt.unified_code.clone(), + unified_message: attempt.unified_message.clone(), + attempts: Some(vec![attempt]), email: customer .as_ref() .and_then(|customer| customer.email.clone()), diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 20b07d8669f..dd7ccd87f38 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -689,6 +689,8 @@ async fn payouts_incoming_webhook_flow( error_message: None, error_code: None, is_eligible: payout_attempt.is_eligible, + unified_code: None, + unified_message: None, }; let action_req = @@ -696,9 +698,15 @@ async fn payouts_incoming_webhook_flow( payout_id: payouts.payout_id.clone(), }); - let payout_data = - payouts::make_payout_data(&state, &merchant_account, None, &key_store, &action_req) - .await?; + let payout_data = payouts::make_payout_data( + &state, + &merchant_account, + None, + &key_store, + &action_req, + common_utils::consts::DEFAULT_LOCALE, + ) + .await?; let updated_payout_attempt = db .update_payout_attempt( @@ -721,7 +729,7 @@ async fn payouts_incoming_webhook_flow( // If event is NOT an UnsupportedEvent, trigger Outgoing Webhook if let Some(outgoing_event_type) = event_type { let router_response = - payouts::response_handler(&merchant_account, &payout_data).await?; + payouts::response_handler(&state, &merchant_account, &payout_data).await?; let payout_create_response: payout_models::PayoutCreateResponse = match router_response { diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index 50c18d71f2a..1b614330ebd 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -1,5 +1,6 @@ use actix_web::{ body::{BoxBody, MessageBody}, + http::header::HeaderMap, web, HttpRequest, HttpResponse, Responder, }; use common_enums::EntityType; @@ -20,6 +21,14 @@ use crate::{ types::api::payouts as payout_types, }; +fn get_locale_from_header(headers: &HeaderMap) -> String { + get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers) + .ok() + .flatten() + .map(|val| val.to_string()) + .unwrap_or(consts::DEFAULT_LOCALE.to_string()) +} + /// Payouts - Create #[instrument(skip_all, fields(flow = ?Flow::PayoutsCreate))] pub async fn payouts_create( @@ -28,11 +37,8 @@ pub async fn payouts_create( json_payload: web::Json<payout_types::PayoutCreateRequest>, ) -> HttpResponse { let flow = Flow::PayoutsCreate; - let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), req.headers()) - .ok() - .flatten() - .map(|val| val.to_string()) - .unwrap_or(consts::DEFAULT_LOCALE.to_string()); + let locale = get_locale_from_header(req.headers()); + Box::pin(api::server_wrap( flow, state, @@ -60,6 +66,8 @@ pub async fn payouts_retrieve( merchant_id: query_params.merchant_id.to_owned(), }; let flow = Flow::PayoutsRetrieve; + let locale = get_locale_from_header(req.headers()); + Box::pin(api::server_wrap( flow, state, @@ -72,6 +80,7 @@ pub async fn payouts_retrieve( auth.profile_id, auth.key_store, req, + &locale, ) }, auth::auth_type( @@ -95,6 +104,7 @@ pub async fn payouts_update( json_payload: web::Json<payout_types::PayoutCreateRequest>, ) -> HttpResponse { let flow = Flow::PayoutsUpdate; + let locale = get_locale_from_header(req.headers()); let payout_id = path.into_inner(); let mut payout_update_payload = json_payload.into_inner(); payout_update_payload.payout_id = Some(payout_id); @@ -104,7 +114,7 @@ pub async fn payouts_update( &req, payout_update_payload, |state, auth, req, _| { - payouts_update_core(state, auth.merchant_account, auth.key_store, req) + payouts_update_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, @@ -130,6 +140,7 @@ pub async fn payouts_confirm( Ok(auth) => auth, Err(e) => return api::log_and_return_error_response(e), }; + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -137,7 +148,7 @@ pub async fn payouts_confirm( &req, payload, |state, auth, req, _| { - payouts_confirm_core(state, auth.merchant_account, auth.key_store, req) + payouts_confirm_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &*auth_type, api_locking::LockAction::NotApplicable, @@ -156,6 +167,7 @@ pub async fn payouts_cancel( let flow = Flow::PayoutsCancel; let mut payload = json_payload.into_inner(); payload.payout_id = path.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -163,7 +175,7 @@ pub async fn payouts_cancel( &req, payload, |state, auth, req, _| { - payouts_cancel_core(state, auth.merchant_account, auth.key_store, req) + payouts_cancel_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, @@ -181,6 +193,7 @@ pub async fn payouts_fulfill( let flow = Flow::PayoutsFulfill; let mut payload = json_payload.into_inner(); payload.payout_id = path.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -188,7 +201,7 @@ pub async fn payouts_fulfill( &req, payload, |state, auth, req, _| { - payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req) + payouts_fulfill_core(state, auth.merchant_account, auth.key_store, req, &locale) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, @@ -206,6 +219,7 @@ pub async fn payouts_list( ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -213,7 +227,14 @@ pub async fn payouts_list( &req, payload, |state, auth, req, _| { - payouts_list_core(state, auth.merchant_account, None, auth.key_store, req) + payouts_list_core( + state, + auth.merchant_account, + None, + auth.key_store, + req, + &locale, + ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), @@ -238,6 +259,7 @@ pub async fn payouts_list_profile( ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -251,6 +273,7 @@ pub async fn payouts_list_profile( auth.profile_id.map(|profile_id| vec![profile_id]), auth.key_store, req, + &locale, ) }, auth::auth_type( @@ -276,6 +299,7 @@ pub async fn payouts_list_by_filter( ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -283,7 +307,14 @@ pub async fn payouts_list_by_filter( &req, payload, |state, auth, req, _| { - payouts_filtered_list_core(state, auth.merchant_account, None, auth.key_store, req) + payouts_filtered_list_core( + state, + auth.merchant_account, + None, + auth.key_store, + req, + &locale, + ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), @@ -308,6 +339,7 @@ pub async fn payouts_list_by_filter_profile( ) -> HttpResponse { let flow = Flow::PayoutsList; let payload = json_payload.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -321,6 +353,7 @@ pub async fn payouts_list_by_filter_profile( auth.profile_id.map(|profile_id| vec![profile_id]), auth.key_store, req, + &locale, ) }, auth::auth_type( @@ -346,6 +379,7 @@ pub async fn payouts_list_available_filters_for_merchant( ) -> HttpResponse { let flow = Flow::PayoutsFilter; let payload = json_payload.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -353,7 +387,7 @@ pub async fn payouts_list_available_filters_for_merchant( &req, payload, |state, auth, req, _| { - payouts_list_available_filters_core(state, auth.merchant_account, None, req) + payouts_list_available_filters_core(state, auth.merchant_account, None, req, &locale) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), @@ -378,6 +412,7 @@ pub async fn payouts_list_available_filters_for_profile( ) -> HttpResponse { let flow = Flow::PayoutsFilter; let payload = json_payload.into_inner(); + let locale = get_locale_from_header(req.headers()); Box::pin(api::server_wrap( flow, @@ -390,6 +425,7 @@ pub async fn payouts_list_available_filters_for_profile( auth.merchant_account, auth.profile_id.map(|profile_id| vec![profile_id]), req, + &locale, ) }, auth::auth_type( diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rs index fa481fdb9d6..b29a15725b0 100644 --- a/crates/router/src/workflows/attach_payout_account_workflow.rs +++ b/crates/router/src/workflows/attach_payout_account_workflow.rs @@ -1,4 +1,7 @@ -use common_utils::ext_traits::{OptionExt, ValueExt}; +use common_utils::{ + consts::DEFAULT_LOCALE, + ext_traits::{OptionExt, ValueExt}, +}; use scheduler::{ consumer::{self, workflows::ProcessTrackerWorkflow}, errors, @@ -46,8 +49,15 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow { let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data); - let mut payout_data = - payouts::make_payout_data(state, &merchant_account, None, &key_store, &request).await?; + let mut payout_data = payouts::make_payout_data( + state, + &merchant_account, + None, + &key_store, + &request, + DEFAULT_LOCALE, + ) + .await?; payouts::payouts_core( state, diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index 138b1477d6a..e29277caf4e 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -5,7 +5,10 @@ use api_models::{ webhook_events::OutgoingWebhookRequestContent, webhooks::{OutgoingWebhook, OutgoingWebhookContent}, }; -use common_utils::ext_traits::{StringExt, ValueExt}; +use common_utils::{ + consts::DEFAULT_LOCALE, + ext_traits::{StringExt, ValueExt}, +}; use diesel_models::process_tracker::business_status; use error_stack::ResultExt; use masking::PeekInterface; @@ -521,12 +524,18 @@ async fn get_outgoing_webhook_content_and_event_type( payout_models::PayoutActionRequest { payout_id }, ); - let payout_data = - payouts::make_payout_data(&state, &merchant_account, None, &key_store, &request) - .await?; + let payout_data = payouts::make_payout_data( + &state, + &merchant_account, + None, + &key_store, + &request, + DEFAULT_LOCALE, + ) + .await?; let router_response = - payouts::response_handler(&merchant_account, &payout_data).await?; + payouts::response_handler(&state, &merchant_account, &payout_data).await?; let payout_create_response: payout_models::PayoutCreateResponse = match router_response { diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs index 697b5d91c93..e5bfe29af54 100644 --- a/crates/storage_impl/src/payouts/payout_attempt.rs +++ b/crates/storage_impl/src/payouts/payout_attempt.rs @@ -84,6 +84,8 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> { profile_id: new_payout_attempt.profile_id.clone(), merchant_connector_id: new_payout_attempt.merchant_connector_id.clone(), routing_info: new_payout_attempt.routing_info.clone(), + unified_code: new_payout_attempt.unified_code.clone(), + unified_message: new_payout_attempt.unified_message.clone(), }; let redis_entry = kv::TypedSql { @@ -525,6 +527,8 @@ impl DataModelExt for PayoutAttempt { profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, + unified_code: self.unified_code, + unified_message: self.unified_message, } } @@ -549,6 +553,8 @@ impl DataModelExt for PayoutAttempt { profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, + unified_code: storage_model.unified_code, + unified_message: storage_model.unified_message, } } } @@ -576,6 +582,8 @@ impl DataModelExt for PayoutAttemptNew { profile_id: self.profile_id, merchant_connector_id: self.merchant_connector_id, routing_info: self.routing_info, + unified_code: self.unified_code, + unified_message: self.unified_message, } } @@ -600,6 +608,8 @@ impl DataModelExt for PayoutAttemptNew { profile_id: storage_model.profile_id, merchant_connector_id: storage_model.merchant_connector_id, routing_info: storage_model.routing_info, + unified_code: storage_model.unified_code, + unified_message: storage_model.unified_message, } } } @@ -613,12 +623,16 @@ impl DataModelExt for PayoutAttemptUpdate { error_message, error_code, is_eligible, + unified_code, + unified_message, } => DieselPayoutAttemptUpdate::StatusUpdate { connector_payout_id, status, error_message, error_code, is_eligible, + unified_code, + unified_message, }, Self::PayoutTokenUpdate { payout_token } => { DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token } diff --git a/migrations/2024-09-03-053218_add_unified_code_message_to_payout/down.sql b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/down.sql new file mode 100644 index 00000000000..b785cad78fb --- /dev/null +++ b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/down.sql @@ -0,0 +1,3 @@ +ALTER TABLE payout_attempt +DROP COLUMN IF EXISTS unified_code, +DROP COLUMN IF EXISTS unified_message; \ No newline at end of file diff --git a/migrations/2024-09-03-053218_add_unified_code_message_to_payout/up.sql b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/up.sql new file mode 100644 index 00000000000..b4ccfb8e525 --- /dev/null +++ b/migrations/2024-09-03-053218_add_unified_code_message_to_payout/up.sql @@ -0,0 +1,3 @@ +ALTER TABLE payout_attempt +ADD COLUMN IF NOT EXISTS unified_code VARCHAR(255) DEFAULT NULL, +ADD COLUMN IF NOT EXISTS unified_message VARCHAR(1024) DEFAULT NULL; \ No newline at end of file
2024-09-05T09:45:42Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This adds `unified_code` and `unified_message` in the payout's API response. These values are looked up in the DB and populated in the API response. `unified_code` and `unified_message` are then used to fetch the translated message string from DB (if present). This is finally returned in the payouts API response and / or embedded in the payout link. ### Additional Changes - [x] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? **Pre-requisites** 1. Ensure payout unified code and messages are inserted in `gateway_status_map` table 2. Ensure the translated messages for these unified code <> messages are inserted in `unified_translations` table <details> <summary>1. Create an invalid payout txn</summary> cURL curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' \ --data '{ "amount": 1, "currency": "EUR", "customer_id": "cus_BF9z0OVpYLybZlkPLdeP", "description": "Its my first payout request", "payout_type": "bank", "priority": "instant", "payout_method_data": { "bank": { "iban": "ES6614657716831375381753" } }, "connector": [ "adyenplatform" ], "billing": { "address": { "line1": "Raadhuisplein", "line2": "92", "city": "Hoogeveen", "state": "FL", "zip": "7901 BW", "country": "DE", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" } }, "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "confirm": true, "auto_fulfill": true, "profile_id": "pro_9GxLZ4gAqCxlLOnAndXp" }' Response with unified code and message { "payout_id": "d0ed3417-5f1f-46ad-8535-f02f2a8c96cf", "merchant_id": "merchant_1726461298", "amount": 1, "currency": "EUR", "connector": "adyenplatform", "payout_type": "bank", "billing": { "address": { "city": "Hoogeveen", "country": "DE", "line1": "Raadhuisplein", "line2": "92", "line3": null, "zip": "7901 BW", "state": "FL", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" }, "email": null }, "auto_fulfill": true, "customer_id": "cus_BF9z0OVpYLybZlkPLdeP", "customer": { "id": "cus_BF9z0OVpYLybZlkPLdeP", "name": "John Doe", "email": "guest@example.com", "phone": "6168205366", "phone_country_code": "+1" }, "client_secret": "payout_d0ed3417-5f1f-46ad-8535-f02f2a8c96cf_secret_xlTRh9qeyr6Y5tb7flCn", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN", "status": "failed", "error_message": "Invalid transfer information provided", "error_code": "30_081", "profile_id": "pro_9GxLZ4gAqCxlLOnAndXp", "created": "2024-09-16T05:37:00.616Z", "connector_transaction_id": null, "priority": "instant", "payout_link": null, "email": "guest@example.com", "name": "John Doe", "phone": "6168205366", "phone_country_code": "+1", "unified_code": "UE_1200", "unified_message": "Invalid recipient details" } </details> <details> <summary>2. Create an invalid payout txn with language in the header</summary> cURL curl --location 'http://localhost:8080/payouts/create' \ --header 'Accept-Language: fr' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' \ --data '{ "amount": 1, "currency": "EUR", "customer_id": "cus_BF9z0OVpYLybZlkPLdeP", "description": "Its my first payout request", "payout_type": "bank", "priority": "instant", "payout_method_data": { "bank": { "iban": "ES6614657716831375381753" } }, "connector": [ "adyenplatform" ], "billing": { "address": { "line1": "Raadhuisplein", "line2": "92", "city": "Hoogeveen", "state": "FL", "zip": "7901 BW", "country": "DE", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" } }, "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "confirm": true, "auto_fulfill": true, "profile_id": "pro_9GxLZ4gAqCxlLOnAndXp" }' Response { "payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56", "merchant_id": "merchant_1726461298", "amount": 1, "currency": "EUR", "connector": "adyenplatform", "payout_type": "bank", "billing": { "address": { "city": "Hoogeveen", "country": "DE", "line1": "Raadhuisplein", "line2": "92", "line3": null, "zip": "7901 BW", "state": "FL", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" }, "email": null }, "auto_fulfill": true, "customer_id": "cus_BF9z0OVpYLybZlkPLdeP", "customer": { "id": "cus_BF9z0OVpYLybZlkPLdeP", "name": "John Doe", "email": "guest@example.com", "phone": "6168205366", "phone_country_code": "+1" }, "client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN", "status": "failed", "error_message": "Invalid transfer information provided", "error_code": "30_081", "profile_id": "pro_9GxLZ4gAqCxlLOnAndXp", "created": "2024-09-16T05:43:24.401Z", "connector_transaction_id": null, "priority": "instant", "payout_link": null, "email": "guest@example.com", "name": "John Doe", "phone": "6168205366", "phone_country_code": "+1", "unified_code": "UE_1200", "unified_message": "Détails du destinataire invalides" } </details> <details> <summary>3. List this payout in different languages</summary> cURL (ENGLISH) curl --location 'http://localhost:8080/payouts/3933b577-8551-4a3b-b3b0-688a1001fe56' \ --header 'Accept-Language: en' \ --header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' Response { "payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56", "merchant_id": "merchant_1726461298", "amount": 1, "currency": "EUR", "connector": "adyenplatform", "payout_type": "bank", "billing": { "address": { "city": "Hoogeveen", "country": "DE", "line1": "Raadhuisplein", "line2": "92", "line3": null, "zip": "7901 BW", "state": "FL", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" }, "email": null }, "auto_fulfill": true, "customer_id": "cus_BF9z0OVpYLybZlkPLdeP", "customer": { "id": "cus_BF9z0OVpYLybZlkPLdeP", "name": "John Doe", "email": "guest@example.com", "phone": "6168205366", "phone_country_code": "+1" }, "client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN", "status": "failed", "error_message": "Invalid transfer information provided", "error_code": "30_081", "profile_id": "pro_9GxLZ4gAqCxlLOnAndXp", "created": "2024-09-16T05:43:24.401Z", "connector_transaction_id": null, "priority": "instant", "payout_link": null, "email": "guest@example.com", "name": "John Doe", "phone": "6168205366", "phone_country_code": "+1", "unified_code": "UE_1200", "unified_message": "Invalid recipient details" } cURL (nl) curl --location 'http://localhost:8080/payouts/3933b577-8551-4a3b-b3b0-688a1001fe56' \ --header 'Accept-Language: nl' \ --header 'api-key: dev_wP9pQWRBOq8PZ96NtlANhOHCevdADP7kWCgoQ6FvHQsjXNeL7JTVlCy7RiVW88t9' Response { "payout_id": "3933b577-8551-4a3b-b3b0-688a1001fe56", "merchant_id": "merchant_1726461298", "amount": 1, "currency": "EUR", "connector": "adyenplatform", "payout_type": "bank", "billing": { "address": { "city": "Hoogeveen", "country": "DE", "line1": "Raadhuisplein", "line2": "92", "line3": null, "zip": "7901 BW", "state": "FL", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "0650242319", "country_code": "+31" }, "email": null }, "auto_fulfill": true, "customer_id": "cus_BF9z0OVpYLybZlkPLdeP", "customer": { "id": "cus_BF9z0OVpYLybZlkPLdeP", "name": "John Doe", "email": "guest@example.com", "phone": "6168205366", "phone_country_code": "+1" }, "client_secret": "payout_3933b577-8551-4a3b-b3b0-688a1001fe56_secret_Dtqie0KfQbmmBHdT1A8H", "return_url": null, "business_country": null, "business_label": null, "description": "Its my first payout request", "entity_type": "Individual", "recurring": true, "metadata": { "ref": "123" }, "merchant_connector_id": "mca_o9Pv2rZNURtL3mWcUGFN", "status": "failed", "error_message": "Invalid transfer information provided", "error_code": "30_081", "profile_id": "pro_9GxLZ4gAqCxlLOnAndXp", "created": "2024-09-16T05:43:24.401Z", "connector_transaction_id": null, "priority": "instant", "payout_link": null, "email": "guest@example.com", "name": "John Doe", "phone": "6168205366", "phone_country_code": "+1", "unified_code": "UE_1200", "unified_message": "Ongeldige ontvangersgegevens" } </details> <details> <summary>4. Submit invalid details in payout details, and open status page</summary> English ![image](https://github.com/user-attachments/assets/344fb32c-baaf-45e6-be1f-f3585bda428d) French ![image](https://github.com/user-attachments/assets/c7a15de2-d4e6-44c1-984f-16132e51c4ea) </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
2aa215440e0531e315e61ee30bbbc5a5685481b3
juspay/hyperswitch
juspay__hyperswitch-5816
Bug: feat(users): Add profile id in JWT and user_info Currently tokens doesn't have profile id. Backend should start sending it or else dashboard will not work at profile level.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 4674abf3976..7bb8409993d 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -1,6 +1,6 @@ use std::fmt::Debug; -use common_enums::{PermissionGroup, RoleScope, TokenPurpose}; +use common_enums::{EntityType, PermissionGroup, RoleScope, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; @@ -158,6 +158,8 @@ pub struct GetUserDetailsResponse { pub org_id: id_type::OrganizationId, pub is_two_factor_auth_setup: bool, pub recovery_codes_left: Option<usize>, + pub profile_id: id_type::ProfileId, + pub entity_type: EntityType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -185,7 +187,7 @@ pub struct GetUserRoleDetailsResponseV2 { pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>, pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, pub status: UserStatus, - pub entity_type: common_enums::EntityType, + pub entity_type: EntityType, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 828dfeb20f8..22aa80a459a 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -63,5 +63,5 @@ pub enum RoleCheckType { #[derive(Debug, serde::Serialize, Clone)] pub struct MinimalRoleInfo { pub role_id: String, - pub role_name: String, + pub role_name: Option<String>, } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 1d235dceaea..dac6027aa19 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -100,6 +100,14 @@ pub async fn get_user_details( ) -> UserResponse<user_api::GetUserDetailsResponse> { let user = user_from_token.get_user_from_db(&state).await?; let verification_days_left = utils::user::get_verification_days_left(&state, &user)?; + let role_info = roles::RoleInfo::from_role_id( + &state, + &user_from_token.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json( user_api::GetUserDetailsResponse { @@ -112,6 +120,10 @@ pub async fn get_user_details( org_id: user_from_token.org_id, is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set, recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()), + profile_id: user_from_token + .profile_id + .ok_or(UserErrors::JwtProfileIdMissing)?, + entity_type: role_info.get_entity_type(), }, )) } @@ -1185,13 +1197,12 @@ pub async fn switch_merchant_id( })? .organization_id; - let token = utils::user::generate_jwt_auth_token_with_attributes( + let token = utils::user::generate_jwt_auth_token_with_attributes_without_profile( &state, user_from_token.user_id, request.merchant_id.clone(), org_id.clone(), user_from_token.role_id.clone(), - None, ) .await?; @@ -2792,7 +2803,6 @@ pub async fn switch_org_for_user( .into()); } - let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id( &state, &user_from_token.role_id, @@ -2830,38 +2840,8 @@ pub async fn switch_org_for_user( "No user role found for the requested org_id".to_string(), ))?; - let merchant_id = utils::user_role::get_single_merchant_id(&state, &user_role).await?; - - let profile_id = if let Some(profile_id) = &user_role.profile_id { - profile_id.clone() - } else { - let merchant_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 - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to retrieve merchant key store by merchant_id")?; - - state - .store - .list_business_profile_by_merchant_id( - key_manager_state, - &merchant_key_store, - &merchant_id, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to list business profiles by merchant_id")? - .pop() - .ok_or(UserErrors::InternalServerError) - .attach_printable("No business profile found for the merchant_id")? - .get_id() - .to_owned() - }; + let (merchant_id, profile_id) = + utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?; let token = utils::user::generate_jwt_auth_token_with_attributes( &state, @@ -2869,7 +2849,7 @@ pub async fn switch_org_for_user( merchant_id.clone(), request.org_id.clone(), user_role.role_id.clone(), - Some(profile_id.clone()), + profile_id.clone(), ) .await?; @@ -3078,7 +3058,7 @@ pub async fn switch_merchant_for_user_in_org( merchant_id.clone(), org_id.clone(), role_id.clone(), - Some(profile_id), + profile_id, ) .await?; @@ -3183,7 +3163,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( user_from_token.merchant_id.clone(), user_from_token.org_id.clone(), role_id.clone(), - Some(profile_id), + profile_id, ) .await?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 8c955a09517..369ee97a02a 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -744,30 +744,6 @@ pub async fn list_users_in_lineage( .map(|user| (user.user_id.clone(), user.email)) .collect::<HashMap<_, _>>(); - let role_info_map = - futures::future::try_join_all(user_roles_set.iter().map(|user_role| async { - roles::RoleInfo::from_role_id( - &state, - &user_role.role_id, - &user_from_token.merchant_id, - &user_from_token.org_id, - ) - .await - .map(|role_info| { - ( - user_role.role_id.clone(), - user_role_api::role::MinimalRoleInfo { - role_id: user_role.role_id.clone(), - role_name: role_info.get_role_name().to_string(), - }, - ) - }) - })) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .collect::<HashMap<_, _>>(); - let user_role_map = user_roles_set .into_iter() .fold(HashMap::new(), |mut map, user_role| { @@ -787,13 +763,11 @@ pub async fn list_users_in_lineage( .ok_or(UserErrors::InternalServerError)?, roles: role_id_vec .into_iter() - .map(|role_id| { - role_info_map - .get(&role_id) - .cloned() - .ok_or(UserErrors::InternalServerError) + .map(|role_id| user_role_api::role::MinimalRoleInfo { + role_id, + role_name: None, }) - .collect::<Result<Vec<_>, _>>()?, + .collect(), }) }) .collect::<Result<Vec<_>, _>>()?, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 1a81c49d5a9..8c9cd1da0ab 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -348,7 +348,7 @@ pub async fn list_roles_at_entity_level( if check_type && role_info.get_entity_type() == req.entity_type { Some(role_api::MinimalRoleInfo { role_id: role_info.get_role_id().to_string(), - role_name: role_info.get_role_name().to_string(), + role_name: Some(role_info.get_role_name().to_string()), }) } else { None diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 36af30cd9fa..2a8e3563fb6 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -5,7 +5,7 @@ use api_models::{ }; use common_enums::EntityType; use common_utils::{ - crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name, + crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name, types::keymanager::Identifier, }; use diesel_models::{ @@ -28,7 +28,7 @@ use crate::{ consts, core::{ admin, - errors::{self, UserErrors, UserResult}, + errors::{UserErrors, UserResult}, }, db::{user_role::InsertUserRolePayload, GlobalStorageInterface}, routes::SessionState, @@ -867,22 +867,6 @@ impl UserFromStorage { self.0.email.clone() } - pub async fn get_role_from_db(&self, state: SessionState) -> UserResult<UserRole> { - state - .store - .find_user_role_by_user_id(&self.0.user_id, UserRoleVersion::V1) - .await - .change_context(UserErrors::InternalServerError) - } - - pub async fn get_roles_from_db(&self, state: &SessionState) -> UserResult<Vec<UserRole>> { - state - .store - .list_user_roles_by_user_id_and_version(&self.0.user_id, UserRoleVersion::V1) - .await - .change_context(UserErrors::InternalServerError) - } - #[cfg(feature = "email")] pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult<Option<i64>> { if self.0.is_verified { @@ -930,21 +914,6 @@ impl UserFromStorage { Ok(days_left_for_password_rotate.whole_days() < 0) } - pub async fn get_role_from_db_by_merchant_id( - &self, - state: &SessionState, - merchant_id: &id_type::MerchantId, - ) -> CustomResult<UserRole, errors::StorageError> { - state - .store - .find_user_role_by_user_id_merchant_id( - self.get_user_id(), - merchant_id, - UserRoleVersion::V1, - ) - .await - } - pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> { let master_key = state.store.get_master_key(); let key_manager_state = &state.into(); @@ -1253,7 +1222,7 @@ where } } - async fn insert_v1_and_v2_in_db_and_get_v1( + async fn insert_v1_and_v2_in_db_and_get_v2( state: &SessionState, v1_role: UserRoleNew, v2_role: UserRoleNew, @@ -1264,10 +1233,9 @@ where .await .change_context(UserErrors::InternalServerError)?; - // Returning v1 role so other code which was not migrated doesn't break inserted_roles .into_iter() - .find(|role| role.version == UserRoleVersion::V1) + .find(|role| role.version == UserRoleVersion::V2) .ok_or(report!(UserErrors::InternalServerError)) } } @@ -1323,7 +1291,7 @@ impl NewUserRole<OrganizationLevel> { entity_type: EntityType::Organization, }); - Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await + Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await } } @@ -1343,7 +1311,7 @@ impl NewUserRole<MerchantLevel> { entity_type: EntityType::Merchant, }); - Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await + Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await } } @@ -1366,7 +1334,7 @@ impl NewUserRole<InternalLevel> { entity_type: EntityType::Internal, }); - Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await + Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await } } diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index af9918af673..3fc05285ea8 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,8 +1,5 @@ use common_enums::TokenPurpose; -use diesel_models::{ - enums::{UserRoleVersion, UserStatus}, - user_role::UserRole, -}; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::{report, ResultExt}; use masking::Secret; @@ -67,10 +64,21 @@ impl SPTFlow { Self::ForceSetPassword => user .is_password_rotate_required(state) .map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)), - Self::MerchantSelect => user - .get_roles_from_db(state) + Self::MerchantSelect => Ok(state + .store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: user.get_user_id(), + org_id: None, + merchant_id: None, + profile_id: None, + entity_id: None, + version: None, + status: Some(UserStatus::Active), + limit: Some(1), + }) .await - .map(|roles| !roles.iter().any(|role| role.status == UserStatus::Active)), + .change_context(UserErrors::InternalServerError)? + .is_empty()), } } @@ -105,15 +113,17 @@ impl JWTFlow { Ok(true) } - pub async fn generate_jwt_without_profile( + pub async fn generate_jwt( self, state: &SessionState, next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { + let (merchant_id, profile_id) = + utils::user_role::get_single_merchant_id_and_profile_id(state, user_role).await?; auth::AuthToken::new_token( next_flow.user.get_user_id().to_string(), - utils::user_role::get_single_merchant_id(state, user_role).await?, + merchant_id, user_role.role_id.clone(), &state.conf, user_role @@ -121,7 +131,7 @@ impl JWTFlow { .clone() .ok_or(report!(UserErrors::InternalServerError)) .attach_printable("org_id not found")?, - None, + Some(profile_id), ) .await .map(|token| token.into()) @@ -296,7 +306,7 @@ impl NextFlow { merchant_id: None, profile_id: None, entity_id: None, - version: Some(UserRoleVersion::V1), + version: None, status: Some(UserStatus::Active), limit: Some(1), }) @@ -307,9 +317,7 @@ impl NextFlow { utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role) .await; - jwt_flow - .generate_jwt_without_profile(state, self, &user_role) - .await + jwt_flow.generate_jwt(state, self, &user_role).await } } } @@ -329,9 +337,7 @@ impl NextFlow { utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role) .await; - jwt_flow - .generate_jwt_without_profile(state, self, user_role) - .await + jwt_flow.generate_jwt(state, self, user_role).await } } } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index a1bd6972dab..3da24f2be7d 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -108,13 +108,25 @@ pub async fn generate_jwt_auth_token_without_profile( Ok(Secret::new(token)) } +pub async fn generate_jwt_auth_token_with_attributes_without_profile( + state: &SessionState, + user_id: String, + merchant_id: id_type::MerchantId, + org_id: id_type::OrganizationId, + role_id: String, +) -> UserResult<Secret<String>> { + let token = + AuthToken::new_token(user_id, merchant_id, role_id, &state.conf, org_id, None).await?; + Ok(Secret::new(token)) +} + pub async fn generate_jwt_auth_token_with_attributes( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, role_id: String, - profile_id: Option<id_type::ProfileId>, + profile_id: id_type::ProfileId, ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user_id, @@ -122,7 +134,7 @@ pub async fn generate_jwt_auth_token_with_attributes( role_id, &state.conf, org_id, - profile_id, + Some(profile_id), ) .await?; Ok(Secret::new(token)) diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index aeb866d8d03..ecf12742e32 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -358,3 +358,42 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( } } } + +pub async fn get_single_merchant_id_and_profile_id( + state: &SessionState, + user_role: &UserRole, +) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> { + let merchant_id = get_single_merchant_id(state, user_role).await?; + let (_, entity_type) = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError)?; + let profile_id = match entity_type { + EntityType::Organization | EntityType::Merchant | EntityType::Internal => { + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + &state.into(), + &merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError)?; + + state + .store + .list_business_profile_by_merchant_id(&state.into(), &key_store, &merchant_id) + .await + .change_context(UserErrors::InternalServerError)? + .pop() + .ok_or(UserErrors::InternalServerError)? + .get_id() + .to_owned() + } + EntityType::Profile => user_role + .profile_id + .clone() + .ok_or(UserErrors::InternalServerError)?, + }; + + Ok((merchant_id, profile_id)) +}
2024-09-05T11:52:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> 1. This PR changes list users in lineage API so that it don't do any db call to get the role info which leads us to send null in role name in the response. 2. This PR will add profile_id in JWT and user info API. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 3. `crates/router/src/configs` 4. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5816. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "name" } ' ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y", "token_type": "totp" } ``` ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \ --header 'Authorization: ••••••' ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y", "token_type": "user_info" } ``` The user info token should have profile_id. ``` curl --location 'http://localhost:8080/user' \ --header 'Authorization: Bearer JWT with profile id' ``` ``` { "merchant_id": "juspay", "name": "name", "email": "email", "verification_days_left": null, "role_id": "org_admin", "org_id": "org_hyDLeoUiRctzT45RG6vF", "is_two_factor_auth_setup": false, "recovery_codes_left": null, "profile_id": "pro_chs9bTt49POqaQBeMdq4", "entity_type": "organization" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
dfebc29c2b1398ac8934bd350eefcd4fa4f10d84
juspay/hyperswitch
juspay__hyperswitch-5815
Bug: fix(user_roles): List users in lineage API failing List users in lineage API sends response like following: ```json [ { "email": "e1", "roles": [ { "role_id": "r1", "role_name": "name", } ] } ] ``` To get the role name, this API does a db call to get the role info in the JWT merchant scope. But if org admin is hitting this API we should also have to get the role_name from other merchant scopes which this API is not doing currently. Temporarily fix will be don't send role name. Permanent fix should also see in other merchant scopes.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 4674abf3976..7bb8409993d 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -1,6 +1,6 @@ use std::fmt::Debug; -use common_enums::{PermissionGroup, RoleScope, TokenPurpose}; +use common_enums::{EntityType, PermissionGroup, RoleScope, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; @@ -158,6 +158,8 @@ pub struct GetUserDetailsResponse { pub org_id: id_type::OrganizationId, pub is_two_factor_auth_setup: bool, pub recovery_codes_left: Option<usize>, + pub profile_id: id_type::ProfileId, + pub entity_type: EntityType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -185,7 +187,7 @@ pub struct GetUserRoleDetailsResponseV2 { pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>, pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, pub status: UserStatus, - pub entity_type: common_enums::EntityType, + pub entity_type: EntityType, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs index 828dfeb20f8..22aa80a459a 100644 --- a/crates/api_models/src/user_role/role.rs +++ b/crates/api_models/src/user_role/role.rs @@ -63,5 +63,5 @@ pub enum RoleCheckType { #[derive(Debug, serde::Serialize, Clone)] pub struct MinimalRoleInfo { pub role_id: String, - pub role_name: String, + pub role_name: Option<String>, } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 1d235dceaea..dac6027aa19 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -100,6 +100,14 @@ pub async fn get_user_details( ) -> UserResponse<user_api::GetUserDetailsResponse> { let user = user_from_token.get_user_from_db(&state).await?; let verification_days_left = utils::user::get_verification_days_left(&state, &user)?; + let role_info = roles::RoleInfo::from_role_id( + &state, + &user_from_token.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json( user_api::GetUserDetailsResponse { @@ -112,6 +120,10 @@ pub async fn get_user_details( org_id: user_from_token.org_id, is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set, recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()), + profile_id: user_from_token + .profile_id + .ok_or(UserErrors::JwtProfileIdMissing)?, + entity_type: role_info.get_entity_type(), }, )) } @@ -1185,13 +1197,12 @@ pub async fn switch_merchant_id( })? .organization_id; - let token = utils::user::generate_jwt_auth_token_with_attributes( + let token = utils::user::generate_jwt_auth_token_with_attributes_without_profile( &state, user_from_token.user_id, request.merchant_id.clone(), org_id.clone(), user_from_token.role_id.clone(), - None, ) .await?; @@ -2792,7 +2803,6 @@ pub async fn switch_org_for_user( .into()); } - let key_manager_state = &(&state).into(); let role_info = roles::RoleInfo::from_role_id( &state, &user_from_token.role_id, @@ -2830,38 +2840,8 @@ pub async fn switch_org_for_user( "No user role found for the requested org_id".to_string(), ))?; - let merchant_id = utils::user_role::get_single_merchant_id(&state, &user_role).await?; - - let profile_id = if let Some(profile_id) = &user_role.profile_id { - profile_id.clone() - } else { - let merchant_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 - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to retrieve merchant key store by merchant_id")?; - - state - .store - .list_business_profile_by_merchant_id( - key_manager_state, - &merchant_key_store, - &merchant_id, - ) - .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to list business profiles by merchant_id")? - .pop() - .ok_or(UserErrors::InternalServerError) - .attach_printable("No business profile found for the merchant_id")? - .get_id() - .to_owned() - }; + let (merchant_id, profile_id) = + utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?; let token = utils::user::generate_jwt_auth_token_with_attributes( &state, @@ -2869,7 +2849,7 @@ pub async fn switch_org_for_user( merchant_id.clone(), request.org_id.clone(), user_role.role_id.clone(), - Some(profile_id.clone()), + profile_id.clone(), ) .await?; @@ -3078,7 +3058,7 @@ pub async fn switch_merchant_for_user_in_org( merchant_id.clone(), org_id.clone(), role_id.clone(), - Some(profile_id), + profile_id, ) .await?; @@ -3183,7 +3163,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( user_from_token.merchant_id.clone(), user_from_token.org_id.clone(), role_id.clone(), - Some(profile_id), + profile_id, ) .await?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 8c955a09517..369ee97a02a 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -744,30 +744,6 @@ pub async fn list_users_in_lineage( .map(|user| (user.user_id.clone(), user.email)) .collect::<HashMap<_, _>>(); - let role_info_map = - futures::future::try_join_all(user_roles_set.iter().map(|user_role| async { - roles::RoleInfo::from_role_id( - &state, - &user_role.role_id, - &user_from_token.merchant_id, - &user_from_token.org_id, - ) - .await - .map(|role_info| { - ( - user_role.role_id.clone(), - user_role_api::role::MinimalRoleInfo { - role_id: user_role.role_id.clone(), - role_name: role_info.get_role_name().to_string(), - }, - ) - }) - })) - .await - .change_context(UserErrors::InternalServerError)? - .into_iter() - .collect::<HashMap<_, _>>(); - let user_role_map = user_roles_set .into_iter() .fold(HashMap::new(), |mut map, user_role| { @@ -787,13 +763,11 @@ pub async fn list_users_in_lineage( .ok_or(UserErrors::InternalServerError)?, roles: role_id_vec .into_iter() - .map(|role_id| { - role_info_map - .get(&role_id) - .cloned() - .ok_or(UserErrors::InternalServerError) + .map(|role_id| user_role_api::role::MinimalRoleInfo { + role_id, + role_name: None, }) - .collect::<Result<Vec<_>, _>>()?, + .collect(), }) }) .collect::<Result<Vec<_>, _>>()?, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 1a81c49d5a9..8c9cd1da0ab 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -348,7 +348,7 @@ pub async fn list_roles_at_entity_level( if check_type && role_info.get_entity_type() == req.entity_type { Some(role_api::MinimalRoleInfo { role_id: role_info.get_role_id().to_string(), - role_name: role_info.get_role_name().to_string(), + role_name: Some(role_info.get_role_name().to_string()), }) } else { None diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 36af30cd9fa..2a8e3563fb6 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -5,7 +5,7 @@ use api_models::{ }; use common_enums::EntityType; use common_utils::{ - crypto::Encryptable, errors::CustomResult, id_type, new_type::MerchantName, pii, type_name, + crypto::Encryptable, id_type, new_type::MerchantName, pii, type_name, types::keymanager::Identifier, }; use diesel_models::{ @@ -28,7 +28,7 @@ use crate::{ consts, core::{ admin, - errors::{self, UserErrors, UserResult}, + errors::{UserErrors, UserResult}, }, db::{user_role::InsertUserRolePayload, GlobalStorageInterface}, routes::SessionState, @@ -867,22 +867,6 @@ impl UserFromStorage { self.0.email.clone() } - pub async fn get_role_from_db(&self, state: SessionState) -> UserResult<UserRole> { - state - .store - .find_user_role_by_user_id(&self.0.user_id, UserRoleVersion::V1) - .await - .change_context(UserErrors::InternalServerError) - } - - pub async fn get_roles_from_db(&self, state: &SessionState) -> UserResult<Vec<UserRole>> { - state - .store - .list_user_roles_by_user_id_and_version(&self.0.user_id, UserRoleVersion::V1) - .await - .change_context(UserErrors::InternalServerError) - } - #[cfg(feature = "email")] pub fn get_verification_days_left(&self, state: &SessionState) -> UserResult<Option<i64>> { if self.0.is_verified { @@ -930,21 +914,6 @@ impl UserFromStorage { Ok(days_left_for_password_rotate.whole_days() < 0) } - pub async fn get_role_from_db_by_merchant_id( - &self, - state: &SessionState, - merchant_id: &id_type::MerchantId, - ) -> CustomResult<UserRole, errors::StorageError> { - state - .store - .find_user_role_by_user_id_merchant_id( - self.get_user_id(), - merchant_id, - UserRoleVersion::V1, - ) - .await - } - pub async fn get_or_create_key_store(&self, state: &SessionState) -> UserResult<UserKeyStore> { let master_key = state.store.get_master_key(); let key_manager_state = &state.into(); @@ -1253,7 +1222,7 @@ where } } - async fn insert_v1_and_v2_in_db_and_get_v1( + async fn insert_v1_and_v2_in_db_and_get_v2( state: &SessionState, v1_role: UserRoleNew, v2_role: UserRoleNew, @@ -1264,10 +1233,9 @@ where .await .change_context(UserErrors::InternalServerError)?; - // Returning v1 role so other code which was not migrated doesn't break inserted_roles .into_iter() - .find(|role| role.version == UserRoleVersion::V1) + .find(|role| role.version == UserRoleVersion::V2) .ok_or(report!(UserErrors::InternalServerError)) } } @@ -1323,7 +1291,7 @@ impl NewUserRole<OrganizationLevel> { entity_type: EntityType::Organization, }); - Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await + Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await } } @@ -1343,7 +1311,7 @@ impl NewUserRole<MerchantLevel> { entity_type: EntityType::Merchant, }); - Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await + Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await } } @@ -1366,7 +1334,7 @@ impl NewUserRole<InternalLevel> { entity_type: EntityType::Internal, }); - Self::insert_v1_and_v2_in_db_and_get_v1(state, new_v1_role, new_v2_role).await + Self::insert_v1_and_v2_in_db_and_get_v2(state, new_v1_role, new_v2_role).await } } diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index af9918af673..3fc05285ea8 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,8 +1,5 @@ use common_enums::TokenPurpose; -use diesel_models::{ - enums::{UserRoleVersion, UserStatus}, - user_role::UserRole, -}; +use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::{report, ResultExt}; use masking::Secret; @@ -67,10 +64,21 @@ impl SPTFlow { Self::ForceSetPassword => user .is_password_rotate_required(state) .map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)), - Self::MerchantSelect => user - .get_roles_from_db(state) + Self::MerchantSelect => Ok(state + .store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: user.get_user_id(), + org_id: None, + merchant_id: None, + profile_id: None, + entity_id: None, + version: None, + status: Some(UserStatus::Active), + limit: Some(1), + }) .await - .map(|roles| !roles.iter().any(|role| role.status == UserStatus::Active)), + .change_context(UserErrors::InternalServerError)? + .is_empty()), } } @@ -105,15 +113,17 @@ impl JWTFlow { Ok(true) } - pub async fn generate_jwt_without_profile( + pub async fn generate_jwt( self, state: &SessionState, next_flow: &NextFlow, user_role: &UserRole, ) -> UserResult<Secret<String>> { + let (merchant_id, profile_id) = + utils::user_role::get_single_merchant_id_and_profile_id(state, user_role).await?; auth::AuthToken::new_token( next_flow.user.get_user_id().to_string(), - utils::user_role::get_single_merchant_id(state, user_role).await?, + merchant_id, user_role.role_id.clone(), &state.conf, user_role @@ -121,7 +131,7 @@ impl JWTFlow { .clone() .ok_or(report!(UserErrors::InternalServerError)) .attach_printable("org_id not found")?, - None, + Some(profile_id), ) .await .map(|token| token.into()) @@ -296,7 +306,7 @@ impl NextFlow { merchant_id: None, profile_id: None, entity_id: None, - version: Some(UserRoleVersion::V1), + version: None, status: Some(UserStatus::Active), limit: Some(1), }) @@ -307,9 +317,7 @@ impl NextFlow { utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role) .await; - jwt_flow - .generate_jwt_without_profile(state, self, &user_role) - .await + jwt_flow.generate_jwt(state, self, &user_role).await } } } @@ -329,9 +337,7 @@ impl NextFlow { utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role) .await; - jwt_flow - .generate_jwt_without_profile(state, self, user_role) - .await + jwt_flow.generate_jwt(state, self, user_role).await } } } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index a1bd6972dab..3da24f2be7d 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -108,13 +108,25 @@ pub async fn generate_jwt_auth_token_without_profile( Ok(Secret::new(token)) } +pub async fn generate_jwt_auth_token_with_attributes_without_profile( + state: &SessionState, + user_id: String, + merchant_id: id_type::MerchantId, + org_id: id_type::OrganizationId, + role_id: String, +) -> UserResult<Secret<String>> { + let token = + AuthToken::new_token(user_id, merchant_id, role_id, &state.conf, org_id, None).await?; + Ok(Secret::new(token)) +} + pub async fn generate_jwt_auth_token_with_attributes( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, role_id: String, - profile_id: Option<id_type::ProfileId>, + profile_id: id_type::ProfileId, ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user_id, @@ -122,7 +134,7 @@ pub async fn generate_jwt_auth_token_with_attributes( role_id, &state.conf, org_id, - profile_id, + Some(profile_id), ) .await?; Ok(Secret::new(token)) diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index aeb866d8d03..ecf12742e32 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -358,3 +358,42 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( } } } + +pub async fn get_single_merchant_id_and_profile_id( + state: &SessionState, + user_role: &UserRole, +) -> UserResult<(id_type::MerchantId, id_type::ProfileId)> { + let merchant_id = get_single_merchant_id(state, user_role).await?; + let (_, entity_type) = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError)?; + let profile_id = match entity_type { + EntityType::Organization | EntityType::Merchant | EntityType::Internal => { + let key_store = state + .store + .get_merchant_key_store_by_merchant_id( + &state.into(), + &merchant_id, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError)?; + + state + .store + .list_business_profile_by_merchant_id(&state.into(), &key_store, &merchant_id) + .await + .change_context(UserErrors::InternalServerError)? + .pop() + .ok_or(UserErrors::InternalServerError)? + .get_id() + .to_owned() + } + EntityType::Profile => user_role + .profile_id + .clone() + .ok_or(UserErrors::InternalServerError)?, + }; + + Ok((merchant_id, profile_id)) +}
2024-09-05T11:52:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> 1. This PR changes list users in lineage API so that it don't do any db call to get the role info which leads us to send null in role name in the response. 2. This PR will add profile_id in JWT and user info API. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 3. `crates/router/src/configs` 4. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5816. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/user/v2/signin' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "email", "password": "name" } ' ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y", "token_type": "totp" } ``` ``` curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \ --header 'Authorization: ••••••' ``` ``` { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZTY2NjM4OGYtMzE3OC00YmRiLTlhYTYtNjQwNjJkOTIyZTRlIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwicGF0aCI6W10sImV4cCI6MTcyNTY0MzU5N30.ZEpzU7m9bYyM0ViTJJQEPcGr4m-O2Snn0W3qE9q7-1Y", "token_type": "user_info" } ``` The user info token should have profile_id. ``` curl --location 'http://localhost:8080/user' \ --header 'Authorization: Bearer JWT with profile id' ``` ``` { "merchant_id": "juspay", "name": "name", "email": "email", "verification_days_left": null, "role_id": "org_admin", "org_id": "org_hyDLeoUiRctzT45RG6vF", "is_two_factor_auth_setup": false, "recovery_codes_left": null, "profile_id": "pro_chs9bTt49POqaQBeMdq4", "entity_type": "organization" } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
dfebc29c2b1398ac8934bd350eefcd4fa4f10d84
juspay/hyperswitch
juspay__hyperswitch-5809
Bug: [FEATURE] add support to forward x-request-id to keymanager service ### Feature Description To ease debugging the keymanager service, x-request-id from application should be forwarded in the header while calling encryption service. This will be used by the keymanager service for the requests instead of creating one of its own. ### Possible Implementation Pass x-request-id In the headers while calling keymanager service ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml index eee1bd573ef..c6e29801b2f 100644 --- a/crates/common_utils/Cargo.toml +++ b/crates/common_utils/Cargo.toml @@ -12,6 +12,7 @@ default = ["v1"] keymanager = ["dep:router_env"] keymanager_mtls = ["reqwest/rustls-tls"] encryption_service = ["dep:router_env"] +km_forward_x_request_id = ["dep:router_env", "router_env/actix_web"] signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"] async_ext = ["dep:async-trait", "dep:futures"] logs = ["dep:router_env"] diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs index 9d6e9315074..53761951791 100644 --- a/crates/common_utils/src/keymanager.rs +++ b/crates/common_utils/src/keymanager.rs @@ -23,6 +23,8 @@ use crate::{ const CONTENT_TYPE: &str = "Content-Type"; static ENCRYPTION_API_CLIENT: OnceCell<reqwest::Client> = OnceCell::new(); static DEFAULT_ENCRYPTION_VERSION: &str = "v1"; +#[cfg(feature = "km_forward_x_request_id")] +const X_REQUEST_ID: &str = "X-Request-Id"; /// Get keymanager client constructed from the url and state #[instrument(skip_all)] @@ -104,18 +106,25 @@ where let url = format!("{}/{endpoint}", &state.url); logger::info!(key_manager_request=?request_body); - + let mut header = vec![]; + header.push(( + HeaderName::from_str(CONTENT_TYPE) + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + HeaderValue::from_str("application/json") + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + )); + #[cfg(feature = "km_forward_x_request_id")] + if let Some(request_id) = state.request_id { + header.push(( + HeaderName::from_str(X_REQUEST_ID) + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + HeaderValue::from_str(request_id.as_hyphenated().to_string().as_str()) + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + )) + } let response = send_encryption_request( state, - HeaderMap::from_iter( - vec![( - HeaderName::from_str(CONTENT_TYPE) - .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, - HeaderValue::from_str("application/json") - .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, - )] - .into_iter(), - ), + HeaderMap::from_iter(header.into_iter()), url, method, request_body, diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs index 05305b53707..abcb7aa87f7 100644 --- a/crates/common_utils/src/types/keymanager.rs +++ b/crates/common_utils/src/types/keymanager.rs @@ -6,6 +6,8 @@ use base64::Engine; use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret}; #[cfg(feature = "encryption_service")] use router_env::logger; +#[cfg(feature = "km_forward_x_request_id")] +use router_env::tracing_actix_web::RequestId; use rustc_hash::FxHashMap; use serde::{ de::{self, Unexpected, Visitor}, @@ -26,6 +28,8 @@ pub struct KeyManagerState { pub enabled: Option<bool>, pub url: String, pub client_idle_timeout: Option<u64>, + #[cfg(feature = "km_forward_x_request_id")] + pub request_id: Option<RequestId>, #[cfg(feature = "keymanager_mtls")] pub ca: Secret<String>, #[cfg(feature = "keymanager_mtls")] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 7da8327b5b8..a614e5d1e7a 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true [features] default = ["common_default", "v1"] -common_default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls", "partial-auth"] +common_default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache", "dummy_connector", "payouts", "payout_retry", "retry", "frm", "tls", "partial-auth", "km_forward_x_request_id"] olap = ["hyperswitch_domain_models/olap", "storage_impl/olap", "scheduler/olap", "api_models/olap", "dep:analytics"] tls = ["actix-web/rustls-0_22"] email = ["external_services/email", "scheduler/email", "olap"] @@ -18,6 +18,7 @@ email = ["external_services/email", "scheduler/email", "olap"] keymanager_create = [] keymanager_mtls = ["reqwest/rustls-tls", "common_utils/keymanager_mtls"] encryption_service = ["hyperswitch_domain_models/encryption_service", "common_utils/encryption_service"] +km_forward_x_request_id = ["common_utils/km_forward_x_request_id"] frm = ["api_models/frm", "hyperswitch_domain_models/frm", "hyperswitch_connectors/frm", "hyperswitch_interfaces/frm"] stripe = [] release = ["stripe", "email", "accounts_cache", "kv_store", "vergen", "recon", "external_services/aws_kms", "external_services/aws_s3", "keymanager_mtls", "keymanager_create", "encryption_service"] diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index 10657adc122..082e8df4bfc 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -10,6 +10,8 @@ impl From<&crate::SessionState> for KeyManagerState { enabled: conf.enabled, url: conf.url.clone(), client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout, + #[cfg(feature = "km_forward_x_request_id")] + request_id: state.request_id, #[cfg(feature = "keymanager_mtls")] cert: conf.cert.clone(), #[cfg(feature = "keymanager_mtls")]
2024-09-05T07:02:28Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description To ease debugging the keymanager service, x-request-id from application will be forwarded in the header while calling encryption service. This will be used by the keymanager service for the requests instead of creating one of its own. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context For debugging keymanager service ## How did you test it? Manually enabling logging in the key manager. x-request-id from the router can be used for debugging key manger service. ![Screenshot 2024-09-05 at 12 29 43 PM](https://github.com/user-attachments/assets/46ae387d-1ed9-4958-a90d-9816b124d498) <img width="423" alt="Screenshot 2024-09-05 at 12 30 00 PM" src="https://github.com/user-attachments/assets/96377881-7fb0-46d4-886f-ce5ed1f8fb5c"> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d3a1703bf59afc06e87e94433bc10a01e413259b
juspay/hyperswitch
juspay__hyperswitch-5806
Bug: feat(analytics): add card_network as a field in clickhouse payment_attempts table Add `card_network` as a field in clickhosue `payment_attempts.sql` file.
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql index 5c1ee8754c9..f5d0ca51fd7 100644 --- a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql +++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql @@ -42,6 +42,7 @@ CREATE TABLE payment_attempt_queue ( `client_version` LowCardinality(Nullable(String)), `organization_id` String, `profile_id` String, + `card_network` Nullable(String), `sign_flag` Int8 ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-payment-attempt-events', @@ -94,6 +95,7 @@ CREATE TABLE payment_attempts ( `client_version` LowCardinality(Nullable(String)), `organization_id` String, `profile_id` String, + `card_network` Nullable(String), `sign_flag` Int8, INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1, INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1, @@ -149,6 +151,7 @@ CREATE MATERIALIZED VIEW payment_attempt_mv TO payment_attempts ( `client_version` LowCardinality(Nullable(String)), `organization_id` String, `profile_id` String, + `card_network` Nullable(String), `sign_flag` Int8 ) AS SELECT @@ -196,8 +199,9 @@ SELECT client_version, organization_id, profile_id, + card_network, sign_flag FROM payment_attempt_queue WHERE - length(_error) = 0; \ No newline at end of file + length(_error) = 0;
2024-09-05T08:24:47Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Added card_network as a field in payment_attempts clickhouse table ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Made sample payments on sandbox dashboard and confirmed the data for card_network on clickhouse sandbox ![image](https://github.com/user-attachments/assets/e7c955ed-c331-4563-ad8d-32ab5fd605e4) ![image](https://github.com/user-attachments/assets/ce351d3d-9091-4f97-91fc-d77531e1d45a) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
db04ded4a460abfb073167d59b3c51a4e7972c54
juspay/hyperswitch
juspay__hyperswitch-5871
Bug: feat(analytics): Add metrics, filters and APIs for Analytics v2 Dashboard - Payments Page Add metrics, filters and APIs for Analytics v2 Dashboard - Payments page The following filters should be added: Payment Attempts: - Merchant_id - Card last 4 - Error Reason - Card Issuer Payment Intents: - connector - authentication_type - payment_method - payment_method_type - card_network - merchant id - card_last_4 - error_reason - card_issuer New API endpoints for Payments Lifecycle (Sankey) on different levels should be created
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs index 37a011c9a5a..546b57f99af 100644 --- a/crates/analytics/src/clickhouse.rs +++ b/crates/analytics/src/clickhouse.rs @@ -130,9 +130,12 @@ impl AnalyticsDataSource for ClickhouseClient { fn get_table_engine(table: AnalyticsCollection) -> TableEngine { match table { AnalyticsCollection::Payment + | AnalyticsCollection::PaymentSessionized | AnalyticsCollection::Refund + | AnalyticsCollection::RefundSessionized | AnalyticsCollection::FraudCheck | AnalyticsCollection::PaymentIntent + | AnalyticsCollection::PaymentIntentSessionized | AnalyticsCollection::Dispute => { TableEngine::CollapsingMergeTree { sign: "sign_flag" } } @@ -423,13 +426,16 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempts".to_string()), + Self::PaymentSessionized => Ok("sessionizer_payment_attempts".to_string()), Self::Refund => Ok("refunds".to_string()), + Self::RefundSessionized => Ok("sessionizer_refunds".to_string()), Self::FraudCheck => Ok("fraud_check".to_string()), Self::SdkEvents => Ok("sdk_events_audit".to_string()), Self::SdkEventsAnalytics => Ok("sdk_events".to_string()), Self::ApiEvents => Ok("api_events_audit".to_string()), Self::ApiEventsAnalytics => Ok("api_events".to_string()), Self::PaymentIntent => Ok("payment_intents".to_string()), + Self::PaymentIntentSessionized => Ok("sessionizer_payment_intents".to_string()), Self::ConnectorEvents => Ok("connector_events_audit".to_string()), Self::OutgoingWebhookEvent => Ok("outgoing_webhook_events_audit".to_string()), Self::Dispute => Ok("dispute".to_string()), diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index d5cb3c718df..224cd82ccd3 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -996,6 +996,7 @@ pub enum AnalyticsFlow { GetSearchResults, GetDisputeFilters, GetDisputeMetrics, + GetSankey, } impl FlowMetric for AnalyticsFlow {} diff --git a/crates/analytics/src/payment_intents.rs b/crates/analytics/src/payment_intents.rs index 449dd94788c..809be1b20a1 100644 --- a/crates/analytics/src/payment_intents.rs +++ b/crates/analytics/src/payment_intents.rs @@ -2,6 +2,7 @@ pub mod accumulator; mod core; pub mod filters; pub mod metrics; +pub mod sankey; pub mod types; pub use accumulator::{PaymentIntentMetricAccumulator, PaymentIntentMetricsAccumulator}; @@ -10,4 +11,4 @@ pub trait PaymentIntentAnalytics: { } -pub use self::core::{get_filters, get_metrics}; +pub use self::core::{get_filters, get_metrics, get_sankey}; diff --git a/crates/analytics/src/payment_intents/accumulator.rs b/crates/analytics/src/payment_intents/accumulator.rs index 8fd98a1e73c..cbb8335cea0 100644 --- a/crates/analytics/src/payment_intents/accumulator.rs +++ b/crates/analytics/src/payment_intents/accumulator.rs @@ -1,5 +1,6 @@ use api_models::analytics::payment_intents::PaymentIntentMetricsBucketValue; use bigdecimal::ToPrimitive; +use diesel_models::enums as storage_enums; use super::metrics::PaymentIntentMetricRow; @@ -7,8 +8,11 @@ use super::metrics::PaymentIntentMetricRow; pub struct PaymentIntentMetricsAccumulator { pub successful_smart_retries: CountAccumulator, pub total_smart_retries: CountAccumulator, - pub smart_retried_amount: SumAccumulator, + pub smart_retried_amount: SmartRetriedAmountAccumulator, pub payment_intent_count: CountAccumulator, + pub payments_success_rate: PaymentsSuccessRateAccumulator, + pub payment_processed_amount: ProcessedAmountAccumulator, + pub payments_distribution: PaymentsDistributionAccumulator, } #[derive(Debug, Default)] @@ -38,9 +42,31 @@ pub trait PaymentIntentMetricAccumulator { } #[derive(Debug, Default)] -#[repr(transparent)] -pub struct SumAccumulator { - pub total: Option<i64>, +pub struct SmartRetriedAmountAccumulator { + pub amount: Option<i64>, + pub amount_without_retries: Option<i64>, +} + +#[derive(Debug, Default)] +pub struct PaymentsSuccessRateAccumulator { + pub success: u32, + pub success_without_retries: u32, + pub total: u32, +} + +#[derive(Debug, Default)] +pub struct ProcessedAmountAccumulator { + pub count_with_retries: Option<i64>, + pub total_with_retries: Option<i64>, + pub count_without_retries: Option<i64>, + pub total_without_retries: Option<i64>, +} + +#[derive(Debug, Default)] +pub struct PaymentsDistributionAccumulator { + pub success_without_retries: u32, + pub failed_without_retries: u32, + pub total: u32, } impl PaymentIntentMetricAccumulator for CountAccumulator { @@ -59,32 +85,251 @@ impl PaymentIntentMetricAccumulator for CountAccumulator { } } -impl PaymentIntentMetricAccumulator for SumAccumulator { - type MetricOutput = Option<u64>; +impl PaymentIntentMetricAccumulator for SmartRetriedAmountAccumulator { + type MetricOutput = (Option<u64>, Option<u64>); #[inline] fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { - self.total = match ( - self.total, + self.amount = match ( + self.amount, metrics.total.as_ref().and_then(ToPrimitive::to_i64), ) { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), + }; + if metrics.first_attempt.unwrap_or(0) == 1 { + self.amount_without_retries = match ( + self.amount_without_retries, + metrics.total.as_ref().and_then(ToPrimitive::to_i64), + ) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + } + } else { + self.amount_without_retries = Some(0); } } #[inline] fn collect(self) -> Self::MetricOutput { - self.total.and_then(|i| u64::try_from(i).ok()) + let with_retries = self.amount.and_then(|i| u64::try_from(i).ok()).or(Some(0)); + let without_retries = self + .amount_without_retries + .and_then(|i| u64::try_from(i).ok()) + .or(Some(0)); + (with_retries, without_retries) + } +} + +impl PaymentIntentMetricAccumulator for PaymentsSuccessRateAccumulator { + type MetricOutput = ( + Option<u32>, + Option<u32>, + Option<u32>, + Option<f64>, + Option<f64>, + ); + + fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { + if let Some(ref status) = metrics.status { + if status.as_ref() == &storage_enums::IntentStatus::Succeeded { + if let Some(success) = metrics + .count + .and_then(|success| u32::try_from(success).ok()) + { + self.success += success; + if metrics.first_attempt.unwrap_or(0) == 1 { + self.success_without_retries += success; + } + } + } + if status.as_ref() != &storage_enums::IntentStatus::RequiresCustomerAction + && status.as_ref() != &storage_enums::IntentStatus::RequiresPaymentMethod + && status.as_ref() != &storage_enums::IntentStatus::RequiresMerchantAction + && status.as_ref() != &storage_enums::IntentStatus::RequiresConfirmation + { + if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { + self.total += total; + } + } + } + } + + fn collect(self) -> Self::MetricOutput { + if self.total == 0 { + (None, None, None, None, None) + } else { + let success = Some(self.success); + let success_without_retries = Some(self.success_without_retries); + let total = Some(self.total); + + let success_rate = match (success, total) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + + let success_without_retries_rate = match (success_without_retries, total) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + + ( + success, + success_without_retries, + total, + success_rate, + success_without_retries_rate, + ) + } + } +} + +impl PaymentIntentMetricAccumulator for ProcessedAmountAccumulator { + type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>); + #[inline] + fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { + self.total_with_retries = match ( + self.total_with_retries, + metrics.total.as_ref().and_then(ToPrimitive::to_i64), + ) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + + self.count_with_retries = match (self.count_with_retries, metrics.count) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + + if metrics.first_attempt.unwrap_or(0) == 1 { + self.total_without_retries = match ( + self.total_without_retries, + metrics.total.as_ref().and_then(ToPrimitive::to_i64), + ) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + + self.count_without_retries = match (self.count_without_retries, metrics.count) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + } + } + #[inline] + fn collect(self) -> Self::MetricOutput { + let total_with_retries = u64::try_from(self.total_with_retries.unwrap_or(0)).ok(); + let count_with_retries = self.count_with_retries.and_then(|i| u64::try_from(i).ok()); + + let total_without_retries = u64::try_from(self.total_without_retries.unwrap_or(0)).ok(); + let count_without_retries = self + .count_without_retries + .and_then(|i| u64::try_from(i).ok()); + + ( + total_with_retries, + count_with_retries, + total_without_retries, + count_without_retries, + ) + } +} + +impl PaymentIntentMetricAccumulator for PaymentsDistributionAccumulator { + type MetricOutput = (Option<f64>, Option<f64>); + + fn add_metrics_bucket(&mut self, metrics: &PaymentIntentMetricRow) { + let first_attempt = metrics.first_attempt.unwrap_or(0); + if let Some(ref status) = metrics.status { + if status.as_ref() == &storage_enums::IntentStatus::Succeeded { + if let Some(success) = metrics + .count + .and_then(|success| u32::try_from(success).ok()) + { + if first_attempt == 1 { + self.success_without_retries += success; + } + } + } + if let Some(failed) = metrics.count.and_then(|failed| u32::try_from(failed).ok()) { + if first_attempt == 0 + || (first_attempt == 1 + && status.as_ref() == &storage_enums::IntentStatus::Failed) + { + self.failed_without_retries += failed; + } + } + + if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { + self.total += total; + } + } + } + + fn collect(self) -> Self::MetricOutput { + if self.total == 0 { + (None, None) + } else { + let success_without_retries = Some(self.success_without_retries); + let failed_without_retries = Some(self.failed_without_retries); + let total = Some(self.total); + + let success_rate_without_retries = match (success_without_retries, total) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + + let failed_rate_without_retries = match (failed_without_retries, total) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + (success_rate_without_retries, failed_rate_without_retries) + } } } impl PaymentIntentMetricsAccumulator { pub fn collect(self) -> PaymentIntentMetricsBucketValue { + let ( + successful_payments, + successful_payments_without_smart_retries, + total_payments, + payments_success_rate, + payments_success_rate_without_smart_retries, + ) = self.payments_success_rate.collect(); + let (smart_retried_amount, smart_retried_amount_without_smart_retries) = + self.smart_retried_amount.collect(); + let ( + payment_processed_amount, + payment_processed_count, + payment_processed_amount_without_smart_retries, + payment_processed_count_without_smart_retries, + ) = self.payment_processed_amount.collect(); + let ( + payments_success_rate_distribution_without_smart_retries, + payments_failure_rate_distribution_without_smart_retries, + ) = self.payments_distribution.collect(); PaymentIntentMetricsBucketValue { successful_smart_retries: self.successful_smart_retries.collect(), total_smart_retries: self.total_smart_retries.collect(), - smart_retried_amount: self.smart_retried_amount.collect(), + smart_retried_amount, + smart_retried_amount_without_smart_retries, payment_intent_count: self.payment_intent_count.collect(), + successful_payments, + successful_payments_without_smart_retries, + total_payments, + payments_success_rate, + payments_success_rate_without_smart_retries, + payment_processed_amount, + payment_processed_count, + payment_processed_amount_without_smart_retries, + payment_processed_count_without_smart_retries, + payments_success_rate_distribution_without_smart_retries, + payments_failure_rate_distribution_without_smart_retries, } } } diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index f8a5c48986a..e04c3b7bd9e 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -6,10 +6,12 @@ use api_models::analytics::{ MetricsBucketResponse, PaymentIntentDimensions, PaymentIntentMetrics, PaymentIntentMetricsBucketIdentifier, }, - AnalyticsMetadata, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, - MetricsResponse, PaymentIntentFilterValue, PaymentIntentFiltersResponse, + GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, PaymentIntentFilterValue, + PaymentIntentFiltersResponse, PaymentIntentsAnalyticsMetadata, PaymentIntentsMetricsResponse, + SankeyResponse, }; -use common_utils::errors::CustomResult; +use common_enums::IntentStatus; +use common_utils::{errors::CustomResult, types::TimeRange}; use error_stack::ResultExt; use router_env::{ instrument, logger, @@ -20,6 +22,7 @@ use router_env::{ use super::{ filters::{get_payment_intent_filter_for_dimension, PaymentIntentFilterRow}, metrics::PaymentIntentMetricRow, + sankey::{get_sankey_data, SessionizerRefundStatus}, PaymentIntentMetricsAccumulator, }; use crate::{ @@ -41,12 +44,85 @@ pub enum TaskType { ), } +#[instrument(skip_all)] +pub async fn get_sankey( + pool: &AnalyticsProvider, + auth: &AuthInfo, + req: TimeRange, +) -> AnalyticsResult<SankeyResponse> { + match pool { + AnalyticsProvider::Sqlx(_) => Err(AnalyticsError::NotImplemented( + "Sankey not implemented for sqlx", + ))?, + AnalyticsProvider::Clickhouse(ckh_pool) + | AnalyticsProvider::CombinedCkh(_, ckh_pool) + | AnalyticsProvider::CombinedSqlx(_, ckh_pool) => { + let sankey_rows = get_sankey_data(ckh_pool, auth, &req) + .await + .change_context(AnalyticsError::UnknownError)?; + let mut sankey_response = SankeyResponse::default(); + for i in sankey_rows { + match ( + i.status.as_ref(), + i.refunds_status.unwrap_or_default().as_ref(), + i.attempt_count, + ) { + (IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, _) => { + sankey_response.refunded += i.count + } + (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, _) => { + sankey_response.partial_refunded += i.count + } + ( + IntentStatus::Succeeded + | IntentStatus::PartiallyCaptured + | IntentStatus::PartiallyCapturedAndCapturable + | IntentStatus::RequiresCapture, + SessionizerRefundStatus::NotRefunded, + 1, + ) => sankey_response.normal_success += i.count, + ( + IntentStatus::Succeeded + | IntentStatus::PartiallyCaptured + | IntentStatus::PartiallyCapturedAndCapturable + | IntentStatus::RequiresCapture, + SessionizerRefundStatus::NotRefunded, + _, + ) => sankey_response.smart_retried_success += i.count, + (IntentStatus::Failed, _, 1) => sankey_response.normal_failure += i.count, + (IntentStatus::Failed, _, _) => { + sankey_response.smart_retried_failure += i.count + } + (IntentStatus::Cancelled, _, _) => sankey_response.cancelled += i.count, + (IntentStatus::Processing, _, _) => sankey_response.pending += i.count, + (IntentStatus::RequiresCustomerAction, _, _) => { + sankey_response.customer_awaited += i.count + } + (IntentStatus::RequiresMerchantAction, _, _) => { + sankey_response.merchant_awaited += i.count + } + (IntentStatus::RequiresPaymentMethod, _, _) => { + sankey_response.pm_awaited += i.count + } + (IntentStatus::RequiresConfirmation, _, _) => { + sankey_response.confirmation_awaited += i.count + } + i @ (_, _, _) => { + router_env::logger::error!(status=?i, "Unknown status in sankey data"); + } + } + } + Ok(sankey_response) + } + } +} + #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, auth: &AuthInfo, req: GetPaymentIntentMetricRequest, -) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { +) -> AnalyticsResult<PaymentIntentsMetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricsAccumulator, @@ -107,18 +183,34 @@ pub async fn get_metrics( logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { - PaymentIntentMetrics::SuccessfulSmartRetries => metrics_builder - .successful_smart_retries - .add_metrics_bucket(&value), - PaymentIntentMetrics::TotalSmartRetries => metrics_builder + PaymentIntentMetrics::SuccessfulSmartRetries + | PaymentIntentMetrics::SessionizedSuccessfulSmartRetries => { + metrics_builder + .successful_smart_retries + .add_metrics_bucket(&value) + } + PaymentIntentMetrics::TotalSmartRetries + | PaymentIntentMetrics::SessionizedTotalSmartRetries => metrics_builder .total_smart_retries .add_metrics_bucket(&value), - PaymentIntentMetrics::SmartRetriedAmount => metrics_builder + PaymentIntentMetrics::SmartRetriedAmount + | PaymentIntentMetrics::SessionizedSmartRetriedAmount => metrics_builder .smart_retried_amount .add_metrics_bucket(&value), - PaymentIntentMetrics::PaymentIntentCount => metrics_builder + PaymentIntentMetrics::PaymentIntentCount + | PaymentIntentMetrics::SessionizedPaymentIntentCount => metrics_builder .payment_intent_count .add_metrics_bucket(&value), + PaymentIntentMetrics::PaymentsSuccessRate + | PaymentIntentMetrics::SessionizedPaymentsSuccessRate => metrics_builder + .payments_success_rate + .add_metrics_bucket(&value), + PaymentIntentMetrics::SessionizedPaymentProcessedAmount => metrics_builder + .payment_processed_amount + .add_metrics_bucket(&value), + PaymentIntentMetrics::SessionizedPaymentsDistribution => metrics_builder + .payments_distribution + .add_metrics_bucket(&value), } } @@ -131,18 +223,80 @@ pub async fn get_metrics( } } + let mut success = 0; + let mut success_without_smart_retries = 0; + let mut total_smart_retried_amount = 0; + let mut total_smart_retried_amount_without_smart_retries = 0; + let mut total = 0; + let mut total_payment_processed_amount = 0; + let mut total_payment_processed_count = 0; + let mut total_payment_processed_amount_without_smart_retries = 0; + let mut total_payment_processed_count_without_smart_retries = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() - .map(|(id, val)| MetricsBucketResponse { - values: val.collect(), - dimensions: id, + .map(|(id, val)| { + let collected_values = val.collect(); + if let Some(success_count) = collected_values.successful_payments { + success += success_count; + } + if let Some(success_count) = collected_values.successful_payments_without_smart_retries + { + success_without_smart_retries += success_count; + } + if let Some(total_count) = collected_values.total_payments { + total += total_count; + } + if let Some(retried_amount) = collected_values.smart_retried_amount { + total_smart_retried_amount += retried_amount; + } + if let Some(retried_amount) = + collected_values.smart_retried_amount_without_smart_retries + { + total_smart_retried_amount_without_smart_retries += retried_amount; + } + if let Some(amount) = collected_values.payment_processed_amount { + total_payment_processed_amount += amount; + } + if let Some(count) = collected_values.payment_processed_count { + total_payment_processed_count += count; + } + if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { + total_payment_processed_amount_without_smart_retries += amount; + } + if let Some(count) = collected_values.payment_processed_count_without_smart_retries { + total_payment_processed_count_without_smart_retries += count; + } + MetricsBucketResponse { + values: collected_values, + dimensions: id, + } }) .collect(); - - Ok(MetricsResponse { + let total_success_rate = match (success, total) { + (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + let total_success_rate_without_smart_retries = match (success_without_smart_retries, total) { + (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + Ok(PaymentIntentsMetricsResponse { query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, + meta_data: [PaymentIntentsAnalyticsMetadata { + total_success_rate, + total_success_rate_without_smart_retries, + total_smart_retried_amount: Some(total_smart_retried_amount), + total_smart_retried_amount_without_smart_retries: Some( + total_smart_retried_amount_without_smart_retries, + ), + total_payment_processed_amount: Some(total_payment_processed_amount), + total_payment_processed_amount_without_smart_retries: Some( + total_payment_processed_amount_without_smart_retries, + ), + total_payment_processed_count: Some(total_payment_processed_count), + total_payment_processed_count_without_smart_retries: Some( + total_payment_processed_count_without_smart_retries, + ), }], }) } @@ -217,6 +371,15 @@ pub async fn get_filters( PaymentIntentDimensions::PaymentIntentStatus => fil.status.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), PaymentIntentDimensions::ProfileId => fil.profile_id, + PaymentIntentDimensions::Connector => fil.connector, + PaymentIntentDimensions::AuthType => fil.authentication_type.map(|i| i.as_ref().to_string()), + PaymentIntentDimensions::PaymentMethod => fil.payment_method, + PaymentIntentDimensions::PaymentMethodType => fil.payment_method_type, + PaymentIntentDimensions::CardNetwork => fil.card_network, + PaymentIntentDimensions::MerchantId => fil.merchant_id, + PaymentIntentDimensions::CardLast4 => fil.card_last_4, + PaymentIntentDimensions::CardIssuer => fil.card_issuer, + PaymentIntentDimensions::ErrorReason => fil.error_reason, }) .collect::<Vec<String>>(); res.query_data.push(PaymentIntentFilterValue { diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs index e81b050214c..25d43e76f03 100644 --- a/crates/analytics/src/payment_intents/filters.rs +++ b/crates/analytics/src/payment_intents/filters.rs @@ -1,6 +1,6 @@ use api_models::analytics::{payment_intents::PaymentIntentDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; -use diesel_models::enums::{Currency, IntentStatus}; +use diesel_models::enums::{AuthenticationType, Currency, IntentStatus}; use error_stack::ResultExt; use time::PrimitiveDateTime; @@ -54,4 +54,13 @@ pub struct PaymentIntentFilterRow { pub status: Option<DBEnumWrapper<IntentStatus>>, pub currency: Option<DBEnumWrapper<Currency>>, pub profile_id: Option<String>, + pub connector: Option<String>, + pub authentication_type: Option<DBEnumWrapper<AuthenticationType>>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, } diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs index f27a02368ae..8ee9d24b5a0 100644 --- a/crates/analytics/src/payment_intents/metrics.rs +++ b/crates/analytics/src/payment_intents/metrics.rs @@ -17,11 +17,14 @@ use crate::{ }; mod payment_intent_count; +mod payments_success_rate; +mod sessionized_metrics; mod smart_retried_amount; mod successful_smart_retries; mod total_smart_retries; use payment_intent_count::PaymentIntentCount; +use payments_success_rate::PaymentsSuccessRate; use smart_retried_amount::SmartRetriedAmount; use successful_smart_retries::SuccessfulSmartRetries; use total_smart_retries::TotalSmartRetries; @@ -31,6 +34,16 @@ pub struct PaymentIntentMetricRow { pub status: Option<DBEnumWrapper<storage_enums::IntentStatus>>, pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub profile_id: Option<String>, + pub connector: Option<String>, + pub authentication_type: Option<DBEnumWrapper<storage_enums::AuthenticationType>>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, + pub first_attempt: Option<i64>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, #[serde(with = "common_utils::custom_serde::iso8601::option")] @@ -98,6 +111,46 @@ where .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } + Self::PaymentsSuccessRate => { + PaymentsSuccessRate + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedSuccessfulSmartRetries => { + sessionized_metrics::SuccessfulSmartRetries + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedTotalSmartRetries => { + sessionized_metrics::TotalSmartRetries + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedSmartRetriedAmount => { + sessionized_metrics::SmartRetriedAmount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedPaymentIntentCount => { + sessionized_metrics::PaymentIntentCount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedPaymentsSuccessRate => { + sessionized_metrics::PaymentsSuccessRate + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedPaymentProcessedAmount => { + sessionized_metrics::PaymentProcessedAmount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedPaymentsDistribution => { + sessionized_metrics::PaymentsDistribution + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } } } } diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs index 4632cbe9f37..b301a9b9b23 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs @@ -101,6 +101,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs new file mode 100644 index 00000000000..07b1bfcf69f --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs @@ -0,0 +1,146 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(super) struct PaymentsSuccessRate; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for PaymentsSuccessRate +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntent); + + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentIntentDimensions::PaymentIntentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder + .add_select_column("(attempt_count == 1) as first_attempt".to_string()) + .switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + None, + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs new file mode 100644 index 00000000000..fcd9a2b8adf --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs @@ -0,0 +1,17 @@ +mod payment_intent_count; +mod payment_processed_amount; +mod payments_distribution; +mod payments_success_rate; +mod smart_retried_amount; +mod successful_smart_retries; +mod total_smart_retries; + +pub(super) use payment_intent_count::PaymentIntentCount; +pub(super) use payment_processed_amount::PaymentProcessedAmount; +pub(super) use payments_distribution::PaymentsDistribution; +pub(super) use payments_success_rate::PaymentsSuccessRate; +pub(super) use smart_retried_amount::SmartRetriedAmount; +pub(super) use successful_smart_retries::SuccessfulSmartRetries; +pub(super) use total_smart_retries::TotalSmartRetries; + +pub use super::{PaymentIntentMetric, PaymentIntentMetricAnalytics, PaymentIntentMetricRow}; diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs new file mode 100644 index 00000000000..7475a75bb53 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs @@ -0,0 +1,133 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentIntentCount; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for PaymentIntentCount +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs new file mode 100644 index 00000000000..506965375f5 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs @@ -0,0 +1,160 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentProcessedAmount; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for PaymentProcessedAmount +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentIntentDimensions::PaymentIntentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder + .add_select_column("attempt_count == 1 as first_attempt") + .switch()?; + + query_builder + .add_select_column(Aggregate::Sum { + field: "amount", + alias: Some("total"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + query_builder + .add_group_by_clause("attempt_count") + .attach_printable("Error grouping by attempt_count") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .add_filter_clause( + PaymentIntentDimensions::PaymentIntentStatus, + storage_enums::IntentStatus::Succeeded, + ) + .switch()?; + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + None, + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs new file mode 100644 index 00000000000..0b55c101a7c --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs @@ -0,0 +1,145 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentsDistribution; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for PaymentsDistribution +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentIntentDimensions::PaymentIntentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder + .add_select_column("attempt_count == 1 as first_attempt") + .switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + None, + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs new file mode 100644 index 00000000000..8c340d0b2d6 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs @@ -0,0 +1,146 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentsSuccessRate; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for PaymentsSuccessRate +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentIntentDimensions::PaymentIntentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder + .add_select_column("(attempt_count == 1) as first_attempt".to_string()) + .switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + None, + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs new file mode 100644 index 00000000000..8105a4c82a4 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs @@ -0,0 +1,154 @@ +use std::collections::HashSet; + +use api_models::{ + analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, + }, + enums::IntentStatus, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct SmartRetriedAmount; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for SmartRetriedAmount +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Sum { + field: "amount", + alias: Some("total"), + }) + .switch()?; + + query_builder + .add_select_column("attempt_count == 1 as first_attempt") + .switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + query_builder + .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs new file mode 100644 index 00000000000..0b28cb5366d --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/successful_smart_retries.rs @@ -0,0 +1,143 @@ +use std::collections::HashSet; + +use api_models::{ + analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, + }, + enums::IntentStatus, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct SuccessfulSmartRetries; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for SuccessfulSmartRetries +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + query_builder + .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs new file mode 100644 index 00000000000..20ef8be6277 --- /dev/null +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/total_smart_retries.rs @@ -0,0 +1,138 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payment_intents::{ + PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, + }, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentIntentMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct TotalSmartRetries; + +#[async_trait::async_trait] +impl<T> super::PaymentIntentMetric<T> for TotalSmartRetries +where + T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentIntentDimensions], + auth: &AuthInfo, + filters: &PaymentIntentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> + { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentIntentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentIntentMetricsBucketIdentifier::new( + i.status.as_ref().map(|i| i.0), + i.currency.as_ref().map(|i| i.0), + i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs index e1df9fe50d3..8468911f7bb 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -58,6 +58,11 @@ where alias: Some("total"), }) .switch()?; + + query_builder + .add_select_column("attempt_count == 1 as first_attempt") + .switch()?; + query_builder .add_select_column(Aggregate::Min { field: "created_at", @@ -93,6 +98,11 @@ where .switch()?; } + query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + if let Some(granularity) = granularity.as_ref() { granularity .set_group_by_clause(&mut query_builder) @@ -112,6 +122,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs index 4fe5f3a26f5..a19bdec518c 100644 --- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs @@ -111,6 +111,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs index e98efa9f6ab..f5539abd9f5 100644 --- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs +++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs @@ -106,6 +106,15 @@ where i.status.as_ref().map(|i| i.0), i.currency.as_ref().map(|i| i.0), i.profile_id.clone(), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payment_intents/sankey.rs b/crates/analytics/src/payment_intents/sankey.rs new file mode 100644 index 00000000000..53fd03562f1 --- /dev/null +++ b/crates/analytics/src/payment_intents/sankey.rs @@ -0,0 +1,127 @@ +use common_enums::enums; +use common_utils::{ + errors::ParsingError, + types::{authentication::AuthInfo, TimeRange}, +}; +use error_stack::ResultExt; +use router_env::logger; +use time::PrimitiveDateTime; + +use crate::{ + clickhouse::ClickhouseClient, + query::{Aggregate, QueryBuilder, QueryFilter}, + types::{AnalyticsCollection, DBEnumWrapper, MetricsError, MetricsResult}, +}; + +#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)] +pub struct PaymentIntentMetricRow { + pub profile_id: Option<String>, + pub connector: Option<String>, + pub authentication_type: Option<DBEnumWrapper<enums::AuthenticationType>>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, + pub first_attempt: Option<i64>, + pub total: Option<bigdecimal::BigDecimal>, + pub count: Option<i64>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub start_bucket: Option<PrimitiveDateTime>, + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub end_bucket: Option<PrimitiveDateTime>, +} + +#[derive( + Debug, Default, serde::Deserialize, strum::AsRefStr, strum::EnumString, strum::Display, +)] +#[serde(rename_all = "snake_case")] +pub enum SessionizerRefundStatus { + FullRefunded, + #[default] + NotRefunded, + PartialRefunded, +} + +#[derive(Debug, serde::Deserialize)] +pub struct SankeyRow { + pub status: DBEnumWrapper<enums::IntentStatus>, + #[serde(default)] + pub refunds_status: Option<DBEnumWrapper<SessionizerRefundStatus>>, + pub attempt_count: i64, + pub count: i64, +} + +impl TryInto<SankeyRow> for serde_json::Value { + type Error = error_stack::Report<ParsingError>; + + fn try_into(self) -> Result<SankeyRow, Self::Error> { + logger::debug!("Parsing SankeyRow from {:?}", self); + serde_json::from_value(self).change_context(ParsingError::StructParseFailure( + "Failed to parse Sankey in clickhouse results", + )) + } +} + +pub async fn get_sankey_data( + clickhouse_client: &ClickhouseClient, + auth: &AuthInfo, + time_range: &TimeRange, +) -> MetricsResult<Vec<SankeyRow>> { + let mut query_builder = + QueryBuilder::<ClickhouseClient>::new(AnalyticsCollection::PaymentIntentSessionized); + query_builder + .add_select_column(Aggregate::<String>::Count { + field: None, + alias: Some("count"), + }) + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_select_column("status") + .attach_printable("Error adding select clause") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_select_column("refunds_status") + .attach_printable("Error adding select clause") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_select_column("attempt_count") + .attach_printable("Error adding select clause") + .change_context(MetricsError::QueryBuildingError)?; + + auth.set_filter_clause(&mut query_builder) + .change_context(MetricsError::QueryBuildingError)?; + + time_range + .set_filter_clause(&mut query_builder) + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_group_by_clause("status") + .attach_printable("Error adding group by clause") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_group_by_clause("refunds_status") + .attach_printable("Error adding group by clause") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_group_by_clause("attempt_count") + .attach_printable("Error adding group by clause") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .execute_query::<SankeyRow, _>(clickhouse_client) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(Ok) + .collect() +} diff --git a/crates/analytics/src/payment_intents/types.rs b/crates/analytics/src/payment_intents/types.rs index 03f2a196c20..1a9a2f2ed65 100644 --- a/crates/analytics/src/payment_intents/types.rs +++ b/crates/analytics/src/payment_intents/types.rs @@ -30,6 +30,63 @@ where .add_filter_in_range_clause(PaymentIntentDimensions::ProfileId, &self.profile_id) .attach_printable("Error adding profile id filter")?; } + if !self.connector.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::Connector, &self.connector) + .attach_printable("Error adding connector filter")?; + } + if !self.auth_type.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::AuthType, &self.auth_type) + .attach_printable("Error adding auth type filter")?; + } + if !self.payment_method.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::PaymentMethod, + &self.payment_method, + ) + .attach_printable("Error adding payment method filter")?; + } + if !self.payment_method_type.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::PaymentMethodType, + &self.payment_method_type, + ) + .attach_printable("Error adding payment method type filter")?; + } + if !self.card_network.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::CardNetwork, + &self.card_network, + ) + .attach_printable("Error adding card network filter")?; + } + if !self.merchant_id.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::MerchantId, &self.merchant_id) + .attach_printable("Error adding merchant id filter")?; + } + if !self.card_last_4.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::CardLast4, &self.card_last_4) + .attach_printable("Error adding card last 4 filter")?; + } + if !self.card_issuer.is_empty() { + builder + .add_filter_in_range_clause(PaymentIntentDimensions::CardIssuer, &self.card_issuer) + .attach_printable("Error adding card issuer filter")?; + } + if !self.error_reason.is_empty() { + builder + .add_filter_in_range_clause( + PaymentIntentDimensions::ErrorReason, + &self.error_reason, + ) + .attach_printable("Error adding error reason filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs index efc8aaf6983..4388b2071fe 100644 --- a/crates/analytics/src/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -10,12 +10,14 @@ pub struct PaymentMetricsAccumulator { pub payment_success_rate: SuccessRateAccumulator, pub payment_count: CountAccumulator, pub payment_success: CountAccumulator, - pub processed_amount: SumAccumulator, + pub processed_amount: ProcessedAmountAccumulator, pub avg_ticket_size: AverageAccumulator, pub payment_error_message: ErrorDistributionAccumulator, pub retries_count: CountAccumulator, - pub retries_amount_processed: SumAccumulator, + pub retries_amount_processed: RetriesAmountAccumulator, pub connector_success_rate: SuccessRateAccumulator, + pub payments_distribution: PaymentsDistributionAccumulator, + pub failure_reasons_distribution: FailureReasonsDistributionAccumulator, } #[derive(Debug, Default)] @@ -30,6 +32,12 @@ pub struct ErrorDistributionAccumulator { pub error_vec: Vec<ErrorDistributionRow>, } +#[derive(Debug, Default)] +pub struct FailureReasonsDistributionAccumulator { + pub count: u64, + pub count_without_retries: u64, +} + #[derive(Debug, Default)] pub struct SuccessRateAccumulator { pub success: i64, @@ -43,9 +51,11 @@ pub struct CountAccumulator { } #[derive(Debug, Default)] -#[repr(transparent)] -pub struct SumAccumulator { - pub total: Option<i64>, +pub struct ProcessedAmountAccumulator { + pub count_with_retries: Option<i64>, + pub total_with_retries: Option<i64>, + pub count_without_retries: Option<i64>, + pub total_without_retries: Option<i64>, } #[derive(Debug, Default)] @@ -54,6 +64,22 @@ pub struct AverageAccumulator { pub count: u32, } +#[derive(Debug, Default)] +#[repr(transparent)] +pub struct RetriesAmountAccumulator { + pub total: Option<i64>, +} + +#[derive(Debug, Default)] +pub struct PaymentsDistributionAccumulator { + pub success: u32, + pub failed: u32, + pub total: u32, + pub success_without_retries: u32, + pub failed_without_retries: u32, + pub total_without_retries: u32, +} + pub trait PaymentMetricAccumulator { type MetricOutput; @@ -107,6 +133,29 @@ impl PaymentDistributionAccumulator for ErrorDistributionAccumulator { } } +impl PaymentMetricAccumulator for FailureReasonsDistributionAccumulator { + type MetricOutput = (Option<u64>, Option<u64>); + + fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { + if let Some(count) = metrics.count { + if let Ok(count_u64) = u64::try_from(count) { + self.count += count_u64; + } + } + if metrics.first_attempt.unwrap_or(false) { + if let Some(count) = metrics.count { + if let Ok(count_u64) = u64::try_from(count) { + self.count_without_retries += count_u64; + } + } + } + } + + fn collect(self) -> Self::MetricOutput { + (Some(self.count), Some(self.count_without_retries)) + } +} + impl PaymentMetricAccumulator for SuccessRateAccumulator { type MetricOutput = Option<f64>; @@ -131,6 +180,81 @@ impl PaymentMetricAccumulator for SuccessRateAccumulator { } } +impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { + type MetricOutput = (Option<f64>, Option<f64>, Option<f64>, Option<f64>); + + fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { + if let Some(ref status) = metrics.status { + if status.as_ref() == &storage_enums::AttemptStatus::Charged { + if let Some(success) = metrics + .count + .and_then(|success| u32::try_from(success).ok()) + { + self.success += success; + if metrics.first_attempt.unwrap_or(false) { + self.success_without_retries += success; + } + } + } + if status.as_ref() == &storage_enums::AttemptStatus::Failure { + if let Some(failed) = metrics.count.and_then(|failed| u32::try_from(failed).ok()) { + self.failed += failed; + if metrics.first_attempt.unwrap_or(false) { + self.failed_without_retries += failed; + } + } + } + if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { + self.total += total; + if metrics.first_attempt.unwrap_or(false) { + self.total_without_retries += total; + } + } + } + } + + fn collect(self) -> Self::MetricOutput { + if self.total == 0 { + (None, None, None, None) + } else { + let success = Some(self.success); + let success_without_retries = Some(self.success_without_retries); + let failed = Some(self.failed); + let failed_without_retries = Some(self.failed_without_retries); + let total = Some(self.total); + let total_without_retries = Some(self.total_without_retries); + + let success_rate = match (success, total) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + + let success_rate_without_retries = + match (success_without_retries, total_without_retries) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + + let failed_rate = match (failed, total) { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + + let failed_rate_without_retries = match (failed_without_retries, total_without_retries) + { + (Some(s), Some(t)) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), + _ => None, + }; + ( + success_rate, + success_rate_without_retries, + failed_rate, + failed_rate_without_retries, + ) + } + } +} + impl PaymentMetricAccumulator for CountAccumulator { type MetricOutput = Option<u64>; #[inline] @@ -147,9 +271,63 @@ impl PaymentMetricAccumulator for CountAccumulator { } } -impl PaymentMetricAccumulator for SumAccumulator { - type MetricOutput = Option<u64>; +impl PaymentMetricAccumulator for ProcessedAmountAccumulator { + type MetricOutput = (Option<u64>, Option<u64>, Option<u64>, Option<u64>); #[inline] + fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { + self.total_with_retries = match ( + self.total_with_retries, + metrics.total.as_ref().and_then(ToPrimitive::to_i64), + ) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + + self.count_with_retries = match (self.count_with_retries, metrics.count) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + + if metrics.first_attempt.unwrap_or(false) { + self.total_without_retries = match ( + self.total_without_retries, + metrics.total.as_ref().and_then(ToPrimitive::to_i64), + ) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + + self.count_without_retries = match (self.count_without_retries, metrics.count) { + (None, None) => None, + (None, i @ Some(_)) | (i @ Some(_), None) => i, + (Some(a), Some(b)) => Some(a + b), + }; + } + } + #[inline] + fn collect(self) -> Self::MetricOutput { + let total_with_retries = u64::try_from(self.total_with_retries.unwrap_or(0)).ok(); + let count_with_retries = self.count_with_retries.and_then(|i| u64::try_from(i).ok()); + + let total_without_retries = u64::try_from(self.total_without_retries.unwrap_or(0)).ok(); + let count_without_retries = self + .count_without_retries + .and_then(|i| u64::try_from(i).ok()); + + ( + total_with_retries, + count_with_retries, + total_without_retries, + count_without_retries, + ) + } +} + +impl PaymentMetricAccumulator for RetriesAmountAccumulator { + type MetricOutput = Option<u64>; fn add_metrics_bucket(&mut self, metrics: &PaymentMetricRow) { self.total = match ( self.total, @@ -158,7 +336,7 @@ impl PaymentMetricAccumulator for SumAccumulator { (None, None) => None, (None, i @ Some(_)) | (i @ Some(_), None) => i, (Some(a), Some(b)) => Some(a + b), - } + }; } #[inline] fn collect(self) -> Self::MetricOutput { @@ -195,16 +373,39 @@ impl PaymentMetricAccumulator for AverageAccumulator { impl PaymentMetricsAccumulator { pub fn collect(self) -> PaymentMetricsBucketValue { + let ( + payment_processed_amount, + payment_processed_count, + payment_processed_amount_without_smart_retries, + payment_processed_count_without_smart_retries, + ) = self.processed_amount.collect(); + let ( + payments_success_rate_distribution, + payments_success_rate_distribution_without_smart_retries, + payments_failure_rate_distribution, + payments_failure_rate_distribution_without_smart_retries, + ) = self.payments_distribution.collect(); + let (failure_reason_count, failure_reason_count_without_smart_retries) = + self.failure_reasons_distribution.collect(); PaymentMetricsBucketValue { payment_success_rate: self.payment_success_rate.collect(), payment_count: self.payment_count.collect(), payment_success_count: self.payment_success.collect(), - payment_processed_amount: self.processed_amount.collect(), + payment_processed_amount, + payment_processed_count, + payment_processed_amount_without_smart_retries, + payment_processed_count_without_smart_retries, avg_ticket_size: self.avg_ticket_size.collect(), payment_error_message: self.payment_error_message.collect(), retries_count: self.retries_count.collect(), retries_amount_processed: self.retries_amount_processed.collect(), connector_success_rate: self.connector_success_rate.collect(), + payments_success_rate_distribution, + payments_success_rate_distribution_without_smart_retries, + payments_failure_rate_distribution, + payments_failure_rate_distribution_without_smart_retries, + failure_reason_count, + failure_reason_count_without_smart_retries, } } } diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index f41e1719450..59ae549b283 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -6,8 +6,8 @@ use api_models::analytics::{ MetricsBucketResponse, PaymentDimensions, PaymentDistributions, PaymentMetrics, PaymentMetricsBucketIdentifier, }, - AnalyticsMetadata, FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, - MetricsResponse, PaymentFiltersResponse, + FilterValue, GetPaymentFiltersRequest, GetPaymentMetricRequest, PaymentFiltersResponse, + PaymentsAnalyticsMetadata, PaymentsMetricsResponse, }; use common_utils::errors::CustomResult; use error_stack::ResultExt; @@ -48,7 +48,7 @@ pub async fn get_metrics( pool: &AnalyticsProvider, auth: &AuthInfo, req: GetPaymentMetricRequest, -) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { +) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> { let mut metrics_accumulator: HashMap< PaymentMetricsBucketIdentifier, PaymentMetricsAccumulator, @@ -137,32 +137,47 @@ pub async fn get_metrics( logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { - PaymentMetrics::PaymentSuccessRate => metrics_builder + PaymentMetrics::PaymentSuccessRate + | PaymentMetrics::SessionizedPaymentSuccessRate => metrics_builder .payment_success_rate .add_metrics_bucket(&value), - PaymentMetrics::PaymentCount => { + PaymentMetrics::PaymentCount | PaymentMetrics::SessionizedPaymentCount => { metrics_builder.payment_count.add_metrics_bucket(&value) } - PaymentMetrics::PaymentSuccessCount => { + PaymentMetrics::PaymentSuccessCount + | PaymentMetrics::SessionizedPaymentSuccessCount => { metrics_builder.payment_success.add_metrics_bucket(&value) } - PaymentMetrics::PaymentProcessedAmount => { + PaymentMetrics::PaymentProcessedAmount + | PaymentMetrics::SessionizedPaymentProcessedAmount => { metrics_builder.processed_amount.add_metrics_bucket(&value) } - PaymentMetrics::AvgTicketSize => { + PaymentMetrics::AvgTicketSize + | PaymentMetrics::SessionizedAvgTicketSize => { metrics_builder.avg_ticket_size.add_metrics_bucket(&value) } - PaymentMetrics::RetriesCount => { + PaymentMetrics::RetriesCount | PaymentMetrics::SessionizedRetriesCount => { metrics_builder.retries_count.add_metrics_bucket(&value); metrics_builder .retries_amount_processed .add_metrics_bucket(&value) } - PaymentMetrics::ConnectorSuccessRate => { + PaymentMetrics::ConnectorSuccessRate + | PaymentMetrics::SessionizedConnectorSuccessRate => { metrics_builder .connector_success_rate .add_metrics_bucket(&value); } + PaymentMetrics::PaymentsDistribution => { + metrics_builder + .payments_distribution + .add_metrics_bucket(&value); + } + PaymentMetrics::FailureReasons => { + metrics_builder + .failure_reasons_distribution + .add_metrics_bucket(&value); + } } } @@ -203,19 +218,56 @@ pub async fn get_metrics( } } } - + let mut total_payment_processed_amount = 0; + let mut total_payment_processed_count = 0; + let mut total_payment_processed_amount_without_smart_retries = 0; + let mut total_payment_processed_count_without_smart_retries = 0; + let mut total_failure_reasons_count = 0; + let mut total_failure_reasons_count_without_smart_retries = 0; let query_data: Vec<MetricsBucketResponse> = metrics_accumulator .into_iter() - .map(|(id, val)| MetricsBucketResponse { - values: val.collect(), - dimensions: id, + .map(|(id, val)| { + let collected_values = val.collect(); + if let Some(amount) = collected_values.payment_processed_amount { + total_payment_processed_amount += amount; + } + if let Some(count) = collected_values.payment_processed_count { + total_payment_processed_count += count; + } + if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { + total_payment_processed_amount_without_smart_retries += amount; + } + if let Some(count) = collected_values.payment_processed_count_without_smart_retries { + total_payment_processed_count_without_smart_retries += count; + } + if let Some(count) = collected_values.failure_reason_count { + total_failure_reasons_count += count; + } + if let Some(count) = collected_values.failure_reason_count_without_smart_retries { + total_failure_reasons_count_without_smart_retries += count; + } + MetricsBucketResponse { + values: collected_values, + dimensions: id, + } }) .collect(); - Ok(MetricsResponse { + Ok(PaymentsMetricsResponse { query_data, - meta_data: [AnalyticsMetadata { - current_time_range: req.time_range, + meta_data: [PaymentsAnalyticsMetadata { + total_payment_processed_amount: Some(total_payment_processed_amount), + total_payment_processed_amount_without_smart_retries: Some( + total_payment_processed_amount_without_smart_retries, + ), + total_payment_processed_count: Some(total_payment_processed_count), + total_payment_processed_count_without_smart_retries: Some( + total_payment_processed_count_without_smart_retries, + ), + total_failure_reasons_count: Some(total_failure_reasons_count), + total_failure_reasons_count_without_smart_retries: Some( + total_failure_reasons_count_without_smart_retries, + ), }], }) } @@ -297,6 +349,10 @@ pub async fn get_filters( PaymentDimensions::ClientVersion => fil.client_version, PaymentDimensions::ProfileId => fil.profile_id, PaymentDimensions::CardNetwork => fil.card_network, + PaymentDimensions::MerchantId => fil.merchant_id, + PaymentDimensions::CardLast4 => fil.card_last_4, + PaymentDimensions::CardIssuer => fil.card_issuer, + PaymentDimensions::ErrorReason => fil.error_reason, }) .collect::<Vec<String>>(); res.query_data.push(FilterValue { diff --git a/crates/analytics/src/payments/distribution.rs b/crates/analytics/src/payments/distribution.rs index 3bd8e5f7815..213b6244574 100644 --- a/crates/analytics/src/payments/distribution.rs +++ b/crates/analytics/src/payments/distribution.rs @@ -28,6 +28,12 @@ pub struct PaymentDistributionRow { pub client_source: Option<String>, pub client_version: Option<String>, pub profile_id: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, + pub first_attempt: Option<bool>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, pub error_message: Option<String>, diff --git a/crates/analytics/src/payments/distribution/payment_error_message.rs b/crates/analytics/src/payments/distribution/payment_error_message.rs index 087ec5a640e..241754ee041 100644 --- a/crates/analytics/src/payments/distribution/payment_error_message.rs +++ b/crates/analytics/src/payments/distribution/payment_error_message.rs @@ -155,6 +155,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/filters.rs b/crates/analytics/src/payments/filters.rs index 094fd574169..51805acaae2 100644 --- a/crates/analytics/src/payments/filters.rs +++ b/crates/analytics/src/payments/filters.rs @@ -60,4 +60,8 @@ pub struct PaymentFilterRow { pub client_version: Option<String>, pub profile_id: Option<String>, pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, } diff --git a/crates/analytics/src/payments/metrics.rs b/crates/analytics/src/payments/metrics.rs index 731f03a247a..23b133ad035 100644 --- a/crates/analytics/src/payments/metrics.rs +++ b/crates/analytics/src/payments/metrics.rs @@ -19,6 +19,7 @@ mod payment_count; mod payment_processed_amount; mod payment_success_count; mod retries_count; +mod sessionized_metrics; mod success_rate; use avg_ticket_size::AvgTicketSize; @@ -41,6 +42,12 @@ pub struct PaymentMetricRow { pub client_source: Option<String>, pub client_version: Option<String>, pub profile_id: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, + pub first_attempt: Option<bool>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, #[serde(with = "common_utils::custom_serde::iso8601::option")] @@ -122,6 +129,51 @@ where .load_metrics(dimensions, auth, filters, granularity, time_range, pool) .await } + Self::SessionizedPaymentSuccessRate => { + sessionized_metrics::PaymentSuccessRate + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedPaymentCount => { + sessionized_metrics::PaymentCount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedPaymentSuccessCount => { + sessionized_metrics::PaymentSuccessCount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedPaymentProcessedAmount => { + sessionized_metrics::PaymentProcessedAmount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedAvgTicketSize => { + sessionized_metrics::AvgTicketSize + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedRetriesCount => { + sessionized_metrics::RetriesCount + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::SessionizedConnectorSuccessRate => { + sessionized_metrics::ConnectorSuccessRate + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::PaymentsDistribution => { + sessionized_metrics::PaymentsDistribution + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } + Self::FailureReasons => { + sessionized_metrics::FailureReasons + .load_metrics(dimensions, auth, filters, granularity, time_range, pool) + .await + } } } } diff --git a/crates/analytics/src/payments/metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/avg_ticket_size.rs index ec76bfc86dc..fc2f44cada2 100644 --- a/crates/analytics/src/payments/metrics/avg_ticket_size.rs +++ b/crates/analytics/src/payments/metrics/avg_ticket_size.rs @@ -117,6 +117,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/connector_success_rate.rs index e44e87a7e5f..36783eda72a 100644 --- a/crates/analytics/src/payments/metrics/connector_success_rate.rs +++ b/crates/analytics/src/payments/metrics/connector_success_rate.rs @@ -112,6 +112,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/metrics/payment_count.rs b/crates/analytics/src/payments/metrics/payment_count.rs index 642ba9ef035..bd0b52d7cf8 100644 --- a/crates/analytics/src/payments/metrics/payment_count.rs +++ b/crates/analytics/src/payments/metrics/payment_count.rs @@ -103,6 +103,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs index c31b8873cb8..b8b3868803c 100644 --- a/crates/analytics/src/payments/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs @@ -111,6 +111,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/payment_success_count.rs index a45a4557c52..ea926761c13 100644 --- a/crates/analytics/src/payments/metrics/payment_success_count.rs +++ b/crates/analytics/src/payments/metrics/payment_success_count.rs @@ -110,6 +110,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/metrics/retries_count.rs b/crates/analytics/src/payments/metrics/retries_count.rs index c3c7d40e321..9695e1fe18b 100644 --- a/crates/analytics/src/payments/metrics/retries_count.rs +++ b/crates/analytics/src/payments/metrics/retries_count.rs @@ -107,6 +107,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs new file mode 100644 index 00000000000..b7f13667917 --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/avg_ticket_size.rs @@ -0,0 +1,146 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::{PaymentMetric, PaymentMetricRow}; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct AvgTicketSize; + +#[async_trait::async_trait] +impl<T> PaymentMetric<T> for AvgTicketSize +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Sum { + field: "amount", + alias: Some("total"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .add_filter_clause( + PaymentDimensions::PaymentStatus, + storage_enums::AttemptStatus::Charged, + ) + .switch()?; + + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + i.status.as_ref().map(|i| i.0), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs new file mode 100644 index 00000000000..66006c15a2a --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/connector_success_rate.rs @@ -0,0 +1,141 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct ConnectorSuccessRate; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for ConnectorSuccessRate +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentDimensions::PaymentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_custom_filter_clause(PaymentDimensions::Connector, "NULL", FilterTypes::IsNotNull) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs new file mode 100644 index 00000000000..70ae64e0115 --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs @@ -0,0 +1,208 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, + ToSql, Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct FailureReasons; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for FailureReasons +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut inner_query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + inner_query_builder + .add_select_column("sum(sign_flag)") + .switch()?; + + inner_query_builder + .add_custom_filter_clause( + PaymentDimensions::ErrorReason, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + + time_range + .set_filter_clause(&mut inner_query_builder) + .attach_printable("Error filtering time range for inner query") + .switch()?; + + let inner_query_string = inner_query_builder + .build_query() + .attach_printable("Error building inner query") + .change_context(MetricsError::QueryBuildingError)?; + + let mut outer_query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + + for dim in dimensions.iter() { + outer_query_builder.add_select_column(dim).switch()?; + } + + outer_query_builder + .add_select_column("sum(sign_flag) AS count") + .switch()?; + + outer_query_builder + .add_select_column(format!("({}) AS total", inner_query_string)) + .switch()?; + + outer_query_builder + .add_select_column("first_attempt") + .switch()?; + + outer_query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + + outer_query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters + .set_filter_clause(&mut outer_query_builder) + .switch()?; + + auth.set_filter_clause(&mut outer_query_builder).switch()?; + + time_range + .set_filter_clause(&mut outer_query_builder) + .attach_printable("Error filtering time range for outer query") + .switch()?; + + outer_query_builder + .add_filter_clause( + PaymentDimensions::PaymentStatus, + storage_enums::AttemptStatus::Failure, + ) + .switch()?; + + outer_query_builder + .add_custom_filter_clause( + PaymentDimensions::ErrorReason, + "NULL", + FilterTypes::IsNotNull, + ) + .switch()?; + + for dim in dimensions.iter() { + outer_query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + outer_query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut outer_query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + outer_query_builder + .add_order_by_clause("count", Order::Descending) + .attach_printable("Error adding order by clause") + .switch()?; + + for dim in dimensions.iter() { + if dim != &PaymentDimensions::ErrorReason { + outer_query_builder + .add_order_by_clause(dim, Order::Ascending) + .attach_printable("Error adding order by clause") + .switch()?; + } + } + + outer_query_builder + .set_limit_by(5, &[PaymentDimensions::Connector]) + .attach_printable("Error adding limit clause") + .switch()?; + + outer_query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs new file mode 100644 index 00000000000..e3a5e370534 --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs @@ -0,0 +1,20 @@ +mod avg_ticket_size; +mod connector_success_rate; +mod failure_reasons; +mod payment_count; +mod payment_processed_amount; +mod payment_success_count; +mod payments_distribution; +mod retries_count; +mod success_rate; +pub(super) use avg_ticket_size::AvgTicketSize; +pub(super) use connector_success_rate::ConnectorSuccessRate; +pub(super) use failure_reasons::FailureReasons; +pub(super) use payment_count::PaymentCount; +pub(super) use payment_processed_amount::PaymentProcessedAmount; +pub(super) use payment_success_count::PaymentSuccessCount; +pub(super) use payments_distribution::PaymentsDistribution; +pub(super) use retries_count::RetriesCount; +pub(super) use success_rate::PaymentSuccessRate; + +pub use super::{PaymentMetric, PaymentMetricAnalytics, PaymentMetricRow}; diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs new file mode 100644 index 00000000000..29d083dd232 --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_count.rs @@ -0,0 +1,129 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentCount; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for PaymentCount +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + i.status.as_ref().map(|i| i.0), + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs new file mode 100644 index 00000000000..9bc554eaae7 --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_processed_amount.rs @@ -0,0 +1,155 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentProcessedAmount; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for PaymentProcessedAmount +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentDimensions::PaymentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder.add_select_column("first_attempt").switch()?; + + query_builder + .add_select_column(Aggregate::Sum { + field: "amount", + alias: Some("total"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .add_filter_clause( + PaymentDimensions::PaymentStatus, + storage_enums::AttemptStatus::Charged, + ) + .switch()?; + + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs new file mode 100644 index 00000000000..b307b77d5da --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payment_success_count.rs @@ -0,0 +1,139 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use diesel_models::enums as storage_enums; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentSuccessCount; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for PaymentSuccessCount +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .add_filter_clause( + PaymentDimensions::PaymentStatus, + storage_enums::AttemptStatus::Charged, + ) + .switch()?; + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs new file mode 100644 index 00000000000..e0987dd0d22 --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/payments_distribution.rs @@ -0,0 +1,142 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentsDistribution; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for PaymentsDistribution +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentDimensions::PaymentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + + query_builder.add_select_column("first_attempt").switch()?; + + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + query_builder + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") + .switch()?; + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs new file mode 100644 index 00000000000..b79489744cc --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/retries_count.rs @@ -0,0 +1,135 @@ +use std::collections::HashSet; + +use api_models::{ + analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, + }, + enums::IntentStatus, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{ + Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, + Window, + }, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct RetriesCount; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for RetriesCount +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + _dimensions: &[PaymentDimensions], + auth: &AuthInfo, + _filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized); + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Sum { + field: "amount", + alias: Some("total"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + auth.set_filter_clause(&mut query_builder).switch()?; + + query_builder + .add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt) + .switch()?; + query_builder + .add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal) + .switch()?; + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs new file mode 100644 index 00000000000..30e7471d608 --- /dev/null +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/success_rate.rs @@ -0,0 +1,135 @@ +use std::collections::HashSet; + +use api_models::analytics::{ + payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, + Granularity, TimeRange, +}; +use common_utils::errors::ReportSwitchExt; +use error_stack::ResultExt; +use time::PrimitiveDateTime; + +use super::PaymentMetricRow; +use crate::{ + enums::AuthInfo, + query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, + types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, +}; + +#[derive(Default)] +pub(crate) struct PaymentSuccessRate; + +#[async_trait::async_trait] +impl<T> super::PaymentMetric<T> for PaymentSuccessRate +where + T: AnalyticsDataSource + super::PaymentMetricAnalytics, + PrimitiveDateTime: ToSql<T>, + AnalyticsCollection: ToSql<T>, + Granularity: GroupByClause<T>, + Aggregate<&'static str>: ToSql<T>, + Window<&'static str>: ToSql<T>, +{ + async fn load_metrics( + &self, + dimensions: &[PaymentDimensions], + auth: &AuthInfo, + filters: &PaymentFilters, + granularity: &Option<Granularity>, + time_range: &TimeRange, + pool: &T, + ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { + let mut query_builder: QueryBuilder<T> = + QueryBuilder::new(AnalyticsCollection::PaymentSessionized); + let mut dimensions = dimensions.to_vec(); + + dimensions.push(PaymentDimensions::PaymentStatus); + + for dim in dimensions.iter() { + query_builder.add_select_column(dim).switch()?; + } + + query_builder + .add_select_column(Aggregate::Count { + field: None, + alias: Some("count"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Min { + field: "created_at", + alias: Some("start_bucket"), + }) + .switch()?; + query_builder + .add_select_column(Aggregate::Max { + field: "created_at", + alias: Some("end_bucket"), + }) + .switch()?; + + filters.set_filter_clause(&mut query_builder).switch()?; + + auth.set_filter_clause(&mut query_builder).switch()?; + + time_range + .set_filter_clause(&mut query_builder) + .attach_printable("Error filtering time range") + .switch()?; + + for dim in dimensions.iter() { + query_builder + .add_group_by_clause(dim) + .attach_printable("Error grouping by dimensions") + .switch()?; + } + + if let Some(granularity) = granularity.as_ref() { + granularity + .set_group_by_clause(&mut query_builder) + .attach_printable("Error adding granularity") + .switch()?; + } + + query_builder + .execute_query::<PaymentMetricRow, _>(pool) + .await + .change_context(MetricsError::QueryBuildingError)? + .change_context(MetricsError::QueryExecutionFailure)? + .into_iter() + .map(|i| { + Ok(( + PaymentMetricsBucketIdentifier::new( + i.currency.as_ref().map(|i| i.0), + None, + i.connector.clone(), + i.authentication_type.as_ref().map(|i| i.0), + i.payment_method.clone(), + i.payment_method_type.clone(), + i.client_source.clone(), + i.client_version.clone(), + i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), + TimeRange { + start_time: match (granularity, i.start_bucket) { + (Some(g), Some(st)) => g.clip_to_start(st)?, + _ => time_range.start_time, + }, + end_time: granularity.as_ref().map_or_else( + || Ok(time_range.end_time), + |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(), + )?, + }, + ), + i, + )) + }) + .collect::<error_stack::Result< + HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, + crate::query::PostProcessingError, + >>() + .change_context(MetricsError::PostProcessingFailure) + } +} diff --git a/crates/analytics/src/payments/metrics/success_rate.rs b/crates/analytics/src/payments/metrics/success_rate.rs index b8e840c2203..e756115a67d 100644 --- a/crates/analytics/src/payments/metrics/success_rate.rs +++ b/crates/analytics/src/payments/metrics/success_rate.rs @@ -106,6 +106,11 @@ where i.client_source.clone(), i.client_version.clone(), i.profile_id.clone(), + i.card_network.clone(), + i.merchant_id.clone(), + i.card_last_4.clone(), + i.card_issuer.clone(), + i.error_reason.clone(), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/payments/types.rs b/crates/analytics/src/payments/types.rs index b7984a19ea3..e23fc6cbbb3 100644 --- a/crates/analytics/src/payments/types.rs +++ b/crates/analytics/src/payments/types.rs @@ -48,7 +48,7 @@ where PaymentDimensions::PaymentMethodType, &self.payment_method_type, ) - .attach_printable("Error adding payment method filter")?; + .attach_printable("Error adding payment method type filter")?; } if !self.client_source.is_empty() { builder @@ -84,6 +84,26 @@ where ) .attach_printable("Error adding card network filter")?; } + if !self.merchant_id.is_empty() { + builder + .add_filter_in_range_clause(PaymentDimensions::MerchantId, &self.merchant_id) + .attach_printable("Error adding merchant id filter")?; + } + if !self.card_last_4.is_empty() { + builder + .add_filter_in_range_clause(PaymentDimensions::CardLast4, &self.card_last_4) + .attach_printable("Error adding card last 4 filter")?; + } + if !self.card_issuer.is_empty() { + builder + .add_filter_in_range_clause(PaymentDimensions::CardIssuer, &self.card_issuer) + .attach_printable("Error adding card issuer filter")?; + } + if !self.error_reason.is_empty() { + builder + .add_filter_in_range_clause(PaymentDimensions::ErrorReason, &self.error_reason) + .attach_printable("Error adding error reason filter")?; + } Ok(()) } } diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index 5f8a2f4a330..7ce338f7db3 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -1,4 +1,4 @@ -use std::marker::PhantomData; +use std::{fmt, marker::PhantomData}; use api_models::{ analytics::{ @@ -301,8 +301,8 @@ pub enum Order { Descending, } -impl std::fmt::Display for Order { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Display for Order { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Ascending => write!(f, "asc"), Self::Descending => write!(f, "desc"), @@ -335,6 +335,68 @@ pub struct TopN { pub order: Order, } +#[derive(Debug, Clone)] +pub struct LimitByClause { + limit: u64, + columns: Vec<String>, +} + +impl fmt::Display for LimitByClause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "LIMIT {} BY {}", self.limit, self.columns.join(", ")) + } +} + +#[derive(Debug, Default, Clone, Copy)] +pub enum FilterCombinator { + #[default] + And, + Or, +} + +impl<T: AnalyticsDataSource> ToSql<T> for FilterCombinator { + fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + Ok(match self { + Self::And => " AND ", + Self::Or => " OR ", + } + .to_owned()) + } +} + +#[derive(Debug, Clone)] +pub enum Filter { + Plain(String, FilterTypes, String), + NestedFilter(FilterCombinator, Vec<Filter>), +} + +impl Default for Filter { + fn default() -> Self { + Self::NestedFilter(FilterCombinator::default(), Vec::new()) + } +} + +impl<T: AnalyticsDataSource> ToSql<T> for Filter { + fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { + Ok(match self { + Self::Plain(l, op, r) => filter_type_to_sql(l, op, r), + Self::NestedFilter(operator, filters) => { + format!( + "( {} )", + filters + .iter() + .map(|f| <Self as ToSql<T>>::to_sql(f, table_engine)) + .collect::<Result<Vec<String>, _>>()? + .join( + <FilterCombinator as ToSql<T>>::to_sql(operator, table_engine)? + .as_ref() + ) + ) + } + }) + } +} + #[derive(Debug)] pub struct QueryBuilder<T> where @@ -342,9 +404,11 @@ where AnalyticsCollection: ToSql<T>, { columns: Vec<String>, - filters: Vec<(String, FilterTypes, String)>, + filters: Filter, group_by: Vec<String>, + order_by: Vec<String>, having: Option<Vec<(String, FilterTypes, String)>>, + limit_by: Option<LimitByClause>, outer_select: Vec<String>, top_n: Option<TopN>, table: AnalyticsCollection, @@ -444,7 +508,7 @@ impl_to_sql_for_to_string!( DisputeStage ); -#[derive(Debug)] +#[derive(Debug, Clone, Copy)] pub enum FilterTypes { Equal, NotEqual, @@ -483,7 +547,9 @@ where columns: Default::default(), filters: Default::default(), group_by: Default::default(), + order_by: Default::default(), having: Default::default(), + limit_by: Default::default(), outer_select: Default::default(), top_n: Default::default(), table, @@ -580,7 +646,7 @@ where rhs: impl ToSql<T>, comparison: FilterTypes, ) -> QueryResult<()> { - self.filters.push(( + let filter = Filter::Plain( lhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter key")?, @@ -588,9 +654,18 @@ where rhs.to_sql(&self.table_engine) .change_context(QueryBuildingError::SqlSerializeError) .attach_printable("Error serializing filter value")?, - )); + ); + self.add_nested_filter_clause(filter); Ok(()) } + pub fn add_nested_filter_clause(&mut self, filter: Filter) { + match &mut self.filters { + Filter::NestedFilter(_, ref mut filters) => filters.push(filter), + f @ Filter::Plain(_, _, _) => { + self.filters = Filter::NestedFilter(FilterCombinator::And, vec![f.clone(), filter]); + } + } + } pub fn add_filter_in_range_clause( &mut self, @@ -623,6 +698,37 @@ where Ok(()) } + pub fn add_order_by_clause( + &mut self, + column: impl ToSql<T>, + order: impl ToSql<T>, + ) -> QueryResult<()> { + let column_sql = column + .to_sql(&self.table_engine) + .change_context(QueryBuildingError::SqlSerializeError) + .attach_printable("Error serializing order by column")?; + + let order_sql = order + .to_sql(&self.table_engine) + .change_context(QueryBuildingError::SqlSerializeError) + .attach_printable("Error serializing order direction")?; + + self.order_by.push(format!("{} {}", column_sql, order_sql)); + Ok(()) + } + + pub fn set_limit_by(&mut self, limit: u64, columns: &[impl ToSql<T>]) -> QueryResult<()> { + let columns = columns + .iter() + .map(|col| col.to_sql(&self.table_engine)) + .collect::<Result<Vec<String>, _>>() + .change_context(QueryBuildingError::SqlSerializeError) + .attach_printable("Error serializing LIMIT BY columns")?; + + self.limit_by = Some(LimitByClause { limit, columns }); + Ok(()) + } + pub fn add_granularity_in_mins(&mut self, granularity: &Granularity) -> QueryResult<()> { let interval = match granularity { Granularity::OneMin => "1", @@ -638,12 +744,9 @@ where Ok(()) } - fn get_filter_clause(&self) -> String { - self.filters - .iter() - .map(|(l, op, r)| filter_type_to_sql(l, op, r)) - .collect::<Vec<String>>() - .join(" AND ") + fn get_filter_clause(&self) -> QueryResult<String> { + <Filter as ToSql<T>>::to_sql(&self.filters, &self.table_engine) + .change_context(QueryBuildingError::SqlSerializeError) } fn get_select_clause(&self) -> String { @@ -731,9 +834,10 @@ where .attach_printable("Error serializing table value")?, ); - if !self.filters.is_empty() { + let filter_clause = self.get_filter_clause()?; + if !filter_clause.is_empty() { query.push_str(" WHERE "); - query.push_str(&self.get_filter_clause()); + query.push_str(filter_clause.as_str()); } if !self.group_by.is_empty() { @@ -758,6 +862,15 @@ where } } + if !self.order_by.is_empty() { + query.push_str(" ORDER BY "); + query.push_str(&self.order_by.join(", ")); + } + + if let Some(limit_by) = &self.limit_by { + query.push_str(&format!(" {}", limit_by)); + } + if !self.outer_select.is_empty() { query.insert_str( 0, diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index e9395439209..ae72bbeffea 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -330,6 +330,30 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -355,6 +379,12 @@ impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow { client_source, client_version, profile_id, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, + first_attempt, total, count, start_bucket, @@ -407,6 +437,26 @@ impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributi ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -419,6 +469,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributi ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let first_attempt: Option<bool> = row.try_get("first_attempt").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? @@ -436,6 +490,12 @@ impl<'a> FromRow<'a, PgRow> for super::payments::distribution::PaymentDistributi client_source, client_version, profile_id, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, + first_attempt, total, count, error_message, @@ -493,6 +553,22 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { currency, status, @@ -504,6 +580,10 @@ impl<'a> FromRow<'a, PgRow> for super::payments::filters::PaymentFilterRow { client_version, profile_id, card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, }) } } @@ -524,6 +604,45 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let connector: Option<String> = row.try_get("connector").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method: Option<String> = + row.try_get("payment_method").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method_type: Option<String> = + row.try_get("payment_method_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), @@ -532,6 +651,10 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let first_attempt: Option<i64> = row.try_get("first_attempt").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; // Removing millisecond precision to get accurate diffs against clickhouse let start_bucket: Option<PrimitiveDateTime> = row .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")? @@ -543,6 +666,16 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::metrics::PaymentIntentMe status, currency, profile_id, + connector, + authentication_type, + payment_method, + payment_method_type, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, + first_attempt, total, count, start_bucket, @@ -567,11 +700,58 @@ impl<'a> FromRow<'a, PgRow> for super::payment_intents::filters::PaymentIntentFi ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; - + let connector: Option<String> = row.try_get("connector").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let authentication_type: Option<DBEnumWrapper<AuthenticationType>> = + row.try_get("authentication_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method: Option<String> = + row.try_get("payment_method").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let payment_method_type: Option<String> = + row.try_get("payment_method_type").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_network: Option<String> = row.try_get("card_network").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let merchant_id: Option<String> = row.try_get("merchant_id").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_last_4: Option<String> = row.try_get("card_last_4").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let card_issuer: Option<String> = row.try_get("card_issuer").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; + let error_reason: Option<String> = row.try_get("error_reason").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { status, currency, profile_id, + connector, + authentication_type, + payment_method, + payment_method_type, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, }) } } @@ -716,7 +896,11 @@ impl ToSql<SqlxClient> for AnalyticsCollection { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { match self { Self::Payment => Ok("payment_attempt".to_string()), + Self::PaymentSessionized => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("PaymentSessionized table is not implemented for Sqlx"))?, Self::Refund => Ok("refund".to_string()), + Self::RefundSessionized => Err(error_stack::report!(ParsingError::UnknownError) + .attach_printable("RefundSessionized table is not implemented for Sqlx"))?, Self::SdkEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("SdkEventsAudit table is not implemented for Sqlx"))?, Self::SdkEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) @@ -725,6 +909,10 @@ impl ToSql<SqlxClient> for AnalyticsCollection { .attach_printable("ApiEvents table is not implemented for Sqlx"))?, Self::FraudCheck => Ok("fraud_check".to_string()), Self::PaymentIntent => Ok("payment_intent".to_string()), + Self::PaymentIntentSessionized => Err(error_stack::report!( + ParsingError::UnknownError + ) + .attach_printable("PaymentIntentSessionized table is not implemented for Sqlx"))?, Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError) .attach_printable("ConnectorEvents table is not implemented for Sqlx"))?, Self::ApiEventsAnalytics => Err(error_stack::report!(ParsingError::UnknownError) diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs index 6593e5d6eb0..6bdd11fcd73 100644 --- a/crates/analytics/src/types.rs +++ b/crates/analytics/src/types.rs @@ -26,12 +26,15 @@ pub enum AnalyticsDomain { #[derive(Debug, strum::AsRefStr, strum::Display, Clone, Copy)] pub enum AnalyticsCollection { Payment, + PaymentSessionized, Refund, + RefundSessionized, FraudCheck, SdkEvents, SdkEventsAnalytics, ApiEvents, PaymentIntent, + PaymentIntentSessionized, ConnectorEvents, OutgoingWebhookEvent, Dispute, @@ -56,6 +59,12 @@ impl<T: FromStr + Display> AsRef<T> for DBEnumWrapper<T> { } } +impl<T: FromStr + Display + Default> Default for DBEnumWrapper<T> { + fn default() -> Self { + Self(T::default()) + } +} + impl<T> FromStr for DBEnumWrapper<T> where T: FromStr + Display, diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs index 7b73f5a1c1d..fc21bf09819 100644 --- a/crates/analytics/src/utils.rs +++ b/crates/analytics/src/utils.rs @@ -12,11 +12,39 @@ use api_models::analytics::{ use strum::IntoEnumIterator; pub fn get_payment_dimensions() -> Vec<NameDescription> { - PaymentDimensions::iter().map(Into::into).collect() + vec![ + PaymentDimensions::Connector, + PaymentDimensions::PaymentMethod, + PaymentDimensions::PaymentMethodType, + PaymentDimensions::Currency, + PaymentDimensions::AuthType, + PaymentDimensions::PaymentStatus, + PaymentDimensions::ClientSource, + PaymentDimensions::ClientVersion, + PaymentDimensions::ProfileId, + PaymentDimensions::CardNetwork, + PaymentDimensions::MerchantId, + ] + .into_iter() + .map(Into::into) + .collect() } pub fn get_payment_intent_dimensions() -> Vec<NameDescription> { - PaymentIntentDimensions::iter().map(Into::into).collect() + vec![ + PaymentIntentDimensions::PaymentIntentStatus, + PaymentIntentDimensions::Currency, + PaymentIntentDimensions::ProfileId, + PaymentIntentDimensions::Connector, + PaymentIntentDimensions::AuthType, + PaymentIntentDimensions::PaymentMethod, + PaymentIntentDimensions::PaymentMethodType, + PaymentIntentDimensions::CardNetwork, + PaymentIntentDimensions::MerchantId, + ] + .into_iter() + .map(Into::into) + .collect() } pub fn get_refund_dimensions() -> Vec<NameDescription> { diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 0379ec09547..b95404080b0 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -200,6 +200,28 @@ pub struct AnalyticsMetadata { pub current_time_range: TimeRange, } +#[derive(Debug, serde::Serialize)] +pub struct PaymentsAnalyticsMetadata { + pub total_payment_processed_amount: Option<u64>, + pub total_payment_processed_amount_without_smart_retries: Option<u64>, + pub total_payment_processed_count: Option<u64>, + pub total_payment_processed_count_without_smart_retries: Option<u64>, + pub total_failure_reasons_count: Option<u64>, + pub total_failure_reasons_count_without_smart_retries: Option<u64>, +} + +#[derive(Debug, serde::Serialize)] +pub struct PaymentIntentsAnalyticsMetadata { + pub total_success_rate: Option<f64>, + pub total_success_rate_without_smart_retries: Option<f64>, + pub total_smart_retried_amount: Option<u64>, + pub total_smart_retried_amount_without_smart_retries: Option<u64>, + pub total_payment_processed_amount: Option<u64>, + pub total_payment_processed_amount_without_smart_retries: Option<u64>, + pub total_payment_processed_count: Option<u64>, + pub total_payment_processed_count_without_smart_retries: Option<u64>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentFiltersRequest { @@ -320,6 +342,20 @@ pub struct MetricsResponse<T> { pub meta_data: [AnalyticsMetadata; 1], } +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentsMetricsResponse<T> { + pub query_data: Vec<T>, + pub meta_data: [PaymentsAnalyticsMetadata; 1], +} + +#[derive(Debug, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PaymentIntentsMetricsResponse<T> { + pub query_data: Vec<T>, + pub meta_data: [PaymentIntentsAnalyticsMetadata; 1], +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventFiltersRequest { @@ -390,3 +426,21 @@ pub struct GetDisputeMetricRequest { #[serde(default)] pub delta: bool, } + +#[derive(Clone, Debug, Default, serde::Serialize)] +#[serde(rename_all = "snake_case")] +pub struct SankeyResponse { + pub normal_success: i64, + pub normal_failure: i64, + pub cancelled: i64, + pub smart_retried_success: i64, + pub smart_retried_failure: i64, + pub pending: i64, + pub partial_refunded: i64, + pub refunded: i64, + pub disputed: i64, + pub pm_awaited: i64, + pub customer_awaited: i64, + pub merchant_awaited: i64, + pub confirmation_awaited: i64, +} diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index 61e336185b6..41f11c19ef8 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -6,7 +6,9 @@ use std::{ use common_utils::id_type; use super::{NameDescription, TimeRange}; -use crate::enums::{Currency, IntentStatus}; +use crate::enums::{ + AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, +}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct PaymentIntentFilters { @@ -16,6 +18,24 @@ pub struct PaymentIntentFilters { pub currency: Vec<Currency>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, + #[serde(default)] + pub connector: Vec<Connector>, + #[serde(default)] + pub auth_type: Vec<AuthenticationType>, + #[serde(default)] + pub payment_method: Vec<PaymentMethod>, + #[serde(default)] + pub payment_method_type: Vec<PaymentMethodType>, + #[serde(default)] + pub card_network: Vec<String>, + #[serde(default)] + pub merchant_id: Vec<id_type::MerchantId>, + #[serde(default)] + pub card_last_4: Vec<String>, + #[serde(default)] + pub card_issuer: Vec<String>, + #[serde(default)] + pub error_reason: Vec<String>, } #[derive( @@ -40,6 +60,15 @@ pub enum PaymentIntentDimensions { PaymentIntentStatus, Currency, ProfileId, + Connector, + AuthType, + PaymentMethod, + PaymentMethodType, + CardNetwork, + MerchantId, + CardLast4, + CardIssuer, + ErrorReason, } #[derive( @@ -61,6 +90,14 @@ pub enum PaymentIntentMetrics { TotalSmartRetries, SmartRetriedAmount, PaymentIntentCount, + PaymentsSuccessRate, + SessionizedSuccessfulSmartRetries, + SessionizedTotalSmartRetries, + SessionizedSmartRetriedAmount, + SessionizedPaymentIntentCount, + SessionizedPaymentsSuccessRate, + SessionizedPaymentProcessedAmount, + SessionizedPaymentsDistribution, } #[derive(Debug, Default, serde::Serialize)] @@ -75,6 +112,7 @@ pub mod metric_behaviour { pub struct TotalSmartRetries; pub struct SmartRetriedAmount; pub struct PaymentIntentCount; + pub struct PaymentsSuccessRate; } impl From<PaymentIntentMetrics> for NameDescription { @@ -100,6 +138,15 @@ pub struct PaymentIntentMetricsBucketIdentifier { pub status: Option<IntentStatus>, pub currency: Option<Currency>, pub profile_id: Option<String>, + pub connector: Option<String>, + pub auth_type: Option<AuthenticationType>, + pub payment_method: Option<String>, + pub payment_method_type: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -113,12 +160,30 @@ impl PaymentIntentMetricsBucketIdentifier { status: Option<IntentStatus>, currency: Option<Currency>, profile_id: Option<String>, + connector: Option<String>, + auth_type: Option<AuthenticationType>, + payment_method: Option<String>, + payment_method_type: Option<String>, + card_network: Option<String>, + merchant_id: Option<String>, + card_last_4: Option<String>, + card_issuer: Option<String>, + error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { status, currency, profile_id, + connector, + auth_type, + payment_method, + payment_method_type, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -130,6 +195,15 @@ impl Hash for PaymentIntentMetricsBucketIdentifier { self.status.map(|i| i.to_string()).hash(state); self.currency.hash(state); self.profile_id.hash(state); + self.connector.hash(state); + self.auth_type.map(|i| i.to_string()).hash(state); + self.payment_method.hash(state); + self.payment_method_type.hash(state); + self.card_network.hash(state); + self.merchant_id.hash(state); + self.card_last_4.hash(state); + self.card_issuer.hash(state); + self.error_reason.hash(state); self.time_bucket.hash(state); } } @@ -149,7 +223,19 @@ pub struct PaymentIntentMetricsBucketValue { pub successful_smart_retries: Option<u64>, pub total_smart_retries: Option<u64>, pub smart_retried_amount: Option<u64>, + pub smart_retried_amount_without_smart_retries: Option<u64>, pub payment_intent_count: Option<u64>, + pub successful_payments: Option<u32>, + pub successful_payments_without_smart_retries: Option<u32>, + pub total_payments: Option<u32>, + pub payments_success_rate: Option<f64>, + pub payments_success_rate_without_smart_retries: Option<f64>, + pub payment_processed_amount: Option<u64>, + pub payment_processed_count: Option<u64>, + pub payment_processed_amount_without_smart_retries: Option<u64>, + pub payment_processed_count_without_smart_retries: Option<u64>, + pub payments_success_rate_distribution_without_smart_retries: Option<f64>, + pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index c474d47ee63..1120ab092d7 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -33,6 +33,14 @@ pub struct PaymentFilters { pub card_network: Vec<CardNetwork>, #[serde(default)] pub profile_id: Vec<id_type::ProfileId>, + #[serde(default)] + pub merchant_id: Vec<id_type::MerchantId>, + #[serde(default)] + pub card_last_4: Vec<String>, + #[serde(default)] + pub card_issuer: Vec<String>, + #[serde(default)] + pub error_reason: Vec<String>, } #[derive( @@ -68,6 +76,12 @@ pub enum PaymentDimensions { ClientVersion, ProfileId, CardNetwork, + MerchantId, + #[strum(serialize = "card_last_4")] + #[serde(rename = "card_last_4")] + CardLast4, + CardIssuer, + ErrorReason, } #[derive( @@ -92,6 +106,15 @@ pub enum PaymentMetrics { AvgTicketSize, RetriesCount, ConnectorSuccessRate, + SessionizedPaymentSuccessRate, + SessionizedPaymentCount, + SessionizedPaymentSuccessCount, + SessionizedPaymentProcessedAmount, + SessionizedAvgTicketSize, + SessionizedRetriesCount, + SessionizedConnectorSuccessRate, + PaymentsDistribution, + FailureReasons, } #[derive(Debug, Default, serde::Serialize)] @@ -159,6 +182,11 @@ pub struct PaymentMetricsBucketIdentifier { pub client_source: Option<String>, pub client_version: Option<String>, pub profile_id: Option<String>, + pub card_network: Option<String>, + pub merchant_id: Option<String>, + pub card_last_4: Option<String>, + pub card_issuer: Option<String>, + pub error_reason: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, // Coz FE sucks @@ -179,6 +207,11 @@ impl PaymentMetricsBucketIdentifier { client_source: Option<String>, client_version: Option<String>, profile_id: Option<String>, + card_network: Option<String>, + merchant_id: Option<String>, + card_last_4: Option<String>, + card_issuer: Option<String>, + error_reason: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { @@ -191,6 +224,11 @@ impl PaymentMetricsBucketIdentifier { client_source, client_version, profile_id, + card_network, + merchant_id, + card_last_4, + card_issuer, + error_reason, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } @@ -208,6 +246,11 @@ impl Hash for PaymentMetricsBucketIdentifier { self.client_source.hash(state); self.client_version.hash(state); self.profile_id.hash(state); + self.card_network.hash(state); + self.merchant_id.hash(state); + self.card_last_4.hash(state); + self.card_issuer.hash(state); + self.error_reason.hash(state); self.time_bucket.hash(state); } } @@ -228,11 +271,20 @@ pub struct PaymentMetricsBucketValue { pub payment_count: Option<u64>, pub payment_success_count: Option<u64>, pub payment_processed_amount: Option<u64>, + pub payment_processed_count: Option<u64>, + pub payment_processed_amount_without_smart_retries: Option<u64>, + pub payment_processed_count_without_smart_retries: Option<u64>, pub avg_ticket_size: Option<f64>, pub payment_error_message: Option<Vec<ErrorResult>>, pub retries_count: Option<u64>, pub retries_amount_processed: Option<u64>, pub connector_success_rate: Option<f64>, + pub payments_success_rate_distribution: Option<f64>, + pub payments_success_rate_distribution_without_smart_retries: Option<f64>, + pub payments_failure_rate_distribution: Option<f64>, + pub payments_failure_rate_distribution_without_smart_retries: Option<f64>, + pub failure_reason_count: Option<u64>, + pub failure_reason_count_without_smart_retries: Option<u64>, } #[derive(Debug, serde::Serialize)] diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs index 5816df518bd..7272abffbff 100644 --- a/crates/api_models/src/events.rs +++ b/crates/api_models/src/events.rs @@ -131,6 +131,7 @@ impl_api_event_type!( GetDisputeFilterRequest, DisputeFiltersResponse, GetDisputeMetricRequest, + SankeyResponse, OrganizationResponse, OrganizationCreateRequest, OrganizationUpdateRequest, @@ -155,6 +156,18 @@ impl<T> ApiEventMetric for MetricsResponse<T> { } } +impl<T> ApiEventMetric for PaymentsMetricsResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Miscellaneous) + } +} + +impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Miscellaneous) + } +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 89159bcff86..aa6db56bb34 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -26,6 +26,7 @@ pub mod routes { GetSdkEventMetricRequest, ReportRequest, }; use common_enums::EntityType; + use common_utils::types::TimeRange; use error_stack::{report, ResultExt}; use futures::{stream::FuturesUnordered, StreamExt}; @@ -142,6 +143,10 @@ pub mod routes { web::resource("filters/disputes") .route(web::post().to(get_merchant_dispute_filters)), ) + .service( + web::resource("metrics/sankey") + .route(web::post().to(get_merchant_sankey)), + ) .service( web::scope("/merchant") .service( @@ -190,6 +195,10 @@ pub mod routes { .service( web::resource("filters/disputes") .route(web::post().to(get_merchant_dispute_filters)), + ) + .service( + web::resource("metrics/sankey") + .route(web::post().to(get_merchant_sankey)), ), ) .service( @@ -232,6 +241,10 @@ pub mod routes { .service( web::resource("report/payments") .route(web::post().to(generate_org_payment_report)), + ) + .service( + web::resource("metrics/sankey") + .route(web::post().to(get_org_sankey)), ), ) .service( @@ -290,6 +303,10 @@ pub mod routes { .service( web::resource("sdk_event_logs") .route(web::post().to(get_profile_sdk_events)), + ) + .service( + web::resource("metrics/sankey") + .route(web::post().to(get_profile_sankey)), ), ), ) @@ -2277,4 +2294,103 @@ pub mod routes { )) .await } + + pub async fn get_merchant_sankey( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<TimeRange>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSankey; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let auth: AuthInfo = AuthInfo::MerchantLevel { + org_id: org_id.clone(), + merchant_ids: vec![merchant_id.clone()], + }; + analytics::payment_intents::get_sankey(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_org_sankey( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<TimeRange>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSankey; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let auth: AuthInfo = AuthInfo::OrgLevel { + org_id: org_id.clone(), + }; + analytics::payment_intents::get_sankey(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Organization, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } + + pub async fn get_profile_sankey( + state: web::Data<AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<TimeRange>, + ) -> impl Responder { + let flow = AnalyticsFlow::GetSankey; + let payload = json_payload.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state: crate::routes::SessionState, auth: AuthenticationData, req, _| async move { + let org_id = auth.merchant_account.get_org_id(); + let merchant_id = auth.merchant_account.get_id(); + let profile_id = auth + .profile_id + .ok_or(report!(UserErrors::JwtProfileIdMissing)) + .change_context(AnalyticsError::AccessForbiddenError)?; + let auth: AuthInfo = AuthInfo::ProfileLevel { + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + profile_ids: vec![profile_id.clone()], + }; + analytics::payment_intents::get_sankey(&state.pool, &auth, req) + .await + .map(ApplicationResponse::Json) + }, + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Profile, + }, + api_locking::LockAction::NotApplicable, + )) + .await + } }
2024-09-12T08:10:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Adding metrics, filters and APIs for Analytics v2 Dashboard - Payments page The new Analytics Dashboard will now have the following metrics: - Sessionizer Payment Intents based Metrics: - Total Payments Savings - Amount saved via Smart Retries - Payments Success Rate - Overall successful payment intents divided by total intents - Payment Lifecycle - Displayed as a Sankey - Total Payments Processed - Total payments processed amount and count based on all successful intents - Successful Payments Distribution - Overall successful intents divided by total number of intents based on group by - Failed Payments Distribution - Overall failed intents divided by total number of intents based on group by - Sessionizer Payment Attempts based Metrics: - Total Payments Processed - Total payments processed amount and count based on all successful attempts - Successful Payments Distribution - Overall successful attempts divided by total number of attempts based on group by - Failed Payments Distribution - Overall failed attempts divided by total number of attempts based on group by - Failure Reasons Distribution - Failure Reason count along with ratio of count / total failed attempts based on group by - Refunds based Metrics: - Total Refunds Processed - Successful refunds - Disputes based Metrics: - All Disputes - Total number of disputes irrespective of status The following filters have been added: - Payment Attempts: - Merchant_id - Card last 4 - Error Reason - Card Issuer - Payment Intents: - connector - authentication_type - payment_method - payment_method_type - card_network - merchant id - card_last_4 - error_reason - card_issuer New API endpoints for Payments Lifecycle (Sankey) on different levels: Payments Lifecycle (Sankey) |   -- | -- Org Level | /analytics/v1/org/metrics/sankey Merchant Level | /analytics/v1/merchant/metrics/sankey Profile Level | /analytics/v1/profile/metrics/sankey Separated out the existing payment_attempts and payment_intents based metrics and sessionizer_payment_attempts and sessionizer_payment_intents based metrics to support backwards compatibility ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Enhancing dashboard experience and providing meaningful and important data analytics for the merchants to make informed decisions ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Curls for different metrics (which are newly created or modified): Payment Attempts based metrics: - sessionized_payment_processed_amount ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-10-01T23:30:00Z" }, "groupByNames": [ "connector", "payment_method" ], "filters": { "merchant_id": ["merchant_1726046328"] }, "timeSeries": { "granularity": "G_ONEDAY" }, "source": "BATCH", "metrics": [ "sessionized_payment_processed_amount" ], "delta": true } ]' ``` Fields to look out for in the response body: queryData: ```bash "payment_processed_amount": 6540, "payment_processed_count": 1, "payment_processed_amount_without_smart_retries": 0, "payment_processed_count_without_smart_retries": null, ``` metaData: ```bash "total_payment_processed_amount": 117720, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_count": 18, "total_payment_processed_count_without_smart_retries": 0, ``` - payments_distribution ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-10-01T23:30:00Z" }, "groupByNames": [ "connector" ], "filters": { "merchant_id": ["merchant_1726046328"] }, "source": "BATCH", "metrics": [ "payments_distribution" ], "delta": true } ]' ``` Fields to look out for in the response body: queryData: ```bash "payments_success_rate_distribution": 75.0, "payments_failure_rate_distribution": 25.0, ``` - failure_reasons ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: test_admin' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-10-01T23:30:00Z" }, "groupByNames": [ "connector", "error_reason" ], "filters": { "merchant_id": ["merchant_1726046328"] }, "source": "BATCH", "metrics": [ "failure_reasons" ], "delta": true } ]' ``` Fields to look out for in the response body: queryData: ```bash "connector": "adyen", "failure_reason_count": 1, "failure_reason_count_without_smart_retries": 0, "error_reason": "Test Failure Reason 4", ``` metaData: ```bash "total_failure_reasons_count": 7, "total_failure_reasons_count_without_smart_retries": 0 ``` Payment Intents based metrics: - sessionized_smart_retried_amount ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-09-26T09:22:30Z" }, "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "merchant_id": ["merchant_1726046328"] }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_smart_retried_amount" ] } ]' ``` Fields to look out for in the response body queryData: ```bash "smart_retried_amount": 6540, "smart_retried_amount_without_smart_retries": 0, ``` metaData ```bash "total_smart_retried_amount": 6540, "total_smart_retried_amount_without_smart_retries": 0 ``` - sessionized_payments_success_rate ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODIxMTk4Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb19BN1F4SjN6TG05Z1NmYkZqUTNpNSJ9.RG85zvOvkm3vikVXppvevenXHkr-cI0nfIhGhiZcMts' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-09-26T09:22:30Z" }, "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "merchant_id": ["merchant_1726046328"] }, "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_payments_success_rate" ] } ]' ``` Fields to look out for in the response body: queryData: ```bash "successful_payments": 7, "successful_payments_without_smart_retries": 7, "total_payments": 7, "payments_success_rate": 100.0, "payments_success_rate_without_smart_retries": 100.0, ``` metaData: ```bash "total_success_rate": 88.23529411764706, "total_success_rate_without_smart_retries": 82.3529411764706, ``` - sessionized_payment_processed_amount ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODczNDQyMywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.716-yn9HhCUU6-1lymVwVWtd82GG4u2m2t_bbcG3cwc' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-10-26T09:22:30Z" }, "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "merchant_id": ["merchant_1726046328"] }, "groupByNames": [ "connector" ], "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_payment_processed_amount" ] } ]' ``` Fields to look out for in the response body: queryData: ```bash "payment_processed_amount": 26160, "payment_processed_count": 4, "payment_processed_amount_without_smart_retries": 19620, "payment_processed_count_without_smart_retries": 3, ``` metaData: ```bash "total_payment_processed_amount": 26160, "total_payment_processed_amount_without_smart_retries": 19620, "total_payment_processed_count": 4, "total_payment_processed_count_without_smart_retries": 3 ``` - sessionized_payments_distribution ```bash curl --location 'http://localhost:8080/analytics/v2/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-US,en;q=0.9' \ --header 'Connection: keep-alive' \ --header 'Content-Type: application/json' \ --header 'Origin: http://localhost:9000' \ --header 'QueryType: SingleStatTimeseries' \ --header 'Referer: http://localhost:9000/' \ --header 'Sec-Fetch-Dest: empty' \ --header 'Sec-Fetch-Mode: cors' \ --header 'Sec-Fetch-Site: same-site' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyODczNDQyMywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSJ9.716-yn9HhCUU6-1lymVwVWtd82GG4u2m2t_bbcG3cwc' \ --header 'sec-ch-ua: "Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-09-11T00:00:00Z", "endTime": "2024-10-26T09:22:30Z" }, "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "merchant_id": ["merchant_1726046328"] }, "groupByNames": [ "connector" ], "mode": "ORDER", "source": "BATCH", "metrics": [ "sessionized_payments_distribution" ] } ]' ``` Fields to look out for in the response body: queryData: ```bash "payments_success_rate_distribution_without_smart_retries": 50.0, "payments_failure_rate_distribution_without_smart_retries": 16.666666666666668, ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
b7139483bb4735b7dfaf7e659ab33a16a90af1db
juspay/hyperswitch
juspay__hyperswitch-5805
Bug: feat(payouts): Add profile level get filters API for payouts Currently payout get filter API gives filters whole merchant. Since dashboard is being moved to profile level, filter API at profile level should be needed.
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 515a7be959a..65490e2d270 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -947,10 +947,11 @@ pub async fn payouts_filtered_list_core( pub async fn payouts_list_available_filters_core( state: SessionState, merchant_account: domain::MerchantAccount, + profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>, time_range: api::TimeRange, ) -> RouterResponse<api::PayoutListFilters> { let db = state.store.as_ref(); - let payout = db + let payouts = db .filter_payouts_by_time_range_constraints( merchant_account.get_id(), &time_range, @@ -959,9 +960,11 @@ pub async fn payouts_list_available_filters_core( .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts); + let filters = db .get_filters_for_payouts( - payout.as_slice(), + payouts.as_slice(), merchant_account.get_id(), storage_enums::MerchantStorageScheme::PostgresOnly, ) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 8201380cc29..d3b9801cedf 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1021,7 +1021,12 @@ impl Payouts { .route(web::post().to(payouts_list_by_filter_profile)), ) .service( - web::resource("/filter").route(web::post().to(payouts_list_available_filters)), + web::resource("/filter") + .route(web::post().to(payouts_list_available_filters_for_merchant)), + ) + .service( + web::resource("/profile/filter") + .route(web::post().to(payouts_list_available_filters_for_profile)), ); } route = route diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index bc14a619745..8c45f9fdfd9 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -320,10 +320,10 @@ pub async fn payouts_list_by_filter_profile( .await } -/// Payouts - Available filters +/// Payouts - Available filters for Merchant #[cfg(feature = "olap")] #[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))] -pub async fn payouts_list_available_filters( +pub async fn payouts_list_available_filters_for_merchant( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<payment_types::TimeRange>, @@ -337,7 +337,41 @@ pub async fn payouts_list_available_filters( &req, payload, |state, auth, req, _| { - payouts_list_available_filters_core(state, auth.merchant_account, req) + payouts_list_available_filters_core(state, auth.merchant_account, None, req) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuth(Permission::PayoutRead), + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +/// Payouts - Available filters for Profile +#[cfg(feature = "olap")] +#[instrument(skip_all, fields(flow = ?Flow::PayoutsFilter))] +pub async fn payouts_list_available_filters_for_profile( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<payment_types::TimeRange>, +) -> HttpResponse { + let flow = Flow::PayoutsFilter; + let payload = json_payload.into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, req, _| { + payouts_list_available_filters_core( + state, + auth.merchant_account, + auth.profile_id.map(|profile_id| vec![profile_id]), + req, + ) }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth),
2024-09-05T08:25:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> - This PR adds a profile level get filters api for payouts. ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> Closes #5805. ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ``` curl --location 'http://localhost:8080/payouts/profile/filter' \ --header 'Content-Type: application/json' \ --header 'authorization: Bearer JWT with profile_id' \ --data '{"start_time":"2024-08-05T18:30:00Z","end_time":"2024-09-05T08:19:00Z"}' ``` Response will look like this ```json { "connector": [], "currency": [], "status": [], "payout_method": [] } ``` This API should only give filters for payouts which have profile_id as the one in JWT. This cannot be tested in integ/sandbox as the JWT currently doesn't have profile_id. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
db04ded4a460abfb073167d59b3c51a4e7972c54
juspay/hyperswitch
juspay__hyperswitch-5802
Bug: [BUG] Fix errors on Payment methods v2 ### Feature Description Fix errors on Payment methods v2 ### Possible Implementation Fix errors on Payment methods v2 ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e9c9d504b47..7da8327b5b8 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -36,7 +36,7 @@ v2 = ["customer_v2", "payment_methods_v2", "payment_v2", "common_default", "api_ 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"] +payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2"] # Partial Auth # The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
2024-09-05T06:31:14Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Build was failing so Fixed errors on payment_methods_v2 for the build to succeed. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [ ] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
db04ded4a460abfb073167d59b3c51a4e7972c54
juspay/hyperswitch
juspay__hyperswitch-5820
Bug: feat(users): Add profile level role and profile level authz - Create profile level users. - Create authorization checks for entity level in apis. default to merchant
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index a6e94ed294a..7c4d1acc6bf 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -20,6 +20,7 @@ pub mod routes { GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, }; + use common_enums::EntityType; use error_stack::{report, ResultExt}; use crate::{ @@ -393,7 +394,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -429,7 +433,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -472,7 +479,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -510,7 +520,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -546,7 +559,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -589,7 +605,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -627,7 +646,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -663,7 +685,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -706,7 +731,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -738,7 +766,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -774,7 +805,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -811,7 +845,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -848,7 +885,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -876,7 +916,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -902,7 +945,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -935,7 +981,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -961,7 +1010,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -989,7 +1041,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1015,7 +1070,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1048,7 +1106,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1070,7 +1131,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1096,7 +1160,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1126,7 +1193,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1157,7 +1227,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1186,7 +1259,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1234,7 +1310,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1280,7 +1359,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Organization, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1333,7 +1415,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1381,7 +1466,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1427,7 +1515,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Organization, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1480,7 +1571,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1528,7 +1622,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1574,7 +1671,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Organization, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1626,7 +1726,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::GenerateReport), + &auth::JWTAuth { + permission: Permission::GenerateReport, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1664,7 +1767,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1700,7 +1806,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1743,7 +1852,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1771,7 +1883,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1797,7 +1912,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1830,7 +1948,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1859,7 +1980,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1899,7 +2023,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1939,7 +2066,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1967,7 +2097,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -2000,7 +2133,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -2026,7 +2162,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -2064,7 +2203,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -2107,7 +2249,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -2143,7 +2288,10 @@ pub mod routes { .await .map(ApplicationResponse::Json) }, - &auth::JWTAuth(Permission::Analytics), + &auth::JWTAuth { + permission: Permission::Analytics, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index d7afe8dafde..3f315360211 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -90,7 +90,7 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day #[cfg(feature = "email")] pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_"; -pub const ROLE_CACHE_PREFIX: &str = "CR_"; +pub const ROLE_INFO_CACHE_PREFIX: &str = "CR_INFO_"; #[cfg(feature = "olap")] pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify"; diff --git a/crates/router/src/consts/user_role.rs b/crates/router/src/consts/user_role.rs index 672e5830013..fbabec67291 100644 --- a/crates/router/src/consts/user_role.rs +++ b/crates/router/src/consts/user_role.rs @@ -5,5 +5,6 @@ pub const ROLE_ID_MERCHANT_IAM_ADMIN: &str = "merchant_iam_admin"; pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer"; pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator"; pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support"; +pub const ROLE_ID_PROFILE_CUSTOMER_SUPPORT: &str = "profile_customer_support"; pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000"; pub const MAX_ROLE_NAME_LENGTH: usize = 64; diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index ae97bfe6044..ae92360b13e 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -1,4 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -118,6 +119,7 @@ pub async fn retrieve_merchant_account( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -170,6 +172,7 @@ pub async fn update_merchant_account( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -230,6 +233,7 @@ pub async fn connector_create( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -261,6 +265,7 @@ pub async fn connector_create( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -323,6 +328,7 @@ pub async fn connector_retrieve( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorAccountRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -361,6 +367,7 @@ pub async fn connector_retrieve( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorAccountRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -406,6 +413,7 @@ pub async fn payment_connector_list( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorAccountRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -457,6 +465,7 @@ pub async fn payment_connector_list_profile( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorAccountRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -517,6 +526,7 @@ pub async fn connector_update( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -568,6 +578,7 @@ pub async fn connector_update( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -623,6 +634,7 @@ pub async fn connector_delete( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -661,6 +673,7 @@ pub async fn connector_delete( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -743,6 +756,7 @@ pub async fn business_profile_create( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -773,6 +787,7 @@ pub async fn business_profile_create( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -807,6 +822,7 @@ pub async fn business_profile_retrieve( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -837,6 +853,7 @@ pub async fn business_profile_retrieve( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -872,6 +889,7 @@ pub async fn business_profile_update( &auth::JWTAuthMerchantAndProfileFromRoute { merchant_id: merchant_id.clone(), profile_id: profile_id.clone(), + minimum_entity_level: EntityType::Merchant, required_permission: Permission::MerchantAccountWrite, }, req.headers(), @@ -904,6 +922,7 @@ pub async fn business_profile_update( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -955,6 +974,7 @@ pub async fn business_profiles_list( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -989,6 +1009,7 @@ pub async fn business_profiles_list_at_profile_level( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -1018,7 +1039,10 @@ pub async fn toggle_connector_agnostic_mit( |state, _, req, _| connector_agnostic_mit_toggle(state, &merchant_id, &profile_id, req), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs index 68e5687e249..71632cc5749 100644 --- a/crates/router/src/routes/api_keys.rs +++ b/crates/router/src/routes/api_keys.rs @@ -1,4 +1,5 @@ use actix_web::{web, HttpRequest, Responder}; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -37,6 +38,7 @@ pub async fn api_key_create( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ApiKeyWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -67,6 +69,7 @@ pub async fn api_key_create( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::ApiKeyWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -104,6 +107,7 @@ pub async fn api_key_retrieve( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromHeader { required_permission: Permission::ApiKeyRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -136,6 +140,7 @@ pub async fn api_key_retrieve( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ApiKeyRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -172,6 +177,7 @@ pub async fn api_key_update( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ApiKeyWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -204,6 +210,7 @@ pub async fn api_key_update( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ApiKeyWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -237,6 +244,7 @@ pub async fn api_key_revoke( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ApiKeyWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -266,6 +274,7 @@ pub async fn api_key_revoke( &auth::JWTAuthMerchantFromRoute { merchant_id: merchant_id.clone(), required_permission: Permission::ApiKeyWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -318,6 +327,7 @@ pub async fn api_key_list( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::ApiKeyRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs index f2a70a7b905..4738df5ed2c 100644 --- a/crates/router/src/routes/blocklist.rs +++ b/crates/router/src/routes/blocklist.rs @@ -1,5 +1,6 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::blocklist as api_blocklist; +use common_enums::EntityType; use router_env::Flow; use crate::{ @@ -36,7 +37,10 @@ pub async fn add_entry_to_blocklist( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -72,7 +76,10 @@ pub async fn remove_entry_from_blocklist( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -110,7 +117,10 @@ pub async fn list_blocked_payment_methods( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MerchantAccountRead), + &auth::JWTAuth { + permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -148,7 +158,10 @@ pub async fn toggle_blocklist_guard( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/connector_onboarding.rs b/crates/router/src/routes/connector_onboarding.rs index f5555f5bf9b..f7494e182c1 100644 --- a/crates/router/src/routes/connector_onboarding.rs +++ b/crates/router/src/routes/connector_onboarding.rs @@ -1,5 +1,6 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::connector_onboarding as api_types; +use common_enums::EntityType; use router_env::Flow; use super::AppState; @@ -21,7 +22,10 @@ pub async fn get_action_url( &http_req, req_payload.clone(), core::get_action_url, - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -40,7 +44,10 @@ pub async fn sync_onboarding_status( &http_req, req_payload.clone(), core::sync_onboarding_status, - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -59,7 +66,10 @@ pub async fn reset_tracking_id( &http_req, req_payload.clone(), core::reset_tracking_id, - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index 2e3ce35a974..66ff1f8e323 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -1,4 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse, Responder}; +use common_enums::EntityType; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use common_utils::id_type; use router_env::{instrument, tracing, Flow}; @@ -25,7 +26,10 @@ pub async fn customers_create( |state, auth, req, _| create_customer(state, auth.merchant_account, auth.key_store, req), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::CustomerWrite), + &auth::JWTAuth { + permission: Permission::CustomerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -48,7 +52,10 @@ pub async fn customers_retrieve( .into_inner(); let auth = if auth::is_jwt_auth(req.headers()) { - Box::new(auth::JWTAuth(Permission::CustomerRead)) + Box::new(auth::JWTAuth { + permission: Permission::CustomerRead, + minimum_entity_level: EntityType::Merchant, + }) } else { match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, @@ -88,7 +95,10 @@ pub async fn customers_retrieve( let payload = web::Json(customers::GlobalId::new(path.into_inner())).into_inner(); let auth = if auth::is_jwt_auth(req.headers()) { - Box::new(auth::JWTAuth(Permission::CustomerRead)) + Box::new(auth::JWTAuth { + permission: Permission::CustomerRead, + minimum_entity_level: EntityType::Merchant, + }) } else { match auth::is_ephemeral_auth(req.headers()) { Ok(auth) => auth, @@ -133,7 +143,10 @@ pub async fn customers_list( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::CustomerRead), + &auth::JWTAuth { + permission: Permission::CustomerRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -169,7 +182,10 @@ pub async fn customers_update( }, auth::auth_type( &auth::ApiKeyAuth, - &auth::JWTAuth(Permission::CustomerWrite), + &auth::JWTAuth { + permission: Permission::CustomerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -204,7 +220,10 @@ pub async fn customers_update( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::CustomerWrite), + &auth::JWTAuth { + permission: Permission::CustomerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -230,7 +249,10 @@ pub async fn customers_delete( |state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::CustomerWrite), + &auth::JWTAuth { + permission: Permission::CustomerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -259,7 +281,10 @@ pub async fn customers_delete( |state, auth, req, _| delete_customer(state, auth.merchant_account, req, auth.key_store), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::CustomerWrite), + &auth::JWTAuth { + permission: Permission::CustomerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -294,7 +319,10 @@ pub async fn get_customer_mandates( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MandateRead), + &auth::JWTAuth { + permission: Permission::MandateRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs index e8edcd704d7..98ba33a64b4 100644 --- a/crates/router/src/routes/disputes.rs +++ b/crates/router/src/routes/disputes.rs @@ -1,6 +1,7 @@ use actix_multipart::Multipart; use actix_web::{web, HttpRequest, HttpResponse}; use api_models::disputes as dispute_models; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use crate::{core::api_locking, services::authorization::permissions::Permission}; @@ -48,7 +49,10 @@ pub async fn retrieve_dispute( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeRead), + &auth::JWTAuth { + permission: Permission::DisputeRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -97,7 +101,10 @@ pub async fn retrieve_disputes_list( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeRead), + &auth::JWTAuth { + permission: Permission::DisputeRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -152,7 +159,10 @@ pub async fn retrieve_disputes_list_profile( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeRead), + &auth::JWTAuth { + permission: Permission::DisputeRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -201,7 +211,10 @@ pub async fn accept_dispute( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeWrite), + &auth::JWTAuth { + permission: Permission::DisputeWrite, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -244,7 +257,10 @@ pub async fn submit_dispute_evidence( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeWrite), + &auth::JWTAuth { + permission: Permission::DisputeWrite, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -295,7 +311,10 @@ pub async fn attach_dispute_evidence( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeWrite), + &auth::JWTAuth { + permission: Permission::DisputeWrite, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -338,7 +357,10 @@ pub async fn retrieve_dispute_evidence( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeRead), + &auth::JWTAuth { + permission: Permission::DisputeRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -376,7 +398,10 @@ pub async fn delete_dispute_evidence( |state, auth, req, _| disputes::delete_evidence(state, auth.merchant_account, req), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::DisputeWrite), + &auth::JWTAuth { + permission: Permission::DisputeWrite, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index d2c5d5e4644..70b36f87983 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -1,4 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -131,7 +132,10 @@ pub async fn retrieve_mandates_list( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MandateRead), + &auth::JWTAuth { + permission: Permission::MandateRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index b3c7f5cc59b..e4d7337ef72 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -4,6 +4,7 @@ ))] use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; +use common_enums::EntityType; use common_utils::{errors::CustomResult, id_type}; use diesel_models::enums::IntentStatus; use error_stack::ResultExt; @@ -663,11 +664,17 @@ pub async fn list_countries_currencies_for_connector_payment_method( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 95b65e5be57..f249285c554 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -6,6 +6,7 @@ pub mod helpers; use actix_web::{web, Responder}; use api_models::payments::HeaderPayload; +use common_enums::EntityType; use error_stack::report; use masking::PeekInterface; use router_env::{env, instrument, logger, tracing, types, Flow}; @@ -149,7 +150,10 @@ pub async fn payments_create( env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PaymentWrite), + &auth::JWTAuth { + permission: Permission::PaymentWrite, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), }, @@ -309,7 +313,10 @@ pub async fn payments_retrieve( }, auth::auth_type( &*auth_type, - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), locking_action, @@ -1016,7 +1023,10 @@ pub async fn payments_list( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -1073,7 +1083,10 @@ pub async fn profile_payments_list( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -1103,7 +1116,10 @@ pub async fn payments_list_by_filter( req, ) }, - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1132,7 +1148,10 @@ pub async fn profile_payments_list_by_filter( req, ) }, - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1155,7 +1174,10 @@ pub async fn get_filters_for_payments( |state, auth: auth::AuthenticationData, req, _| { payments::get_filters_for_payments(state, auth.merchant_account, auth.key_store, req) }, - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1176,7 +1198,10 @@ pub async fn get_payment_filters( |state, auth: auth::AuthenticationData, _, _| { payments::get_payment_filters(state, auth.merchant_account, None) }, - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1201,7 +1226,10 @@ pub async fn get_payment_filters_profile( auth.profile_id.map(|profile_id| vec![profile_id]), ) }, - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1224,7 +1252,10 @@ pub async fn get_payments_aggregates( |state, auth: auth::AuthenticationData, req, _| { payments::get_aggregates_for_payments(state, auth.merchant_account, req) }, - &auth::JWTAuth(Permission::PaymentRead), + &auth::JWTAuth { + permission: Permission::PaymentRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -1275,7 +1306,10 @@ pub async fn payments_approve( env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PaymentWrite), + &auth::JWTAuth { + permission: Permission::PaymentWrite, + minimum_entity_level: EntityType::Profile, + }, http_req.headers(), ), }, @@ -1331,7 +1365,10 @@ pub async fn payments_reject( env::Env::Production => &auth::HeaderAuth(auth::ApiKeyAuth), _ => auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PaymentWrite), + &auth::JWTAuth { + permission: Permission::PaymentWrite, + minimum_entity_level: EntityType::Profile, + }, http_req.headers(), ), }, diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs index 8c45f9fdfd9..50c18d71f2a 100644 --- a/crates/router/src/routes/payouts.rs +++ b/crates/router/src/routes/payouts.rs @@ -2,6 +2,7 @@ use actix_web::{ body::{BoxBody, MessageBody}, web, HttpRequest, HttpResponse, Responder, }; +use common_enums::EntityType; use common_utils::consts; use router_env::{instrument, tracing, Flow}; @@ -75,7 +76,10 @@ pub async fn payouts_retrieve( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PayoutRead), + &auth::JWTAuth { + permission: Permission::PayoutRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -213,7 +217,10 @@ pub async fn payouts_list( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PayoutRead), + &auth::JWTAuth { + permission: Permission::PayoutRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -248,7 +255,10 @@ pub async fn payouts_list_profile( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PayoutRead), + &auth::JWTAuth { + permission: Permission::PayoutRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -277,7 +287,10 @@ pub async fn payouts_list_by_filter( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PayoutRead), + &auth::JWTAuth { + permission: Permission::PayoutRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -312,7 +325,10 @@ pub async fn payouts_list_by_filter_profile( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PayoutRead), + &auth::JWTAuth { + permission: Permission::PayoutRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -341,7 +357,10 @@ pub async fn payouts_list_available_filters_for_merchant( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PayoutRead), + &auth::JWTAuth { + permission: Permission::PayoutRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -375,7 +394,10 @@ pub async fn payouts_list_available_filters_for_profile( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::PayoutRead), + &auth::JWTAuth { + permission: Permission::PayoutRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index bdef96794f4..4b964dba626 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -1,4 +1,5 @@ use actix_web::{web, HttpRequest, HttpResponse}; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -47,7 +48,10 @@ pub async fn refunds_create( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RefundWrite), + &auth::JWTAuth { + permission: Permission::RefundWrite, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -108,7 +112,10 @@ pub async fn refunds_retrieve( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RefundRead), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -233,7 +240,10 @@ pub async fn refunds_list( |state, auth, req, _| refund_list(state, auth.merchant_account, None, req), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RefundRead), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -278,7 +288,10 @@ pub async fn refunds_list_profile( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RefundRead), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -316,7 +329,10 @@ pub async fn refunds_filter_list( |state, auth, req, _| refund_filter_list(state, auth.merchant_account, req), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RefundRead), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -349,7 +365,10 @@ pub async fn get_refunds_filters(state: web::Data<AppState>, req: HttpRequest) - |state, auth, _, _| get_filters_for_refunds(state, auth.merchant_account, None), auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RefundRead), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -391,7 +410,10 @@ pub async fn get_refunds_filters_profile( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RefundRead), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 09bf77c62ef..8533c9ddea9 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -5,6 +5,7 @@ use actix_web::{web, HttpRequest, Responder}; use api_models::{enums, routing as routing_types, routing::RoutingRetrieveQuery}; +use common_enums::EntityType; use router_env::{ tracing::{self, instrument}, Flow, @@ -42,11 +43,17 @@ pub async fn routing_create_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -79,11 +86,17 @@ pub async fn routing_link_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -125,6 +138,7 @@ pub async fn routing_link_config( &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -132,6 +146,7 @@ pub async fn routing_link_config( &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) @@ -164,11 +179,17 @@ pub async fn routing_retrieve_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -200,11 +221,17 @@ pub async fn list_routing_configs( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -236,11 +263,17 @@ pub async fn list_routing_configs_for_profile( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -283,6 +316,7 @@ pub async fn routing_unlink_config( &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) @@ -316,11 +350,17 @@ pub async fn routing_unlink_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -355,11 +395,17 @@ pub async fn routing_update_default_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -389,11 +435,17 @@ pub async fn routing_update_default_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingWrite), + &auth::JWTAuth { + permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -426,6 +478,7 @@ pub async fn routing_retrieve_default_config( &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -433,6 +486,7 @@ pub async fn routing_retrieve_default_config( &auth::JWTAuthProfileFromRoute { profile_id: path, required_permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -457,11 +511,17 @@ pub async fn routing_retrieve_default_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -491,11 +551,17 @@ pub async fn upsert_surcharge_decision_manager_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -522,11 +588,17 @@ pub async fn delete_surcharge_decision_manager_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -553,11 +625,17 @@ pub async fn retrieve_surcharge_decision_manager_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::SurchargeDecisionManagerRead), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::SurchargeDecisionManagerRead), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, ) .await @@ -587,11 +665,17 @@ pub async fn upsert_decision_manager_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::SurchargeDecisionManagerRead), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::SurchargeDecisionManagerRead), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -619,11 +703,17 @@ pub async fn delete_decision_manager_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerWrite, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::SurchargeDecisionManagerWrite), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -647,11 +737,17 @@ pub async fn retrieve_decision_manager_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::SurchargeDecisionManagerRead), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::SurchargeDecisionManagerRead), + &auth::JWTAuth { + permission: Permission::SurchargeDecisionManagerRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, ) .await @@ -690,6 +786,7 @@ pub async fn routing_retrieve_linked_config( &auth::JWTAuthProfileFromRoute { profile_id, required_permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -697,6 +794,7 @@ pub async fn routing_retrieve_linked_config( &auth::JWTAuthProfileFromRoute { profile_id, required_permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -720,11 +818,17 @@ pub async fn routing_retrieve_linked_config( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), #[cfg(feature = "release")] - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, + }, api_locking::LockAction::NotApplicable, )) .await @@ -767,6 +871,7 @@ pub async fn routing_retrieve_linked_config( &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, }, req.headers(), ), @@ -774,6 +879,7 @@ pub async fn routing_retrieve_linked_config( &auth::JWTAuthProfileFromRoute { profile_id: wrapper.profile_id, required_permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Profile, }, api_locking::LockAction::NotApplicable, )) @@ -803,13 +909,19 @@ pub async fn routing_retrieve_default_config_for_profiles( #[cfg(not(feature = "release"))] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), #[cfg(feature = "release")] auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::RoutingRead), + &auth::JWTAuth { + permission: Permission::RoutingRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -851,6 +963,7 @@ pub async fn routing_update_default_config_for_profile( &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -858,6 +971,7 @@ pub async fn routing_update_default_config_for_profile( &auth::JWTAuthProfileFromRoute { profile_id: routing_payload_wrapper.profile_id, required_permission: Permission::RoutingWrite, + minimum_entity_level: EntityType::Merchant, }, api_locking::LockAction::NotApplicable, )) diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index dfc25c68945..85850c39e30 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -5,7 +5,7 @@ use api_models::{ errors::types::ApiErrorResponse, user::{self as user_api}, }; -use common_enums::TokenPurpose; +use common_enums::{EntityType, TokenPurpose}; use common_utils::errors::ReportSwitchExt; use router_env::Flow; @@ -175,7 +175,10 @@ pub async fn set_dashboard_metadata( &req, payload, user_core::dashboard_metadata::set_metadata, - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -257,7 +260,10 @@ pub async fn user_merchant_account_create( |state, auth: auth::UserFromToken, json_payload, _| { user_core::create_merchant_account(state, auth, json_payload) }, - &auth::JWTAuth(Permission::MerchantAccountCreate), + &auth::JWTAuth { + permission: Permission::MerchantAccountCreate, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -278,7 +284,10 @@ pub async fn generate_sample_data( &http_req, payload.into_inner(), sample_data::generate_sample_data_for_user, - &auth::JWTAuth(Permission::PaymentWrite), + &auth::JWTAuth { + permission: Permission::PaymentWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -298,7 +307,10 @@ pub async fn delete_sample_data( &http_req, payload.into_inner(), sample_data::delete_sample_data_for_user, - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -330,7 +342,10 @@ pub async fn get_user_role_details( &req, payload.into_inner(), user_core::get_user_details_in_merchant_account, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -348,7 +363,10 @@ pub async fn list_user_roles_details( &req, payload.into_inner(), user_core::list_user_roles_details, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -365,7 +383,10 @@ pub async fn list_users_for_merchant_account( &req, (), |state, user, _, _| user_core::list_users_for_merchant_account(state, user), - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -445,7 +466,10 @@ pub async fn invite_multiple_user( |state, user, payload, req_state| { user_core::invite_multiple_user(state, user, payload, req_state, auth_id.clone()) }, - &auth::JWTAuth(Permission::UsersWrite), + &auth::JWTAuth { + permission: Permission::UsersWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -468,7 +492,10 @@ pub async fn resend_invite( |state, user, req_payload, _| { user_core::resend_invite(state, user, req_payload, auth_id.clone()) }, - &auth::JWTAuth(Permission::UsersWrite), + &auth::JWTAuth { + permission: Permission::UsersWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs index 35c9098edd2..00b289b0b80 100644 --- a/crates/router/src/routes/user_role.rs +++ b/crates/router/src/routes/user_role.rs @@ -1,6 +1,6 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::user_role::{self as user_role_api, role as role_api}; -use common_enums::TokenPurpose; +use common_enums::{EntityType, TokenPurpose}; use router_env::Flow; use super::AppState; @@ -29,7 +29,10 @@ pub async fn get_authorization_info( |state, _: (), _, _| async move { user_role_core::get_authorization_info_with_groups(state).await }, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -64,7 +67,10 @@ pub async fn create_role( &req, json_payload.into_inner(), role_core::create_role, - &auth::JWTAuth(Permission::UsersWrite), + &auth::JWTAuth { + permission: Permission::UsersWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -80,7 +86,10 @@ pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> Htt |state, user, _, _| async move { role_core::list_invitable_roles_with_groups(state, user).await }, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -103,7 +112,10 @@ pub async fn get_role( |state, user, payload, _| async move { role_core::get_role_with_groups(state, user, payload).await }, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -124,7 +136,10 @@ pub async fn update_role( &req, json_payload.into_inner(), |state, user, req, _| role_core::update_role(state, user, req, &role_id), - &auth::JWTAuth(Permission::UsersWrite), + &auth::JWTAuth { + permission: Permission::UsersWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -143,7 +158,10 @@ pub async fn update_user_role( &req, payload, user_role_core::update_user_role, - &auth::JWTAuth(Permission::UsersWrite), + &auth::JWTAuth { + permission: Permission::UsersWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -241,7 +259,10 @@ pub async fn delete_user_role( &req, payload.into_inner(), user_role_core::delete_user_role, - &auth::JWTAuth(Permission::UsersWrite), + &auth::JWTAuth { + permission: Permission::UsersWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -261,7 +282,9 @@ pub async fn get_role_information( |_, _: (), _, _| async move { user_role_core::get_authorization_info_with_group_tag().await }, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth{ + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant}, api_locking::LockAction::NotApplicable, )) .await @@ -293,7 +316,10 @@ pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest) &req, (), |state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token), - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -319,7 +345,10 @@ pub async fn list_invitable_roles_at_entity_level( role_api::RoleCheckType::Invite, ) }, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await @@ -345,7 +374,10 @@ pub async fn list_updatable_roles_at_entity_level( role_api::RoleCheckType::Update, ) }, - &auth::JWTAuth(Permission::UsersRead), + &auth::JWTAuth { + permission: Permission::UsersRead, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs index b818fcfc1d4..f2996009f82 100644 --- a/crates/router/src/routes/verification.rs +++ b/crates/router/src/routes/verification.rs @@ -1,5 +1,6 @@ use actix_web::{web, HttpRequest, Responder}; use api_models::verifications; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::app::AppState; @@ -32,7 +33,10 @@ pub async fn apple_pay_merchant_registration( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MerchantAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantAccountWrite, + minimum_entity_level: EntityType::Profile, + }, req.headers(), ), api_locking::LockAction::NotApplicable, @@ -64,7 +68,10 @@ pub async fn retrieve_apple_pay_verified_domains( }, auth::auth_type( &auth::HeaderAuth(auth::ApiKeyAuth), - &auth::JWTAuth(Permission::MerchantAccountRead), + &auth::JWTAuth { + permission: Permission::MerchantAccountRead, + minimum_entity_level: EntityType::Merchant, + }, req.headers(), ), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs index b510ba29637..29f8c154bc0 100644 --- a/crates/router/src/routes/verify_connector.rs +++ b/crates/router/src/routes/verify_connector.rs @@ -1,5 +1,6 @@ use actix_web::{web, HttpRequest, HttpResponse}; use api_models::verify_connector::VerifyConnectorRequest; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use super::AppState; @@ -23,7 +24,10 @@ pub async fn payment_connector_verify( |state, auth: auth::AuthenticationData, req, _| { verify_connector::verify_connector_credentials(state, req, auth.profile_id) }, - &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), + &auth::JWTAuth { + permission: Permission::MerchantConnectorAccountWrite, + minimum_entity_level: EntityType::Merchant, + }, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/routes/webhook_events.rs b/crates/router/src/routes/webhook_events.rs index d5150ad1fef..8b94fb61f56 100644 --- a/crates/router/src/routes/webhook_events.rs +++ b/crates/router/src/routes/webhook_events.rs @@ -1,4 +1,5 @@ use actix_web::{web, HttpRequest, Responder}; +use common_enums::EntityType; use router_env::{instrument, tracing, Flow}; use crate::{ @@ -44,6 +45,7 @@ pub async fn list_initial_webhook_delivery_attempts( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::WebhookEventRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -83,6 +85,7 @@ pub async fn list_webhook_delivery_attempts( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::WebhookEventRead, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), @@ -122,6 +125,7 @@ pub async fn retry_webhook_delivery_attempt( &auth::JWTAuthMerchantFromRoute { merchant_id, required_permission: Permission::WebhookEventWrite, + minimum_entity_level: EntityType::Merchant, }, req.headers(), ), diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 4f9a222db5e..6d100ab3576 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -10,7 +10,7 @@ use api_models::payment_methods::PaymentMethodIntentConfirm; use api_models::payouts; use api_models::{payment_methods::PaymentMethodListRequest, payments}; use async_trait::async_trait; -use common_enums::TokenPurpose; +use common_enums::{EntityType, TokenPurpose}; use common_utils::{date_time, id_type}; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; @@ -1004,12 +1004,9 @@ where } #[derive(Debug)] -pub(crate) struct JWTAuth(pub Permission); - -#[derive(serde::Deserialize)] -struct JwtAuthPayloadFetchUnit { - #[serde(rename(deserialize = "exp"))] - _exp: u64, +pub(crate) struct JWTAuth { + pub permission: Permission, + pub minimum_entity_level: EntityType, } #[async_trait] @@ -1027,8 +1024,9 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.0, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; Ok(( (), @@ -1056,8 +1054,9 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.0, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; Ok(( UserFromToken { @@ -1091,8 +1090,10 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.0, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -1132,10 +1133,12 @@ where pub struct JWTAuthMerchantFromRoute { pub merchant_id: id_type::MerchantId, pub required_permission: Permission, + pub minimum_entity_level: EntityType, } pub struct JWTAuthMerchantFromHeader { pub required_permission: Permission, + pub minimum_entity_level: EntityType, } #[async_trait] @@ -1153,8 +1156,9 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.required_permission, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers).get_merchant_id_from_header()?; @@ -1188,8 +1192,9 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.required_permission, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; let merchant_id_from_header = HeaderMapStruct::new(request_headers).get_merchant_id_from_header()?; @@ -1254,8 +1259,9 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.required_permission, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; // Check if token has access to MerchantId that has been requested through query param if payload.merchant_id != self.merchant_id { @@ -1290,8 +1296,10 @@ where return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.required_permission, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -1333,6 +1341,7 @@ pub struct JWTAuthMerchantAndProfileFromRoute { pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, pub required_permission: Permission, + pub minimum_entity_level: EntityType, } #[async_trait] @@ -1362,8 +1371,10 @@ where return Err(report!(errors::ApiErrorResponse::InvalidJwtToken)); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.required_permission, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -1406,6 +1417,7 @@ where pub struct JWTAuthProfileFromRoute { pub profile_id: id_type::ProfileId, pub required_permission: Permission, + pub minimum_entity_level: EntityType, } #[async_trait] @@ -1423,8 +1435,10 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.required_permission, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.required_permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -1517,8 +1531,10 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.0, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -1574,8 +1590,10 @@ where return Err(errors::ApiErrorResponse::InvalidJwtToken.into()); } - let permissions = authorization::get_permissions(state, &payload).await?; - authorization::check_authorization(&self.0, &permissions)?; + let role_info = authorization::get_role_info(state, &payload).await?; + authorization::check_permission(&self.permission, &role_info)?; + authorization::check_entity(self.minimum_entity_level, &role_info)?; + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index ea1264bde06..78af4c00884 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -1,6 +1,5 @@ use std::sync::Arc; -use common_enums::PermissionGroup; use common_utils::id_type; use error_stack::ResultExt; use redis_interface::RedisConnectionPool; @@ -19,69 +18,57 @@ pub mod permission_groups; pub mod permissions; pub mod roles; -pub async fn get_permissions<A>( - state: &A, - token: &AuthToken, -) -> RouterResult<Vec<permissions::Permission>> +pub async fn get_role_info<A>(state: &A, token: &AuthToken) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { - if let Some(permissions) = get_permissions_from_predefined_roles(&token.role_id) { - return Ok(permissions); + if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) { + return Ok(role_info.clone()); } - if let Ok(permissions) = get_permissions_from_cache(state, &token.role_id) + if let Ok(role_info) = get_role_info_from_cache(state, &token.role_id) .await .map_err(|e| logger::error!("Failed to get permissions from cache {e:?}")) { - return Ok(permissions); + return Ok(role_info.clone()); } - let permissions = - get_permissions_from_db(state, &token.role_id, &token.merchant_id, &token.org_id).await?; + let role_info = + get_role_info_from_db(state, &token.role_id, &token.merchant_id, &token.org_id).await?; let token_expiry = i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp(); - set_permissions_in_cache(state, &token.role_id, &permissions, cache_ttl) + set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) .await - .map_err(|e| logger::error!("Failed to set permissions in cache {e:?}")) + .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) .ok(); - Ok(permissions) + Ok(role_info) } -async fn get_permissions_from_cache<A>( - state: &A, - role_id: &str, -) -> RouterResult<Vec<permissions::Permission>> +async fn get_role_info_from_cache<A>(state: &A, role_id: &str) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { let redis_conn = get_redis_connection(state)?; redis_conn - .get_and_deserialize_key(&get_cache_key_from_role_id(role_id), "Vec<Permission>") + .get_and_deserialize_key(&get_cache_key_from_role_id(role_id), "RoleInfo") .await .change_context(ApiErrorResponse::InternalServerError) } pub fn get_cache_key_from_role_id(role_id: &str) -> String { - format!("{}{}", consts::ROLE_CACHE_PREFIX, role_id) + format!("{}{}", consts::ROLE_INFO_CACHE_PREFIX, role_id) } -fn get_permissions_from_predefined_roles(role_id: &str) -> Option<Vec<permissions::Permission>> { - roles::predefined_roles::PREDEFINED_ROLES - .get(role_id) - .map(|role_info| get_permissions_from_groups(role_info.get_permission_groups())) -} - -async fn get_permissions_from_db<A>( +async fn get_role_info_from_db<A>( state: &A, role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, -) -> RouterResult<Vec<permissions::Permission>> +) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, { @@ -89,14 +76,14 @@ where .store() .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) .await - .map(|role| get_permissions_from_groups(&role.groups)) + .map(roles::RoleInfo::from) .to_not_found_response(ApiErrorResponse::InvalidJwtToken) } -pub async fn set_permissions_in_cache<A>( +pub async fn set_role_info_in_cache<A>( state: &A, role_id: &str, - permissions: &Vec<permissions::Permission>, + role_info: &roles::RoleInfo, expiry: i64, ) -> RouterResult<()> where @@ -105,32 +92,17 @@ where let redis_conn = get_redis_connection(state)?; redis_conn - .serialize_and_set_key_with_expiry( - &get_cache_key_from_role_id(role_id), - permissions, - expiry, - ) + .serialize_and_set_key_with_expiry(&get_cache_key_from_role_id(role_id), role_info, expiry) .await .change_context(ApiErrorResponse::InternalServerError) } -pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> { - groups - .iter() - .flat_map(|group| { - permission_groups::get_permissions_vec(group) - .iter() - .cloned() - }) - .collect() -} - -pub fn check_authorization( +pub fn check_permission( required_permission: &permissions::Permission, - permissions: &[permissions::Permission], + role_info: &roles::RoleInfo, ) -> RouterResult<()> { - permissions - .contains(required_permission) + role_info + .check_permission_exists(required_permission) .then_some(()) .ok_or( ApiErrorResponse::AccessForbidden { @@ -140,6 +112,18 @@ pub fn check_authorization( ) } +pub fn check_entity( + required_minimum_entity: common_enums::EntityType, + role_info: &roles::RoleInfo, +) -> RouterResult<()> { + if required_minimum_entity > role_info.get_entity_type() { + Err(ApiErrorResponse::AccessForbidden { + resource: required_minimum_entity.to_string(), + })?; + } + Ok(()) +} + fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> { state .store() diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index 9b506cc5ef7..c498a33614e 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -8,7 +8,7 @@ use crate::{core::errors, routes::SessionState}; pub mod predefined_roles; -#[derive(Clone)] +#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)] pub struct RoleInfo { role_id: String, role_name: String, diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index f5320c41335..9d55c5b2d16 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -215,5 +215,24 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| is_internal: false, }, ); + roles.insert( + consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT, + RoleInfo { + groups: vec![ + PermissionGroup::OperationsView, + PermissionGroup::OperationsManage, + PermissionGroup::ConnectorsView, + PermissionGroup::WorkflowsView, + ], + role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(), + role_name: "profile_support".to_string(), + scope: RoleScope::Organization, + entity_type: EntityType::Profile, + is_invitable: true, + is_deletable: true, + is_updatable: true, + is_internal: false, + }, + ); roles }); diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index ecf12742e32..cf02d7766b5 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -156,10 +156,10 @@ pub async fn set_role_permissions_in_cache_if_required( .change_context(UserErrors::InternalServerError) .attach_printable("Error getting role_info from role_id")?; - authz::set_permissions_in_cache( + authz::set_role_info_in_cache( state, role_id, - &role_info.get_permissions_set().into_iter().collect(), + &role_info, i64::try_from(consts::JWT_TOKEN_TIME_IN_SECS) .change_context(UserErrors::InternalServerError)?, )
2024-09-05T13:54:50Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Created a profile level user. - Added entity level authorization in routes. <!-- Describe your changes in detail --> ### Additional Changes - [X] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Dashboards users to be restricted at profile level. <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Dashboard UI. 1. Login to dashboard. 2. Invite a user at profile level. 3. Login using profile level user. 4. Check if APIs are working. <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [X] I formatted the code `cargo +nightly fmt --all` - [X] I addressed lints thrown by `cargo clippy` - [X] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
4d499038c03986a6f3ecee742c5add1c55789b01
juspay/hyperswitch
juspay__hyperswitch-5782
Bug: skip 3DS in `network_transaction_id` flow for cybersource During the MIT with cybersource connector we check if the connector mandate details are present. If is present then we make a no_three_ds api request. Same check needs to be added in case of network transaction id flow as MIT can be done using card details and network transaction id as well. As this check is not present threeds is triggered even during MITs with card details and network transaction id.
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 15242ddb119..806cf67b2da 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -901,7 +901,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) -> CustomResult<String, errors::ConnectorError> { if req.is_three_ds() && req.request.is_card() - && req.request.connector_mandate_id().is_none() + && (req.request.connector_mandate_id().is_none() + && req.request.get_optional_network_transaction_id().is_none()) && req.request.authentication_data.is_none() { Ok(format!( @@ -929,7 +930,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ))?; if req.is_three_ds() && req.request.is_card() - && req.request.connector_mandate_id().is_none() + && (req.request.connector_mandate_id().is_none() + && req.request.get_optional_network_transaction_id().is_none()) && req.request.authentication_data.is_none() { let connector_req = @@ -970,7 +972,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { if data.is_three_ds() && data.request.is_card() - && data.request.connector_mandate_id().is_none() + && (data.request.connector_mandate_id().is_none() + && data.request.get_optional_network_transaction_id().is_none()) && data.request.authentication_data.is_none() { let response: cybersource::CybersourceAuthSetupResponse = res diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 2375dd578b3..d1f15082ee3 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -1043,12 +1043,23 @@ impl Err(_) => None, }; + let security_code = if item + .router_data + .request + .get_optional_network_transaction_id() + .is_some() + { + None + } else { + Some(ccard.card_cvc) + }; + 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: Some(ccard.card_cvc), + security_code, card_type: card_type.clone(), }, })); diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index d5c01503ed8..f8eed11d161 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -763,6 +763,7 @@ pub trait PaymentsAuthorizeRequestData { fn get_card(&self) -> Result<domain::Card, Error>; fn get_return_url(&self) -> Result<String, Error>; fn connector_mandate_id(&self) -> Option<String>; + fn get_optional_network_transaction_id(&self) -> Option<String>; fn is_mandate_payment(&self) -> bool; fn is_customer_initiated_mandate_payment(&self) -> bool; fn get_webhook_url(&self) -> Result<String, Error>; @@ -843,6 +844,18 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { Some(payments::MandateReferenceId::NetworkMandateId(_)) | None => None, }) } + + fn get_optional_network_transaction_id(&self) -> Option<String> { + self.mandate_id + .as_ref() + .and_then(|mandate_ids| match &mandate_ids.mandate_reference_id { + Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { + Some(network_transaction_id.clone()) + } + Some(payments::MandateReferenceId::ConnectorMandateId(_)) | None => None, + }) + } + 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| {
2024-09-03T08:20:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> During the MIT with cybersource connector we check if the connector mandate details are present. If is present then we make a no_three_ds api request. Same check needs to be added in case of network transaction id flow as MIT can be done using card details and network transaction id as well. As this check is not present threeds is triggered even during MITs with card details and network transaction id. ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> -> Create mca of cybersource -> enable the `is_connector_agnostic_mit_enabled` config ``` curl --location 'http://localhost:8080/account/merchant_1725355756/business_profile/pro_jQJ4qqk9cMEsOfzx4jjP' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key:' \ --data '{ "is_connector_agnostic_mit_enabled": true }' ``` ``` { "merchant_id": "merchant_1725355756", "profile_id": "pro_jQJ4qqk9cMEsOfzx4jjP", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "BKfZiBAT1keoPmkDRu4lyN2hAS4hKh1Uv79ydDs32kDCLrbTV5U7Xp9ZuuTgYgrp", "redirect_to_merchant_with_http_post": false, "webhook_details": { "webhook_version": "1.0.1", "webhook_username": "ekart_retail", "webhook_password": "password_ekart@123", "webhook_url": null, "payment_created_enabled": true, "payment_succeeded_enabled": true, "payment_failed_enabled": true }, "metadata": null, "routing_algorithm": null, "intent_fulfillment_time": 900, "frm_routing_algorithm": null, "payout_routing_algorithm": null, "applepay_verified_domains": null, "session_expiry": 900, "payment_link_config": null, "authentication_connector_details": null, "use_billing_as_payment_method_billing": true, "extended_card_info_config": null, "collect_shipping_details_from_wallet_connector": false, "collect_billing_details_from_wallet_connector": false, "always_collect_shipping_details_from_wallet_connector": false, "always_collect_billing_details_from_wallet_connector": false, "is_connector_agnostic_mit_enabled": true, "payout_link_config": null, "outgoing_webhook_custom_http_headers": null, "tax_connector_id": null, "is_tax_connector_enabled": false } ``` -> Create a payment with `"setup_future_usage": "off_session"` and `"authentication_type": "three_ds"` ``` { "amount": 1000, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_{{$timestamp}}", "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://google.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "5454545454545454", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "name name", "card_cvc": "737" } }, "setup_future_usage": "off_session", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" } }, "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": "125.0.0.1" }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": {}, "order_details": [ { "product_name": "Apple iphone 15", "quantity": 1, "amount": 0, "account_name": "transaction_processing" } ] } ``` ``` { "payment_id": "pay_rsLVCXS2Q8uTBPdF4P1j", "merchant_id": "merchant_1725355756", "status": "requires_customer_action", "amount": 1000, "net_amount": 1000, "amount_capturable": 1000, "amount_received": null, "connector": "cybersource", "client_secret": "pay_rsLVCXS2Q8uTBPdF4P1j_secret_z1CCqBhaQSvZPuiWogkN", "created": "2024-09-03T09:37:00.475Z", "currency": "USD", "customer_id": "cu_1725356220", "customer": { "id": "cu_1725356220", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_WoDIt3orfsK8JrDJVLoA", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": [ { "brand": null, "amount": 0, "category": null, "quantity": 1, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "requires_shipping": null } ], "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": { "type": "redirect_to_url", "redirect_to_url": "http://localhost:8080/payments/redirect/pay_rsLVCXS2Q8uTBPdF4P1j/merchant_1725355756/pay_rsLVCXS2Q8uTBPdF4P1j_1" }, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1725356220", "created_at": 1725356220, "expires": 1725359820, "secret": "epk_256f65862c0b4553b26432c036b4f748" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_rsLVCXS2Q8uTBPdF4P1j_1", "payment_link": null, "profile_id": "pro_jQJ4qqk9cMEsOfzx4jjP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1jo1uMz1tfWZk0FydFQQ", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-03T09:52:00.475Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_rr5fO13rR1AEOearzGCl", "payment_method_status": null, "updated": "2024-09-03T09:37:02.019Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> perform the 3ds action -> payments retrieve ``` { "payment_id": "pay_rsLVCXS2Q8uTBPdF4P1j", "merchant_id": "merchant_1725355756", "status": "succeeded", "amount": 1000, "net_amount": 1000, "amount_capturable": 0, "amount_received": 1000, "connector": "cybersource", "client_secret": "pay_rsLVCXS2Q8uTBPdF4P1j_secret_z1CCqBhaQSvZPuiWogkN", "created": "2024-09-03T09:37:00.475Z", "currency": "USD", "customer_id": "cu_1725356220", "customer": { "id": "cu_1725356220", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": "Its my first payment request", "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_WoDIt3orfsK8JrDJVLoA", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": null }, "order_details": [ { "brand": null, "amount": 0, "category": null, "quantity": 1, "product_id": null, "product_name": "Apple iphone 15", "product_type": null, "sub_category": null, "product_img_link": null, "requires_shipping": null } ], "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "three_ds", "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": "credit", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7253562280536560303954", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_rsLVCXS2Q8uTBPdF4P1j_1", "payment_link": null, "profile_id": "pro_jQJ4qqk9cMEsOfzx4jjP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1jo1uMz1tfWZk0FydFQQ", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-03T09:52:00.475Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "125.0.0.1", "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", "color_depth": 24, "java_enabled": true, "screen_width": 1536, "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "screen_height": 723, "java_script_enabled": true }, "payment_method_id": "pm_rr5fO13rR1AEOearzGCl", "payment_method_status": "active", "updated": "2024-09-03T09:37:10.120Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` screenshot of `network_transaction_id` stored in db <img width="653" alt="image" src="https://github.com/user-attachments/assets/38c049c5-e311-4114-a9ed-608ac455d105"> -> Make an MIT by passing `"authentication_type": "three_ds"` ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_Wj8BGLQOST1LIlLtkqvFa5Ny19SM8qDTFWlFeVLAuPwxzdP2aKqzXhixqdHzfvUD' \ --header 'Content-Type: application/json' \ --data '{ "amount": 10000, "currency": "USD", "capture_method": "automatic", "authentication_type": "three_ds", "confirm": false, "setup_future_usage": "off_session", "customer_id": "cu_1725356220" }' ``` ``` { "payment_id": "pay_g0jDr2tevq4O4iuRLrkl", "merchant_id": "merchant_1725355756", "status": "requires_payment_method", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_g0jDr2tevq4O4iuRLrkl_secret_Hib6ubDZBOEvGCi95wUF", "created": "2024-09-03T09:48:41.237Z", "currency": "USD", "customer_id": "cu_1725356220", "customer": { "id": "cu_1725356220", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": null, "payment_method_data": null, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cu_1725356220", "created_at": 1725356921, "expires": 1725360521, "secret": "epk_eaf976174caa4444a402c8682ef968be" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_jQJ4qqk9cMEsOfzx4jjP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": null, "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-03T10:03:41.237Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-09-03T09:48:41.285Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` -> List customer payment method ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_g0jDr2tevq4O4iuRLrkl_secret_Hib6ubDZBOEvGCi95wUF' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_7aad1e742bd64afeac0e9335cbb68a52' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_aGOLcq6wQAslGXTO9qLG", "payment_method_id": "pm_rr5fO13rR1AEOearzGCl", "customer_id": "cu_1725356220", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": null, "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": null, "issuer_country": null, "last4_digits": "5454", "expiry_month": "03", "expiry_year": "2030", "card_token": null, "card_holder_name": "name name", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": "545454", "card_issuer": null, "card_type": null, "saved_to_locker": true }, "metadata": null, "created": "2024-09-03T09:37:02.012Z", "bank": null, "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-09-03T09:44:18.004Z", "default_payment_method_set": true, "billing": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "name", "last_name": "name" }, "phone": null, "email": null } } ], "is_guest_customer": false } ``` -> Confirm the payment with payment id ``` curl --location 'http://localhost:8080/payments/pay_g0jDr2tevq4O4iuRLrkl/confirm' \ --header 'api-key: pk_dev_7aad1e742bd64afeac0e9335cbb68a52' \ --header 'Content-Type: application/json' \ --data '{ "payment_token": "token_aGOLcq6wQAslGXTO9qLG", "client_secret": "pay_g0jDr2tevq4O4iuRLrkl_secret_Hib6ubDZBOEvGCi95wUF", "payment_method": "card" }' ``` ``` { "payment_id": "pay_g0jDr2tevq4O4iuRLrkl", "merchant_id": "merchant_1725355756", "status": "succeeded", "amount": 10000, "net_amount": 10000, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_g0jDr2tevq4O4iuRLrkl_secret_Hib6ubDZBOEvGCi95wUF", "created": "2024-09-03T09:48:41.237Z", "currency": "USD", "customer_id": "cu_1725356220", "customer": { "id": "cu_1725356220", "name": "John Doe", "email": "guest@example.com", "phone": "999999999", "phone_country_code": "+65" }, "description": null, "refunds": null, "disputes": null, "mandate_id": null, "mandate_data": null, "setup_future_usage": "off_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "5454", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "545454", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": { "avs_response": { "code": "Y", "codeRaw": "Y" }, "card_verification": null }, "authentication_data": null }, "billing": null }, "payment_token": "token_aGOLcq6wQAslGXTO9qLG", "shipping": null, "billing": null, "order_details": null, "email": "guest@example.com", "name": "John Doe", "phone": "999999999", "return_url": null, "authentication_type": "three_ds", "statement_descriptor_name": null, "statement_descriptor_suffix": null, "next_action": null, "cancellation_reason": null, "error_code": null, "error_message": null, "unified_code": null, "unified_message": null, "payment_experience": null, "payment_method_type": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "7253569912966834103954", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_g0jDr2tevq4O4iuRLrkl_1", "payment_link": null, "profile_id": "pro_jQJ4qqk9cMEsOfzx4jjP", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_1jo1uMz1tfWZk0FydFQQ", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-09-03T10:03:41.237Z", "fingerprint": null, "browser_info": { "language": null, "time_zone": null, "ip_address": "::1", "user_agent": null, "color_depth": null, "java_enabled": null, "screen_width": null, "accept_header": null, "screen_height": null, "java_script_enabled": null }, "payment_method_id": "pm_rr5fO13rR1AEOearzGCl", "payment_method_status": "active", "updated": "2024-09-03T09:49:52.659Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null } ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e3a9fb16c518d09313d00a23ece70a26d4728f63
juspay/hyperswitch
juspay__hyperswitch-5776
Bug: feat(user_role): add support to get user role details v2 Add support to return user role details v2 Request will take email and response will return something like ``` [ { role_id: "r1", role_name: "name", org: { name: "Juspay", id: "o1" }, merchant: { // Optional name: "Juspay merchant", id: "m1" }, profile: { // Optional name: "Juspay profile", id: "p1" }, status: "status", entity_type: "type" } ] ```
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 8d1ae60b325..9b100a7321e 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -14,11 +14,11 @@ use crate::user::{ ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, CreateUserAuthenticationMethodRequest, DashboardEntryResponse, ForgotPasswordRequest, GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, - GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, - ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, - SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, - SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, - TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, + GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, GetUserRoleDetailsResponseV2, + InviteUserRequest, ListUsersResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, + RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, + SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, + TokenResponse, TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; @@ -70,6 +70,7 @@ common_utils::impl_api_event_type!( GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, + GetUserRoleDetailsResponseV2, TokenResponse, TwoFactorAuthStatusResponse, UserFromEmailRequest, diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 78157f62bc5..4674abf3976 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -1,3 +1,5 @@ +use std::fmt::Debug; + use common_enums::{PermissionGroup, RoleScope, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; @@ -176,6 +178,22 @@ pub struct GetUserRoleDetailsResponse { pub role_scope: RoleScope, } +#[derive(Debug, serde::Serialize)] +pub struct GetUserRoleDetailsResponseV2 { + pub role_id: String, + pub org: NameIdUnit<Option<String>, id_type::OrganizationId>, + pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>, + pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, + pub status: UserStatus, + pub entity_type: common_enums::EntityType, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] +pub struct NameIdUnit<N: Debug + Clone, I: Debug + Clone> { + pub name: N, + pub id: I, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyEmailRequest { pub token: Secret<String>, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 0c4afbe4ecd..1d235dceaea 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -5,7 +5,7 @@ use std::{ use api_models::{ payments::RedirectionResponse, - user::{self as user_api, InviteMultipleUserResponse}, + user::{self as user_api, InviteMultipleUserResponse, NameIdUnit}, }; use common_enums::EntityType; use common_utils::{type_name, types::keymanager::Identifier}; @@ -1407,6 +1407,237 @@ pub async fn get_user_details_in_merchant_account( )) } +pub async fn list_user_roles_details( + state: SessionState, + user_from_token: auth::UserFromToken, + request: user_api::GetUserRoleDetailsRequest, + _req_state: ReqState, +) -> UserResponse<Vec<user_api::GetUserRoleDetailsResponseV2>> { + let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?) + .await + .to_not_found_response(UserErrors::InvalidRoleOperation)?; + + let requestor_role_info = roles::RoleInfo::from_role_id( + &state, + &user_from_token.role_id, + &user_from_token.merchant_id, + &user_from_token.org_id, + ) + .await + .to_not_found_response(UserErrors::InternalServerError) + .attach_printable("Failed to fetch role info")?; + + let user_roles_set: HashSet<_> = state + .store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: required_user.get_user_id(), + org_id: Some(&user_from_token.org_id), + merchant_id: (requestor_role_info.get_entity_type() <= EntityType::Merchant) + .then_some(&user_from_token.merchant_id), + profile_id: (requestor_role_info.get_entity_type() <= EntityType::Profile) + .then_some(&user_from_token.profile_id) + .cloned() + .flatten() + .as_ref(), + entity_id: None, + version: None, + status: None, + limit: None, + }) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to fetch user roles")? + .into_iter() + .collect(); + + let org_name = state + .store + .find_organization_by_org_id(&user_from_token.org_id) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Org id not found")? + .get_organization_name(); + + let org = NameIdUnit { + id: user_from_token.org_id.clone(), + name: org_name, + }; + + let (merchant_ids, merchant_profile_ids) = user_roles_set.iter().try_fold( + (Vec::new(), Vec::new()), + |(mut merchant, mut merchant_profile), user_role| { + let entity_type = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError) + .attach_printable("Failed to fetch entity id and type")? + .1; + match entity_type { + EntityType::Merchant => { + let merchant_id = user_role + .merchant_id + .clone() + .ok_or(UserErrors::InternalServerError) + .attach_printable( + "Merchant id not found in user role for merchant level entity", + )?; + merchant.push(merchant_id) + } + EntityType::Profile => { + let merchant_id = user_role + .merchant_id + .clone() + .ok_or(UserErrors::InternalServerError) + .attach_printable( + "Merchant id not found in user role for merchant level entity", + )?; + let profile_id = user_role + .profile_id + .clone() + .ok_or(UserErrors::InternalServerError) + .attach_printable( + "Profile id not found in user role for profile level entity", + )?; + + merchant.push(merchant_id.clone()); + merchant_profile.push((merchant_id, profile_id)) + } + EntityType::Internal => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Internal roles are not allowed for this operation".to_string(), + ) + .into()); + } + EntityType::Organization => (), + }; + + Ok::<_, error_stack::Report<UserErrors>>((merchant, merchant_profile)) + }, + )?; + + let merchant_map: HashMap<_, _> = state + .store + .list_multiple_merchant_accounts(&(&state).into(), merchant_ids) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while listing merchant accounts")? + .into_iter() + .map(|merchant_account| { + ( + merchant_account.get_id().to_owned(), + merchant_account.merchant_name.clone(), + ) + }) + .collect(); + + let key_manager_state = &(&state).into(); + + let profile_map: HashMap<_, _> = + futures::future::try_join_all(merchant_profile_ids.iter().map( + |merchant_profile_id| async { + let merchant_key_store = state + .store + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_profile_id.0, + &state.store.get_master_key().to_vec().into(), + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve merchant key store by merchant_id")?; + + state + .store + .find_business_profile_by_profile_id( + key_manager_state, + &merchant_key_store, + &merchant_profile_id.1, + ) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to retrieve business profile") + }, + )) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to construct proifle map")? + .into_iter() + .map(|profile| (profile.get_id().to_owned(), profile.profile_name)) + .collect(); + + let role_details_list: Vec<_> = user_roles_set + .iter() + .map(|user_role| { + let entity_type = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError)? + .1; + let (merchant, profile) = match entity_type { + EntityType::Internal => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Internal roles are not allowed for this operation".to_string(), + )); + } + EntityType::Organization => (None, None), + EntityType::Merchant => { + let merchant_id = &user_role + .merchant_id + .clone() + .ok_or(UserErrors::InternalServerError)?; + + ( + Some(NameIdUnit { + id: merchant_id.clone(), + name: merchant_map + .get(merchant_id) + .ok_or(UserErrors::InternalServerError)? + .to_owned(), + }), + None, + ) + } + EntityType::Profile => { + let merchant_id = &user_role + .merchant_id + .clone() + .ok_or(UserErrors::InternalServerError)?; + let profile_id = &user_role + .profile_id + .clone() + .ok_or(UserErrors::InternalServerError)?; + + ( + Some(NameIdUnit { + id: merchant_id.clone(), + name: merchant_map + .get(merchant_id) + .ok_or(UserErrors::InternalServerError)? + .to_owned(), + }), + Some(NameIdUnit { + id: profile_id.clone(), + name: profile_map + .get(profile_id) + .ok_or(UserErrors::InternalServerError)? + .to_owned(), + }), + ) + } + }; + + Ok(user_api::GetUserRoleDetailsResponseV2 { + role_id: user_role.role_id.clone(), + org: org.clone(), + merchant, + profile, + status: user_role.status.foreign_into(), + entity_type, + }) + }) + .collect::<Result<Vec<_>, UserErrors>>()?; + + Ok(ApplicationResponse::Json(role_details_list)) +} + pub async fn list_users_for_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 98ced576105..f57ca47612b 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1817,6 +1817,7 @@ impl User { route = route.service( web::scope("/user") .service(web::resource("").route(web::get().to(get_user_role_details))) + .service(web::resource("/v2").route(web::post().to(list_user_roles_details))) .service( web::resource("/list").route(web::get().to(list_users_for_merchant_account)), ) diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index 1d5e3d601b6..dfc25c68945 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -336,6 +336,24 @@ pub async fn get_user_role_details( .await } +pub async fn list_user_roles_details( + state: web::Data<AppState>, + req: HttpRequest, + payload: web::Json<user_api::GetUserRoleDetailsRequest>, +) -> HttpResponse { + let flow = Flow::GetUserRoleDetails; + Box::pin(api::server_wrap( + flow, + state.clone(), + &req, + payload.into_inner(), + user_core::list_user_roles_details, + &auth::JWTAuth(Permission::UsersRead), + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn list_users_for_merchant_account( state: web::Data<AppState>, req: HttpRequest,
2024-09-02T20:08:54Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Add support to get user role details ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closes [#5776](https://github.com/juspay/hyperswitch/issues/5776) ## How did you test it? Request: ``` curl --location 'http://localhost:8080/user/user/v2' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data-raw '{ "email": "some_email" }' ``` Response ``` [ { "role_id": "org_admin", "org": { "name": null, "id": "org_SDzPXs082bpEQt3jbPlE" }, "merchant": null, "profile": null, "status": "Active", "entity_type": "organization" } ] ``` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
28e7a7fc5e49029dc5e7a367bb4d2a946ed1fe45
juspay/hyperswitch
juspay__hyperswitch-5768
Bug: fix spell check for CI pull request Rename `ApplePayDecryptConifg` to `ApplePayDecryptConfig` as the CI spell checks are failing.
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 312a475b8ba..c7d08d6f5ac 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -137,7 +137,7 @@ impl SecretsHandler for settings::ApiKeys { } #[async_trait::async_trait] -impl SecretsHandler for settings::ApplePayDecryptConifg { +impl SecretsHandler for settings::ApplePayDecryptConfig { async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, @@ -338,7 +338,7 @@ pub(crate) async fn fetch_raw_secrets( .expect("Failed to decrypt connector_onboarding configs"); #[allow(clippy::expect_used)] - let applepay_decrypt_keys = settings::ApplePayDecryptConifg::convert_to_raw_secret( + let applepay_decrypt_keys = settings::ApplePayDecryptConfig::convert_to_raw_secret( conf.applepay_decrypt_keys, secret_management_client, ) diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 312b7711f30..2ed72320194 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -94,7 +94,7 @@ pub struct Settings<S: SecretState> { #[cfg(feature = "payouts")] pub payouts: Payouts, pub payout_method_filters: ConnectorFilters, - pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConifg, S>, + pub applepay_decrypt_keys: SecretStateContainer<ApplePayDecryptConfig, S>, pub multiple_api_version_supported_connectors: MultipleApiVersionSupportedConnectors, pub applepay_merchant_configs: SecretStateContainer<ApplepayMerchantConfigs, S>, pub lock_settings: LockSettings, @@ -684,7 +684,7 @@ pub struct WebhookSourceVerificationCall { } #[derive(Debug, Deserialize, Clone, Default)] -pub struct ApplePayDecryptConifg { +pub struct ApplePayDecryptConfig { pub apple_pay_ppc: Secret<String>, pub apple_pay_ppc_key: Secret<String>, pub apple_pay_merchant_cert: Secret<String>,
2024-09-02T07:37:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e4f1fbc5a5622a86c3e3c27ae20e4b7b05f0a7ef
juspay/hyperswitch
juspay__hyperswitch-5773
Bug: [FEATURE] [DEUTSCHEBANK] Add template code ### Feature Description Template code needs to be added for new connector Deutsche Bank https://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html ### Possible Implementation Template code needs to be added for new connector Deutsche Bank https://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/config/config.example.toml b/config/config.example.toml index b54cd0df0d1..c02402c0471 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -202,6 +202,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" +deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -305,6 +306,7 @@ cards = [ "checkout", "cybersource", "datatrans", + "deutschebank", "globalpay", "globepay", "gocardless", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index ed2981fb79c..eeec8f31bf4 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -42,6 +42,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" +deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 78c6f3ea66d..3f744891b07 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -47,6 +47,7 @@ cryptopay.base_url = "https://business.cryptopay.me/" cybersource.base_url = "https://api.cybersource.com/" datatrans.base_url = "https://api.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" +deutschebank.base_url = "https://merch.directpos.de/rest-api/services/v2.1" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" fiserv.base_url = "https://cert.api.fiservapps.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index cf5f360cedf..31514982c2f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -47,6 +47,7 @@ cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" dlocal.base_url = "https://sandbox.dlocal.com/" +deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" fiserv.base_url = "https://cert.api.fiservapps.com/" diff --git a/config/development.toml b/config/development.toml index b920923f8c6..5c849a284c8 100644 --- a/config/development.toml +++ b/config/development.toml @@ -114,6 +114,7 @@ cards = [ "cryptopay", "cybersource", "datatrans", + "deutschebank", "dlocal", "dummyconnector", "ebanx", @@ -209,6 +210,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" +deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index bac365eedae..421984a7741 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -131,6 +131,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" +deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -222,6 +223,7 @@ cards = [ "cryptopay", "cybersource", "datatrans", + "deutschebank", "dlocal", "dummyconnector", "ebanx", diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 7c730f45aeb..eea76ab4bf0 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -95,6 +95,7 @@ pub enum Connector { Cryptopay, Cybersource, Datatrans, + // Deutschebank, Dlocal, Ebanx, Fiserv, @@ -231,6 +232,7 @@ impl Connector { | Self::Cashtocode | Self::Coinbase | Self::Cryptopay + // | Self::Deutschebank | Self::Dlocal | Self::Ebanx | Self::Fiserv diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 4b6e5b5a8df..507db0301dd 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -208,6 +208,7 @@ pub enum RoutableConnectors { Cryptopay, Cybersource, Datatrans, + // Deutschebank, Dlocal, Ebanx, Fiserv, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 88715a36e8a..79024411320 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -1,5 +1,6 @@ pub mod bambora; pub mod bitpay; +pub mod deutschebank; pub mod fiserv; pub mod fiservemea; pub mod fiuu; @@ -14,7 +15,8 @@ pub mod tsys; pub mod worldline; pub use self::{ - bambora::Bambora, bitpay::Bitpay, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, - globepay::Globepay, helcim::Helcim, nexixpay::Nexixpay, novalnet::Novalnet, - powertranz::Powertranz, stax::Stax, taxjar::Taxjar, tsys::Tsys, worldline::Worldline, + bambora::Bambora, bitpay::Bitpay, deutschebank::Deutschebank, fiserv::Fiserv, + fiservemea::Fiservemea, fiuu::Fiuu, globepay::Globepay, helcim::Helcim, nexixpay::Nexixpay, + novalnet::Novalnet, powertranz::Powertranz, stax::Stax, taxjar::Taxjar, tsys::Tsys, + worldline::Worldline, }; diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs new file mode 100644 index 00000000000..3d7e55c3a90 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -0,0 +1,569 @@ +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, ConnectorValidation}, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as deutschebank; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Deutschebank { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Deutschebank { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Deutschebank {} +impl api::PaymentSession for Deutschebank {} +impl api::ConnectorAccessToken for Deutschebank {} +impl api::MandateSetup for Deutschebank {} +impl api::PaymentAuthorize for Deutschebank {} +impl api::PaymentSync for Deutschebank {} +impl api::PaymentCapture for Deutschebank {} +impl api::PaymentVoid for Deutschebank {} +impl api::Refund for Deutschebank {} +impl api::RefundExecute for Deutschebank {} +impl api::RefundSync for Deutschebank {} +impl api::PaymentToken for Deutschebank {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Deutschebank +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Deutschebank +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 Deutschebank { + fn id(&self) -> &'static str { + "deutschebank" + } + + fn get_currency_unit(&self) -> api::CurrencyUnit { + api::CurrencyUnit::Base + // TODO! Check connector documentation, on which unit they are processing the currency. + // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, + // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { + connectors.deutschebank.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = deutschebank::DeutschebankAuthType::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: deutschebank::DeutschebankErrorResponse = res + .response + .parse_struct("DeutschebankErrorResponse") + .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 Deutschebank { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Deutschebank { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Deutschebank {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Deutschebank +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Deutschebank { + 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 = deutschebank::DeutschebankRouterData::from((amount, req)); + let connector_req = + deutschebank::DeutschebankPaymentsRequest::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: deutschebank::DeutschebankPaymentsResponse = res + .response + .parse_struct("Deutschebank 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 Deutschebank { + 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: deutschebank::DeutschebankPaymentsResponse = res + .response + .parse_struct("deutschebank 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 Deutschebank { + 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: deutschebank::DeutschebankPaymentsResponse = res + .response + .parse_struct("Deutschebank 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 Deutschebank {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Deutschebank { + 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 = + deutschebank::DeutschebankRouterData::from((refund_amount, req)); + let connector_req = + deutschebank::DeutschebankRefundRequest::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: deutschebank::RefundResponse = res + .response + .parse_struct("deutschebank 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 Deutschebank { + 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: deutschebank::RefundResponse = res + .response + .parse_struct("deutschebank 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 Deutschebank { + 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)) + } +} diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs new file mode 100644 index 00000000000..aca2bd497b6 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -0,0 +1,230 @@ +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 DeutschebankRouterData<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 DeutschebankRouterData<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 DeutschebankPaymentsRequest { + amount: StringMinorUnit, + card: DeutschebankCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct DeutschebankCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> + for DeutschebankPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = DeutschebankCard { + 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 methods".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct DeutschebankAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for DeutschebankAuthType { + 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 DeutschebankPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<DeutschebankPaymentStatus> for common_enums::AttemptStatus { + fn from(item: DeutschebankPaymentStatus) -> Self { + match item { + DeutschebankPaymentStatus::Succeeded => Self::Charged, + DeutschebankPaymentStatus::Failed => Self::Failure, + DeutschebankPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankPaymentsResponse { + status: DeutschebankPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, DeutschebankPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, DeutschebankPaymentsResponse, 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: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct DeutschebankRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&DeutschebankRouterData<&RefundsRouterData<F>>> for DeutschebankRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &DeutschebankRouterData<&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 DeutschebankErrorResponse { + 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 11a071d135e..02d83636b59 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -88,6 +88,7 @@ macro_rules! default_imp_for_authorize_session_token { default_imp_for_authorize_session_token!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -120,6 +121,7 @@ macro_rules! default_imp_for_complete_authorize { default_imp_for_complete_authorize!( connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -151,6 +153,7 @@ macro_rules! default_imp_for_incremental_authorization { default_imp_for_incremental_authorization!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -183,6 +186,7 @@ macro_rules! default_imp_for_create_customer { default_imp_for_create_customer!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -215,6 +219,7 @@ macro_rules! default_imp_for_connector_redirect_response { default_imp_for_connector_redirect_response!( connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -247,6 +252,7 @@ macro_rules! default_imp_for_pre_processing_steps{ default_imp_for_pre_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -279,6 +285,7 @@ macro_rules! default_imp_for_post_processing_steps{ default_imp_for_post_processing_steps!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -311,6 +318,7 @@ macro_rules! default_imp_for_approve { default_imp_for_approve!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -343,6 +351,7 @@ macro_rules! default_imp_for_reject { default_imp_for_reject!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -375,6 +384,7 @@ macro_rules! default_imp_for_webhook_source_verification { default_imp_for_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -408,6 +418,7 @@ macro_rules! default_imp_for_accept_dispute { default_imp_for_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -440,6 +451,7 @@ macro_rules! default_imp_for_submit_evidence { default_imp_for_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -472,6 +484,7 @@ macro_rules! default_imp_for_defend_dispute { default_imp_for_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -513,6 +526,7 @@ macro_rules! default_imp_for_file_upload { default_imp_for_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -547,6 +561,7 @@ macro_rules! default_imp_for_payouts_create { default_imp_for_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -581,6 +596,7 @@ macro_rules! default_imp_for_payouts_retrieve { default_imp_for_payouts_retrieve!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -615,6 +631,7 @@ macro_rules! default_imp_for_payouts_eligibility { default_imp_for_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -649,6 +666,7 @@ macro_rules! default_imp_for_payouts_fulfill { default_imp_for_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -683,6 +701,7 @@ macro_rules! default_imp_for_payouts_cancel { default_imp_for_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -717,6 +736,7 @@ macro_rules! default_imp_for_payouts_quote { default_imp_for_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -751,6 +771,7 @@ macro_rules! default_imp_for_payouts_recipient { default_imp_for_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -785,6 +806,7 @@ macro_rules! default_imp_for_payouts_recipient_account { default_imp_for_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -819,6 +841,7 @@ macro_rules! default_imp_for_frm_sale { default_imp_for_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -853,6 +876,7 @@ macro_rules! default_imp_for_frm_checkout { default_imp_for_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -887,6 +911,7 @@ macro_rules! default_imp_for_frm_transaction { default_imp_for_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -921,6 +946,7 @@ macro_rules! default_imp_for_frm_fulfillment { default_imp_for_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -955,6 +981,7 @@ macro_rules! default_imp_for_frm_record_return { default_imp_for_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -986,6 +1013,7 @@ macro_rules! default_imp_for_revoking_mandates { default_imp_for_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index ae7f81ffd30..fcab2b721d2 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -183,6 +183,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { default_imp_for_new_connector_integration_payment!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -216,6 +217,7 @@ macro_rules! default_imp_for_new_connector_integration_refund { default_imp_for_new_connector_integration_refund!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -244,6 +246,7 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token { default_imp_for_new_connector_integration_connector_access_token!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -278,6 +281,7 @@ macro_rules! default_imp_for_new_connector_integration_accept_dispute { default_imp_for_new_connector_integration_accept_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -311,6 +315,7 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence { default_imp_for_new_connector_integration_submit_evidence!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -344,6 +349,7 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute { default_imp_for_new_connector_integration_defend_dispute!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -387,6 +393,7 @@ macro_rules! default_imp_for_new_connector_integration_file_upload { default_imp_for_new_connector_integration_file_upload!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -422,6 +429,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create { default_imp_for_new_connector_integration_payouts_create!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -457,6 +465,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility { default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -492,6 +501,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill { default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -527,6 +537,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel { default_imp_for_new_connector_integration_payouts_cancel!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -562,6 +573,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote { default_imp_for_new_connector_integration_payouts_quote!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -597,6 +609,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient { default_imp_for_new_connector_integration_payouts_recipient!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -632,6 +645,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync { default_imp_for_new_connector_integration_payouts_sync!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -667,6 +681,7 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -700,6 +715,7 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -735,6 +751,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale { default_imp_for_new_connector_integration_frm_sale!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -770,6 +787,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout { default_imp_for_new_connector_integration_frm_checkout!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -805,6 +823,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction { default_imp_for_new_connector_integration_frm_transaction!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -840,6 +859,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment { default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -875,6 +895,7 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return { default_imp_for_new_connector_integration_frm_record_return!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, @@ -907,6 +928,7 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates { default_imp_for_new_connector_integration_revoking_mandates!( connectors::Bambora, connectors::Bitpay, + connectors::Deutschebank, connectors::Fiserv, connectors::Fiservemea, connectors::Fiuu, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index e68a10e7bef..37e5eecea6a 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -29,6 +29,7 @@ pub struct Connectors { pub cryptopay: ConnectorParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParams, + pub deutschebank: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index e6e7453b033..1fea8015def 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -64,10 +64,11 @@ pub mod zen; pub mod zsl; pub use hyperswitch_connectors::connectors::{ - bambora, bambora::Bambora, bitpay, bitpay::Bitpay, fiserv, fiserv::Fiserv, fiservemea, - fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, globepay::Globepay, helcim, helcim::Helcim, - nexixpay, nexixpay::Nexixpay, novalnet, novalnet::Novalnet, powertranz, powertranz::Powertranz, - stax, stax::Stax, taxjar, taxjar::Taxjar, tsys, tsys::Tsys, worldline, worldline::Worldline, + bambora, bambora::Bambora, bitpay, bitpay::Bitpay, deutschebank, deutschebank::Deutschebank, + fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, globepay, + globepay::Globepay, helcim, helcim::Helcim, nexixpay, nexixpay::Nexixpay, novalnet, + novalnet::Novalnet, powertranz, powertranz::Powertranz, stax, stax::Stax, taxjar, + taxjar::Taxjar, tsys, tsys::Tsys, worldline, worldline::Worldline, }; #[cfg(feature = "dummy_connector")] 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 0a98fdfdb92..a0b7b530bfc 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -1203,6 +1203,7 @@ default_imp_for_new_connector_integration_payouts!( connector::Coinbase, connector::Cybersource, connector::Datatrans, + connector::Deutschebank, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2015,6 +2016,7 @@ default_imp_for_new_connector_integration_frm!( connector::Coinbase, connector::Cybersource, connector::Datatrans, + connector::Deutschebank, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2618,6 +2620,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connector::Coinbase, connector::Cybersource, connector::Datatrans, + connector::Deutschebank, connector::Dlocal, connector::Ebanx, connector::Fiserv, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 0650797ce1d..c7045733cb4 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -536,6 +536,7 @@ default_imp_for_connector_request_id!( connector::Cryptopay, connector::Cybersource, connector::Datatrans, + connector::Deutschebank, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -1168,6 +1169,7 @@ default_imp_for_payouts!( connector::Cryptopay, connector::Coinbase, connector::Datatrans, + connector::Deutschebank, connector::Dlocal, connector::Fiserv, connector::Fiservemea, @@ -2149,6 +2151,7 @@ default_imp_for_fraud_check!( connector::Cybersource, connector::Coinbase, connector::Datatrans, + connector::Deutschebank, connector::Dlocal, connector::Ebanx, connector::Fiserv, @@ -2940,6 +2943,7 @@ default_imp_for_connector_authentication!( connector::Coinbase, connector::Cybersource, connector::Datatrans, + connector::Deutschebank, connector::Dlocal, connector::Ebanx, connector::Fiserv, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 352e5c45030..da37e0f8544 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -357,6 +357,9 @@ impl ConnectorData { enums::Connector::Datatrans => { Ok(ConnectorEnum::Old(Box::new(connector::Datatrans::new()))) } + // enums::Connector::Deutschebank => { + // Ok(ConnectorEnum::Old(Box::new(connector::Deutschebank::new()))) + // } enums::Connector::Dlocal => Ok(ConnectorEnum::Old(Box::new(&connector::Dlocal))), #[cfg(feature = "dummy_connector")] enums::Connector::DummyConnector1 => Ok(ConnectorEnum::Old(Box::new( diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index abde1e4ff98..964d6536471 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -275,6 +275,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Cryptopay => Self::Cryptopay, api_enums::Connector::Cybersource => Self::Cybersource, api_enums::Connector::Datatrans => Self::Datatrans, + // api_enums::Connector::Deutschebank => Self::Deutschebank, api_enums::Connector::Dlocal => Self::Dlocal, api_enums::Connector::Ebanx => Self::Ebanx, api_enums::Connector::Fiserv => Self::Fiserv, diff --git a/crates/router/tests/connectors/deutschebank.rs b/crates/router/tests/connectors/deutschebank.rs new file mode 100644 index 00000000000..e5d8896444b --- /dev/null +++ b/crates/router/tests/connectors/deutschebank.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 DeutschebankTest; +impl ConnectorActions for DeutschebankTest {} +impl utils::Connector for DeutschebankTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Deutschebank; + utils::construct_connector_data_old( + Box::new(Deutschebank::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .deutschebank + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "deutschebank".to_string() + } +} + +static CONNECTOR: DeutschebankTest = DeutschebankTest {}; + +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/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 55adb3e066f..433f2d03eea 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -26,6 +26,7 @@ mod coinbase; mod cryptopay; mod cybersource; mod datatrans; +mod deutschebank; mod dlocal; #[cfg(feature = "dummy_connector")] mod dummyconnector; diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 1fa302c7161..fe5820d34e5 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -273,4 +273,7 @@ api_secret = "Consumer Secret" api_key = "API Key" [novalnet] +api_key="API Key" + +[deutschebank] api_key="API Key" \ No newline at end of file diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 202446cd59e..a1261e6edb1 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -31,6 +31,7 @@ pub struct ConnectorAuthentication { pub cryptopay: Option<BodyKey>, pub cybersource: Option<SignatureKey>, pub datatrans: Option<HeaderKey>, + pub deutschebank: Option<HeaderKey>, pub dlocal: Option<SignatureKey>, #[cfg(feature = "dummy_connector")] pub dummyconnector: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 6f4628196ea..6dd25f8fbd2 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -96,6 +96,7 @@ coinbase.base_url = "https://api.commerce.coinbase.com" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" +deutschebank.base_url = "https://sandbox.directpos.de/rest-api/services/v2.1" dlocal.base_url = "https://sandbox.dlocal.com/" dummyconnector.base_url = "http://localhost:8080/dummy-connector" ebanx.base_url = "https://sandbox.ebanxpay.com/" @@ -187,6 +188,7 @@ cards = [ "cryptopay", "cybersource", "datatrans", + "deutschebank", "dlocal", "dummyconnector", "ebanx", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 7b2a351398a..0dd3b6434c8 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 applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1") + connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank dlocal dummyconnector ebanx fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay itaubank klarna mifinity mollie multisafepay netcetera nexinets nexixpay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res=`echo ${sorted[@]}` sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-09-02T11:57:57Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> Template code for new connector Deutsche Bank https://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html ### Additional Changes - [ ] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> https://github.com/juspay/hyperswitch/issues/5773 ## How did you test it? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Only template code added hence no testing required. ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
1d149716ba47d3e3f4c749687cff851e18ec77c0
juspay/hyperswitch
juspay__hyperswitch-5796
Bug: feat(payments): show aggregate count of refund status
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 6b9ba4afd01..923881ae376 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -15715,6 +15715,22 @@ } } }, + "RefundAggregateResponse": { + "type": "object", + "required": [ + "status_with_count" + ], + "properties": { + "status_with_count": { + "type": "object", + "description": "The list of refund status with their count", + "additionalProperties": { + "type": "integer", + "format": "int64" + } + } + } + }, "RefundListRequest": { "allOf": [ { diff --git a/crates/api_models/src/events/refund.rs b/crates/api_models/src/events/refund.rs index 0717b66c6bf..d180753735f 100644 --- a/crates/api_models/src/events/refund.rs +++ b/crates/api_models/src/events/refund.rs @@ -1,9 +1,9 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::refunds::{ - RefundListFilters, RefundListMetaData, RefundListRequest, RefundListResponse, - RefundManualUpdateRequest, RefundRequest, RefundResponse, RefundUpdateRequest, - RefundsRetrieveRequest, + RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest, + RefundListResponse, RefundManualUpdateRequest, RefundRequest, RefundResponse, + RefundUpdateRequest, RefundsRetrieveRequest, }; impl ApiEventMetric for RefundRequest { @@ -66,6 +66,12 @@ impl ApiEventMetric for RefundListResponse { } } +impl ApiEventMetric for RefundAggregateResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::ResourceListAPI) + } +} + impl ApiEventMetric for RefundListMetaData { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index 649c0dbf5cf..edc0e75bdf2 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -234,6 +234,12 @@ pub struct RefundListFilters { pub refund_status: Vec<enums::RefundStatus>, } +#[derive(Clone, Debug, serde::Serialize, ToSchema)] +pub struct RefundAggregateResponse { + /// The list of refund status with their count + pub status_with_count: HashMap<enums::RefundStatus, i64>, +} + /// The status for refunds #[derive( Debug, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index f12539cc232..301a51089cf 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -458,6 +458,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, + api_models::refunds::RefundAggregateResponse, api_models::payments::TimeRange, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index c58e4c5183b..e221fab6ac9 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -376,6 +376,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, + api_models::refunds::RefundAggregateResponse, api_models::payments::TimeRange, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 1761c0bad03..8eed5ecfda5 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -1034,6 +1034,32 @@ pub async fn get_filters_for_refunds( )) } +#[instrument(skip_all)] +#[cfg(feature = "olap")] +pub async fn get_aggregates_for_refunds( + state: SessionState, + merchant: domain::MerchantAccount, + time_range: api::TimeRange, +) -> RouterResponse<api_models::refunds::RefundAggregateResponse> { + let db = state.store.as_ref(); + let refund_status_with_count = db + .get_refund_status_with_count(merchant.get_id(), &time_range, merchant.storage_scheme) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to find status count")?; + let mut status_map: HashMap<enums::RefundStatus, i64> = + refund_status_with_count.into_iter().collect(); + for status in enums::RefundStatus::iter() { + status_map.entry(status).or_default(); + } + + Ok(services::ApplicationResponse::Json( + api_models::refunds::RefundAggregateResponse { + status_with_count: status_map, + }, + )) +} + impl ForeignFrom<storage::Refund> for api::RefundResponse { fn foreign_from(refund: storage::Refund) -> Self { let refund = refund; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 31ed4ad93e2..e34339fbc7b 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -2389,6 +2389,18 @@ impl RefundInterface for KafkaStore { .await } + #[cfg(feature = "olap")] + async fn get_refund_status_with_count( + &self, + merchant_id: &id_type::MerchantId, + constraints: &api_models::payments::TimeRange, + storage_scheme: MerchantStorageScheme, + ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { + self.diesel_store + .get_refund_status_with_count(merchant_id, constraints, storage_scheme) + .await + } + #[cfg(feature = "olap")] async fn get_total_count_of_refunds( &self, diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index e6b46c5af5c..a78a4122f4a 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -1,5 +1,5 @@ #[cfg(feature = "olap")] -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; #[cfg(feature = "olap")] use common_utils::types::MinorUnit; @@ -83,6 +83,14 @@ pub trait RefundInterface { storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>; + #[cfg(feature = "olap")] + async fn get_refund_status_with_count( + &self, + merchant_id: &common_utils::id_type::MerchantId, + constraints: &api_models::payments::TimeRange, + storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>; + #[cfg(feature = "olap")] async fn get_total_count_of_refunds( &self, @@ -250,6 +258,21 @@ mod storage { .await .map_err(|error|report!(errors::StorageError::from(error))) } + + #[cfg(feature = "olap")] + #[instrument(skip_all)] + async fn get_refund_status_with_count( + &self, + merchant_id: &common_utils::id_type::MerchantId, + time_range: &api_models::payments::TimeRange, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id, time_range) + .await + .map_err(|error|report!(errors::StorageError::from(error))) + } + #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_total_count_of_refunds( @@ -783,6 +806,20 @@ mod storage { .map_err(|error|report!(errors::StorageError::from(error))) } + #[cfg(feature = "olap")] + #[instrument(skip_all)] + async fn get_refund_status_with_count( + &self, + merchant_id: &common_utils::id_type::MerchantId, + constraints: &api_models::payments::TimeRange, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + <diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id, constraints) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + #[cfg(feature = "olap")] #[instrument(skip_all)] async fn get_total_count_of_refunds( @@ -1112,6 +1149,41 @@ impl RefundInterface for MockDb { Ok(refund_meta_data) } + #[cfg(feature = "olap")] + async fn get_refund_status_with_count( + &self, + _merchant_id: &common_utils::id_type::MerchantId, + time_range: &api_models::payments::TimeRange, + _storage_scheme: enums::MerchantStorageScheme, + ) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> { + let refunds = self.refunds.lock().await; + + let start_time = time_range.start_time; + let end_time = time_range + .end_time + .unwrap_or_else(common_utils::date_time::now); + + let filtered_refunds = refunds + .iter() + .filter(|refund| refund.created_at >= start_time && refund.created_at <= end_time) + .cloned() + .collect::<Vec<diesel_models::refund::Refund>>(); + + let mut refund_status_counts: HashMap<api_models::enums::RefundStatus, i64> = + HashMap::new(); + + for refund in filtered_refunds { + *refund_status_counts + .entry(refund.refund_status) + .or_insert(0) += 1; + } + + let result: Vec<(api_models::enums::RefundStatus, i64)> = + refund_status_counts.into_iter().collect(); + + Ok(result) + } + #[cfg(feature = "olap")] async fn get_total_count_of_refunds( &self, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 4f8e269dff9..56991c6da1d 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -991,6 +991,7 @@ impl Refunds { .service(web::resource("/profile/list").route(web::post().to(refunds_list_profile))) .service(web::resource("/filter").route(web::post().to(refunds_filter_list))) .service(web::resource("/v2/filter").route(web::get().to(get_refunds_filters))) + .service(web::resource("/aggregate").route(web::get().to(get_refunds_aggregates))) .service( web::resource("/v2/profile/filter") .route(web::get().to(get_refunds_filters_profile)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 13148801aa9..0cdfd90e998 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -153,6 +153,7 @@ impl From<Flow> for ApiIdentifier { | Flow::RefundsUpdate | Flow::RefundsList | Flow::RefundsFilters + | Flow::RefundsAggregate | Flow::RefundsManualUpdate => Self::Refunds, Flow::FrmFulfillment diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index 4b964dba626..2f5cb332837 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -421,6 +421,36 @@ pub async fn get_refunds_filters_profile( .await } +#[instrument(skip_all, fields(flow = ?Flow::RefundsAggregate))] +#[cfg(feature = "olap")] +pub async fn get_refunds_aggregates( + state: web::Data<AppState>, + req: HttpRequest, + query_params: web::Query<api_models::payments::TimeRange>, +) -> HttpResponse { + let flow = Flow::RefundsAggregate; + let query_params = query_params.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + query_params, + |state, auth: auth::AuthenticationData, req, _| { + get_aggregates_for_refunds(state, auth.merchant_account, req) + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuth { + permission: Permission::RefundRead, + minimum_entity_level: EntityType::Merchant, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::RefundsManualUpdate))] #[cfg(feature = "olap")] pub async fn refunds_manual_update( diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index 1860771d026..38556f77506 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -36,6 +36,12 @@ pub trait RefundDbExt: Sized { merchant_id: &common_utils::id_type::MerchantId, refund_list_details: &api_models::refunds::RefundListRequest, ) -> CustomResult<i64, errors::DatabaseError>; + + async fn get_refund_status_with_count( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>; } #[async_trait::async_trait] @@ -288,4 +294,33 @@ impl RefundDbExt for Refund { .change_context(errors::DatabaseError::NotFound) .attach_printable_lazy(|| "Error filtering count of refunds") } + + async fn get_refund_status_with_count( + conn: &PgPooledConn, + merchant_id: &common_utils::id_type::MerchantId, + time_range: &api_models::payments::TimeRange, + ) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> { + let mut query = <Self as HasTable>::table() + .group_by(dsl::refund_status) + .select((dsl::refund_status, diesel::dsl::count_star())) + .filter(dsl::merchant_id.eq(merchant_id.to_owned())) + .into_boxed(); + + query = query.filter(dsl::created_at.ge(time_range.start_time)); + + query = match time_range.end_time { + Some(ending_at) => query.filter(dsl::created_at.le(ending_at)), + None => query, + }; + + logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string()); + + db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>( + query.get_results_async::<(RefundStatus, i64)>(conn), + db_metrics::DatabaseOperation::Count, + ) + .await + .change_context(errors::DatabaseError::NotFound) + .attach_printable_lazy(|| "Error filtering status count of refunds") + } } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 79ab704fbbe..6126ca9afbe 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -212,6 +212,8 @@ pub enum Flow { RefundsList, /// Refunds filters flow RefundsFilters, + /// Refunds aggregates flow + RefundsAggregate, // Retrieve forex flow. RetrieveForexFlow, /// Toggles recon service for a merchant.
2024-09-04T11:12:56Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Added new api for refunds status aggregate ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Closed #5796 <!-- Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless it is an obvious bug or documentation fix that will have little conversation). --> ## How did you test it? Request ``` curl --location 'http://localhost:8080/refunds/aggregate?start_time=2022-08-28T18%3A30%3A00Z' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjNmYzEyNjYtZDQ2MS00NWU3LWFkMzEtODdlMDA4ZWVlYjZjIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI0NjYxNjQ3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNTYyMDQ1MSwib3JnX2lkIjoib3JnX3pXYVBBZDBxOGtxcnRpQzN4U3o3IiwicHJvZmlsZV9pZCI6bnVsbH0.VXacvv96BOspj033EFwKvaYdyqjlSNIzMFXYQ-DvsvE' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjNmYzEyNjYtZDQ2MS00NWU3LWFkMzEtODdlMDA4ZWVlYjZjIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI0NjYxNjQ3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcyNTYyMDQ1MSwib3JnX2lkIjoib3JnX3pXYVBBZDBxOGtxcnRpQzN4U3o3IiwicHJvZmlsZV9pZCI6bnVsbH0.VXacvv96BOspj033EFwKvaYdyqjlSNIzMFXYQ-DvsvE' ``` Response ``` { "status_with_count": { "pending": 0, "transaction_failure": 0, "success": 40, "failure": 0, "manual_review": 0 } } ``` <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
aa2f5d147561f6e996228d269e6a54c5d1f53a60
juspay/hyperswitch
juspay__hyperswitch-5765
Bug: [FEATURE] extend dynamic fields support for payout use cases ### Feature Description Dynamic fields helps SDK decide what fields are to be collected from the user. Dynamic fields are defined for a given pm<>pmt<>connector combination. These are attached in the pm list response. These fields are mapped in SDK and collected and sent in the `POST :/confirm` API. ### Possible Implementation #### Define defaults A default implementation for RequiredFields is added in Settings. Same types can be extended to define PayoutRequiredFields for a given pm<>pmt<>connector combination. These can be fetched from state config at any given instance. #### Consumption This list is fetched during payout link render request. Any data that was provided during `POST :/create` request are populated in the dynamic fields and embedded in the payout link. ### Have you spent some time checking if this feature request has been raised before? - [X] I checked and didn't find a similar issue ### Have you read the Contributing Guidelines? - [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md) ### Are you willing to submit a PR? Yes, I am willing to submit a PR!
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 6b9ba4afd01..256832c376d 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3534,6 +3534,14 @@ { "type": "object", "properties": { + "form_layout": { + "allOf": [ + { + "$ref": "#/components/schemas/UIWidgetFormLayout" + } + ], + "nullable": true + }, "payout_test_mode": { "type": "boolean", "description": "Allows for removing any validations / pre-requisites which are necessary in a production environment", @@ -6576,6 +6584,12 @@ "enum": [ "user_cnpj" ] + }, + { + "type": "string", + "enum": [ + "user_iban" + ] } ], "description": "Possible field type of required fields in payment_method_data" @@ -14484,6 +14498,14 @@ "example": "[{\"payment_method\": \"bank_transfer\", \"payment_method_types\": [\"ach\", \"bacs\"]}]", "nullable": true }, + "form_layout": { + "allOf": [ + { + "$ref": "#/components/schemas/UIWidgetFormLayout" + } + ], + "nullable": true + }, "test_mode": { "type": "boolean", "description": "`test_mode` allows for opening payout links without any restrictions. This removes\n- domain name validations\n- check for making sure link is accessed within an iframe", @@ -14787,8 +14809,11 @@ "nullable": true }, "billing": { - "type": "object", - "description": "The billing address for the payout", + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], "nullable": true }, "auto_fulfill": { @@ -17376,6 +17401,13 @@ "payout" ] }, + "UIWidgetFormLayout": { + "type": "string", + "enum": [ + "tabs", + "journey" + ] + }, "UpdateApiKeyRequest": { "type": "object", "description": "The request body for updating an API Key.", diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 0b77fd15a30..2b185d202e1 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2473,6 +2473,10 @@ pub struct BusinessPayoutLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, + /// Form layout of the payout link + #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] + pub form_layout: Option<api_enums::UIWidgetFormLayout>, + /// Allows for removing any validations / pre-requisites which are necessary in a production environment #[schema(value_type = Option<bool>, default = false)] pub payout_test_mode: Option<bool>, diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 5db816305bd..4f6a327b28f 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -512,6 +512,7 @@ pub enum FieldType { UserPixKey, UserCpf, UserCnpj, + UserIban, } impl FieldType { diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index aad0cfcf303..01bb63642be 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use cards::CardNumber; use common_utils::{ consts::default_payouts_list_limit, @@ -5,11 +7,12 @@ use common_utils::{ pii::{self, Email}, }; use masking::Secret; +use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; -use crate::{enums as api_enums, payments}; +use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] pub enum PayoutRequest { @@ -204,6 +207,10 @@ pub struct PayoutCreatePayoutLinkConfig { #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, + /// Form layout of the payout link + #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] + pub form_layout: Option<api_enums::UIWidgetFormLayout>, + /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe @@ -411,7 +418,7 @@ pub struct PayoutCreateResponse { pub payout_type: Option<api_enums::PayoutType>, /// The billing address for the payout - #[schema(value_type = Option<Object>, example = json!(r#"{ + #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", @@ -778,12 +785,31 @@ pub struct PayoutLinkDetails { #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, + pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, + pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } +#[derive(Clone, Debug, serde::Serialize)] +pub struct PayoutEnabledPaymentMethodsInfo { + pub payment_method: common_enums::PaymentMethod, + pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, +} + +#[derive(Clone, Debug, serde::Serialize)] +pub struct PaymentMethodTypeInfo { + pub payment_method_type: common_enums::PaymentMethodType, + pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, +} + +#[derive(Clone, Debug, serde::Serialize, FlatStruct)] +pub struct RequiredFieldsOverrideRequest { + pub billing: Option<payments::Address>, +} + #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index eef23ff5b89..de4ef498793 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3159,6 +3159,27 @@ pub enum OrderFulfillmentTimeOrigin { Confirm, } +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, + Hash, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum UIWidgetFormLayout { + Tabs, + Journey, +} + #[derive( Clone, Copy, diff --git a/crates/common_utils/src/link_utils.rs b/crates/common_utils/src/link_utils.rs index dc7153f2c5b..2201000d062 100644 --- a/crates/common_utils/src/link_utils.rs +++ b/crates/common_utils/src/link_utils.rs @@ -2,7 +2,7 @@ use std::{collections::HashSet, primitive::i64}; -use common_enums::enums; +use common_enums::{enums, UIWidgetFormLayout}; use diesel::{ backend::Backend, deserialize, @@ -167,6 +167,8 @@ pub struct PayoutLinkData { pub currency: enums::Currency, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: HashSet<String>, + /// Form layout of the payout link + pub form_layout: Option<UIWidgetFormLayout>, /// `test_mode` can be used for testing payout links without any restrictions pub test_mode: Option<bool>, } diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 549ad47609f..029add42ced 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -1,6 +1,6 @@ use std::collections::{HashMap, HashSet}; -use common_enums::AuthenticationConnectors; +use common_enums::{AuthenticationConnectors, UIWidgetFormLayout}; use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use masking::Secret; @@ -556,6 +556,7 @@ common_utils::impl_to_sql_from_sql_json!(BusinessPaymentLinkConfig); pub struct BusinessPayoutLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, + pub form_layout: Option<UIWidgetFormLayout>, pub payout_test_mode: Option<bool>, } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index f12539cc232..291b883561d 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -264,6 +264,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::ConnectorStatus, api_models::enums::AuthorizationStatus, api_models::enums::PaymentMethodStatus, + api_models::enums::UIWidgetFormLayout, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::MerchantRecipientData, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index c58e4c5183b..26765a29c3b 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -182,6 +182,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::AuthorizationStatus, api_models::enums::PaymentMethodStatus, api_models::enums::OrderFulfillmentTimeOrigin, + api_models::enums::UIWidgetFormLayout, api_models::admin::MerchantConnectorCreate, api_models::admin::AdditionalMerchantData, api_models::admin::MerchantRecipientData, diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 6898a9e002f..8814e9156b7 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -4,6 +4,9 @@ use api_models::{enums, payment_methods::RequiredFieldInfo}; use super::settings::{ConnectorFields, PaymentMethodType, RequiredFieldFinal}; +#[cfg(feature = "payouts")] +pub mod payout_required_fields; + impl Default for super::settings::Server { fn default() -> Self { Self { diff --git a/crates/router/src/configs/defaults/payout_required_fields.rs b/crates/router/src/configs/defaults/payout_required_fields.rs new file mode 100644 index 00000000000..0b8d380f7a3 --- /dev/null +++ b/crates/router/src/configs/defaults/payout_required_fields.rs @@ -0,0 +1,603 @@ +use std::collections::HashMap; + +use api_models::{ + enums::{ + CountryAlpha2, FieldType, + PaymentMethod::{BankTransfer, Card, Wallet}, + PaymentMethodType, PayoutConnectors, + }, + payment_methods::RequiredFieldInfo, +}; + +use crate::settings::{ + ConnectorFields, PaymentMethodType as PaymentMethodTypeInfo, PayoutRequiredFields, + RequiredFieldFinal, +}; + +impl Default for PayoutRequiredFields { + fn default() -> Self { + Self(HashMap::from([ + ( + Card, + PaymentMethodTypeInfo(HashMap::from([ + // Adyen + get_connector_payment_method_type_fields( + PayoutConnectors::Adyenplatform, + PaymentMethodType::Debit, + ), + get_connector_payment_method_type_fields( + PayoutConnectors::Adyenplatform, + PaymentMethodType::Credit, + ), + ])), + ), + ( + BankTransfer, + PaymentMethodTypeInfo(HashMap::from([ + // Adyen + get_connector_payment_method_type_fields( + PayoutConnectors::Adyenplatform, + PaymentMethodType::Sepa, + ), + // Ebanx + get_connector_payment_method_type_fields( + PayoutConnectors::Ebanx, + PaymentMethodType::Pix, + ), + // Wise + get_connector_payment_method_type_fields( + PayoutConnectors::Wise, + PaymentMethodType::Bacs, + ), + ])), + ), + ( + Wallet, + PaymentMethodTypeInfo(HashMap::from([ + // Adyen + get_connector_payment_method_type_fields( + PayoutConnectors::Adyenplatform, + PaymentMethodType::Paypal, + ), + ])), + ), + ])) + } +} + +fn get_connector_payment_method_type_fields( + connector: PayoutConnectors, + payment_method_type: PaymentMethodType, +) -> (PaymentMethodType, ConnectorFields) { + let mut common_fields = get_billing_details(connector); + match payment_method_type { + // Card + PaymentMethodType::Debit => { + common_fields.extend(get_card_fields()); + ( + payment_method_type, + ConnectorFields { + fields: HashMap::from([( + connector.into(), + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: common_fields, + }, + )]), + }, + ) + } + PaymentMethodType::Credit => { + common_fields.extend(get_card_fields()); + ( + payment_method_type, + ConnectorFields { + fields: HashMap::from([( + connector.into(), + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: common_fields, + }, + )]), + }, + ) + } + + // Banks + PaymentMethodType::Bacs => { + common_fields.extend(get_bacs_fields()); + ( + payment_method_type, + ConnectorFields { + fields: HashMap::from([( + connector.into(), + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: common_fields, + }, + )]), + }, + ) + } + PaymentMethodType::Pix => { + common_fields.extend(get_pix_bank_transfer_fields()); + ( + payment_method_type, + ConnectorFields { + fields: HashMap::from([( + connector.into(), + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: common_fields, + }, + )]), + }, + ) + } + PaymentMethodType::Sepa => { + common_fields.extend(get_sepa_fields()); + ( + payment_method_type, + ConnectorFields { + fields: HashMap::from([( + connector.into(), + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: common_fields, + }, + )]), + }, + ) + } + + // Wallets + PaymentMethodType::Paypal => { + common_fields.extend(get_paypal_fields()); + ( + payment_method_type, + ConnectorFields { + fields: HashMap::from([( + connector.into(), + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate: HashMap::new(), + common: common_fields, + }, + )]), + }, + ) + } + + _ => ( + payment_method_type, + ConnectorFields { + fields: HashMap::new(), + }, + ), + } +} + +fn get_card_fields() -> HashMap<String, RequiredFieldInfo> { + HashMap::from([ + ( + "payout_method_data.card.card_number".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.card.card_number".to_string(), + display_name: "card_number".to_string(), + field_type: FieldType::UserCardNumber, + value: None, + }, + ), + ( + "payout_method_data.card.expiry_month".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.card.expiry_month".to_string(), + display_name: "exp_month".to_string(), + field_type: FieldType::UserCardExpiryMonth, + value: None, + }, + ), + ( + "payout_method_data.card.expiry_year".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.card.expiry_year".to_string(), + display_name: "exp_year".to_string(), + field_type: FieldType::UserCardExpiryYear, + value: None, + }, + ), + ( + "payout_method_data.card.card_holder_name".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.card.card_holder_name".to_string(), + display_name: "card_holder_name".to_string(), + field_type: FieldType::UserFullName, + value: None, + }, + ), + ]) +} + +fn get_bacs_fields() -> HashMap<String, RequiredFieldInfo> { + HashMap::from([ + ( + "payout_method_data.bank.bank_sort_code".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.bank.bank_sort_code".to_string(), + display_name: "bank_sort_code".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "payout_method_data.bank.bank_account_number".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.bank.bank_account_number".to_string(), + display_name: "bank_account_number".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]) +} + +fn get_pix_bank_transfer_fields() -> HashMap<String, RequiredFieldInfo> { + HashMap::from([ + ( + "payout_method_data.bank.bank_account_number".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.bank.bank_account_number".to_string(), + display_name: "bank_account_number".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "payout_method_data.bank.pix_key".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.bank.pix_key".to_string(), + display_name: "pix_key".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]) +} + +fn get_sepa_fields() -> HashMap<String, RequiredFieldInfo> { + HashMap::from([ + ( + "payout_method_data.bank.iban".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.bank.iban".to_string(), + display_name: "iban".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "payout_method_data.bank.bic".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.bank.bic".to_string(), + display_name: "bic".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]) +} + +fn get_paypal_fields() -> HashMap<String, RequiredFieldInfo> { + HashMap::from([( + "payout_method_data.wallet.telephone_number".to_string(), + RequiredFieldInfo { + required_field: "payout_method_data.wallet.telephone_number".to_string(), + display_name: "telephone_number".to_string(), + field_type: FieldType::Text, + value: None, + }, + )]) +} + +fn get_countries_for_connector(connector: PayoutConnectors) -> Vec<CountryAlpha2> { + match connector { + PayoutConnectors::Adyenplatform => vec![ + CountryAlpha2::ES, + CountryAlpha2::SK, + CountryAlpha2::AT, + CountryAlpha2::NL, + CountryAlpha2::DE, + CountryAlpha2::BE, + CountryAlpha2::FR, + CountryAlpha2::FI, + CountryAlpha2::PT, + CountryAlpha2::IE, + CountryAlpha2::EE, + CountryAlpha2::LT, + CountryAlpha2::LV, + CountryAlpha2::IT, + CountryAlpha2::CZ, + CountryAlpha2::DE, + CountryAlpha2::HU, + CountryAlpha2::NO, + CountryAlpha2::PL, + CountryAlpha2::SE, + CountryAlpha2::GB, + CountryAlpha2::CH, + ], + PayoutConnectors::Stripe => vec![CountryAlpha2::US], + _ => vec![], + } +} + +fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredFieldInfo> { + match connector { + PayoutConnectors::Adyen => HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_address_line1".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.line2".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line2".to_string(), + display_name: "billing_address_line2".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "billing_address_city".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "billing_address_zip".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "billing_address_country".to_string(), + field_type: FieldType::UserAddressCountry { + options: get_countries_for_connector(connector) + .iter() + .map(|country| country.to_string()) + .collect::<Vec<String>>(), + }, + value: None, + }, + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_address_first_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "billing_address_last_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]), + PayoutConnectors::Adyenplatform => HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_address_line1".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.line2".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line2".to_string(), + display_name: "billing_address_line2".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "billing_address_city".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "billing_address_zip".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "billing_address_country".to_string(), + field_type: FieldType::UserAddressCountry { + options: get_countries_for_connector(connector) + .iter() + .map(|country| country.to_string()) + .collect::<Vec<String>>(), + }, + value: None, + }, + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_address_first_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]), + PayoutConnectors::Wise => HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_address_line1".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "billing_address_city".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.state".to_string(), + RequiredFieldInfo { + required_field: "billing.address.state".to_string(), + display_name: "billing_address_state".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "billing_address_zip".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "billing_address_country".to_string(), + field_type: FieldType::UserAddressCountry { + options: get_countries_for_connector(connector) + .iter() + .map(|country| country.to_string()) + .collect::<Vec<String>>(), + }, + value: None, + }, + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_address_first_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]), + _ => HashMap::from([ + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line1".to_string(), + display_name: "billing_address_line1".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.line2".to_string(), + RequiredFieldInfo { + required_field: "billing.address.line2".to_string(), + display_name: "billing_address_line2".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "billing.address.city".to_string(), + display_name: "billing_address_city".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "billing.address.zip".to_string(), + display_name: "billing_address_zip".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "billing.address.country".to_string(), + display_name: "billing_address_country".to_string(), + field_type: FieldType::UserAddressCountry { + options: get_countries_for_connector(connector) + .iter() + .map(|country| country.to_string()) + .collect::<Vec<String>>(), + }, + value: None, + }, + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.first_name".to_string(), + display_name: "billing_address_first_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "billing.address.last_name".to_string(), + display_name: "billing_address_last_name".to_string(), + field_type: FieldType::Text, + value: None, + }, + ), + ]), + } +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 2c27b0cfc72..0a65d935f50 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -491,6 +491,10 @@ pub struct NotAvailableFlows { pub capture_method: Option<enums::CaptureMethod>, } +#[cfg(feature = "payouts")] +#[derive(Debug, Deserialize, Clone)] +pub struct PayoutRequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); + #[derive(Debug, Deserialize, Clone)] pub struct RequiredFields(pub HashMap<enums::PaymentMethod, PaymentMethodType>); @@ -841,6 +845,8 @@ impl Settings<RawSecret> { #[derive(Debug, Deserialize, Clone, Default)] pub struct Payouts { pub payout_eligibility: bool, + #[serde(default)] + pub required_fields: PayoutRequiredFields, } #[derive(Debug, Clone, Default)] diff --git a/crates/router/src/core/generic_link/payout_link/initiate/script.js b/crates/router/src/core/generic_link/payout_link/initiate/script.js index abbfbb896ac..2d3592256e2 100644 --- a/crates/router/src/core/generic_link/payout_link/initiate/script.js +++ b/crates/router/src/core/generic_link/payout_link/initiate/script.js @@ -160,12 +160,13 @@ if (!isTestMode && !isFramed) { theme: payoutDetails.theme, collectorName: payoutDetails.merchant_name, logo: payoutDetails.logo, - enabledPaymentMethods: payoutDetails.enabled_payment_methods, + enabledPaymentMethods: payoutDetails.enabled_payment_methods_with_required_fields, returnUrl: payoutDetails.return_url, sessionExpiry, amount: payoutDetails.amount, currency: payoutDetails.currency, flow: "PayoutLinkInitiate", + formLayout: payoutDetails.form_layout, }; payoutWidget = widgets.create("paymentMethodCollect", payoutOptions); diff --git a/crates/router/src/core/generic_link/payout_link/status/script.js b/crates/router/src/core/generic_link/payout_link/status/script.js index 828ea7f7fc4..aa75676153a 100644 --- a/crates/router/src/core/generic_link/payout_link/status/script.js +++ b/crates/router/src/core/generic_link/payout_link/status/script.js @@ -121,10 +121,10 @@ function renderStatusDetails(payoutDetails) { "{{i18n_ref_id_text}}": payoutDetails.payout_id, }; if (typeof payoutDetails.error_code === "string") { - resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code; + // resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code; } if (typeof payoutDetails.error_message === "string") { - resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message; + // resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message; } var resourceNode = document.createElement("div"); resourceNode.id = "resource-info-container"; diff --git a/crates/router/src/core/generic_link/payout_link/status/styles.css b/crates/router/src/core/generic_link/payout_link/status/styles.css index ff922298fad..a10bfe7e3c0 100644 --- a/crates/router/src/core/generic_link/payout_link/status/styles.css +++ b/crates/router/src/core/generic_link/payout_link/status/styles.css @@ -80,7 +80,7 @@ body { #resource-info-container { width: 100%; border-top: 1px solid rgb(231, 234, 241); - padding: 20px 0; + padding: 20px 10px; } #resource-info { display: flex; diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs index 210d0e6d38b..a153d071088 100644 --- a/crates/router/src/core/payout_link.rs +++ b/crates/router/src/core/payout_link.rs @@ -21,7 +21,7 @@ use crate::{ errors, routes::{app::StorageInterface, SessionState}, services, - types::domain, + types::{api, domain, transformers::ForeignFrom}, }; #[cfg(all(feature = "v2", feature = "customer_v2"))] @@ -156,9 +156,31 @@ pub async fn initiate_payout_link( .attach_printable_lazy(|| { format!("customer [{}] not found", payout_link.primary_reference) })?; + let address = payout + .address_id + .as_ref() + .async_map(|address_id| async { + db.find_address_by_address_id(&(&state).into(), address_id, &key_store) + .await + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Failed while fetching address [id - {:?}] for payout [id - {}]", + payout.address_id, payout.payout_id + ) + })?; - let enabled_payout_methods = - filter_payout_methods(&state, &merchant_account, &key_store, &payout).await?; + let enabled_payout_methods = filter_payout_methods( + &state, + &merchant_account, + &key_store, + &payout, + address.as_ref(), + ) + .await?; // Fetch default enabled_payout_methods let mut default_enabled_payout_methods: Vec<link_utils::EnabledPaymentMethod> = vec![]; for (payment_method, payment_method_types) in @@ -188,6 +210,16 @@ pub async fn initiate_payout_link( _ => Ordering::Equal, }); + let required_field_override = api::RequiredFieldsOverrideRequest { + billing: address.as_ref().map(From::from), + }; + + let enabled_payment_methods_with_required_fields = ForeignFrom::foreign_from(( + &state.conf.payouts.required_fields, + enabled_payment_methods.clone(), + required_field_override, + )); + let js_data = payouts::PayoutLinkDetails { publishable_key: masking::Secret::new(merchant_account.publishable_key), client_secret: link_data.client_secret.clone(), @@ -204,9 +236,11 @@ pub async fn initiate_payout_link( .attach_printable("Failed to parse payout status link's return URL")?, ui_config: ui_config_data, enabled_payment_methods, + enabled_payment_methods_with_required_fields, amount, currency: payout.destination_currency, locale: locale.clone(), + form_layout: link_data.form_layout, test_mode: link_data.test_mode.unwrap_or(false), }; @@ -287,6 +321,7 @@ pub async fn filter_payout_methods( merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, payout: &hyperswitch_domain_models::payouts::payouts::Payouts, + address: Option<&domain::Address>, ) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> { use masking::ExposeInterface; @@ -308,22 +343,6 @@ pub async fn filter_payout_methods( &payout.profile_id, common_enums::ConnectorType::PayoutProcessor, ); - let address = payout - .address_id - .as_ref() - .async_map(|address_id| async { - db.find_address_by_address_id(key_manager_state, address_id, key_store) - .await - }) - .await - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable_lazy(|| { - format!( - "Failed while fetching address [id - {:?}] for payout [id - {}]", - payout.address_id, payout.payout_id - ) - })?; let mut response: Vec<link_utils::EnabledPaymentMethod> = vec![]; let mut payment_method_list_hm: HashMap< diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 0e9df5284da..82128f98a52 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -11,11 +11,9 @@ use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse}; use common_enums::PayoutRetryType; use common_utils::{ consts, - crypto::Encryptable, ext_traits::{AsyncExt, ValueExt}, id_type::CustomerId, link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus}, - pii, types::MinorUnit, }; use diesel_models::{ @@ -2142,29 +2140,7 @@ pub async fn response_handler( let billing_address = payout_data.billing_address.to_owned(); let customer_details = payout_data.customer_details.to_owned(); let customer_id = payouts.customer_id; - - let address = billing_address.as_ref().map(|a| { - let phone_details = payment_api_types::PhoneDetails { - number: a.phone_number.to_owned().map(Encryptable::into_inner), - country_code: a.country_code.to_owned(), - }; - let address_details = payment_api_types::AddressDetails { - city: a.city.to_owned(), - country: a.country.to_owned(), - line1: a.line1.to_owned().map(Encryptable::into_inner), - line2: a.line2.to_owned().map(Encryptable::into_inner), - line3: a.line3.to_owned().map(Encryptable::into_inner), - zip: a.zip.to_owned().map(Encryptable::into_inner), - first_name: a.first_name.to_owned().map(Encryptable::into_inner), - last_name: a.last_name.to_owned().map(Encryptable::into_inner), - state: a.state.to_owned().map(Encryptable::into_inner), - }; - api::payments::Address { - phone: Some(phone_details), - address: Some(address_details), - email: a.email.to_owned().map(pii::Email::from), - } - }); + let billing = billing_address.as_ref().map(From::from); let response = api::PayoutCreateResponse { payout_id: payouts.payout_id.to_owned(), @@ -2173,7 +2149,7 @@ pub async fn response_handler( currency: payouts.destination_currency.to_owned(), connector: payout_attempt.connector.to_owned(), payout_type: payouts.payout_type.to_owned(), - billing: address, + billing, auto_fulfill: payouts.auto_fulfill, customer_id, email: customer_details.as_ref().and_then(|c| c.email.clone()), @@ -2746,6 +2722,14 @@ pub async fn create_payout_link( .and_then(|config| config.payout_link_id.clone()), "payout_link", )?; + let form_layout = payout_link_config_req + .as_ref() + .and_then(|config| config.form_layout.to_owned()) + .or_else(|| { + profile_config + .as_ref() + .and_then(|config| config.form_layout.to_owned()) + }); let data = PayoutLinkData { payout_link_id: payout_link_id.clone(), @@ -2759,6 +2743,7 @@ pub async fn create_payout_link( amount: MinorUnit::from(*amount), currency: *currency, allowed_domains, + form_layout, test_mode: test_mode_in_config, }; diff --git a/crates/router/src/core/payouts/transformers.rs b/crates/router/src/core/payouts/transformers.rs index d10e56cff43..35919abb1f0 100644 --- a/crates/router/src/core/payouts/transformers.rs +++ b/crates/router/src/core/payouts/transformers.rs @@ -1,3 +1,7 @@ +use std::collections::HashMap; + +use common_utils::link_utils::EnabledPaymentMethod; + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "customer_v2"), @@ -5,7 +9,11 @@ ))] use crate::types::transformers::ForeignInto; #[cfg(feature = "olap")] -use crate::types::{api, domain, storage, transformers::ForeignFrom}; +use crate::types::{domain, storage}; +use crate::{ + settings::PayoutRequiredFields, + types::{api, transformers::ForeignFrom}, +}; #[cfg(all(feature = "v2", feature = "customer_v2", feature = "olap"))] impl @@ -103,3 +111,72 @@ impl } } } + +impl + ForeignFrom<( + &PayoutRequiredFields, + Vec<EnabledPaymentMethod>, + api::RequiredFieldsOverrideRequest, + )> for Vec<api::PayoutEnabledPaymentMethodsInfo> +{ + fn foreign_from( + (payout_required_fields, enabled_payout_methods, value_overrides): ( + &PayoutRequiredFields, + Vec<EnabledPaymentMethod>, + api::RequiredFieldsOverrideRequest, + ), + ) -> Self { + let value_overrides = value_overrides.flat_struct(); + + enabled_payout_methods + .into_iter() + .map(|enabled_payout_method| { + let payment_method = enabled_payout_method.payment_method; + let payment_method_types_info = enabled_payout_method + .payment_method_types + .into_iter() + .filter_map(|pmt| { + payout_required_fields + .0 + .get(&payment_method) + .and_then(|pmt_info| { + pmt_info.0.get(&pmt).map(|connector_fields| { + let mut required_fields = HashMap::new(); + + for required_field_final in connector_fields.fields.values() { + required_fields.extend(required_field_final.common.clone()); + } + + for (key, value) in &value_overrides { + required_fields.entry(key.to_string()).and_modify( + |required_field| { + required_field.value = + Some(masking::Secret::new(value.to_string())); + }, + ); + } + api::PaymentMethodTypeInfo { + payment_method_type: pmt, + required_fields: if required_fields.is_empty() { + None + } else { + Some(required_fields) + }, + } + }) + }) + .or(Some(api::PaymentMethodTypeInfo { + payment_method_type: pmt, + required_fields: None, + })) + }) + .collect(); + + api::PayoutEnabledPaymentMethodsInfo { + payment_method, + payment_method_types_info, + } + }) + .collect() + } +} diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs index 84b7d93d68a..984fba1c8db 100644 --- a/crates/router/src/types/api/payouts.rs +++ b/crates/router/src/types/api/payouts.rs @@ -1,9 +1,10 @@ pub use api_models::payouts::{ - AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest, - PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, PayoutLinkResponse, - PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, - PayoutMethodData, PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, - SepaBankTransfer, Wallet as WalletPayout, + AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PaymentMethodTypeInfo, + PayoutActionRequest, PayoutAttemptResponse, PayoutCreateRequest, PayoutCreateResponse, + PayoutEnabledPaymentMethodsInfo, PayoutLinkResponse, PayoutListConstraints, + PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutMethodData, + PayoutRequest, PayoutRetrieveBody, PayoutRetrieveRequest, PixBankTransfer, + RequiredFieldsOverrideRequest, SepaBankTransfer, Wallet as WalletPayout, }; pub use hyperswitch_domain_models::router_flow_types::payouts::{ PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount, PoSync, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index de897c816dd..d8f3ce38d27 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1797,6 +1797,7 @@ impl ForeignFrom<api_models::admin::BusinessPayoutLinkConfig> fn foreign_from(item: api_models::admin::BusinessPayoutLinkConfig) -> Self { Self { config: item.config.foreign_into(), + form_layout: item.form_layout, payout_test_mode: item.payout_test_mode, } } @@ -1808,6 +1809,7 @@ impl ForeignFrom<diesel_models::business_profile::BusinessPayoutLinkConfig> fn foreign_from(item: diesel_models::business_profile::BusinessPayoutLinkConfig) -> Self { Self { config: item.config.foreign_into(), + form_layout: item.form_layout, payout_test_mode: item.payout_test_mode, } } diff --git a/crates/router/tests/macros.rs b/crates/router/tests/macros.rs new file mode 100644 index 00000000000..3a5301efa5f --- /dev/null +++ b/crates/router/tests/macros.rs @@ -0,0 +1,42 @@ +#[cfg(test)] +mod flat_struct_test { + #![allow(clippy::unwrap_used)] + use std::collections::HashMap; + + use router_derive::FlatStruct; + use serde::Serialize; + + #[test] + fn test_flat_struct() { + #[derive(FlatStruct, Serialize)] + struct User { + address: Address, + } + + #[derive(Serialize)] + struct Address { + line1: String, + zip: String, + city: String, + } + + let line1 = "1397".to_string(); + let zip = "Some street".to_string(); + let city = "941222".to_string(); + + let address = Address { + line1: line1.clone(), + zip: zip.clone(), + city: city.clone(), + }; + let user = User { address }; + let flat_user_map = user.flat_struct(); + + let mut required_map = HashMap::new(); + required_map.insert("address.line1".to_string(), line1); + required_map.insert("address.zip".to_string(), zip); + required_map.insert("address.city".to_string(), city); + + assert_eq!(flat_user_map, required_map); + } +} diff --git a/crates/router_derive/Cargo.toml b/crates/router_derive/Cargo.toml index 5a17c32cd01..72cf9605f9b 100644 --- a/crates/router_derive/Cargo.toml +++ b/crates/router_derive/Cargo.toml @@ -15,6 +15,7 @@ doctest = false indexmap = "2.2.6" proc-macro2 = "1.0.79" quote = "1.0.35" +serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } syn = { version = "2.0.57", 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 2931d9bdca2..02179934e38 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -1,10 +1,8 @@ //! Utility macros for the `router` crate. #![warn(missing_docs)] - use syn::parse_macro_input; use crate::macros::diesel::DieselEnumMeta; - mod macros; /// Uses the [`Debug`][Debug] implementation of a type to derive its [`Display`][Display] @@ -615,3 +613,84 @@ pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::Token .unwrap_or_else(|error| error.into_compile_error()) .into() } + +/// Uses the [`Serialize`] implementation of a type to derive a function implementation +/// for converting nested keys structure into a HashMap of key, value where key is in +/// the flattened form. +/// +/// Example +/// +/// #[derive(Default, Serialize, FlatStruct)] +/// pub struct User { +/// name: String, +/// address: Address, +/// email: String, +/// } +/// +/// #[derive(Default, Serialize)] +/// pub struct Address { +/// line1: String, +/// line2: String, +/// zip: String, +/// } +/// +/// let user = User::default(); +/// let flat_struct_map = user.flat_struct(); +/// +/// [ +/// ("name", "Test"), +/// ("address.line1", "1397"), +/// ("address.line2", "Some street"), +/// ("address.zip", "941222"), +/// ("email", "test@example.com"), +/// ] +#[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); + let name = &input.ident; + + let expanded = quote::quote! { + impl #name { + pub fn flat_struct(&self) -> std::collections::HashMap<String, String> { + use serde_json::Value; + use std::collections::HashMap; + + fn flatten_value( + value: &Value, + prefix: &str, + result: &mut HashMap<String, String> + ) { + match value { + Value::Object(map) => { + for (key, val) in map { + let new_key = if prefix.is_empty() { + key.to_string() + } else { + format!("{}.{}", prefix, key) + }; + flatten_value(val, &new_key, result); + } + } + Value::String(s) => { + result.insert(prefix.to_string(), s.clone()); + } + Value::Number(n) => { + result.insert(prefix.to_string(), n.to_string()); + } + Value::Bool(b) => { + result.insert(prefix.to_string(), b.to_string()); + } + _ => {} + } + } + + let mut result = HashMap::new(); + let value = serde_json::to_value(self).unwrap(); + flatten_value(&value, "", &mut result); + result + } + } + }; + + proc_macro::TokenStream::from(expanded) +}
2024-09-01T17:45:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR includes below changes - add dynamic fields support for payout widget (#5765) - expose `formLayout` option in payout link config - journey or tabs ### Additional Changes - [x] This PR modifies the API contract - [ ] This PR modifies the database schema - [x] This PR modifies application configuration/environment variables <!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: 1. `config` 2. `crates/router/src/configs` 3. `loadtest/config` --> ## Motivation and Context Allows for collecting data dynamically based on the selected payout method type. ## How did you test it? Tested locally <details> <summary>1. Create a payout widget which uses journey layout</summary> curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_6lYcIjzguBUudkK9bpoM3LZDod7RdE1wDJWzxwZhGLWWL6mlQIcfbUkXQgTAgj7e' \ --data '{ "amount": 1, "currency": "EUR", "customer_id": "cus_s5yZDiR680XOcGjcZrQ4", "description": "Its my first payout request", "entity_type": "Individual", "confirm": false, "auto_fulfill": true, "session_expiry": 1000000, "priority": "instant", "profile_id": "pro_zFe41ju6ZVZMtuuUHPji", "payout_link": true, "return_url": "https://www.google.com", "payout_link_config": { "formLayout": "journey", "theme": "#0066ff" } }' ![image](https://github.com/user-attachments/assets/603b1d6e-0fa3-4046-a27a-1e4566823032) </details> <details> <summary>2. Create a payout widget which uses tabs layout</summary> curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_6lYcIjzguBUudkK9bpoM3LZDod7RdE1wDJWzxwZhGLWWL6mlQIcfbUkXQgTAgj7e' \ --data '{ "amount": 1, "currency": "EUR", "customer_id": "cus_s5yZDiR680XOcGjcZrQ4", "description": "Its my first payout request", "entity_type": "Individual", "confirm": false, "auto_fulfill": true, "session_expiry": 1000000, "priority": "instant", "profile_id": "pro_zFe41ju6ZVZMtuuUHPji", "payout_link": true, "return_url": "https://www.google.com", "payout_link_config": { "formLayout": "tabs", "theme": "#0066ff" } }' ![image](https://github.com/user-attachments/assets/1eb65fdb-62b7-4784-b83e-554143610352) </details> <details> <summary>3. Create a payout without billing address</summary> curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_6lYcIjzguBUudkK9bpoM3LZDod7RdE1wDJWzxwZhGLWWL6mlQIcfbUkXQgTAgj7e' \ --data '{ "amount": 1, "currency": "EUR", "customer_id": "cus_s5yZDiR680XOcGjcZrQ4", "description": "Its my first payout request", "entity_type": "Individual", "confirm": false, "auto_fulfill": true, "session_expiry": 1000000, "priority": "instant", "profile_id": "pro_zFe41ju6ZVZMtuuUHPji", "payout_link": true, "return_url": "https://www.google.com", "payout_link_config": { "formLayout": "tabs", "theme": "#0066ff" } }' ![image](https://github.com/user-attachments/assets/1eb65fdb-62b7-4784-b83e-554143610352) </details> <details> <summary>4. Create a payout with partial billing address</summary> curl --location 'http://localhost:8080/payouts/create' \ --header 'Content-Type: application/json' \ --header 'api-key: dev_6lYcIjzguBUudkK9bpoM3LZDod7RdE1wDJWzxwZhGLWWL6mlQIcfbUkXQgTAgj7e' \ --data '{ "amount": 1, "currency": "EUR", "customer_id": "cus_s5yZDiR680XOcGjcZrQ4", "description": "Its my first payout request", "entity_type": "Individual", "confirm": false, "auto_fulfill": true, "session_expiry": 1000000, "priority": "instant", "profile_id": "pro_zFe41ju6ZVZMtuuUHPji", "payout_link": true, "return_url": "https://www.google.com", "payout_link_config": { "formLayout": "tabs", "theme": "#0066ff" } }' ![image](https://github.com/user-attachments/assets/4abd4aea-eb9e-49ab-8cbd-901ae562c9e1) </details> ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `cargo +nightly fmt --all` - [x] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
d5fee45ead11e9a03fd6fc15dfd8cf91de27eefa