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-7010
Bug: [FEATURE] [Authorizedotnet]: Add metadata information to connector request ### Feature Description [Authorizedotnet]: Add metadata information to connector request ### Possible Implementation [Authorizedotnet]: Add metadata information to connector request ### 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/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index d2b212e3ea0..8e0af603a3d 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -1,3 +1,5 @@ +use std::collections::BTreeMap; + use common_utils::{ errors::CustomResult, ext_traits::{Encode, ValueExt}, @@ -6,6 +8,7 @@ use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret}; use rand::distributions::{Alphanumeric, DistString}; use serde::{Deserialize, Serialize}; +use serde_json::Value; use crate::{ connector::utils::{ @@ -143,12 +146,27 @@ struct TransactionRequest { #[serde(skip_serializing_if = "Option::is_none")] bill_to: Option<BillTo>, #[serde(skip_serializing_if = "Option::is_none")] + user_fields: Option<UserFields>, + #[serde(skip_serializing_if = "Option::is_none")] processing_options: Option<ProcessingOptions>, #[serde(skip_serializing_if = "Option::is_none")] subsequent_auth_information: Option<SubsequentAuthInformation>, authorization_indicator_type: Option<AuthorizationIndicator>, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct UserFields { + user_field: Vec<UserField>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct UserField { + name: String, + value: String, +} + #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum ProfileDetails { @@ -299,6 +317,25 @@ pub enum ValidationMode { LiveMode, } +impl ForeignTryFrom<Value> for Vec<UserField> { + type Error = error_stack::Report<errors::ConnectorError>; + fn foreign_try_from(metadata: Value) -> Result<Self, Self::Error> { + let hashmap: BTreeMap<String, Value> = serde_json::from_str(&metadata.to_string()) + .change_context(errors::ConnectorError::RequestEncodingFailedWithReason( + "Failed to serialize request metadata".to_owned(), + )) + .attach_printable("")?; + let mut vector: Self = Self::new(); + for (key, value) in hashmap { + vector.push(UserField { + name: key, + value: value.to_string(), + }); + } + Ok(vector) + } +} + impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { @@ -622,6 +659,12 @@ impl zip: address.zip.clone(), country: address.country, }), + user_fields: match item.router_data.request.metadata.clone() { + Some(metadata) => Some(UserFields { + user_field: Vec::<UserField>::foreign_try_from(metadata)?, + }), + None => None, + }, processing_options: Some(ProcessingOptions { is_subsequent_auth: true, }), @@ -675,6 +718,12 @@ impl }, customer: None, bill_to: None, + user_fields: match item.router_data.request.metadata.clone() { + Some(metadata) => Some(UserFields { + user_field: Vec::<UserField>::foreign_try_from(metadata)?, + }), + None => None, + }, processing_options: Some(ProcessingOptions { is_subsequent_auth: true, }), @@ -764,6 +813,12 @@ impl zip: address.zip.clone(), country: address.country, }), + user_fields: match item.router_data.request.metadata.clone() { + Some(metadata) => Some(UserFields { + user_field: Vec::<UserField>::foreign_try_from(metadata)?, + }), + None => None, + }, processing_options: None, subsequent_auth_information: None, authorization_indicator_type: match item.router_data.request.capture_method { @@ -815,6 +870,12 @@ impl zip: address.zip.clone(), country: address.country, }), + user_fields: match item.router_data.request.metadata.clone() { + Some(metadata) => Some(UserFields { + user_field: Vec::<UserField>::foreign_try_from(metadata)?, + }), + None => None, + }, processing_options: None, subsequent_auth_information: None, authorization_indicator_type: match item.router_data.request.capture_method {
2025-01-08T08:42:03Z
## 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 --> This PR is for code changes which sends the metadata passed in payment intent create to authorizedotnet as request payload, as per merchant requirements. The merchant receives a receipt of the transaction through email, which contains the metadata passed by the merchant in payment intent create request. ![image](https://github.com/user-attachments/assets/84fa9591-bf64-473c-aaba-c95b9cf78dcb) ### 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). --> All flows have been tested as per the authorizedotnet developer docs: https://developer.authorize.net/api/reference/index.html#payment-transactions-charge-a-credit-card ## 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)? --> **Postman Tests** **1. Authorize (Manual)** - Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0vV4HvaBn68pmZTvXLzU9V7hR79lgEjiarEG2IDxveccjZ6ypKjpPaRrdeQRHhKu' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "StripeCustomer1", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "likhin", "last_name": "bopanna" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "likhin", "last_name": "bopanna" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "count_tickets": 1, "transaction_number": "5590045" } }' ``` - Response ``` { "payment_id": "pay_aMR57wTed0e8hKIvqEXk", "merchant_id": "postman_merchant_GHAction_4bc8cb40-6e2b-4474-a4ba-662cce1e8224", "status": "requires_capture", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_aMR57wTed0e8hKIvqEXk_secret_7ClGeHihtfOkLr17zmY6", "created": "2025-01-08T12:18:38.236Z", "currency": "USD", "customer_id": "StripeCustomer1", "customer": { "id": "StripeCustomer1", "name": "John Doe", "email": "[email protected]", "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": "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": "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": "likhin", "last_name": "bopanna" }, "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": "likhin", "last_name": "bopanna" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "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": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer1", "created_at": 1736338718, "expires": 1736342318, "secret": "epk_a3fa4b96efa94fbe817dd39b634b4b10" }, "manual_retry_allowed": false, "connector_transaction_id": "80033079979", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "80033079979", "payment_link": null, "profile_id": "pro_54auzGTSaZOQ9xIUOEn8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tFxUMA2vfBlte3s7jSw7", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-08T12:33:38.236Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-01-08T12:18:40.884Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **2. Capture (Manual)** - Request ``` curl --location 'http://localhost:8080/payments/pay_aMR57wTed0e8hKIvqEXk/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0vV4HvaBn68pmZTvXLzU9V7hR79lgEjiarEG2IDxveccjZ6ypKjpPaRrdeQRHhKu' \ --data '{ "amount_to_capture": 6540, "statement_descriptor_name": "Joseph", "statement_descriptor_suffix": "JS" }' ``` - Response ``` { "payment_id": "pay_aMR57wTed0e8hKIvqEXk", "merchant_id": "postman_merchant_GHAction_4bc8cb40-6e2b-4474-a4ba-662cce1e8224", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "authorizedotnet", "client_secret": "pay_aMR57wTed0e8hKIvqEXk_secret_7ClGeHihtfOkLr17zmY6", "created": "2025-01-08T12:18:38.236Z", "currency": "USD", "customer_id": "StripeCustomer1", "customer": { "id": "StripeCustomer1", "name": "John Doe", "email": "[email protected]", "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": "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": "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": "likhin", "last_name": "bopanna" }, "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": "likhin", "last_name": "bopanna" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "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": 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": "80033079979", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "80033079979", "payment_link": null, "profile_id": "pro_54auzGTSaZOQ9xIUOEn8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tFxUMA2vfBlte3s7jSw7", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-08T12:33:38.236Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-01-08T12:20:16.395Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **3. Authorize + Capture** - Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0vV4HvaBn68pmZTvXLzU9V7hR79lgEjiarEG2IDxveccjZ6ypKjpPaRrdeQRHhKu' \ --data-raw '{ "amount": 6550, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6550, "customer_id": "StripeCustomer1", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "01", "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", "last_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari", "last_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "count_tickets": 1, "transaction_number": "5590045" } }' ``` - Response ``` { "payment_id": "pay_EbFXhSWxwVQ0996FxZdt", "merchant_id": "postman_merchant_GHAction_4bc8cb40-6e2b-4474-a4ba-662cce1e8224", "status": "succeeded", "amount": 6550, "net_amount": 6550, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6550, "connector": "authorizedotnet", "client_secret": "pay_EbFXhSWxwVQ0996FxZdt_secret_3J0fmk53qE22LeKiGIGx", "created": "2025-01-08T12:21:59.998Z", "currency": "USD", "customer_id": "StripeCustomer1", "customer": { "id": "StripeCustomer1", "name": "John Doe", "email": "[email protected]", "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": "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": "01", "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": "sundari", "last_name": "sundari" }, "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": "sundari", "last_name": "sundari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "authorizedotnet_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "StripeCustomer1", "created_at": 1736338919, "expires": 1736342519, "secret": "epk_a1b2ad7e39a14673a4e01692f76e5193" }, "manual_retry_allowed": false, "connector_transaction_id": "80033080191", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "80033080191", "payment_link": null, "profile_id": "pro_54auzGTSaZOQ9xIUOEn8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tFxUMA2vfBlte3s7jSw7", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-08T12:36:59.998Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-01-08T12:22:02.624Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **4. PSync** - Request ``` curl --location 'http://localhost:8080/payments/pay_EbFXhSWxwVQ0996FxZdt?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_0vV4HvaBn68pmZTvXLzU9V7hR79lgEjiarEG2IDxveccjZ6ypKjpPaRrdeQRHhKu' ``` - Response ``` { "payment_id": "pay_EbFXhSWxwVQ0996FxZdt", "merchant_id": "postman_merchant_GHAction_4bc8cb40-6e2b-4474-a4ba-662cce1e8224", "status": "succeeded", "amount": 6550, "net_amount": 6550, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6550, "connector": "authorizedotnet", "client_secret": "pay_EbFXhSWxwVQ0996FxZdt_secret_3J0fmk53qE22LeKiGIGx", "created": "2025-01-08T12:21:59.998Z", "currency": "USD", "customer_id": "StripeCustomer1", "customer": { "id": "StripeCustomer1", "name": "John Doe", "email": "[email protected]", "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": "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": "01", "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": "sundari", "last_name": "sundari" }, "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": "sundari", "last_name": "sundari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "authorizedotnet_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "80033080191", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "80033080191", "payment_link": null, "profile_id": "pro_54auzGTSaZOQ9xIUOEn8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tFxUMA2vfBlte3s7jSw7", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-08T12:36:59.998Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-01-08T12:22:02.624Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **5. Refund** - Request ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0vV4HvaBn68pmZTvXLzU9V7hR79lgEjiarEG2IDxveccjZ6ypKjpPaRrdeQRHhKu' \ --data '{ "payment_id": "pay_LdFELbsSHWr31UxLX51l", "amount": 5000, "reason": "Customer returned product", "refund_type": "scheduled", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response ``` { "refund_id": "ref_ht8iD8smYnJl5sDF0BEn", "payment_id": "pay_LdFELbsSHWr31UxLX51l", "amount": 5000, "currency": "USD", "status": "pending", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-01-08T12:31:33.642Z", "updated_at": "2025-01-08T12:31:33.642Z", "connector": "authorizedotnet", "profile_id": "pro_54auzGTSaZOQ9xIUOEn8", "merchant_connector_id": "mca_tFxUMA2vfBlte3s7jSw7", "split_refunds": null } ``` **6. RSync** - Request ``` curl --location 'http://localhost:8080/refunds/ref_ht8iD8smYnJl5sDF0BEn' \ --header 'Accept: application/json' \ --header 'api-key: dev_0vV4HvaBn68pmZTvXLzU9V7hR79lgEjiarEG2IDxveccjZ6ypKjpPaRrdeQRHhKu' ``` - Response ``` { "refund_id": "ref_ht8iD8smYnJl5sDF0BEn", "payment_id": "pay_LdFELbsSHWr31UxLX51l", "amount": 5000, "currency": "USD", "status": "pending", "reason": "Customer returned product", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" }, "error_message": null, "error_code": null, "unified_code": null, "unified_message": null, "created_at": "2025-01-08T12:31:33.642Z", "updated_at": "2025-01-08T12:31:33.642Z", "connector": "authorizedotnet", "profile_id": "pro_54auzGTSaZOQ9xIUOEn8", "merchant_connector_id": "mca_tFxUMA2vfBlte3s7jSw7", "split_refunds": null } ``` **7. Cancel/Void** - Request ``` curl --location 'http://localhost:8080/payments/pay_LdFELbsSHWr31UxLX51l/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_0vV4HvaBn68pmZTvXLzU9V7hR79lgEjiarEG2IDxveccjZ6ypKjpPaRrdeQRHhKu' \ --data '{"cancellation_reason":"requested_by_customer"}' ``` - Response ``` { "payment_id": "pay_wM2Pf7TjLVabcAj41aDz", "merchant_id": "postman_merchant_GHAction_4bc8cb40-6e2b-4474-a4ba-662cce1e8224", "status": "cancelled", "amount": 5000, "net_amount": 5000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "authorizedotnet", "client_secret": "pay_wM2Pf7TjLVabcAj41aDz_secret_vjFJJKmyoVaNqOmQ0Bge", "created": "2025-01-08T12:29:07.232Z", "currency": "USD", "customer_id": "StripeCustomer1", "customer": { "id": "StripeCustomer1", "name": "John Doe", "email": "[email protected]", "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": "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": "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": "likhin", "last_name": "bopanna" }, "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": "likhin", "last_name": "bopanna" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "requested_by_customer", "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": "80033080543", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": "80033080543", "payment_link": null, "profile_id": "pro_54auzGTSaZOQ9xIUOEn8", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tFxUMA2vfBlte3s7jSw7", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-08T12:44:07.232Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-01-08T12:29:28.533Z", "split_payments": 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
ad5491f15bd8f61b2a918f584fe85132986176ad
juspay/hyperswitch
juspay__hyperswitch-7042
Bug: [FIX] add a fallback to key without prefix for redis To keep the tenant data isolated from each other, We are using a prefix for Redis keys i.e A key which would be saved as card123 without multitenancy would be saved as public:card123 with Multitenancy. If the user makes a payment on the older pod where MultiTenancy is disabled and client_secret is saved without a prefix, Now if the confirm calls goes to the pod where Multitenancy is enabled the Payment would fail with Unauthorized. This is just one of the instances where the payments would fail.
diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs index 2ca2c1cc79c..aaf455663f5 100644 --- a/crates/drainer/src/health_check.rs +++ b/crates/drainer/src/health_check.rs @@ -165,21 +165,21 @@ impl HealthCheckInterface for Store { let redis_conn = self.redis_conn.clone(); redis_conn - .serialize_and_set_key_with_expiry("test_key", "test_value", 30) + .serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30) .await .change_context(HealthCheckRedisError::SetFailed)?; logger::debug!("Redis set_key was successful"); redis_conn - .get_key::<()>("test_key") + .get_key::<()>(&"test_key".into()) .await .change_context(HealthCheckRedisError::GetFailed)?; logger::debug!("Redis get_key was successful"); redis_conn - .delete_key("test_key") + .delete_key(&"test_key".into()) .await .change_context(HealthCheckRedisError::DeleteFailed)?; @@ -187,7 +187,7 @@ impl HealthCheckInterface for Store { redis_conn .stream_append_entry( - TEST_STREAM_NAME, + &TEST_STREAM_NAME.into(), &redis_interface::RedisEntryId::AutoGeneratedID, TEST_STREAM_DATA.to_vec(), ) @@ -216,7 +216,7 @@ impl HealthCheckInterface for Store { redis_conn .stream_trim_entries( - TEST_STREAM_NAME, + &TEST_STREAM_NAME.into(), ( redis_interface::StreamCapKind::MinID, redis_interface::StreamCapTrim::Exact, diff --git a/crates/drainer/src/stream.rs b/crates/drainer/src/stream.rs index f5b41c53672..9e092b038e8 100644 --- a/crates/drainer/src/stream.rs +++ b/crates/drainer/src/stream.rs @@ -31,7 +31,7 @@ impl Store { match self .redis_conn - .set_key_if_not_exists_with_expiry(stream_key_flag.as_str(), true, None) + .set_key_if_not_exists_with_expiry(&stream_key_flag.as_str().into(), true, None) .await { Ok(resp) => resp == redis::types::SetnxReply::KeySet, @@ -43,7 +43,7 @@ impl Store { } pub async fn make_stream_available(&self, stream_name_flag: &str) -> errors::DrainerResult<()> { - match self.redis_conn.delete_key(stream_name_flag).await { + match self.redis_conn.delete_key(&stream_name_flag.into()).await { Ok(redis::DelReply::KeyDeleted) => Ok(()), Ok(redis::DelReply::KeyNotDeleted) => { logger::error!("Tried to unlock a stream which is already unlocked"); @@ -87,14 +87,14 @@ impl Store { common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async { let trim_result = self .redis_conn - .stream_trim_entries(stream_name, (trim_kind, trim_type, trim_id)) + .stream_trim_entries(&stream_name.into(), (trim_kind, trim_type, trim_id)) .await .map_err(errors::DrainerError::from)?; // Since xtrim deletes entries below given id excluding the given id. // Hence, deleting the minimum entry id self.redis_conn - .stream_delete_entries(stream_name, minimum_entry_id) + .stream_delete_entries(&stream_name.into(), minimum_entry_id) .await .map_err(errors::DrainerError::from)?; diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml index f9159564830..87f5721365c 100644 --- a/crates/redis_interface/Cargo.toml +++ b/crates/redis_interface/Cargo.toml @@ -7,6 +7,9 @@ rust-version.workspace = true readme = "README.md" license.workspace = true +[features] +multitenancy_fallback = [] + [dependencies] error-stack = "0.4.1" fred = { version = "7.1.2", features = ["metrics", "partial-tracing", "subscriber-client", "check-unresponsive"] } diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 56e9ab98104..affd2b0faa9 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -17,8 +17,7 @@ use fred::{ prelude::{LuaInterface, RedisErrorKind}, types::{ Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings, - MultipleValues, RedisKey, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, - XReadResponse, + MultipleValues, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, XReadResponse, }, }; use futures::StreamExt; @@ -26,7 +25,7 @@ use tracing::instrument; use crate::{ errors, - types::{DelReply, HsetnxReply, MsetnxReply, RedisEntryId, SaddReply, SetnxReply}, + types::{DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetnxReply}, }; impl super::RedisConnectionPool { @@ -37,15 +36,16 @@ impl super::RedisConnectionPool { format!("{}:{}", self.key_prefix, key) } } + #[instrument(level = "DEBUG", skip(self))] - pub async fn set_key<V>(&self, key: &str, value: V) -> CustomResult<(), errors::RedisError> + pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError> where V: TryInto<RedisValue> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool .set( - self.add_prefix(key), + key.tenant_aware_key(self), value, Some(Expiration::EX(self.config.default_ttl.into())), None, @@ -57,7 +57,7 @@ impl super::RedisConnectionPool { pub async fn set_key_without_modifying_ttl<V>( &self, - key: &str, + key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where @@ -65,7 +65,13 @@ impl super::RedisConnectionPool { V::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool - .set(key, value, Some(Expiration::KEEPTTL), None, false) + .set( + key.tenant_aware_key(self), + value, + Some(Expiration::KEEPTTL), + None, + false, + ) .await .change_context(errors::RedisError::SetFailed) } @@ -87,7 +93,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_if_not_exist<V>( &self, - key: &str, + key: &RedisKey, value: V, ttl: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> @@ -104,7 +110,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key<V>( &self, - key: &str, + key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where @@ -120,7 +126,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_without_modifying_ttl<V>( &self, - key: &str, + key: &RedisKey, value: V, ) -> CustomResult<(), errors::RedisError> where @@ -137,7 +143,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_key_with_expiry<V>( &self, - key: &str, + key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> @@ -150,7 +156,7 @@ impl super::RedisConnectionPool { self.pool .set( - self.add_prefix(key), + key.tenant_aware_key(self), serialized.as_slice(), Some(Expiration::EX(seconds)), None, @@ -161,31 +167,67 @@ impl super::RedisConnectionPool { } #[instrument(level = "DEBUG", skip(self))] - pub async fn get_key<V>(&self, key: &str) -> CustomResult<V, errors::RedisError> + pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { - self.pool - .get(self.add_prefix(key)) + match self + .pool + .get(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) + { + Ok(v) => Ok(v), + Err(_err) => { + #[cfg(not(feature = "multitenancy_fallback"))] + { + Err(_err) + } + + #[cfg(feature = "multitenancy_fallback")] + { + self.pool + .get(key.tenant_unaware_key(self)) + .await + .change_context(errors::RedisError::GetFailed) + } + } + } } #[instrument(level = "DEBUG", skip(self))] - pub async fn exists<V>(&self, key: &str) -> CustomResult<bool, errors::RedisError> + pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError> where V: Into<MultipleKeys> + Unpin + Send + 'static, { - self.pool - .exists(self.add_prefix(key)) + match self + .pool + .exists(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetFailed) + { + Ok(v) => Ok(v), + Err(_err) => { + #[cfg(not(feature = "multitenancy_fallback"))] + { + Err(_err) + } + + #[cfg(feature = "multitenancy_fallback")] + { + self.pool + .exists(key.tenant_unaware_key(self)) + .await + .change_context(errors::RedisError::GetFailed) + } + } + } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_and_deserialize_key<T>( &self, - key: &str, + key: &RedisKey, type_name: &'static str, ) -> CustomResult<T, errors::RedisError> where @@ -201,19 +243,37 @@ impl super::RedisConnectionPool { } #[instrument(level = "DEBUG", skip(self))] - pub async fn delete_key(&self, key: &str) -> CustomResult<DelReply, errors::RedisError> { - self.pool - .del(self.add_prefix(key)) + pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> { + match self + .pool + .del(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::DeleteFailed) + { + Ok(v) => Ok(v), + Err(_err) => { + #[cfg(not(feature = "multitenancy_fallback"))] + { + Err(_err) + } + + #[cfg(feature = "multitenancy_fallback")] + { + self.pool + .del(key.tenant_unaware_key(self)) + .await + .change_context(errors::RedisError::DeleteFailed) + } + } + } } #[instrument(level = "DEBUG", skip(self))] pub async fn delete_multiple_keys( &self, - keys: &[String], + keys: &[RedisKey], ) -> CustomResult<Vec<DelReply>, errors::RedisError> { - let futures = keys.iter().map(|key| self.pool.del(self.add_prefix(key))); + let futures = keys.iter().map(|key| self.delete_key(key)); let del_result = futures::future::try_join_all(futures) .await @@ -225,7 +285,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_with_expiry<V>( &self, - key: &str, + key: &RedisKey, value: V, seconds: i64, ) -> CustomResult<(), errors::RedisError> @@ -235,7 +295,7 @@ impl super::RedisConnectionPool { { self.pool .set( - self.add_prefix(key), + key.tenant_aware_key(self), value, Some(Expiration::EX(seconds)), None, @@ -248,7 +308,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn set_key_if_not_exists_with_expiry<V>( &self, - key: &str, + key: &RedisKey, value: V, seconds: Option<i64>, ) -> CustomResult<SetnxReply, errors::RedisError> @@ -258,7 +318,7 @@ impl super::RedisConnectionPool { { self.pool .set( - self.add_prefix(key), + key.tenant_aware_key(self), value, Some(Expiration::EX( seconds.unwrap_or(self.config.default_ttl.into()), @@ -273,11 +333,11 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn set_expiry( &self, - key: &str, + key: &RedisKey, seconds: i64, ) -> CustomResult<(), errors::RedisError> { self.pool - .expire(self.add_prefix(key), seconds) + .expire(key.tenant_aware_key(self), seconds) .await .change_context(errors::RedisError::SetExpiryFailed) } @@ -285,11 +345,11 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn set_expire_at( &self, - key: &str, + key: &RedisKey, timestamp: i64, ) -> CustomResult<(), errors::RedisError> { self.pool - .expire_at(self.add_prefix(key), timestamp) + .expire_at(key.tenant_aware_key(self), timestamp) .await .change_context(errors::RedisError::SetExpiryFailed) } @@ -297,7 +357,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_fields<V>( &self, - key: &str, + key: &RedisKey, values: V, ttl: Option<i64>, ) -> CustomResult<(), errors::RedisError> @@ -307,7 +367,7 @@ impl super::RedisConnectionPool { { let output: Result<(), _> = self .pool - .hset(self.add_prefix(key), values) + .hset(key.tenant_aware_key(self), values) .await .change_context(errors::RedisError::SetHashFailed); // setting expiry for the key @@ -321,7 +381,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn set_hash_field_if_not_exist<V>( &self, - key: &str, + key: &RedisKey, field: &str, value: V, ttl: Option<u32>, @@ -332,7 +392,7 @@ impl super::RedisConnectionPool { { let output: Result<HsetnxReply, _> = self .pool - .hsetnx(self.add_prefix(key), field, value) + .hsetnx(key.tenant_aware_key(self), field, value) .await .change_context(errors::RedisError::SetHashFieldFailed); @@ -348,7 +408,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_hash_field_if_not_exist<V>( &self, - key: &str, + key: &RedisKey, field: &str, value: V, ttl: Option<u32>, @@ -367,7 +427,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>( &self, - kv: &[(&str, V)], + kv: &[(&RedisKey, V)], field: &str, ttl: Option<u32>, ) -> CustomResult<Vec<HsetnxReply>, errors::RedisError> @@ -387,7 +447,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn increment_fields_in_hash<T>( &self, - key: &str, + key: &RedisKey, fields_to_increment: &[(T, i64)], ) -> CustomResult<Vec<usize>, errors::RedisError> where @@ -397,7 +457,7 @@ impl super::RedisConnectionPool { for (field, increment) in fields_to_increment.iter() { values_after_increment.push( self.pool - .hincrby(self.add_prefix(key), field.to_string(), *increment) + .hincrby(key.tenant_aware_key(self), field.to_string(), *increment) .await .change_context(errors::RedisError::IncrementHashFieldFailed)?, ) @@ -409,14 +469,14 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn hscan( &self, - key: &str, + key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() - .hscan::<&str, &str>(&self.add_prefix(key), pattern, count) + .hscan::<&str, &str>(&key.tenant_aware_key(self), pattern, count) .filter_map(|value| async move { match value { Ok(mut v) => { @@ -440,14 +500,14 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn scan( &self, - pattern: &str, + pattern: &RedisKey, count: Option<u32>, scan_type: Option<ScanType>, ) -> CustomResult<Vec<String>, errors::RedisError> { Ok(self .pool .next() - .scan(&self.add_prefix(pattern), count, scan_type) + .scan(pattern.tenant_aware_key(self), count, scan_type) .filter_map(|value| async move { match value { Ok(mut v) => { @@ -471,7 +531,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn hscan_and_deserialize<T>( &self, - key: &str, + key: &RedisKey, pattern: &str, count: Option<u32>, ) -> CustomResult<Vec<T>, errors::RedisError> @@ -491,33 +551,69 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field<V>( &self, - key: &str, + key: &RedisKey, field: &str, ) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { - self.pool - .hget(self.add_prefix(key), field) + match self + .pool + .hget(key.tenant_aware_key(self), field) .await .change_context(errors::RedisError::GetHashFieldFailed) + { + Ok(v) => Ok(v), + Err(_err) => { + #[cfg(feature = "multitenancy_fallback")] + { + self.pool + .hget(key.tenant_unaware_key(self), field) + .await + .change_context(errors::RedisError::GetHashFieldFailed) + } + + #[cfg(not(feature = "multitenancy_fallback"))] + { + Err(_err) + } + } + } } #[instrument(level = "DEBUG", skip(self))] - pub async fn get_hash_fields<V>(&self, key: &str) -> CustomResult<V, errors::RedisError> + pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError> where V: FromRedis + Unpin + Send + 'static, { - self.pool - .hgetall(self.add_prefix(key)) + match self + .pool + .hgetall(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetHashFieldFailed) + { + Ok(v) => Ok(v), + Err(_err) => { + #[cfg(feature = "multitenancy_fallback")] + { + self.pool + .hgetall(key.tenant_unaware_key(self)) + .await + .change_context(errors::RedisError::GetHashFieldFailed) + } + + #[cfg(not(feature = "multitenancy_fallback"))] + { + Err(_err) + } + } + } } #[instrument(level = "DEBUG", skip(self))] pub async fn get_hash_field_and_deserialize<V>( &self, - key: &str, + key: &RedisKey, field: &str, type_name: &'static str, ) -> CustomResult<V, errors::RedisError> @@ -538,7 +634,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn sadd<V>( &self, - key: &str, + key: &RedisKey, members: V, ) -> CustomResult<SaddReply, errors::RedisError> where @@ -546,7 +642,7 @@ impl super::RedisConnectionPool { V::Error: Into<fred::error::RedisError> + Send, { self.pool - .sadd(self.add_prefix(key), members) + .sadd(key.tenant_aware_key(self), members) .await .change_context(errors::RedisError::SetAddMembersFailed) } @@ -554,7 +650,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn stream_append_entry<F>( &self, - stream: &str, + stream: &RedisKey, entry_id: &RedisEntryId, fields: F, ) -> CustomResult<(), errors::RedisError> @@ -563,7 +659,7 @@ impl super::RedisConnectionPool { F::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool - .xadd(self.add_prefix(stream), false, None, entry_id, fields) + .xadd(stream.tenant_aware_key(self), false, None, entry_id, fields) .await .change_context(errors::RedisError::StreamAppendFailed) } @@ -571,14 +667,14 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn stream_delete_entries<Ids>( &self, - stream: &str, + stream: &RedisKey, ids: Ids, ) -> CustomResult<usize, errors::RedisError> where Ids: Into<MultipleStrings> + Debug + Send + Sync, { self.pool - .xdel(self.add_prefix(stream), ids) + .xdel(stream.tenant_aware_key(self), ids) .await .change_context(errors::RedisError::StreamDeleteFailed) } @@ -586,7 +682,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn stream_trim_entries<C>( &self, - stream: &str, + stream: &RedisKey, xcap: C, ) -> CustomResult<usize, errors::RedisError> where @@ -594,7 +690,7 @@ impl super::RedisConnectionPool { C::Error: Into<fred::error::RedisError> + Send + Sync, { self.pool - .xtrim(self.add_prefix(stream), xcap) + .xtrim(stream.tenant_aware_key(self), xcap) .await .change_context(errors::RedisError::StreamTrimFailed) } @@ -602,7 +698,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn stream_acknowledge_entries<Ids>( &self, - stream: &str, + stream: &RedisKey, group: &str, ids: Ids, ) -> CustomResult<usize, errors::RedisError> @@ -610,15 +706,18 @@ impl super::RedisConnectionPool { Ids: Into<MultipleIDs> + Debug + Send + Sync, { self.pool - .xack(self.add_prefix(stream), group, ids) + .xack(stream.tenant_aware_key(self), group, ids) .await .change_context(errors::RedisError::StreamAcknowledgeFailed) } #[instrument(level = "DEBUG", skip(self))] - pub async fn stream_get_length(&self, stream: &str) -> CustomResult<usize, errors::RedisError> { + pub async fn stream_get_length( + &self, + stream: &RedisKey, + ) -> CustomResult<usize, errors::RedisError> { self.pool - .xlen(self.add_prefix(stream)) + .xlen(stream.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetLengthFailed) } @@ -631,10 +730,10 @@ impl super::RedisConnectionPool { let res = multiple_keys .inner() .iter() - .filter_map(|key| key.as_str()) - .map(|k| self.add_prefix(k)) - .map(RedisKey::from) + .filter_map(|key| key.as_str().map(RedisKey::from)) + .map(|k: RedisKey| k.tenant_aware_key(self)) .collect::<Vec<_>>(); + MultipleKeys::from(res) } @@ -710,7 +809,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn append_elements_to_list<V>( &self, - key: &str, + key: &RedisKey, elements: V, ) -> CustomResult<(), errors::RedisError> where @@ -718,7 +817,7 @@ impl super::RedisConnectionPool { V::Error: Into<fred::error::RedisError> + Send, { self.pool - .rpush(self.add_prefix(key), elements) + .rpush(key.tenant_aware_key(self), elements) .await .change_context(errors::RedisError::AppendElementsToListFailed) } @@ -726,20 +825,20 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn get_list_elements( &self, - key: &str, + key: &RedisKey, start: i64, stop: i64, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool - .lrange(self.add_prefix(key), start, stop) + .lrange(key.tenant_aware_key(self), start, stop) .await .change_context(errors::RedisError::GetListElementsFailed) } #[instrument(level = "DEBUG", skip(self))] - pub async fn get_list_length(&self, key: &str) -> CustomResult<usize, errors::RedisError> { + pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> { self.pool - .llen(self.add_prefix(key)) + .llen(key.tenant_aware_key(self)) .await .change_context(errors::RedisError::GetListLengthFailed) } @@ -747,11 +846,11 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn lpop_list_elements( &self, - key: &str, + key: &RedisKey, count: Option<usize>, ) -> CustomResult<Vec<String>, errors::RedisError> { self.pool - .lpop(self.add_prefix(key), count) + .lpop(key.tenant_aware_key(self), count) .await .change_context(errors::RedisError::PopListElementsFailed) } @@ -761,7 +860,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_create( &self, - stream: &str, + stream: &RedisKey, group: &str, id: &RedisEntryId, ) -> CustomResult<(), errors::RedisError> { @@ -774,7 +873,7 @@ impl super::RedisConnectionPool { } self.pool - .xgroup_create(self.add_prefix(stream), group, id, true) + .xgroup_create(stream.tenant_aware_key(self), group, id, true) .await .change_context(errors::RedisError::ConsumerGroupCreateFailed) } @@ -782,11 +881,11 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_destroy( &self, - stream: &str, + stream: &RedisKey, group: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool - .xgroup_destroy(self.add_prefix(stream), group) + .xgroup_destroy(stream.tenant_aware_key(self), group) .await .change_context(errors::RedisError::ConsumerGroupDestroyFailed) } @@ -795,12 +894,12 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_delete_consumer( &self, - stream: &str, + stream: &RedisKey, group: &str, consumer: &str, ) -> CustomResult<usize, errors::RedisError> { self.pool - .xgroup_delconsumer(self.add_prefix(stream), group, consumer) + .xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer) .await .change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed) } @@ -808,12 +907,12 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_set_last_id( &self, - stream: &str, + stream: &RedisKey, group: &str, id: &RedisEntryId, ) -> CustomResult<String, errors::RedisError> { self.pool - .xgroup_setid(self.add_prefix(stream), group, id) + .xgroup_setid(stream.tenant_aware_key(self), group, id) .await .change_context(errors::RedisError::ConsumerGroupSetIdFailed) } @@ -821,7 +920,7 @@ impl super::RedisConnectionPool { #[instrument(level = "DEBUG", skip(self))] pub async fn consumer_group_set_message_owner<Ids, R>( &self, - stream: &str, + stream: &RedisKey, group: &str, consumer: &str, min_idle_time: u64, @@ -833,7 +932,7 @@ impl super::RedisConnectionPool { { self.pool .xclaim( - self.add_prefix(stream), + stream.tenant_aware_key(self), group, consumer, min_idle_time, @@ -888,11 +987,15 @@ mod tests { // Act let result1 = redis_conn - .consumer_group_create("TEST1", "GTEST", &RedisEntryId::AutoGeneratedID) + .consumer_group_create(&"TEST1".into(), "GTEST", &RedisEntryId::AutoGeneratedID) .await; let result2 = redis_conn - .consumer_group_create("TEST3", "GTEST", &RedisEntryId::UndeliveredEntryID) + .consumer_group_create( + &"TEST3".into(), + "GTEST", + &RedisEntryId::UndeliveredEntryID, + ) .await; // Assert Setup @@ -914,10 +1017,10 @@ mod tests { let pool = RedisConnectionPool::new(&RedisSettings::default()) .await .expect("failed to create redis connection pool"); - let _ = pool.set_key("key", "value".to_string()).await; + let _ = pool.set_key(&"key".into(), "value".to_string()).await; // Act - let result = pool.delete_key("key").await; + let result = pool.delete_key(&"key".into()).await; // Assert setup result.is_ok() @@ -938,7 +1041,7 @@ mod tests { .expect("failed to create redis connection pool"); // Act - let result = pool.delete_key("key not exists").await; + let result = pool.delete_key(&"key not exists".into()).await; // Assert Setup result.is_ok() diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index 92429f617d1..848996deb4a 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -4,7 +4,7 @@ use common_utils::errors::CustomResult; use fred::types::RedisValue as FredRedisValue; -use crate::errors; +use crate::{errors, RedisConnectionPool}; pub struct RedisValue { inner: FredRedisValue, @@ -293,3 +293,24 @@ impl fred::types::FromRedis for SaddReply { } } } + +#[derive(Debug)] +pub struct RedisKey(String); + +impl RedisKey { + pub fn tenant_aware_key(&self, pool: &RedisConnectionPool) -> String { + pool.add_prefix(&self.0) + } + + pub fn tenant_unaware_key(&self, _pool: &RedisConnectionPool) -> String { + self.0.clone() + } +} + +impl<T: AsRef<str>> From<T> for RedisKey { + fn from(value: T) -> Self { + let value = value.as_ref(); + + Self(value.to_string()) + } +} diff --git a/crates/router/src/core/api_locking.rs b/crates/router/src/core/api_locking.rs index 9b45fecee4e..7043a090b2b 100644 --- a/crates/router/src/core/api_locking.rs +++ b/crates/router/src/core/api_locking.rs @@ -79,7 +79,7 @@ impl LockAction { for _retry in 0..lock_retries { let redis_lock_result = redis_conn .set_key_if_not_exists_with_expiry( - redis_locking_key.as_str(), + &redis_locking_key.as_str().into(), state.get_request_id(), Some(i64::from(redis_lock_expiry_seconds)), ) @@ -134,12 +134,15 @@ impl LockAction { let redis_locking_key = input.get_redis_locking_key(merchant_id); match redis_conn - .get_key::<Option<String>>(&redis_locking_key) + .get_key::<Option<String>>(&redis_locking_key.as_str().into()) .await { Ok(val) => { if val == state.get_request_id() { - match redis_conn.delete_key(redis_locking_key.as_str()).await { + match redis_conn + .delete_key(&redis_locking_key.as_str().into()) + .await + { Ok(redis::types::DelReply::KeyDeleted) => { logger::info!("Lock freed for locking input {:?}", input); tracing::Span::current() diff --git a/crates/router/src/core/health_check.rs b/crates/router/src/core/health_check.rs index 31e8cc75f5b..2e5c2956013 100644 --- a/crates/router/src/core/health_check.rs +++ b/crates/router/src/core/health_check.rs @@ -52,21 +52,21 @@ impl HealthCheckInterface for app::SessionState { .change_context(errors::HealthCheckRedisError::RedisConnectionError)?; redis_conn - .serialize_and_set_key_with_expiry("test_key", "test_value", 30) + .serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30) .await .change_context(errors::HealthCheckRedisError::SetFailed)?; logger::debug!("Redis set_key was successful"); redis_conn - .get_key::<()>("test_key") + .get_key::<()>(&"test_key".into()) .await .change_context(errors::HealthCheckRedisError::GetFailed)?; logger::debug!("Redis get_key was successful"); redis_conn - .delete_key("test_key") + .delete_key(&"test_key".into()) .await .change_context(errors::HealthCheckRedisError::DeleteFailed)?; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5bd2c07073e..7be645a81c7 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3716,7 +3716,7 @@ pub async fn list_payment_methods( let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry; if let Some(rc) = redis_conn { - rc.serialize_and_set_key_with_expiry(pm_auth_key.as_str(), val, redis_expiry) + rc.serialize_and_set_key_with_expiry(&pm_auth_key.as_str().into(), val, redis_expiry) .await .attach_printable("Failed to store pm auth data in redis") .unwrap_or_else(|error| { @@ -5030,7 +5030,7 @@ pub async fn list_customer_payment_method( ); redis_conn - .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time) + .set_key_with_expiry(&key.into(), pm_metadata.1, intent_fulfillment_time) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 65ef16cb449..300f1e3054f 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1043,7 +1043,7 @@ pub async fn create_tokenize( redis_conn .set_key_if_not_exists_with_expiry( - redis_key.as_str(), + &redis_key.as_str().into(), bytes::Bytes::from(encrypted_payload), Some(i64::from(consts::LOCKER_REDIS_EXPIRY_SECONDS)), ) @@ -1089,7 +1089,9 @@ pub async fn get_tokenized_data( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; - let response = redis_conn.get_key::<bytes::Bytes>(redis_key.as_str()).await; + let response = redis_conn + .get_key::<bytes::Bytes>(&redis_key.as_str().into()) + .await; match response { Ok(resp) => { @@ -1150,7 +1152,7 @@ pub async fn delete_tokenized_data( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; - let response = redis_conn.delete_key(redis_key.as_str()).await; + let response = redis_conn.delete_key(&redis_key.as_str().into()).await; match response { Ok(redis_interface::DelReply::KeyDeleted) => Ok(()), diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index ceeb384ed21..4766dcda6a1 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -2363,7 +2363,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { .attach_printable("Failed to get redis connection")?; redis_conn .set_key_with_expiry( - &poll_id, + &poll_id.into(), api_models::poll::PollStatus::Pending.to_string(), crate::consts::POLL_ID_TTL, ) @@ -4118,7 +4118,7 @@ async fn decide_payment_method_tokenize_action( ); let connector_token_option = redis_conn - .get_key::<Option<String>>(&key) + .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")?; @@ -6705,7 +6705,7 @@ pub async fn get_extended_card_info( let key = helpers::get_redis_key_for_extended_card_info(&merchant_id, &payment_id); let payload = redis_conn - .get_key::<String>(&key) + .get_key::<String>(&key.into()) .await .change_context(errors::ApiErrorResponse::ExtendedCardInfoNotFound)?; diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 93769c71e6c..797aadbbc05 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2289,7 +2289,7 @@ pub async fn retrieve_payment_token_data( ); let token_data_string = redis_conn - .get_key::<Option<String>>(&key) + .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? @@ -3781,7 +3781,7 @@ pub async fn insert_merchant_connector_creds_to_config( redis .serialize_and_set_key_with_expiry( - key.as_str(), + &key.as_str().into(), &encoded_data.peek(), consts::CONNECTOR_CREDS_TOKEN_TTL, ) @@ -3897,7 +3897,7 @@ pub async fn get_merchant_connector_account( .attach_printable("Failed to get redis connection") .async_and_then(|redis| async move { redis - .get_and_deserialize_key(key.clone().as_str(), "String") + .get_and_deserialize_key(&key.as_str().into(), "String") .await .change_context( errors::ApiErrorResponse::MerchantConnectorAccountNotFound { @@ -5843,7 +5843,7 @@ pub async fn get_payment_method_details_from_payment_token( .get_required_value("payment_method")?, ); let token_data_string = redis_conn - .get_key::<Option<String>>(&key) + .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index a87fab9b17a..da68ee27fd9 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1244,7 +1244,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for redis_conn .set_key_with_expiry( - &key, + &key.into(), encrypted_payload.clone(), (*merchant_config.ttl_in_secs).into(), ) diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs index 80813ac29b5..13f4de956ec 100644 --- a/crates/router/src/core/payments/types.rs +++ b/crates/router/src/core/payments/types.rs @@ -325,7 +325,11 @@ impl SurchargeMetadata { .get_order_fulfillment_time() .unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME); redis_conn - .set_hash_fields(&redis_key, value_list, Some(intent_fulfillment_time)) + .set_hash_fields( + &redis_key.as_str().into(), + value_list, + Some(intent_fulfillment_time), + ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to write to redis")?; @@ -347,7 +351,11 @@ impl SurchargeMetadata { let redis_key = Self::get_surcharge_metadata_redis_key(payment_attempt_id); let value_key = Self::get_surcharge_details_redis_hashset_key(&surcharge_key); let result = redis_conn - .get_hash_field_and_deserialize(&redis_key, &value_key, "SurchargeDetails") + .get_hash_field_and_deserialize( + &redis_key.as_str().into(), + &value_key, + "SurchargeDetails", + ) .await; logger::debug!( "Surcharge result fetched from redis with key = {} and {}", diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 060fc64f891..5ebdea0de67 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -79,7 +79,7 @@ pub async fn make_payout_method_data( .attach_printable("Failed to get redis connection")?; let hyperswitch_token = redis_conn - .get_key::<Option<String>>(&key) + .get_key::<Option<String>>(&key.into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to fetch the token from redis")? diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs index afba73e839c..0577b532cf0 100644 --- a/crates/router/src/core/pm_auth.rs +++ b/crates/router/src/core/pm_auth.rs @@ -63,7 +63,7 @@ pub async fn create_link_token( let pm_auth_key = payload.payment_id.get_pm_auth_key(); redis_conn - .exists::<Vec<u8>>(&pm_auth_key) + .exists::<Vec<u8>>(&pm_auth_key.as_str().into()) .await .change_context(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), @@ -77,7 +77,7 @@ pub async fn create_link_token( let pm_auth_configs = redis_conn .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( - pm_auth_key.as_str(), + &pm_auth_key.as_str().into(), "Vec<PaymentMethodAuthConnectorChoice>", ) .await @@ -772,7 +772,7 @@ async fn get_selected_config_from_redis( let pm_auth_key = payload.payment_id.get_pm_auth_key(); redis_conn - .exists::<Vec<u8>>(&pm_auth_key) + .exists::<Vec<u8>>(&pm_auth_key.as_str().into()) .await .change_context(ApiErrorResponse::InvalidRequestData { message: "Incorrect payment_id provided in request".to_string(), @@ -786,7 +786,7 @@ async fn get_selected_config_from_redis( let pm_auth_configs = redis_conn .get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>( - pm_auth_key.as_str(), + &pm_auth_key.as_str().into(), "Vec<PaymentMethodAuthConnectorChoice>", ) .await diff --git a/crates/router/src/core/poll.rs b/crates/router/src/core/poll.rs index f0a464be287..dd468a26a70 100644 --- a/crates/router/src/core/poll.rs +++ b/crates/router/src/core/poll.rs @@ -23,7 +23,7 @@ pub async fn retrieve_poll_status( // prepend 'poll_{merchant_id}_' to restrict access to only fetching Poll IDs, as this is a freely passed string in the request let poll_id = super::utils::get_poll_id(merchant_account.get_id(), request_poll_id.clone()); let redis_value = redis_conn - .get_key::<Option<String>>(poll_id.as_str()) + .get_key::<Option<String>>(&poll_id.as_str().into()) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable_lazy(|| { diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 4c1a5aeb780..71130f247ad 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -1357,7 +1357,7 @@ async fn external_authentication_incoming_webhook_flow( .attach_printable("Failed to get redis connection")?; redis_conn .set_key_without_modifying_ttl( - &poll_id, + &poll_id.into(), api_models::poll::PollStatus::Completed.to_string(), ) .await diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index a77995e4e58..b3e33cd777f 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -103,7 +103,10 @@ mod storage { .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( - &[(&secret_key, &created_ek), (&id_key, &created_ek)], + &[ + (&secret_key.as_str().into(), &created_ek), + (&id_key.as_str().into(), &created_ek), + ], "ephkey", None, ) @@ -120,12 +123,12 @@ mod storage { let expire_at = expires.assume_utc().unix_timestamp(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .set_expire_at(&secret_key, expire_at) + .set_expire_at(&secret_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .set_expire_at(&id_key, expire_at) + .set_expire_at(&id_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; Ok(created_ek) @@ -161,8 +164,8 @@ mod storage { .map_err(Into::<errors::StorageError>::into)? .serialize_and_set_multiple_hash_field_if_not_exist( &[ - (&secret_key, &created_ephemeral_key), - (&id_key, &created_ephemeral_key), + (&secret_key.as_str().into(), &created_ephemeral_key), + (&id_key.as_str().into(), &created_ephemeral_key), ], "ephkey", None, @@ -180,12 +183,12 @@ mod storage { let expire_at = expires.assume_utc().unix_timestamp(); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .set_expire_at(&secret_key, expire_at) + .set_expire_at(&secret_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .set_expire_at(&id_key, expire_at) + .set_expire_at(&id_key.into(), expire_at) .await .change_context(errors::StorageError::KVError)?; Ok(created_ephemeral_key) @@ -203,7 +206,7 @@ mod storage { let key = format!("epkey_{key}"); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .get_hash_field_and_deserialize(&key, "ephkey", "EphemeralKey") + .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKey") .await .change_context(errors::StorageError::KVError) } @@ -217,7 +220,7 @@ mod storage { let key = format!("epkey_{key}"); self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .get_hash_field_and_deserialize(&key, "ephkey", "EphemeralKeyType") + .get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKeyType") .await .change_context(errors::StorageError::KVError) } @@ -231,13 +234,13 @@ mod storage { self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .delete_key(&format!("epkey_{}", &ek.id)) + .delete_key(&format!("epkey_{}", &ek.id).into()) .await .change_context(errors::StorageError::KVError)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .delete_key(&format!("epkey_{}", &ek.secret)) + .delete_key(&format!("epkey_{}", &ek.secret).into()) .await .change_context(errors::StorageError::KVError)?; Ok(ek) @@ -254,7 +257,7 @@ mod storage { self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .delete_key(&redis_id_key) + .delete_key(&redis_id_key.as_str().into()) .await .map_err(|err| match err.current_context() { RedisError::NotFound => { @@ -265,7 +268,7 @@ mod storage { self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .delete_key(&secret_key) + .delete_key(&secret_key.as_str().into()) .await .map_err(|err| match err.current_context() { RedisError::NotFound => { diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index ba654b4fce3..34b23a833ac 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -59,7 +59,7 @@ impl ConnectorAccessToken for Store { let maybe_token = self .get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .get_key::<Option<Vec<u8>>>(&key) + .get_key::<Option<Vec<u8>>>(&key.into()) .await .change_context(errors::StorageError::KVError) .attach_printable("DB error when getting access token")?; @@ -88,7 +88,7 @@ impl ConnectorAccessToken for Store { .change_context(errors::StorageError::SerializationFailed)?; self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .set_key_with_expiry(&key, serialized_access_token, access_token.expires) + .set_key_with_expiry(&key.into(), serialized_access_token, access_token.expires) .await .change_context(errors::StorageError::KVError) } diff --git a/crates/router/src/routes/dummy_connector/core.rs b/crates/router/src/routes/dummy_connector/core.rs index aadd7dcaa72..cafb6b58bca 100644 --- a/crates/router/src/routes/dummy_connector/core.rs +++ b/crates/router/src/routes/dummy_connector/core.rs @@ -109,7 +109,7 @@ pub async fn payment_complete( .change_context(errors::DummyConnectorErrors::InternalServerError) .attach_printable("Failed to get redis connection")?; - let _ = redis_conn.delete_key(req.attempt_id.as_str()).await; + let _ = redis_conn.delete_key(&req.attempt_id.as_str().into()).await; if let Ok(payment_data) = payment_data { let updated_payment_data = types::DummyConnectorPaymentData { @@ -220,7 +220,7 @@ pub async fn refund_data( .attach_printable("Failed to get redis connection")?; let refund_data = redis_conn .get_and_deserialize_key::<types::DummyConnectorRefundResponse>( - refund_id.as_str(), + &refund_id.as_str().into(), "DummyConnectorRefundResponse", ) .await diff --git a/crates/router/src/routes/dummy_connector/utils.rs b/crates/router/src/routes/dummy_connector/utils.rs index 6211c3abf80..edbe6d9dddc 100644 --- a/crates/router/src/routes/dummy_connector/utils.rs +++ b/crates/router/src/routes/dummy_connector/utils.rs @@ -38,7 +38,7 @@ pub async fn store_data_in_redis( .attach_printable("Failed to get redis connection")?; redis_conn - .serialize_and_set_key_with_expiry(&key, data, ttl) + .serialize_and_set_key_with_expiry(&key.into(), data, ttl) .await .change_context(errors::DummyConnectorErrors::PaymentStoringError) .attach_printable("Failed to add data in redis")?; @@ -57,7 +57,7 @@ pub async fn get_payment_data_from_payment_id( redis_conn .get_and_deserialize_key::<types::DummyConnectorPaymentData>( - payment_id.as_str(), + &payment_id.as_str().into(), "types DummyConnectorPaymentData", ) .await @@ -75,12 +75,12 @@ pub async fn get_payment_data_by_attempt_id( .attach_printable("Failed to get redis connection")?; redis_conn - .get_and_deserialize_key::<String>(attempt_id.as_str(), "String") + .get_and_deserialize_key::<String>(&attempt_id.as_str().into(), "String") .await .async_and_then(|payment_id| async move { redis_conn .get_and_deserialize_key::<types::DummyConnectorPaymentData>( - payment_id.as_str(), + &payment_id.as_str().into(), "DummyConnectorPaymentData", ) .await diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index c8e6303562c..5f9fe729eeb 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -980,7 +980,11 @@ impl ParentPaymentMethodToken { .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; redis_conn - .serialize_and_set_key_with_expiry(&self.key_for_token, token, fulfillment_time) + .serialize_and_set_key_with_expiry( + &self.key_for_token.as_str().into(), + token, + fulfillment_time, + ) .await .change_context(errors::StorageError::KVError) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1004,7 +1008,10 @@ impl ParentPaymentMethodToken { .get_redis_conn() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get redis connection")?; - match redis_conn.delete_key(&self.key_for_token).await { + match redis_conn + .delete_key(&self.key_for_token.as_str().into()) + .await + { Ok(_) => Ok(()), Err(err) => { { diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index da5f87a450e..6be6cc467bf 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -30,7 +30,7 @@ pub async fn insert_user_in_blacklist(state: &SessionState, user_id: &str) -> Us let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( - user_blacklist_key.as_str(), + &user_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) @@ -46,7 +46,7 @@ pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> Us let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; redis_conn .set_key_with_expiry( - role_blacklist_key.as_str(), + &role_blacklist_key.as_str().into(), date_time::now_unix_timestamp(), expiry, ) @@ -61,7 +61,7 @@ pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> Us async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> { let redis_conn = get_redis_connection(state)?; redis_conn - .delete_key(authz::get_cache_key_from_role_id(role_id).as_str()) + .delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into()) .await .map(|_| ()) .change_context(ApiErrorResponse::InternalServerError) @@ -76,7 +76,7 @@ pub async fn check_user_in_blacklist<A: SessionStateInfo>( let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; redis_conn - .get_key::<Option<i64>>(token.as_str()) + .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) @@ -91,7 +91,7 @@ pub async fn check_role_in_blacklist<A: SessionStateInfo>( let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?; let redis_conn = get_redis_connection(state)?; redis_conn - .get_key::<Option<i64>>(token.as_str()) + .get_key::<Option<i64>>(&token.as_str().into()) .await .change_context(ApiErrorResponse::InternalServerError) .map(|timestamp| timestamp > Some(token_issued_at)) @@ -104,7 +104,7 @@ pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) let expiry = expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?; redis_conn - .set_key_with_expiry(blacklist_key.as_str(), true, expiry) + .set_key_with_expiry(&blacklist_key.as_str().into(), true, expiry) .await .change_context(UserErrors::InternalServerError) } @@ -114,7 +114,7 @@ pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) - let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?; let blacklist_key = format!("{}{token}", EMAIL_TOKEN_BLACKLIST_PREFIX); let key_exists = redis_conn - .exists::<()>(blacklist_key.as_str()) + .exists::<()>(&blacklist_key.as_str().into()) .await .change_context(UserErrors::InternalServerError)?; diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index db3483f8164..0e66654b7b9 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -64,7 +64,7 @@ where let redis_conn = get_redis_connection(state)?; redis_conn - .get_and_deserialize_key(&get_cache_key_from_role_id(role_id), "RoleInfo") + .get_and_deserialize_key(&get_cache_key_from_role_id(role_id).into(), "RoleInfo") .await .change_context(ApiErrorResponse::InternalServerError) } @@ -103,7 +103,11 @@ where let redis_conn = get_redis_connection(state)?; redis_conn - .serialize_and_set_key_with_expiry(&get_cache_key_from_role_id(role_id), role_info, expiry) + .serialize_and_set_key_with_expiry( + &get_cache_key_from_role_id(role_id).into(), + role_info, + expiry, + ) .await .change_context(ApiErrorResponse::InternalServerError) } diff --git a/crates/router/src/services/openidconnect.rs b/crates/router/src/services/openidconnect.rs index 0c0f86431a1..44f95b42607 100644 --- a/crates/router/src/services/openidconnect.rs +++ b/crates/router/src/services/openidconnect.rs @@ -35,7 +35,7 @@ pub async fn get_authorization_url( // Save csrf & nonce as key value respectively let key = get_oidc_redis_key(csrf_token.secret()); get_redis_connection(&state)? - .set_key_with_expiry(&key, nonce.secret(), consts::user::REDIS_SSO_TTL) + .set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to save csrf-nonce in redis")?; @@ -142,7 +142,7 @@ async fn get_nonce_from_redis( let redirect_state = redirect_state.clone().expose(); let key = get_oidc_redis_key(&redirect_state); redis_connection - .get_key::<Option<String>>(&key) + .get_key::<Option<String>>(&key.into()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Error Fetching CSRF from redis")? diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 9ab2780da73..08077442e73 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -465,7 +465,7 @@ async fn release_redis_lock( .store .get_redis_conn() .change_context(ForexCacheError::RedisConnectionError)? - .delete_key(REDIX_FOREX_CACHE_KEY) + .delete_key(&REDIX_FOREX_CACHE_KEY.into()) .await .change_context(ForexCacheError::RedisLockReleaseFailed) .attach_printable("Unable to release redis lock") @@ -478,7 +478,7 @@ async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCac .get_redis_conn() .change_context(ForexCacheError::RedisConnectionError)? .set_key_if_not_exists_with_expiry( - REDIX_FOREX_CACHE_KEY, + &REDIX_FOREX_CACHE_KEY.into(), "", Some( i64::try_from( @@ -502,7 +502,7 @@ async fn save_forex_to_redis( .store .get_redis_conn() .change_context(ForexCacheError::RedisConnectionError)? - .serialize_and_set_key(REDIX_FOREX_CACHE_DATA, forex_exchange_cache_entry) + .serialize_and_set_key(&REDIX_FOREX_CACHE_DATA.into(), forex_exchange_cache_entry) .await .change_context(ForexCacheError::RedisWriteError) .attach_printable("Unable to save forex data to redis") @@ -515,7 +515,7 @@ async fn retrieve_forex_from_redis( .store .get_redis_conn() .change_context(ForexCacheError::RedisConnectionError)? - .get_and_deserialize_key(REDIX_FOREX_CACHE_DATA, "FxExchangeRatesCache") + .get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache") .await .change_context(ForexCacheError::EntryNotFound) .attach_printable("Forex entry not found in redis") diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index ef06531b421..721b0052bda 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -246,7 +246,7 @@ pub async fn set_sso_id_in_redis( let connection = get_redis_connection(state)?; let key = get_oidc_key(&oidc_state.expose()); connection - .set_key_with_expiry(&key, sso_id, REDIS_SSO_TTL) + .set_key_with_expiry(&key.into(), sso_id, REDIS_SSO_TTL) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to set sso id in redis") @@ -259,7 +259,7 @@ pub async fn get_sso_id_from_redis( let connection = get_redis_connection(state)?; let key = get_oidc_key(&oidc_state.expose()); connection - .get_key::<Option<String>>(&key) + .get_key::<Option<String>>(&key.into()) .await .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get sso id from redis")? diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs index 73d692a00e0..b4ced70d735 100644 --- a/crates/router/src/utils/user/two_factor_auth.rs +++ b/crates/router/src/utils/user/two_factor_auth.rs @@ -36,7 +36,7 @@ pub async fn check_totp_in_redis(state: &SessionState, user_id: &str) -> UserRes let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn - .exists::<()>(&key) + .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) } @@ -45,7 +45,7 @@ pub async fn check_recovery_code_in_redis(state: &SessionState, user_id: &str) - let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn - .exists::<()>(&key) + .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) } @@ -55,7 +55,7 @@ pub async fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserRe let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .set_key_with_expiry( - key.as_str(), + &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) @@ -71,7 +71,7 @@ pub async fn insert_totp_secret_in_redis( let redis_conn = super::get_redis_connection(state)?; redis_conn .set_key_with_expiry( - &get_totp_secret_key(user_id), + &get_totp_secret_key(user_id).into(), secret.peek(), consts::user::REDIS_TOTP_SECRET_TTL_IN_SECS, ) @@ -85,7 +85,7 @@ pub async fn get_totp_secret_from_redis( ) -> UserResult<Option<masking::Secret<String>>> { let redis_conn = super::get_redis_connection(state)?; redis_conn - .get_key::<Option<String>>(&get_totp_secret_key(user_id)) + .get_key::<Option<String>>(&get_totp_secret_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|secret| secret.map(Into::into)) @@ -94,7 +94,7 @@ pub async fn get_totp_secret_from_redis( pub async fn delete_totp_secret_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn - .delete_key(&get_totp_secret_key(user_id)) + .delete_key(&get_totp_secret_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) @@ -109,7 +109,7 @@ pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str) let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .set_key_with_expiry( - key.as_str(), + &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) @@ -121,7 +121,7 @@ pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> User let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn - .delete_key(&key) + .delete_key(&key.into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) @@ -134,7 +134,7 @@ pub async fn delete_recovery_code_from_redis( let redis_conn = super::get_redis_connection(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn - .delete_key(&key) + .delete_key(&key.into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) @@ -159,7 +159,7 @@ pub async fn insert_totp_attempts_in_redis( let redis_conn = super::get_redis_connection(state)?; redis_conn .set_key_with_expiry( - &get_totp_attempts_key(user_id), + &get_totp_attempts_key(user_id).into(), user_totp_attempts, consts::user::REDIS_TOTP_ATTEMPTS_TTL_IN_SECS, ) @@ -169,7 +169,7 @@ pub async fn insert_totp_attempts_in_redis( pub async fn get_totp_attempts_from_redis(state: &SessionState, user_id: &str) -> UserResult<u8> { let redis_conn = super::get_redis_connection(state)?; redis_conn - .get_key::<Option<u8>>(&get_totp_attempts_key(user_id)) + .get_key::<Option<u8>>(&get_totp_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|v| v.unwrap_or(0)) @@ -183,7 +183,7 @@ pub async fn insert_recovery_code_attempts_in_redis( let redis_conn = super::get_redis_connection(state)?; redis_conn .set_key_with_expiry( - &get_recovery_code_attempts_key(user_id), + &get_recovery_code_attempts_key(user_id).into(), user_recovery_code_attempts, consts::user::REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS, ) @@ -197,7 +197,7 @@ pub async fn get_recovery_code_attempts_from_redis( ) -> UserResult<u8> { let redis_conn = super::get_redis_connection(state)?; redis_conn - .get_key::<Option<u8>>(&get_recovery_code_attempts_key(user_id)) + .get_key::<Option<u8>>(&get_recovery_code_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|v| v.unwrap_or(0)) @@ -209,7 +209,7 @@ pub async fn delete_totp_attempts_from_redis( ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn - .delete_key(&get_totp_attempts_key(user_id)) + .delete_key(&get_totp_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) @@ -221,7 +221,7 @@ pub async fn delete_recovery_code_attempts_from_redis( ) -> UserResult<()> { let redis_conn = super::get_redis_connection(state)?; redis_conn - .delete_key(&get_recovery_code_attempts_key(user_id)) + .delete_key(&get_recovery_code_attempts_key(user_id).into()) .await .change_context(UserErrors::InternalServerError) .map(|_| ()) diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs index a1f85534b6b..7e1fab4bc5a 100644 --- a/crates/router/tests/cache.rs +++ b/crates/router/tests/cache.rs @@ -30,7 +30,7 @@ async fn invalidate_existing_cache_success() { .store .get_redis_conn() .unwrap() - .set_key(&cache_key.clone(), cache_key_value.clone()) + .set_key(&cache_key.clone().into(), cache_key_value.clone()) .await; let api_key = ("api-key", "test_admin"); diff --git a/crates/scheduler/src/db/queue.rs b/crates/scheduler/src/db/queue.rs index 748e1f489c2..80f2b8b4c92 100644 --- a/crates/scheduler/src/db/queue.rs +++ b/crates/scheduler/src/db/queue.rs @@ -70,7 +70,7 @@ impl QueueInterface for Store { id: &RedisEntryId, ) -> CustomResult<(), RedisError> { self.get_redis_conn()? - .consumer_group_create(stream, group, id) + .consumer_group_create(&stream.into(), group, id) .await } @@ -83,16 +83,16 @@ impl QueueInterface for Store { ) -> CustomResult<bool, RedisError> { let conn = self.get_redis_conn()?.clone(); let is_lock_acquired = conn - .set_key_if_not_exists_with_expiry(lock_key, lock_val, None) + .set_key_if_not_exists_with_expiry(&lock_key.into(), lock_val, None) .await; Ok(match is_lock_acquired { - Ok(SetnxReply::KeySet) => match conn.set_expiry(lock_key, ttl).await { + Ok(SetnxReply::KeySet) => match conn.set_expiry(&lock_key.into(), ttl).await { Ok(()) => true, #[allow(unused_must_use)] Err(error) => { logger::error!(?error); - conn.delete_key(lock_key).await; + conn.delete_key(&lock_key.into()).await; false } }, @@ -108,7 +108,7 @@ impl QueueInterface for Store { } async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { - let is_lock_released = self.get_redis_conn()?.delete_key(lock_key).await; + let is_lock_released = self.get_redis_conn()?.delete_key(&lock_key.into()).await; Ok(match is_lock_released { Ok(_del_reply) => true, Err(error) => { @@ -125,12 +125,12 @@ impl QueueInterface for Store { fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { self.get_redis_conn()? - .stream_append_entry(stream, entry_id, fields) + .stream_append_entry(&stream.into(), entry_id, fields) .await } async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> { - self.get_redis_conn()?.get_key::<Vec<u8>>(key).await + self.get_redis_conn()?.get_key::<Vec<u8>>(&key.into()).await } } diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 89328479537..51938e6c14d 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -231,13 +231,13 @@ pub async fn get_batches( let batches = batches.into_iter().flatten().collect::<Vec<_>>(); let entry_ids = entry_ids.into_iter().flatten().collect::<Vec<_>>(); - conn.stream_acknowledge_entries(stream_name, group_name, entry_ids.clone()) + conn.stream_acknowledge_entries(&stream_name.into(), group_name, entry_ids.clone()) .await .map_err(|error| { logger::error!(?error, "Error acknowledging batch in stream"); error.change_context(errors::ProcessTrackerError::BatchUpdateFailed) })?; - conn.stream_delete_entries(stream_name, entry_ids.clone()) + conn.stream_delete_entries(&stream_name.into(), entry_ids.clone()) .await .map_err(|error| { logger::error!(?error, "Error deleting batch from stream"); diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs index e0722ef52ea..8a329010447 100644 --- a/crates/storage_impl/src/lib.rs +++ b/crates/storage_impl/src/lib.rs @@ -256,7 +256,7 @@ impl<T: DatabaseStore> KVRouterStore<T> { .cache_store .redis_conn .stream_append_entry( - &stream_name, + &stream_name.into(), &redis_interface::RedisEntryId::AutoGeneratedID, redis_entry .to_field_value_pairs(request_id, global_id) @@ -309,7 +309,7 @@ pub trait UniqueConstraints { let constraints = self.unique_constraints(); let sadd_result = redis_conn .sadd( - &format!("unique_constraint:{}", self.table_name()), + &format!("unique_constraint:{}", self.table_name()).into(), constraints, ) .await?; diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 323d3d6df25..8302b5bf933 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -299,11 +299,13 @@ where { let type_name = std::any::type_name::<T>(); let key = key.as_ref(); - let redis_val = redis.get_and_deserialize_key::<T>(key, type_name).await; + let redis_val = redis + .get_and_deserialize_key::<T>(&key.into(), type_name) + .await; let get_data_set_redis = || async { let data = fun().await?; redis - .serialize_and_set_key(key, &data) + .serialize_and_set_key(&key.into(), &data) .await .change_context(StorageError::KVError)?; Ok::<_, Report<StorageError>>(data) @@ -380,7 +382,7 @@ pub async fn redact_from_redis_and_publish< let redis_keys_to_be_deleted = keys .clone() .into_iter() - .map(|val| val.get_key_without_prefix().to_owned()) + .map(|val| val.get_key_without_prefix().to_owned().into()) .collect::<Vec<_>>(); let del_replies = redis_conn diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 17974a3b9bc..6e1340abca5 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -181,7 +181,7 @@ where logger::debug!(kv_operation= %operation, value = ?value); redis_conn - .set_hash_fields(&key, value, Some(ttl.into())) + .set_hash_fields(&key.into(), value, Some(ttl.into())) .await?; store @@ -193,14 +193,14 @@ where KvOperation::HGet(field) => { let result = redis_conn - .get_hash_field_and_deserialize(&key, field, type_name) + .get_hash_field_and_deserialize(&key.into(), field, type_name) .await?; Ok(KvResult::HGet(result)) } KvOperation::Scan(pattern) => { let result: Vec<T> = redis_conn - .hscan_and_deserialize(&key, pattern, None) + .hscan_and_deserialize(&key.into(), pattern, None) .await .and_then(|result| { if result.is_empty() { @@ -218,7 +218,7 @@ where value.check_for_constraints(&redis_conn).await?; let result = redis_conn - .serialize_and_set_hash_field_if_not_exist(&key, field, value, Some(ttl)) + .serialize_and_set_hash_field_if_not_exist(&key.into(), field, value, Some(ttl)) .await?; if matches!(result, redis_interface::HsetnxReply::KeySet) { @@ -235,7 +235,7 @@ where logger::debug!(kv_operation= %operation, value = ?value); let result = redis_conn - .serialize_and_set_key_if_not_exist(&key, value, Some(ttl.into())) + .serialize_and_set_key_if_not_exist(&key.into(), value, Some(ttl.into())) .await?; value.check_for_constraints(&redis_conn).await?; @@ -251,7 +251,9 @@ where } KvOperation::Get => { - let result = redis_conn.get_and_deserialize_key(&key, type_name).await?; + let result = redis_conn + .get_and_deserialize_key(&key.into(), type_name) + .await?; Ok(KvResult::Get(result)) } }
2025-01-16T10:01:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> - Add a fallback for Redis gets with prefix - Add a Domain type for Redis for the correctness of adding a prefix ## 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 keep the tenant data isolated from each other, We are using a prefix for Redis keys i.e A key which would be saved as card123 without multitenancy would be saved as public:card123 with Multitenancy. If the user makes a payment on the older pod where MultiTenancy is disabled and client_secret is saved without a prefix, Now if the confirm calls goes to the pod where Multitenancy is enabled the Payment would fail with Unauthorized. This is just one of the instances where the payments would fail. ## 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 HIGHER ENVIRONMENTS ** ## 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
3fdc41e6c946609461db6b5459e10e6351694d4c
juspay/hyperswitch
juspay__hyperswitch-7014
Bug: [REFACTOR] modify dynamic fields path This PR modifies dynamic fields path of Adyen and Stripe for Klarna. Also klarnaCheckout is renamed to klarnaRedirect.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 892931256bc..25f0be8594a 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -12387,17 +12387,6 @@ } } }, - { - "type": "object", - "required": [ - "klarna_checkout" - ], - "properties": { - "klarna_checkout": { - "type": "object" - } - } - }, { "type": "object", "required": [ diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b6152cc9787..dece84ee8f0 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1876,7 +1876,6 @@ pub enum PayLaterData { /// The token for the sdk workflow token: String, }, - KlarnaCheckout {}, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option @@ -1934,7 +1933,6 @@ impl GetAddressFromPaymentMethodData for PayLaterData { | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } - | Self::KlarnaCheckout {} | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } @@ -2396,7 +2394,6 @@ impl GetPaymentMethodType for PayLaterData { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, - Self::KlarnaCheckout {} => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs index 160e938ead3..ed3319816d5 100644 --- a/crates/connector_configs/src/transformer.rs +++ b/crates/connector_configs/src/transformer.rs @@ -45,10 +45,11 @@ impl DashboardRequestPayload { Some(api_models::enums::PaymentExperience::RedirectToUrl) } (Connector::Paypal, Paypal) => payment_experience, + (Connector::Klarna, Klarna) => payment_experience, (Connector::Zen, GooglePay) | (Connector::Zen, ApplePay) => { Some(api_models::enums::PaymentExperience::RedirectToUrl) } - (Connector::Braintree, Paypal) | (Connector::Klarna, Klarna) => { + (Connector::Braintree, Paypal) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } (Connector::Globepay, AliPay) diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 2ab348d5dd5..cb9466cef7f 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -1771,6 +1771,10 @@ key1="Client Secret" [klarna] [[klarna.pay_later]] payment_method_type = "klarna" + payment_experience = "invoke_sdk_client" +[[klarna.pay_later]] + payment_method_type = "klarna" + payment_experience = "redirect_to_url" [klarna.connector_auth.BodyKey] key1="Klarna Merchant Username" api_key="Klarna Merchant ID Password" diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index 35f2f14c748..fe927ea6f77 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -1482,6 +1482,10 @@ api_key="Access Token" [klarna] [[klarna.pay_later]] payment_method_type = "klarna" + payment_experience = "invoke_sdk_client" +[[klarna.pay_later]] + payment_method_type = "klarna" + payment_experience = "redirect_to_url" [klarna.connector_auth.BodyKey] key1="Klarna Merchant Username" api_key="Klarna Merchant ID Password" diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index ed903812219..1449f0f4398 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -1718,6 +1718,10 @@ api_key="Access Token" [klarna] [[klarna.pay_later]] payment_method_type = "klarna" + payment_experience = "invoke_sdk_client" +[[klarna.pay_later]] + payment_method_type = "klarna" + payment_experience = "redirect_to_url" [klarna.connector_auth.BodyKey] key1="Klarna Merchant Username" api_key="Klarna Merchant ID Password" diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index a60e8bdc79e..479abf13b13 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -746,7 +746,6 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> email: Some(match paylater { PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?, PayLaterData::KlarnaSdk { token: _ } - | PayLaterData::KlarnaCheckout {} | PayLaterData::AffirmRedirect {} | PayLaterData::AfterpayClearpayRedirect {} | PayLaterData::PayBrightRedirect {} diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index 5abc93b3f88..08ca9a54fa4 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -85,7 +85,6 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ PayLaterData::AfterpayClearpayRedirect { .. } | PayLaterData::KlarnaRedirect { .. } | PayLaterData::KlarnaSdk { .. } - | PayLaterData::KlarnaCheckout {} | PayLaterData::AffirmRedirect { .. } | PayLaterData::PayBrightRedirect { .. } | PayLaterData::WalleyRedirect { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index cc6795f157a..8652b60635b 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -751,7 +751,6 @@ impl TryFrom<&PayLaterData> for ZenPaymentsRequest { match value { PayLaterData::KlarnaRedirect { .. } | PayLaterData::KlarnaSdk { .. } - | PayLaterData::KlarnaCheckout {} | PayLaterData::AffirmRedirect {} | PayLaterData::AfterpayClearpayRedirect { .. } | PayLaterData::PayBrightRedirect {} diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index e99777ad27e..30ad1af721e 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -2293,7 +2293,6 @@ pub enum PaymentMethodDataType { SwishQr, KlarnaRedirect, KlarnaSdk, - KlarnaCheckout, AffirmRedirect, AfterpayClearpayRedirect, PayBrightRedirect, @@ -2418,7 +2417,6 @@ impl From<PaymentMethodData> for PaymentMethodDataType { PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, payment_method_data::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, - payment_method_data::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout, payment_method_data::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, payment_method_data::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 8c19a20ef32..169719cb5da 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -155,7 +155,6 @@ pub enum CardRedirectData { pub enum PayLaterData { KlarnaRedirect {}, KlarnaSdk { token: String }, - KlarnaCheckout {}, AffirmRedirect {}, AfterpayClearpayRedirect {}, PayBrightRedirect {}, @@ -898,7 +897,6 @@ impl From<api_models::payments::PayLaterData> for PayLaterData { match value { api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {}, api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token }, - api_models::payments::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout {}, api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {}, api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect {} @@ -1552,7 +1550,6 @@ impl GetPaymentMethodType for PayLaterData { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, - Self::KlarnaCheckout {} => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index d957109bcef..14b64aa7e88 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -10526,9 +10526,9 @@ impl Default for settings::RequiredFields { RequiredFieldFinal { mandate : HashMap::new(), non_mandate: HashMap::from([ - ( "payment_method_data.pay_later.klarna.billing_country".to_string(), + ( "billing.address.country".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.pay_later.klarna.billing_country".to_string(), + required_field: "payment_method_data.billing.address.country".to_string(), display_name: "billing_country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ @@ -10576,9 +10576,9 @@ impl Default for settings::RequiredFields { mandate : HashMap::new(), non_mandate: HashMap::new(), common : HashMap::from([ - ( "payment_method_data.pay_later.klarna.billing_country".to_string(), + ( "billing.address.country".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.pay_later.klarna.billing_country".to_string(), + required_field: "payment_method_data.billing.address.country".to_string(), display_name: "billing_country".to_string(), field_type: enums::FieldType::UserAddressCountry{ options: vec![ diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 394652c33e1..789c105d9b9 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2350,8 +2350,7 @@ impl check_required_field(billing_address, "billing")?; Ok(AdyenPaymentMethod::Atome) } - domain::payments::PayLaterData::KlarnaCheckout {} - | domain::payments::PayLaterData::KlarnaSdk { .. } => { + domain::payments::PayLaterData::KlarnaSdk { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), ) diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 4e54311a89a..4d593e8fbee 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -671,7 +671,7 @@ impl })), } } - domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaCheckout {}) => { + domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaRedirect {}) => { match (payment_experience, payment_method_type) { ( common_enums::PaymentExperience::RedirectToUrl, diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 3cefa4ec6c9..d1a0b80bad6 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -277,7 +277,7 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP })), } } - domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaCheckout {}) => { + domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaRedirect {}) => { match request.order_details.clone() { Some(order_details) => Ok(Self { purchase_country: item.router_data.get_billing_country()?, diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index c98a0647778..9c44727fc82 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -977,7 +977,6 @@ where get_pay_later_info(AlternativePaymentMethodType::AfterPay, item) } domain::PayLaterData::KlarnaSdk { .. } - | domain::PayLaterData::KlarnaCheckout {} | domain::PayLaterData::AffirmRedirect {} | domain::PayLaterData::PayBrightRedirect {} | domain::PayLaterData::WalleyRedirect {} diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 8f739792a0c..bf61a173104 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1272,7 +1272,6 @@ impl TryFrom<&domain::PayLaterData> for PaypalPaymentsRequest { match value { domain::PayLaterData::KlarnaRedirect { .. } | domain::PayLaterData::KlarnaSdk { .. } - | domain::PayLaterData::KlarnaCheckout {} | domain::PayLaterData::AffirmRedirect {} | domain::PayLaterData::AfterpayClearpayRedirect { .. } | domain::PayLaterData::PayBrightRedirect {} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 48736c00e7d..88045fa4c6a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -992,7 +992,6 @@ impl TryFrom<&domain::payments::PayLaterData> for StripePaymentMethodType { } domain::PayLaterData::KlarnaSdk { .. } - | domain::PayLaterData::KlarnaCheckout {} | domain::PayLaterData::PayBrightRedirect {} | domain::PayLaterData::WalleyRedirect {} | domain::PayLaterData::AlmaRedirect {} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index cbf1867b08b..df72b685bfb 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2771,7 +2771,6 @@ pub enum PaymentMethodDataType { SwishQr, KlarnaRedirect, KlarnaSdk, - KlarnaCheckout, AffirmRedirect, AfterpayClearpayRedirect, PayBrightRedirect, @@ -2895,7 +2894,6 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, domain::payments::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, - domain::payments::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout, domain::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect
2025-01-09T10:40:38Z
## 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 --> 1. Dynamic fields path for `Adyen` and `Stripe` is changed which is a frontend requirement 2. `WASM` for `klarnaCheckout` added in `Klarna` which is a dashboard requirement. 3. Removed `KlarnaCheckout` enum and using the already present `KlarnaRedirect` enum value as it was creating some frontend conflicts with `Adyen's` KlarnaRedirect flow. ### 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. Dynamic fields path for `Adyen` and `Stripe` is changed which is a frontend requirement to show the input boxes, so no testing required. 2. `WASM` for `klarnaCheckout` added in `Klarna` which is a dashboard requirement to list out the Payment Methods for `Klarna`, so no testing required. 3. Have removed `KlarnaCheckout` enum and using the already present `KlarnaRedirect` enum value for the flow. This doesn't effect the payment flow and `klarnaCheckout` is working as previously. ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_nsmdfKGJM74PYSViFQ04zsoTMLFkF2VkcvuRdmerez2zBfHSjCrZIxpEln9vYBgl' \ --data-raw '{ "amount": 50000, "order_tax_amount":0, "confirm": false, "currency": "EUR", "capture_method": "automatic", "customer_id": "klarna", "payment_experience":"redirect_to_url", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "payment_method": "pay_later", "payment_method_type": "klarna", "payment_method_data": { "pay_later": { "klarna_checkout":{} } }, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "return_url": "https://google.com" }' ``` Response ``` { "payment_id": "pay_b9SVvCHWeHFV7jiTCr1v", "merchant_id": "merchant_1734083062", "status": "requires_confirmation", "amount": 50000, "net_amount": 50000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_b9SVvCHWeHFV7jiTCr1v_secret_uTuJ4C4UZtzKWCkJqKyj", "created": "2024-12-16T12:15:12.009Z", "currency": "EUR", "customer_id": "klarna", "customer": { "id": "klarna", "name": "John Doe", "email": "[email protected]", "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": "pay_later", "payment_method_data": { "pay_later": { "klarna_sdk": null }, "billing": null }, "payment_token": null, "shipping": null, "billing": null, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "https://google.com/", "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": "redirect_to_url", "payment_method_type": "klarna", "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "klarna", "created_at": 1734351311, "expires": 1734354911, "secret": "epk_5aaf5ecba75d4de68712573428fe89f2" }, "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_PdHB9mW2uWUx2di0W9u3", "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-12-16T12:30:12.009Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-16T12:15:12.033Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": 0, "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
3fdc41e6c946609461db6b5459e10e6351694d4c
juspay/hyperswitch
juspay__hyperswitch-7005
Bug: feat(analytics): Add currency as dimension and filter for disputes Should add currency as dimension and filter for disputes, required for Analytics V2 Dashboard.
diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs index 540a14104c1..c1dcbaf2b2f 100644 --- a/crates/analytics/src/disputes/core.rs +++ b/crates/analytics/src/disputes/core.rs @@ -204,6 +204,7 @@ pub async fn get_filters( .filter_map(|fil: DisputeFilterRow| match dim { DisputeDimensions::DisputeStage => fil.dispute_stage, DisputeDimensions::Connector => fil.connector, + DisputeDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()), }) .collect::<Vec<String>>(); res.query_data.push(DisputeFilterValue { diff --git a/crates/analytics/src/disputes/filters.rs b/crates/analytics/src/disputes/filters.rs index cd60b502257..9e4aa302644 100644 --- a/crates/analytics/src/disputes/filters.rs +++ b/crates/analytics/src/disputes/filters.rs @@ -1,12 +1,16 @@ use api_models::analytics::{disputes::DisputeDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; +use diesel_models::enums::Currency; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, - types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, + types::{ + AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, + LoadRow, + }, }; pub trait DisputeFilterAnalytics: LoadRow<DisputeFilterRow> {} @@ -48,4 +52,5 @@ pub struct DisputeFilterRow { pub dispute_status: Option<String>, pub connector_status: Option<String>, pub dispute_stage: Option<String>, + pub currency: Option<DBEnumWrapper<Currency>>, } diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs index 6514e5fcbe0..72bb09003d3 100644 --- a/crates/analytics/src/disputes/metrics.rs +++ b/crates/analytics/src/disputes/metrics.rs @@ -27,6 +27,7 @@ pub struct DisputeMetricRow { pub dispute_stage: Option<DBEnumWrapper<storage_enums::DisputeStage>>, pub dispute_status: Option<DBEnumWrapper<storage_enums::DisputeStatus>>, pub connector: Option<String>, + pub currency: Option<DBEnumWrapper<storage_enums::Currency>>, pub total: Option<bigdecimal::BigDecimal>, pub count: Option<i64>, #[serde(with = "common_utils::custom_serde::iso8601::option")] diff --git a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs index ce962e284f6..b23dba4af38 100644 --- a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs +++ b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs @@ -97,6 +97,7 @@ where DisputeMetricsBucketIdentifier::new( i.dispute_stage.as_ref().map(|i| i.0), i.connector.clone(), + i.currency.as_ref().map(|i| i.0), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs index 9a7b0535819..0d54d75aee5 100644 --- a/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs @@ -97,6 +97,7 @@ where DisputeMetricsBucketIdentifier::new( i.dispute_stage.as_ref().map(|i| i.0), i.connector.clone(), + i.currency.as_ref().map(|i| i.0), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs index 5c5eceb0619..bf2332ab12f 100644 --- a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs @@ -98,6 +98,7 @@ where DisputeMetricsBucketIdentifier::new( i.dispute_stage.as_ref().map(|i| i.0), i.connector.clone(), + i.currency.as_ref().map(|i| i.0), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs index d6308b09f33..5d10becbbe2 100644 --- a/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs +++ b/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs @@ -99,6 +99,7 @@ where DisputeMetricsBucketIdentifier::new( i.dispute_stage.as_ref().map(|i| i.0), i.connector.clone(), + i.currency.as_ref().map(|i| i.0), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs index 68c7fa6d166..fc85ee39b26 100644 --- a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs +++ b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs @@ -97,6 +97,7 @@ where DisputeMetricsBucketIdentifier::new( i.dispute_stage.as_ref().map(|i| i.0), i.connector.clone(), + i.currency.as_ref().map(|i| i.0), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs index d14d4982701..33228cbb58b 100644 --- a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs +++ b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs @@ -98,6 +98,7 @@ where DisputeMetricsBucketIdentifier::new( i.dispute_stage.as_ref().map(|i| i.0), i.connector.clone(), + i.currency.as_ref().map(|i| i.0), TimeRange { start_time: match (granularity, i.start_bucket) { (Some(g), Some(st)) => g.clip_to_start(st)?, diff --git a/crates/analytics/src/disputes/types.rs b/crates/analytics/src/disputes/types.rs index 762e8d27554..da66744aede 100644 --- a/crates/analytics/src/disputes/types.rs +++ b/crates/analytics/src/disputes/types.rs @@ -24,6 +24,12 @@ where .attach_printable("Error adding dispute stage filter")?; } + if !self.currency.is_empty() { + builder + .add_filter_in_range_clause(DisputeDimensions::Currency, &self.currency) + .attach_printable("Error adding currency filter")?; + } + Ok(()) } } diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs index 2a94d528768..653d019adeb 100644 --- a/crates/analytics/src/sqlx.rs +++ b/crates/analytics/src/sqlx.rs @@ -933,11 +933,17 @@ impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let currency: Option<DBEnumWrapper<Currency>> = + row.try_get("currency").or_else(|e| match e { + ColumnNotFound(_) => Ok(Default::default()), + e => Err(e), + })?; Ok(Self { dispute_stage, dispute_status, connector, connector_status, + currency, }) } } @@ -957,6 +963,11 @@ impl<'a> FromRow<'a, PgRow> for super::disputes::metrics::DisputeMetricRow { ColumnNotFound(_) => Ok(Default::default()), e => Err(e), })?; + let currency: Option<DBEnumWrapper<Currency>> = + row.try_get("currency").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), @@ -976,6 +987,7 @@ impl<'a> FromRow<'a, PgRow> for super::disputes::metrics::DisputeMetricRow { dispute_stage, dispute_status, connector, + currency, total, count, start_bucket, diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs index e373704b87c..179edee0413 100644 --- a/crates/api_models/src/analytics/disputes.rs +++ b/crates/api_models/src/analytics/disputes.rs @@ -4,7 +4,7 @@ use std::{ }; use super::{ForexMetric, NameDescription, TimeRange}; -use crate::enums::DisputeStage; +use crate::enums::{Currency, DisputeStage}; #[derive( Clone, @@ -58,6 +58,7 @@ pub enum DisputeDimensions { // Consult the Dashboard FE folks since these also affects the order of metrics on FE Connector, DisputeStage, + Currency, } impl From<DisputeDimensions> for NameDescription { @@ -82,13 +83,17 @@ impl From<DisputeMetrics> for NameDescription { pub struct DisputeFilters { #[serde(default)] pub dispute_stage: Vec<DisputeStage>, + #[serde(default)] pub connector: Vec<String>, + #[serde(default)] + pub currency: Vec<Currency>, } #[derive(Debug, serde::Serialize, Eq)] pub struct DisputeMetricsBucketIdentifier { pub dispute_stage: Option<DisputeStage>, pub connector: Option<String>, + pub currency: Option<Currency>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] @@ -100,6 +105,7 @@ impl Hash for DisputeMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.dispute_stage.hash(state); self.connector.hash(state); + self.currency.hash(state); self.time_bucket.hash(state); } } @@ -117,11 +123,13 @@ impl DisputeMetricsBucketIdentifier { pub fn new( dispute_stage: Option<DisputeStage>, connector: Option<String>, + currency: Option<Currency>, normalized_time_range: TimeRange, ) -> Self { Self { dispute_stage, connector, + currency, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, }
2025-01-08T05:53:25Z
## 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 currency as dimension and filter for disputes, required for Analytics V2 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). --> For better filtering related analytics ## 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)? --> Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/disputes' \ --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: Chart' \ --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/129.0.0.0 Safari/537.36' \ --header 'api-key: dev_ssyiqBXK7Ou1HUQuH0Z80BsHuV5pojc0uWli4QbNXGM1f4pn7jCIyb9VFiHlyATQ' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNmNkZTA0NzYtMTFlMi00NGE5LTlkMjUtOTA5M2QzNDQwZjhlIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzM1MDQxMjkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczNjM2MDQ5Mywib3JnX2lkIjoib3JnX2pwanI5TkFEWlhqSENNYTU5MmF3IiwicHJvZmlsZV9pZCI6InByb19QRHUydVA3aWNuM2lXY0I3V0VVSSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.tCy_qvwHxdPO1yor-A6IpZKVpC8uWxFGOgMvS35tRJ4' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-10-16T18:30:00Z", "endTime": "2024-10-24T12:09:00Z" }, "timeSeries": { "granularity": "G_ONEDAY" }, "filters": { "currency": ["USD"] }, "mode": "ORDER", "source": "BATCH", "metrics": [ "dispute_status_metric" ] } ]' ``` `clickhouse` as the source (query) ![image](https://github.com/user-attachments/assets/24323eae-e2c4-4442-9fcb-2c6bbb331678) `sqlx` as the source (query) <img width="1289" alt="image" src="https://github.com/user-attachments/assets/b6f8df85-2a3c-4521-be68-70d48caf9db5" /> Currency filter is now getting added in the query while trying to get the data to calculate the metrics. ## 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
ed8ef2466b7f059ed0f534aa1f3fca9b5ecbeefd
juspay/hyperswitch
juspay__hyperswitch-7020
Bug: chore: address Rust 1.84.0 clippy lints Address the clippy lints occurring due to new rust version 1.84.0 See https://github.com/juspay/hyperswitch/issues/3391 for more information.
diff --git a/Cargo.lock b/Cargo.lock index e34c80bd927..2007f4f88a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9266,9 +9266,9 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" [[package]] name = "wasm-bindgen" -version = "0.2.93" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" +checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396" dependencies = [ "cfg-if 1.0.0", "once_cell", @@ -9277,13 +9277,12 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.93" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" +checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79" dependencies = [ "bumpalo", "log", - "once_cell", "proc-macro2", "quote", "syn 2.0.77", @@ -9304,9 +9303,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.93" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" +checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -9314,9 +9313,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.93" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" +checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2" dependencies = [ "proc-macro2", "quote", @@ -9327,9 +9326,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.93" +version = "0.2.99" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" +checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6" [[package]] name = "web-sys" diff --git a/crates/diesel_models/src/query/address.rs b/crates/diesel_models/src/query/address.rs index 23c3711a8ac..21304a6ab9a 100644 --- a/crates/diesel_models/src/query/address.rs +++ b/crates/diesel_models/src/query/address.rs @@ -15,10 +15,7 @@ impl AddressNew { } impl Address { - pub async fn find_by_address_id<'a>( - conn: &PgPooledConn, - address_id: &str, - ) -> StorageResult<Self> { + pub async fn find_by_address_id(conn: &PgPooledConn, address_id: &str) -> StorageResult<Self> { generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, address_id.to_owned()) .await } @@ -104,7 +101,7 @@ impl Address { .await } - pub async fn find_by_merchant_id_payment_id_address_id<'a>( + pub async fn find_by_merchant_id_payment_id_address_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, @@ -133,7 +130,7 @@ impl Address { } } - pub async fn find_optional_by_address_id<'a>( + pub async fn find_optional_by_address_id( conn: &PgPooledConn, address_id: &str, ) -> StorageResult<Option<Self>> { diff --git a/crates/euclid/src/backend/vir_interpreter/types.rs b/crates/euclid/src/backend/vir_interpreter/types.rs index d0eca5fec2e..c97f60ee17e 100644 --- a/crates/euclid/src/backend/vir_interpreter/types.rs +++ b/crates/euclid/src/backend/vir_interpreter/types.rs @@ -31,8 +31,7 @@ impl Context { .get(&key) .and_then(|value| value.get_num_value()); - value.get_num_value().zip(ctx_num_value).map_or( - false, + value.get_num_value().zip(ctx_num_value).is_some_and( |(program_value, ctx_value)| { let program_num = program_value.number; let ctx_num = ctx_value.number; diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 7ef9bb244d9..c4c8c260861 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -194,11 +194,11 @@ impl cgraph::CheckingContext for AnalysisContext { DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => { value_set.contains(val) } - DataType::Number => val.get_num_value().map_or(false, |num_val| { + DataType::Number => val.get_num_value().is_some_and(|num_val| { value_set.iter().any(|ctx_val| { ctx_val .get_num_value() - .map_or(false, |ctx_num_val| num_val.fits(&ctx_num_val)) + .is_some_and(|ctx_num_val| num_val.fits(&ctx_num_val)) }) }), } diff --git a/crates/euclid_wasm/Cargo.toml b/crates/euclid_wasm/Cargo.toml index 19c425e4c01..4f967df34ad 100644 --- a/crates/euclid_wasm/Cargo.toml +++ b/crates/euclid_wasm/Cargo.toml @@ -35,7 +35,7 @@ ron-parser = "0.1.4" serde = { version = "1.0", features = [] } serde-wasm-bindgen = "0.6.5" strum = { version = "0.26", features = ["derive"] } -wasm-bindgen = { version = "0.2.92" } +wasm-bindgen = { version = "0.2.99" } [lints] workspace = true diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 169e5ae146e..6b75a2148c5 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -1338,9 +1338,7 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == FutureUsage::OffSession - })) + && (self.setup_future_usage == Some(FutureUsage::OffSession))) || self .mandate_id .as_ref() @@ -1409,9 +1407,7 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { fn is_customer_initiated_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == FutureUsage::OffSession - }) + && self.setup_future_usage == Some(FutureUsage::OffSession) } fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> { @@ -1469,9 +1465,7 @@ impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData { } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == FutureUsage::OffSession - }) + && self.setup_future_usage == Some(FutureUsage::OffSession) } } @@ -1687,9 +1681,7 @@ impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData { } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == FutureUsage::OffSession - })) + && self.setup_future_usage == Some(FutureUsage::OffSession)) || self .mandate_id .as_ref() @@ -1712,9 +1704,7 @@ impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData { } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == FutureUsage::OffSession - }) + && self.setup_future_usage == Some(FutureUsage::OffSession) } } pub trait AddressData { diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 9698b4ac5d8..d2b212e3ea0 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -702,39 +702,41 @@ impl &domain::Card, ), ) -> Result<Self, Self::Error> { - let (profile, customer) = if item - .router_data - .request - .setup_future_usage - .map_or(false, |future_usage| { - matches!(future_usage, common_enums::FutureUsage::OffSession) - }) - && (item.router_data.request.customer_acceptance.is_some() - || item - .router_data - .request - .setup_mandate_details - .clone() - .map_or(false, |mandate_details| { - mandate_details.customer_acceptance.is_some() - })) { - ( - Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { - create_profile: true, - })), - Some(CustomerDetails { - //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate. - //If the length exceeds 20 characters, a random alphanumeric string is used instead. - id: if item.router_data.payment_id.len() <= 20 { - item.router_data.payment_id.clone() - } else { - Alphanumeric.sample_string(&mut rand::thread_rng(), 20) - }, - }), - ) - } else { - (None, None) - }; + let (profile, customer) = + if item + .router_data + .request + .setup_future_usage + .is_some_and(|future_usage| { + matches!(future_usage, common_enums::FutureUsage::OffSession) + }) + && (item.router_data.request.customer_acceptance.is_some() + || item + .router_data + .request + .setup_mandate_details + .clone() + .is_some_and(|mandate_details| { + mandate_details.customer_acceptance.is_some() + })) + { + ( + Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails { + create_profile: true, + })), + Some(CustomerDetails { + //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate. + //If the length exceeds 20 characters, a random alphanumeric string is used instead. + id: if item.router_data.payment_id.len() <= 20 { + item.router_data.payment_id.clone() + } else { + Alphanumeric.sample_string(&mut rand::thread_rng(), 20) + }, + }), + ) + } else { + (None, None) + }; Ok(Self { transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?, amount: item.amount, diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 71cc006700e..48363481ad8 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -619,18 +619,15 @@ impl .router_data .request .setup_future_usage - .map_or(false, |future_usage| { - matches!(future_usage, common_enums::FutureUsage::OffSession) - }) + == Some(common_enums::FutureUsage::OffSession) && (item.router_data.request.customer_acceptance.is_some() || item .router_data .request .setup_mandate_details .clone() - .map_or(false, |mandate_details| { - mandate_details.customer_acceptance.is_some() - })) { + .is_some_and(|mandate_details| mandate_details.customer_acceptance.is_some())) + { get_boa_mandate_action_details() } else if item.router_data.request.connector_mandate_id().is_some() { let original_amount = item diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 7ce98d3d5a3..2aa24e5ffdf 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -632,18 +632,15 @@ impl .router_data .request .setup_future_usage - .map_or(false, |future_usage| { - matches!(future_usage, FutureUsage::OffSession) - }) + == Some(FutureUsage::OffSession) && (item.router_data.request.customer_acceptance.is_some() || item .router_data .request .setup_mandate_details .clone() - .map_or(false, |mandate_details| { - mandate_details.customer_acceptance.is_some() - })) { + .is_some_and(|mandate_details| mandate_details.customer_acceptance.is_some())) + { ( Some(vec![CybersourceActionsList::TokenCreate]), Some(vec![ @@ -960,35 +957,30 @@ impl let connector_merchant_config = CybersourceConnectorMetadataObject::try_from(&item.router_data.connector_meta_data)?; - let (action_list, action_token_types, authorization_options) = if item - .router_data - .request - .setup_future_usage - .map_or(false, |future_usage| { - matches!(future_usage, FutureUsage::OffSession) - }) - //TODO check for customer acceptance also - { - ( - Some(vec![CybersourceActionsList::TokenCreate]), - Some(vec![ - CybersourceActionsTokenType::PaymentInstrument, - CybersourceActionsTokenType::Customer, - ]), - Some(CybersourceAuthorizationOptions { - initiator: Some(CybersourcePaymentInitiator { - initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), - credential_stored_on_file: Some(true), - stored_credential_used: None, + let (action_list, action_token_types, authorization_options) = + if item.router_data.request.setup_future_usage == Some(FutureUsage::OffSession) + //TODO check for customer acceptance also + { + ( + Some(vec![CybersourceActionsList::TokenCreate]), + Some(vec![ + CybersourceActionsTokenType::PaymentInstrument, + CybersourceActionsTokenType::Customer, + ]), + Some(CybersourceAuthorizationOptions { + initiator: Some(CybersourcePaymentInitiator { + initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer), + credential_stored_on_file: Some(true), + stored_credential_used: None, + }), + merchant_intitiated_transaction: None, + ignore_avs_result: connector_merchant_config.disable_avs, + ignore_cv_result: connector_merchant_config.disable_cvn, }), - merchant_intitiated_transaction: None, - ignore_avs_result: connector_merchant_config.disable_avs, - ignore_cv_result: connector_merchant_config.disable_cvn, - }), - ) - } else { - (None, None, None) - }; + ) + } else { + (None, None, None) + }; Ok(Self { capture: Some(matches!( item.router_data.request.capture_method, diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index 3e75130f575..b96283247b4 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -879,7 +879,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>> transaction .transaction_reference .clone() - .map_or(false, |transaction_instance| { + .is_some_and(|transaction_instance| { transaction_instance == item.data.request.refund_id }) }) diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 85b1dd221f7..cbf1867b08b 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -893,9 +893,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == storage_enums::FutureUsage::OffSession - })) + && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)) || self .mandate_id .as_ref() @@ -904,9 +902,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == storage_enums::FutureUsage::OffSession - }) + && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } fn get_webhook_url(&self) -> Result<String, Error> { self.webhook_url @@ -973,9 +969,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { fn is_customer_initiated_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == storage_enums::FutureUsage::OffSession - }) + && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> { @@ -1123,9 +1117,7 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { } fn is_mandate_payment(&self) -> bool { ((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == storage_enums::FutureUsage::OffSession - })) + && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession)) || self .mandate_id .as_ref() @@ -1134,9 +1126,7 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData { } fn is_cit_mandate_payment(&self) -> bool { (self.customer_acceptance.is_some() || self.setup_mandate_details.is_some()) - && self.setup_future_usage.map_or(false, |setup_future_usage| { - setup_future_usage == storage_enums::FutureUsage::OffSession - }) + && self.setup_future_usage == Some(storage_enums::FutureUsage::OffSession) } /// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`. fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> { diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index 937af33bd79..0500b098bb1 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -567,18 +567,15 @@ impl .router_data .request .setup_future_usage - .map_or(false, |future_usage| { - matches!(future_usage, FutureUsage::OffSession) - }) + == Some(FutureUsage::OffSession) && (item.router_data.request.customer_acceptance.is_some() || item .router_data .request .setup_mandate_details .clone() - .map_or(false, |mandate_details| { - mandate_details.customer_acceptance.is_some() - })) { + .is_some_and(|mandate_details| mandate_details.customer_acceptance.is_some())) + { ( Some(vec![WellsfargoActionsList::TokenCreate]), Some(vec![ diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 35df1ca8df3..a8db0e998e4 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1748,7 +1748,7 @@ struct PMAuthConfigValidation<'a> { key_manager_state: &'a KeyManagerState, } -impl<'a> PMAuthConfigValidation<'a> { +impl PMAuthConfigValidation<'_> { async fn validate_pm_auth(&self, val: &pii::SecretSerdeValue) -> RouterResponse<()> { let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>( val.clone().expose(), @@ -1865,7 +1865,7 @@ struct MerchantDefaultConfigUpdate<'a> { transaction_type: &'a api_enums::TransactionType, } #[cfg(feature = "v1")] -impl<'a> MerchantDefaultConfigUpdate<'a> { +impl MerchantDefaultConfigUpdate<'_> { async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { @@ -1938,11 +1938,7 @@ impl<'a> MerchantDefaultConfigUpdate<'a> { }; 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 - }) + mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); routing::helpers::update_merchant_default_config( self.store, @@ -1954,11 +1950,7 @@ impl<'a> MerchantDefaultConfigUpdate<'a> { } 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 - }) + mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id) }); routing::helpers::update_merchant_default_config( self.store, @@ -1982,7 +1974,7 @@ struct DefaultFallbackRoutingConfigUpdate<'a> { key_manager_state: &'a KeyManagerState, } #[cfg(feature = "v2")] -impl<'a> DefaultFallbackRoutingConfigUpdate<'a> { +impl DefaultFallbackRoutingConfigUpdate<'_> { async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists( &self, ) -> RouterResult<()> { @@ -2025,11 +2017,7 @@ impl<'a> DefaultFallbackRoutingConfigUpdate<'a> { }; 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 - }) + (mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id)) }); profile_wrapper diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rs index b5b3d6625e1..f1194d7d680 100644 --- a/crates/router/src/core/blocklist/transformers.rs +++ b/crates/router/src/core/blocklist/transformers.rs @@ -32,7 +32,7 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse { } } -async fn generate_fingerprint_request<'a>( +async fn generate_fingerprint_request( jwekey: &settings::Jwekey, locker: &settings::Locker, payload: &blocklist::GenerateFingerprintRequest, diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 65bbf736f1a..4f69cf41963 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -314,7 +314,7 @@ struct AddressStructForDbEntry<'a> { } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -impl<'a> AddressStructForDbEntry<'a> { +impl AddressStructForDbEntry<'_> { async fn encrypt_customer_address_and_set_to_db( &self, db: &dyn StorageInterface, @@ -1029,7 +1029,7 @@ struct AddressStructForDbUpdate<'a> { } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -impl<'a> AddressStructForDbUpdate<'a> { +impl AddressStructForDbUpdate<'_> { async fn update_address_if_sent( &self, db: &dyn StorageInterface, @@ -1131,7 +1131,7 @@ struct VerifyIdForUpdateCustomer<'a> { } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -impl<'a> VerifyIdForUpdateCustomer<'a> { +impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, @@ -1152,7 +1152,7 @@ impl<'a> VerifyIdForUpdateCustomer<'a> { } #[cfg(all(feature = "v2", feature = "customer_v2"))] -impl<'a> VerifyIdForUpdateCustomer<'a> { +impl VerifyIdForUpdateCustomer<'_> { async fn verify_id_and_get_customer_object( &self, db: &dyn StorageInterface, diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 99a60817303..a2a9864aadc 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -379,7 +379,7 @@ where #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] -pub async fn make_frm_data_and_fraud_check_operation<'a, F, D>( +pub async fn make_frm_data_and_fraud_check_operation<F, D>( _db: &dyn StorageInterface, state: &SessionState, merchant_account: &domain::MerchantAccount, @@ -402,7 +402,7 @@ where #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] -pub async fn make_frm_data_and_fraud_check_operation<'a, F, D>( +pub async fn make_frm_data_and_fraud_check_operation<F, D>( _db: &dyn StorageInterface, state: &SessionState, merchant_account: &domain::MerchantAccount, @@ -486,7 +486,7 @@ where } #[allow(clippy::too_many_arguments)] -pub async fn pre_payment_frm_core<'a, F, Req, D>( +pub async fn pre_payment_frm_core<F, Req, D>( state: &SessionState, merchant_account: &domain::MerchantAccount, payment_data: &mut D, @@ -578,7 +578,7 @@ where } #[allow(clippy::too_many_arguments)] -pub async fn post_payment_frm_core<'a, F, D>( +pub async fn post_payment_frm_core<F, D>( state: &SessionState, req_state: ReqState, merchant_account: &domain::MerchantAccount, @@ -674,7 +674,7 @@ where } #[allow(clippy::too_many_arguments)] -pub async fn call_frm_before_connector_call<'a, F, Req, D>( +pub async fn call_frm_before_connector_call<F, Req, D>( operation: &BoxedOperation<'_, F, Req, D>, merchant_account: &domain::MerchantAccount, payment_data: &mut D, 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 e6ff3fdbfca..6711b96b066 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -200,9 +200,9 @@ impl FeatureFrm<frm_api::Checkout, FraudCheckCheckoutData> for FrmCheckoutRouter } } -pub async fn decide_frm_flow<'a, 'b>( - router_data: &'b mut FrmCheckoutRouterData, - state: &'a SessionState, +pub async fn decide_frm_flow( + router_data: &mut FrmCheckoutRouterData, + state: &SessionState, connector: &FraudCheckConnectorData, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, 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 21c5de5ed3b..d639345e227 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -168,9 +168,9 @@ impl FeatureFrm<RecordReturn, FraudCheckRecordReturnData> for FrmRecordReturnRou } } -pub async fn decide_frm_flow<'a, 'b>( - router_data: &'b mut FrmRecordReturnRouterData, - state: &'a SessionState, +pub async fn decide_frm_flow( + router_data: &mut FrmRecordReturnRouterData, + state: &SessionState, connector: &FraudCheckConnectorData, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, 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 189edb5bc08..34fbda2c685 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -176,9 +176,9 @@ impl FeatureFrm<frm_api::Sale, FraudCheckSaleData> for FrmSaleRouterData { } } -pub async fn decide_frm_flow<'a, 'b>( - router_data: &'b mut FrmSaleRouterData, - state: &'a SessionState, +pub async fn decide_frm_flow( + router_data: &mut FrmSaleRouterData, + state: &SessionState, connector: &FraudCheckConnectorData, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, 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 7ddf41c509f..1675fdfb383 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -185,9 +185,9 @@ impl FeatureFrm<frm_api::Transaction, FraudCheckTransactionData> for FrmTransact } } -pub async fn decide_frm_flow<'a, 'b>( - router_data: &'b mut FrmTransactionRouterData, - state: &'a SessionState, +pub async fn decide_frm_flow( + router_data: &mut FrmTransactionRouterData, + state: &SessionState, connector: &frm_api::FraudCheckConnectorData, call_connector_action: payments::CallConnectorAction, _merchant_account: &domain::MerchantAccount, diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 79cfb6950b3..5bd2c07073e 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2303,40 +2303,38 @@ pub fn validate_payment_method_update( card_updation_obj .card_exp_month .map(|exp_month| exp_month.expose()) - .map_or(false, |new_exp_month| { + .is_some_and(|new_exp_month| { existing_card_data .expiry_month .map(|exp_month| exp_month.expose()) - .map_or(true, |old_exp_month| new_exp_month != old_exp_month) + != Some(new_exp_month) }) || card_updation_obj .card_exp_year .map(|exp_year| exp_year.expose()) - .map_or(false, |new_exp_year| { + .is_some_and(|new_exp_year| { existing_card_data .expiry_year .map(|exp_year| exp_year.expose()) - .map_or(true, |old_exp_year| new_exp_year != old_exp_year) + != Some(new_exp_year) }) || card_updation_obj .card_holder_name .map(|name| name.expose()) - .map_or(false, |new_card_holder_name| { + .is_some_and(|new_card_holder_name| { existing_card_data .card_holder_name .map(|name| name.expose()) - .map_or(true, |old_card_holder_name| { - new_card_holder_name != old_card_holder_name - }) + != Some(new_card_holder_name) }) || card_updation_obj .nick_name .map(|nick_name| nick_name.expose()) - .map_or(false, |new_nick_name| { + .is_some_and(|new_nick_name| { existing_card_data .nick_name .map(|nick_name| nick_name.expose()) - .map_or(true, |old_nick_name| new_nick_name != old_nick_name) + != Some(new_nick_name) }) } @@ -4212,9 +4210,9 @@ pub async fn list_payment_methods( } }); - let is_tax_connector_enabled = business_profile.as_ref().map_or(false, |business_profile| { - business_profile.get_is_tax_connector_enabled() - }); + let is_tax_connector_enabled = business_profile + .as_ref() + .is_some_and(|business_profile| business_profile.get_is_tax_connector_enabled()); Ok(services::ApplicationResponse::Json( api::PaymentMethodListResponse { diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs index d7e83cb5bf2..5885b830e7a 100644 --- a/crates/router/src/core/payment_methods/utils.rs +++ b/crates/router/src/core/payment_methods/utils.rs @@ -41,7 +41,7 @@ pub fn make_pm_graph( Ok(()) } -pub async fn get_merchant_pm_filter_graph<'a>( +pub async fn get_merchant_pm_filter_graph( state: &SessionState, key: &str, ) -> Option<Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>>> { diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index b7b3420987d..ed7b84e8329 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1193,7 +1193,7 @@ impl PaymentCreate { payment_id.get_attempt_id(1) }; - if request.mandate_data.as_ref().map_or(false, |mandate_data| { + if request.mandate_data.as_ref().is_some_and(|mandate_data| { mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some() }) { Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})? diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 8f3f40edf06..45bd0a6a015 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -554,7 +554,7 @@ pub fn perform_volume_split( } #[cfg(feature = "v1")] -pub async fn get_merchant_cgraph<'a>( +pub async fn get_merchant_cgraph( state: &SessionState, key_store: &domain::MerchantKeyStore, profile_id: &common_utils::id_type::ProfileId, @@ -601,7 +601,7 @@ pub async fn get_merchant_cgraph<'a>( } #[cfg(feature = "v1")] -pub async fn refresh_cgraph_cache<'a>( +pub async fn refresh_cgraph_cache( state: &SessionState, key_store: &domain::MerchantKeyStore, key: String, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index b07094c321c..060fc64f891 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -49,8 +49,8 @@ use crate::{ }; #[allow(clippy::too_many_arguments)] -pub async fn make_payout_method_data<'a>( - state: &'a SessionState, +pub async fn make_payout_method_data( + state: &SessionState, payout_method_data: Option<&api::PayoutMethodData>, payout_token: Option<&str>, customer_id: &id_type::CustomerId, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index e78c9471e61..1e788b6acee 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -426,7 +426,7 @@ where // ********************************************** REFUND SYNC ********************************************** -pub async fn refund_response_wrapper<'a, F, Fut, T, Req>( +pub async fn refund_response_wrapper<F, Fut, T, Req>( state: SessionState, merchant_account: domain::MerchantAccount, profile_id: Option<common_utils::id_type::ProfileId>, diff --git a/crates/router/src/core/relay/utils.rs b/crates/router/src/core/relay/utils.rs index 1c201fba56f..78e42039e02 100644 --- a/crates/router/src/core/relay/utils.rs +++ b/crates/router/src/core/relay/utils.rs @@ -17,8 +17,8 @@ const IRRELEVANT_PAYMENT_INTENT_ID: &str = "irrelevant_payment_intent_id"; const IRRELEVANT_PAYMENT_ATTEMPT_ID: &str = "irrelevant_payment_attempt_id"; -pub async fn construct_relay_refund_router_data<'a, F>( - state: &'a SessionState, +pub async fn construct_relay_refund_router_data<F>( + state: &SessionState, merchant_id: &id_type::MerchantId, connector_account: &domain::MerchantConnectorAccount, relay_record: &hyperswitch_domain_models::relay::Relay, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 6f739c48ae3..1395563a30a 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -575,7 +575,7 @@ pub fn get_default_config_key( /// Retrieves cached success_based routing configs specific to tenant and profile #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -pub async fn get_cached_success_based_routing_config_for_profile<'a>( +pub async fn get_cached_success_based_routing_config_for_profile( state: &SessionState, key: &str, ) -> Option<Arc<routing_types::SuccessBasedRoutingConfig>> { diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index 5e126310fa6..0f775eda855 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -922,8 +922,8 @@ pub async fn construct_upload_file_router_data<'a>( } #[cfg(feature = "v2")] -pub async fn construct_payments_dynamic_tax_calculation_router_data<'a, F: Clone>( - state: &'a SessionState, +pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>( + state: &SessionState, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, @@ -933,8 +933,8 @@ pub async fn construct_payments_dynamic_tax_calculation_router_data<'a, F: Clone } #[cfg(feature = "v1")] -pub async fn construct_payments_dynamic_tax_calculation_router_data<'a, F: Clone>( - state: &'a SessionState, +pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>( + state: &SessionState, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, payment_data: &mut PaymentData<F>, diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index 256fae78d4a..56957042860 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -57,7 +57,7 @@ pub async fn is_webhook_event_disabled( } } -pub async fn construct_webhook_router_data<'a>( +pub async fn construct_webhook_router_data( state: &SessionState, connector_name: &str, merchant_connector_account: domain::MerchantConnectorAccount, diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs index 742c03dde4a..4f1624f3457 100644 --- a/crates/router/src/db/dashboard_metadata.rs +++ b/crates/router/src/db/dashboard_metadata.rs @@ -332,10 +332,7 @@ impl DashboardMetadataInterface for MockDb { let index_to_remove = dashboard_metadata .iter() .position(|metadata_inner| { - metadata_inner - .user_id - .as_deref() - .map_or(false, |user_id_inner| user_id_inner == user_id) + metadata_inner.user_id.as_deref() == Some(user_id) && metadata_inner.merchant_id == *merchant_id && metadata_inner.data_key == data_key }) diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 88962f73233..e07821cd9a8 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -1136,7 +1136,7 @@ impl RefundInterface for MockDb { || refund .merchant_connector_id .as_ref() - .map_or(false, |id| unique_merchant_connector_ids.contains(id)) + .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) @@ -1342,7 +1342,7 @@ impl RefundInterface for MockDb { || refund .merchant_connector_id .as_ref() - .map_or(false, |id| unique_merchant_connector_ids.contains(id)) + .is_some_and(|id| unique_merchant_connector_ids.contains(id)) }) .filter(|refund| { unique_currencies.is_empty() || unique_currencies.contains(&refund.currency) diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs index 0ac8c419ef6..da5f87a450e 100644 --- a/crates/router/src/services/authentication/blacklist.rs +++ b/crates/router/src/services/authentication/blacklist.rs @@ -79,7 +79,7 @@ pub async fn check_user_in_blacklist<A: SessionStateInfo>( .get_key::<Option<i64>>(token.as_str()) .await .change_context(ApiErrorResponse::InternalServerError) - .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) + .map(|timestamp| timestamp > Some(token_issued_at)) } pub async fn check_role_in_blacklist<A: SessionStateInfo>( @@ -94,7 +94,7 @@ pub async fn check_role_in_blacklist<A: SessionStateInfo>( .get_key::<Option<i64>>(token.as_str()) .await .change_context(ApiErrorResponse::InternalServerError) - .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at)) + .map(|timestamp| timestamp > Some(token_issued_at)) } #[cfg(feature = "email")] diff --git a/crates/router/src/services/pm_auth.rs b/crates/router/src/services/pm_auth.rs index d63dadc8b15..2d8097037dc 100644 --- a/crates/router/src/services/pm_auth.rs +++ b/crates/router/src/services/pm_auth.rs @@ -11,9 +11,9 @@ use crate::{ services::{self}, }; -pub async fn execute_connector_processing_step<'b, 'a, T, Req, Resp>( +pub async fn execute_connector_processing_step<'b, T, Req, Resp>( state: &'b SessionState, - connector_integration: BoxedConnectorIntegration<'a, T, Req, Resp>, + connector_integration: BoxedConnectorIntegration<'_, T, Req, Resp>, req: &'b PaymentAuthRouterData<T, Req, Resp>, connector: &pm_auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError> diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index 39a76844be1..b5e16290fca 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -281,7 +281,7 @@ pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPay fn not_contains_string(value: &Option<String>, value_to_be_checked: &str) -> bool { value .as_ref() - .map_or(false, |mail| !mail.contains(value_to_be_checked)) + .is_some_and(|mail| !mail.contains(value_to_be_checked)) } pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool { diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 9203a14ae21..17974a3b9bc 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -288,10 +288,10 @@ impl std::fmt::Display for Op<'_> { } } -pub async fn decide_storage_scheme<'a, T, D>( +pub async fn decide_storage_scheme<T, D>( store: &KVRouterStore<T>, storage_scheme: MerchantStorageScheme, - operation: Op<'a>, + operation: Op<'_>, ) -> MerchantStorageScheme where D: de::DeserializeOwned
2025-01-10T09:59:26Z
## 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 addresses the clippy lints occurring due to new rust version 1.84.0 Majorly addresses `unnecessary_map_or` clippy lint - https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_map_or ### 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)? --> CI checks should pass as this PR addresses clippy lints. 1. ran `just clippy` with new rust version (1.84.0) ![image](https://github.com/user-attachments/assets/e723951b-e99b-41d3-b677-c15063d84aaf) 2. ran `just clippy_v2` with new rust version (1.84.0) ![image](https://github.com/user-attachments/assets/b5b5eed4-4fc8-4ef9-9513-d45e392aa3bd) ## 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
dbe0cd4d2c368293bec22e2e83571a90b8ce3ee3
juspay/hyperswitch
juspay__hyperswitch-7003
Bug: [FIX] consider status of payment method before filtering wallets in list pm
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 164c0e9557a..deae78b5540 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3470,12 +3470,14 @@ pub async fn list_payment_methods( .any(|mca| mca.payment_method == enums::PaymentMethod::Wallet); if wallet_pm_exists { match db - .find_payment_method_by_customer_id_merchant_id_list( + .find_payment_method_by_customer_id_merchant_id_status( &((&state).into()), &key_store, - &customer.customer_id, - merchant_account.get_id(), + &customer.customer_id, + merchant_account.get_id(), + common_enums::PaymentMethodStatus::Active, None, + merchant_account.storage_scheme, ) .await {
2025-01-07T13:44:49Z
## 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 --> https://github.com/juspay/hyperswitch/pull/3953 We were not considering the status of payment method in above filtering logic ### 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. Create merchant_account, api_key, mca (with any wallet) 2. Create a payment with wallet as payment method with authentication_type as three_ds. Retain the status of payment as processing ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_qVglrYUpCaoLCvnixZd3hX0ls7du5ZmaVMhZJNGt8ezEN4Axn8oU22i2gRz0OTqx' \ --data '{ "amount": 6540, "confirm": true, "currency": "USD", "customer_acceptance": { "acceptance_type": "online" }, "customer_id": "cus_kWEMsP0NufHyhHsBB1Ol", "profile_id": "pro_mjcaEelE0mjdp8ODpfkc", "authentication_type": "three_ds", "payment_method": "wallet", "payment_method_type": "apple_pay", "payment_method_data": { "wallet": { "apple_pay": { "payment_data": "token", "payment_method": { "display_name": "Visa 0326", "network": "Mastercard", "type": "debit" }, "transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8" } } } }' ``` 3. Create another payment with confirm:false ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_qVglrYUpCaoLCvnixZd3hX0ls7du5ZmaVMhZJNGt8ezEN4Axn8oU22i2gRz0OTqx' \ --data '{ "amount": 6540, "confirm": false, "currency": "USD", "customer_acceptance": { "acceptance_type": "online" }, "customer_id": "cus_kWEMsP0NufHyhHsBB1Ol", "profile_id": "pro_mjcaEelE0mjdp8ODpfkc", "authentication_type": "three_ds" }' ``` 4. list merchant pml. When the status of payment_method is inactive in db, the wallet should appear in the list ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_Fvjj9zQjd2BA47M6qFJO_secret_gV3eKHcXxHT9PdA7fBbk' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_c079bd1ada67401fb98568ea6f6043bf' \ --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
c4d36b506e159f39acff17e13f72b5c53edec184
juspay/hyperswitch
juspay__hyperswitch-7009
Bug: [fix]: dummy connector on multitenancy
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index 2970ac127ed..8e4c79a965e 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -22,6 +22,7 @@ pub struct RouterData<Flow, Request, Response> { // Make this change after all the connector dependency has been removed from connectors pub payment_id: String, pub attempt_id: String, + pub tenant_id: id_type::TenantId, pub status: common_enums::enums::AttemptStatus, pub payment_method: common_enums::enums::PaymentMethod, pub connector_auth_type: ConnectorAuthType, diff --git a/crates/hyperswitch_domain_models/src/router_data_v2.rs b/crates/hyperswitch_domain_models/src/router_data_v2.rs index acc7343cb14..7ca106331e4 100644 --- a/crates/hyperswitch_domain_models/src/router_data_v2.rs +++ b/crates/hyperswitch_domain_models/src/router_data_v2.rs @@ -2,6 +2,7 @@ pub mod flow_common_types; use std::{marker::PhantomData, ops::Deref}; +use common_utils::id_type; #[cfg(feature = "frm")] pub use flow_common_types::FrmFlowData; #[cfg(feature = "payouts")] @@ -16,6 +17,7 @@ use crate::router_data::{ConnectorAuthType, ErrorResponse}; #[derive(Debug, Clone)] pub struct RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> { pub flow: PhantomData<Flow>, + pub tenant_id: id_type::TenantId, pub resource_common_data: ResourceCommonData, pub connector_auth_type: ConnectorAuthType, /// Contains flow-specific data required to construct a request and send it to the connector. diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs index 15a2ff69036..226067cef96 100644 --- a/crates/router/src/connector/dummyconnector.rs +++ b/crates/router/src/connector/dummyconnector.rs @@ -2,7 +2,7 @@ pub mod transformers; use std::fmt::Debug; -use common_utils::request::RequestContent; +use common_utils::{consts as common_consts, request::RequestContent}; use diesel_models::enums; use error_stack::{report, ResultExt}; @@ -62,12 +62,18 @@ where req: &types::RouterData<Flow, Request, Response>, _connectors: &settings::Connectors, ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { - let mut header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsAuthorizeType::get_content_type(self) - .to_string() - .into(), - )]; + let mut header = vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self) + .to_string() + .into(), + ), + ( + common_consts::TENANT_HEADER.to_string(), + req.tenant_id.get_string_repr().to_string().into(), + ), + ]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs index 09cebda4908..bedd7787a73 100644 --- a/crates/router/src/core/authentication.rs +++ b/crates/router/src/core/authentication.rs @@ -42,6 +42,7 @@ pub async fn perform_authentication( psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>, ) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> { let router_data = transformers::construct_authentication_router_data( + state, merchant_id, authentication_connector.clone(), payment_method_data, @@ -108,6 +109,7 @@ pub async fn perform_post_authentication( .attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {authentication_id}"))?; if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled { let router_data = transformers::construct_post_authentication_router_data( + state, authentication_connector.to_string(), business_profile, three_ds_connector_account, @@ -151,6 +153,7 @@ pub async fn perform_pre_authentication( let authentication = if authentication_connector.is_separate_version_call_required() { let router_data: core_types::authentication::PreAuthNVersionCallRouterData = transformers::construct_pre_authentication_router_data( + state, authentication_connector_name.clone(), card_number.clone(), &three_ds_connector_account, @@ -178,6 +181,7 @@ pub async fn perform_pre_authentication( let router_data: core_types::authentication::PreAuthNRouterData = transformers::construct_pre_authentication_router_data( + state, authentication_connector_name.clone(), card_number, &three_ds_connector_account, diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs index 30373d1408f..4e7e005c946 100644 --- a/crates/router/src/core/authentication/transformers.rs +++ b/crates/router/src/core/authentication/transformers.rs @@ -15,6 +15,7 @@ use crate::{ transformers::{ForeignFrom, ForeignTryFrom}, }, utils::ext_traits::OptionExt, + SessionState, }; const IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW: &str = @@ -24,6 +25,7 @@ const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str = #[allow(clippy::too_many_arguments)] pub fn construct_authentication_router_data( + state: &SessionState, merchant_id: common_utils::id_type::MerchantId, authentication_connector: String, payment_method_data: domain::PaymentMethodData, @@ -65,6 +67,7 @@ pub fn construct_authentication_router_data( webhook_url, }; construct_router_data( + state, authentication_connector, payment_method, merchant_id.clone(), @@ -76,6 +79,7 @@ pub fn construct_authentication_router_data( } pub fn construct_post_authentication_router_data( + state: &SessionState, authentication_connector: String, business_profile: domain::Profile, merchant_connector_account: payments_helpers::MerchantConnectorAccountType, @@ -90,6 +94,7 @@ pub fn construct_post_authentication_router_data( threeds_server_transaction_id, }; construct_router_data( + state, authentication_connector, PaymentMethod::default(), business_profile.merchant_id.clone(), @@ -101,6 +106,7 @@ pub fn construct_post_authentication_router_data( } pub fn construct_pre_authentication_router_data<F: Clone>( + state: &SessionState, authentication_connector: String, card_holder_account_number: cards::CardNumber, merchant_connector_account: &payments_helpers::MerchantConnectorAccountType, @@ -116,6 +122,7 @@ pub fn construct_pre_authentication_router_data<F: Clone>( card_holder_account_number, }; construct_router_data( + state, authentication_connector, PaymentMethod::default(), merchant_id, @@ -126,7 +133,9 @@ pub fn construct_pre_authentication_router_data<F: Clone>( ) } +#[allow(clippy::too_many_arguments)] pub fn construct_router_data<F: Clone, Req, Res>( + state: &SessionState, authentication_connector_name: String, payment_method: PaymentMethod, merchant_id: common_utils::id_type::MerchantId, @@ -144,6 +153,7 @@ pub fn construct_router_data<F: Clone, Req, Res>( flow: PhantomData, merchant_id, customer_id: None, + tenant_id: state.tenant.tenant_id.clone(), connector_customer: None, connector: authentication_connector_name, payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("authentication") 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 c413208b208..e6ff3fdbfca 100644 --- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs +++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs @@ -47,7 +47,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn construct_router_data<'a>( &self, - _state: &SessionState, + state: &SessionState, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, @@ -75,6 +75,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC flow: std::marker::PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id, + tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_string(), payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(), attempt_id: self.payment_attempt.attempt_id.clone(), 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 640e808d546..4dbe17d17b5 100644 --- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs +++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs @@ -71,6 +71,7 @@ pub async fn construct_fulfillment_router_data<'a>( let router_data = RouterData { flow: std::marker::PhantomData, merchant_id: merchant_account.get_id().clone(), + tenant_id: state.tenant.tenant_id.clone(), connector, payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), 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 5e354031185..21c5de5ed3b 100644 --- a/crates/router/src/core/fraud_check/flows/record_return.rs +++ b/crates/router/src/core/fraud_check/flows/record_return.rs @@ -45,7 +45,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn construct_router_data<'a>( &self, - _state: &SessionState, + state: &SessionState, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, @@ -69,6 +69,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh let router_data = RouterData { flow: std::marker::PhantomData, merchant_id: merchant_account.get_id().clone(), + tenant_id: state.tenant.tenant_id.clone(), customer_id, connector: connector_id.to_string(), payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(), 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 dde9ba52a2a..189edb5bc08 100644 --- a/crates/router/src/core/fraud_check/flows/sale_flow.rs +++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs @@ -42,7 +42,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn construct_router_data<'a>( &self, - _state: &SessionState, + state: &SessionState, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, @@ -69,6 +69,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp connector: connector_id.to_string(), payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(), attempt_id: self.payment_attempt.attempt_id.clone(), + tenant_id: state.tenant.tenant_id.clone(), status, payment_method: self .payment_attempt 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 673753ce4ef..7ddf41c509f 100644 --- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs +++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs @@ -49,7 +49,7 @@ impl #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] async fn construct_router_data<'a>( &self, - _state: &SessionState, + state: &SessionState, connector_id: &str, merchant_account: &domain::MerchantAccount, _key_store: &domain::MerchantKeyStore, @@ -77,6 +77,7 @@ impl let router_data = RouterData { flow: std::marker::PhantomData, merchant_id: merchant_account.get_id().clone(), + tenant_id: state.tenant.tenant_id.clone(), customer_id, connector: connector_id.to_string(), payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(), diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs index 15ceb9b1da2..414bb00e76e 100644 --- a/crates/router/src/core/mandate.rs +++ b/crates/router/src/core/mandate.rs @@ -110,6 +110,7 @@ pub async fn revoke_mandate( > = connector_data.connector.get_connector_integration(); let router_data = utils::construct_mandate_revoke_router_data( + &state, merchant_connector_account, &merchant_account, mandate.clone(), diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs index 5418d7b7a70..95736604fc5 100644 --- a/crates/router/src/core/mandate/utils.rs +++ b/crates/router/src/core/mandate/utils.rs @@ -7,6 +7,7 @@ use error_stack::ResultExt; use crate::{ core::{errors, payments::helpers}, types::{self, domain, PaymentAddress}, + SessionState, }; const IRRELEVANT_ATTEMPT_ID_IN_MANDATE_REVOKE_FLOW: &str = @@ -16,6 +17,7 @@ const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_MANDATE_REVOKE_FLOW: &str = "irrelevant_connector_request_reference_id_in_mandate_revoke_flow"; pub async fn construct_mandate_revoke_router_data( + state: &SessionState, merchant_connector_account: helpers::MerchantConnectorAccountType, merchant_account: &domain::MerchantAccount, mandate: Mandate, @@ -28,6 +30,7 @@ pub async fn construct_mandate_revoke_router_data( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id: Some(mandate.customer_id), + tenant_id: state.tenant.tenant_id.clone(), connector_customer: None, connector: mandate.connector, payment_id: mandate diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index b2c90e03b58..7f6e8c7fc86 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4035,6 +4035,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>( request, response, merchant_id: router_data.merchant_id, + tenant_id: router_data.tenant_id, address: router_data.address, amount_captured: router_data.amount_captured, minor_amount_captured: router_data.minor_amount_captured, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 79bcfb6a497..c6686912193 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -122,6 +122,7 @@ where .payment_id .get_string_repr() .to_owned(), + tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_data.payment_attempt.get_id().to_owned(), status: payment_data.payment_attempt.status, payment_method: diesel_models::enums::PaymentMethod::default(), @@ -301,6 +302,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( let router_data = types::RouterData { flow: PhantomData, merchant_id: merchant_account.get_id().clone(), + tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), @@ -464,6 +466,7 @@ pub async fn construct_payment_router_data_for_capture<'a>( // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), + tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data .payment_attempt @@ -599,6 +602,7 @@ pub async fn construct_router_data_for_psync<'a>( merchant_id: merchant_account.get_id().clone(), // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, + tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_owned(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_intent.id.get_string_repr().to_owned(), @@ -662,7 +666,7 @@ pub async fn construct_router_data_for_psync<'a>( #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn construct_payment_router_data_for_sdk_session<'a>( - _state: &'a SessionState, + state: &'a SessionState, payment_data: hyperswitch_domain_models::payments::PaymentIntentData<api::Session>, connector_id: &str, merchant_account: &domain::MerchantAccount, @@ -756,6 +760,7 @@ pub async fn construct_payment_router_data_for_sdk_session<'a>( // TODO: evaluate why we need customer id at the connector level. We already have connector customer id. customer_id, connector: connector_id.to_owned(), + tenant_id: state.tenant.tenant_id.clone(), // TODO: evaluate why we need payment id at the connector level. We already have connector reference id payment_id: payment_data.payment_intent.id.get_string_repr().to_owned(), // TODO: evaluate why we need attempt id at the connector level. We already have connector reference id @@ -944,6 +949,7 @@ where flow: PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id, + tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_owned(), payment_id: payment_data .payment_attempt diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs index 3c8432795a3..11be2ebfb5b 100644 --- a/crates/router/src/core/payouts.rs +++ b/crates/router/src/core/payouts.rs @@ -1216,9 +1216,13 @@ pub async fn create_recipient( ); if should_call_connector { // 1. Form router data - let router_data = - core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) - .await?; + let router_data = core_utils::construct_payout_router_data( + state, + connector_data, + merchant_account, + payout_data, + ) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -1396,9 +1400,13 @@ pub async fn check_payout_eligibility( payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let router_data = - core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) - .await?; + let router_data = core_utils::construct_payout_router_data( + state, + connector_data, + merchant_account, + payout_data, + ) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -1594,9 +1602,13 @@ pub async fn create_payout( payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let mut router_data = - core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) - .await?; + let mut router_data = core_utils::construct_payout_router_data( + state, + connector_data, + merchant_account, + payout_data, + ) + .await?; // 2. Get/Create access token access_token::create_access_token( @@ -1808,9 +1820,13 @@ pub async fn create_payout_retrieve( payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let mut router_data = - core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) - .await?; + let mut router_data = core_utils::construct_payout_router_data( + state, + connector_data, + merchant_account, + payout_data, + ) + .await?; // 2. Get/Create access token access_token::create_access_token( @@ -1964,9 +1980,13 @@ pub async fn create_recipient_disburse_account( payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let router_data = - core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) - .await?; + let router_data = core_utils::construct_payout_router_data( + state, + connector_data, + merchant_account, + payout_data, + ) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -2067,9 +2087,13 @@ pub async fn cancel_payout( payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let router_data = - core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) - .await?; + let router_data = core_utils::construct_payout_router_data( + state, + connector_data, + merchant_account, + payout_data, + ) + .await?; // 2. Fetch connector integration details let connector_integration: services::BoxedPayoutConnectorIntegrationInterface< @@ -2191,9 +2215,13 @@ pub async fn fulfill_payout( payout_data: &mut PayoutData, ) -> RouterResult<()> { // 1. Form Router data - let mut router_data = - core_utils::construct_payout_router_data(connector_data, merchant_account, payout_data) - .await?; + let mut router_data = core_utils::construct_payout_router_data( + state, + connector_data, + merchant_account, + payout_data, + ) + .await?; // 2. Get/Create access token access_token::create_access_token( diff --git a/crates/router/src/core/relay/utils.rs b/crates/router/src/core/relay/utils.rs index 946f8df7d64..0829934fdc7 100644 --- a/crates/router/src/core/relay/utils.rs +++ b/crates/router/src/core/relay/utils.rs @@ -71,6 +71,7 @@ pub async fn construct_relay_refund_router_data<'a, F>( flow: std::marker::PhantomData, merchant_id: merchant_id.clone(), customer_id: None, + tenant_id: state.tenant.tenant_id.clone(), connector: connector_name.to_string(), payment_id: IRRELEVANT_PAYMENT_INTENT_ID.to_string(), attempt_id: IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rs index 5ed1b63d721..2afd8477f1f 100644 --- a/crates/router/src/core/unified_authentication_service.rs +++ b/crates/router/src/core/unified_authentication_service.rs @@ -43,6 +43,7 @@ impl<F: Clone + Sync> UnifiedAuthenticationService<F> for ClickToPay { let pre_auth_router_data: hyperswitch_domain_models::types::UasPreAuthenticationRouterData = utils::construct_uas_router_data( + state, connector_name.to_string(), payment_method, payment_data.payment_attempt.merchant_id.clone(), @@ -81,6 +82,7 @@ impl<F: Clone + Sync> UnifiedAuthenticationService<F> for ClickToPay { let post_authentication_data = UasPostAuthenticationRequestData {}; let post_auth_router_data: hyperswitch_domain_models::types::UasPostAuthenticationRouterData = utils::construct_uas_router_data( + state, connector_name.to_string(), payment_method, payment_data.payment_attempt.merchant_id.clone(), diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rs index fe4f864604e..dfa56628c87 100644 --- a/crates/router/src/core/unified_authentication_service/utils.rs +++ b/crates/router/src/core/unified_authentication_service/utils.rs @@ -102,7 +102,9 @@ where Ok(router_data) } +#[allow(clippy::too_many_arguments)] pub fn construct_uas_router_data<F: Clone, Req, Res>( + state: &SessionState, authentication_connector_name: String, payment_method: PaymentMethod, merchant_id: common_utils::id_type::MerchantId, @@ -125,6 +127,7 @@ pub fn construct_uas_router_data<F: Clone, Req, Res>( payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("authentication") .get_string_repr() .to_owned(), + tenant_id: state.tenant.tenant_id.clone(), attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(), status: common_enums::AttemptStatus::default(), payment_method, diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs index c441e32581e..fac89112df8 100644 --- a/crates/router/src/core/utils.rs +++ b/crates/router/src/core/utils.rs @@ -54,6 +54,7 @@ const IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW: &str = "irrelevant_attempt_id_in_di #[cfg(all(feature = "payouts", feature = "v2", feature = "customer_v2"))] #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( + _state: &SessionState, _connector_data: &api::ConnectorData, _merchant_account: &domain::MerchantAccount, _payout_data: &mut PayoutData, @@ -68,6 +69,7 @@ pub async fn construct_payout_router_data<'a, F>( ))] #[instrument(skip_all)] pub async fn construct_payout_router_data<'a, F>( + state: &SessionState, connector_data: &api::ConnectorData, merchant_account: &domain::MerchantAccount, payout_data: &mut PayoutData, @@ -152,6 +154,7 @@ pub async fn construct_payout_router_data<'a, F>( flow: PhantomData, merchant_id: merchant_account.get_id().to_owned(), customer_id: customer_details.to_owned().map(|c| c.customer_id), + tenant_id: state.tenant.tenant_id.clone(), connector_customer: connector_customer_id, connector: connector_name.to_string(), payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout") @@ -330,6 +333,7 @@ pub async fn construct_refund_router_data<'a, F>( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), customer_id: payment_intent.customer_id.to_owned(), + tenant_id: state.tenant.tenant_id.clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), @@ -652,6 +656,7 @@ pub async fn construct_accept_dispute_router_data<'a>( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: dispute.connector.to_string(), + tenant_id: state.tenant.tenant_id.clone(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, @@ -753,6 +758,7 @@ pub async fn construct_submit_evidence_router_data<'a>( merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), + tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, @@ -851,6 +857,7 @@ pub async fn construct_upload_file_router_data<'a>( merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), + tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, @@ -978,6 +985,7 @@ pub async fn construct_payments_dynamic_tax_calculation_router_data<'a, F: Clone connector: merchant_connector_account.connector_name.clone(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), attempt_id: payment_attempt.attempt_id.clone(), + tenant_id: state.tenant.tenant_id.clone(), status: payment_attempt.status, payment_method: diesel_models::enums::PaymentMethod::default(), connector_auth_type, @@ -1076,6 +1084,7 @@ pub async fn construct_defend_dispute_router_data<'a>( merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), payment_id: payment_attempt.payment_id.get_string_repr().to_owned(), + tenant_id: state.tenant.tenant_id.clone(), attempt_id: payment_attempt.attempt_id.clone(), status: payment_attempt.status, payment_method, @@ -1169,6 +1178,7 @@ pub async fn construct_retrieve_file_router_data<'a>( flow: PhantomData, merchant_id: merchant_account.get_id().clone(), connector: connector_id.to_string(), + tenant_id: state.tenant.tenant_id.clone(), customer_id: None, connector_customer: None, payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("dispute") diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index ff9849958b5..474a0c628e2 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -1658,6 +1658,7 @@ async fn verify_webhook_source_verification_call( .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let router_data = construct_webhook_router_data( + state, connector_name, merchant_connector_account, merchant_account, diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs index 569cd330a07..39b7091e73c 100644 --- a/crates/router/src/core/webhooks/incoming_v2.rs +++ b/crates/router/src/core/webhooks/incoming_v2.rs @@ -665,6 +665,7 @@ async fn verify_webhook_source_verification_call( .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?; let router_data = construct_webhook_router_data( + state, connector_name, merchant_connector_account, merchant_account, diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs index b21ec0056c1..256fae78d4a 100644 --- a/crates/router/src/core/webhooks/utils.rs +++ b/crates/router/src/core/webhooks/utils.rs @@ -11,6 +11,7 @@ use crate::{ db::{get_and_deserialize_key, StorageInterface}, services::logger, types::{self, api, domain, PaymentAddress}, + SessionState, }; const IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW: &str = @@ -57,6 +58,7 @@ pub async fn is_webhook_event_disabled( } pub async fn construct_webhook_router_data<'a>( + state: &SessionState, connector_name: &str, merchant_connector_account: domain::MerchantConnectorAccount, merchant_account: &domain::MerchantAccount, @@ -74,6 +76,7 @@ pub async fn construct_webhook_router_data<'a>( merchant_id: merchant_account.get_id().clone(), connector: connector_name.to_string(), customer_id: None, + tenant_id: state.tenant.tenant_id.clone(), payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("source_verification_flow") .get_string_repr() .to_owned(), diff --git a/crates/router/src/services/conversion_impls.rs b/crates/router/src/services/conversion_impls.rs index 9bb88cf4ecc..8572add041e 100644 --- a/crates/router/src/services/conversion_impls.rs +++ b/crates/router/src/services/conversion_impls.rs @@ -1,3 +1,4 @@ +use common_utils::id_type; use error_stack::ResultExt; #[cfg(feature = "frm")] use hyperswitch_domain_models::router_data_v2::flow_common_types::FrmFlowData; @@ -23,17 +24,19 @@ fn get_irrelevant_id_string(id_name: &str, flow_name: &str) -> String { format!("irrelevant {id_name} in {flow_name} flow") } fn get_default_router_data<F, Req, Resp>( + tenant_id: id_type::TenantId, flow_name: &str, request: Req, response: Result<Resp, router_data::ErrorResponse>, ) -> RouterData<F, Req, Resp> { RouterData { + tenant_id, flow: std::marker::PhantomData, - merchant_id: common_utils::id_type::MerchantId::get_irrelevant_merchant_id(), + merchant_id: id_type::MerchantId::get_irrelevant_merchant_id(), customer_id: None, connector_customer: None, connector: get_irrelevant_id_string("connector", flow_name), - payment_id: common_utils::id_type::PaymentId::get_irrelevant_id(flow_name) + payment_id: id_type::PaymentId::get_irrelevant_id(flow_name) .get_string_repr() .to_owned(), attempt_id: get_irrelevant_id_string("attempt_id", flow_name), @@ -93,6 +96,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AccessTo let resource_common_data = Self {}; Ok(RouterDataV2 { flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), @@ -109,7 +113,12 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AccessTo let Self {} = new_router_data.resource_common_data; let request = new_router_data.request.clone(); let response = new_router_data.response.clone(); - let router_data = get_default_router_data("access token", request, response); + let router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "access token", + request, + response, + ); Ok(router_data) } } @@ -153,6 +162,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentF }; Ok(RouterDataV2 { flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), @@ -196,8 +206,12 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentF connector_response, payment_method_status, } = new_router_data.resource_common_data; - let mut router_data = - get_default_router_data("payment", new_router_data.request, new_router_data.response); + let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "payment", + new_router_data.request, + new_router_data.response, + ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; @@ -256,6 +270,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for RefundFl }; Ok(RouterDataV2 { flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), @@ -282,8 +297,12 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for RefundFl connector_request_reference_id, refund_id, } = new_router_data.resource_common_data; - let mut router_data = - get_default_router_data("refund", new_router_data.request, new_router_data.response); + let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "refund", + new_router_data.request, + new_router_data.response, + ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.payment_id = payment_id; @@ -323,6 +342,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for Disputes }; Ok(RouterDataV2 { flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), @@ -348,6 +368,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for Disputes dispute_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), "Disputes", new_router_data.request, new_router_data.response, @@ -386,6 +407,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FrmFlowD minor_amount_captured: old_router_data.minor_amount_captured, }; Ok(RouterDataV2 { + tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), @@ -412,8 +434,12 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FrmFlowD amount_captured, minor_amount_captured, } = new_router_data.resource_common_data; - let mut router_data = - get_default_router_data("frm", new_router_data.request, new_router_data.response); + let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "frm", + new_router_data.request, + new_router_data.response, + ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; @@ -446,6 +472,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FilesFlo }; Ok(RouterDataV2 { flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), @@ -466,8 +493,12 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FilesFlo connector_meta_data, connector_request_reference_id, } = new_router_data.resource_common_data; - let mut router_data = - get_default_router_data("files", new_router_data.request, new_router_data.response); + let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "files", + new_router_data.request, + new_router_data.response, + ); router_data.merchant_id = merchant_id; router_data.payment_id = payment_id; router_data.attempt_id = attempt_id; @@ -489,6 +520,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for WebhookS merchant_id: old_router_data.merchant_id.clone(), }; Ok(RouterDataV2 { + tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), @@ -505,6 +537,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for WebhookS { let Self { merchant_id } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), "webhook source verify", new_router_data.request, new_router_data.response, @@ -532,6 +565,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for MandateR }; Ok(RouterDataV2 { flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), @@ -551,6 +585,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for MandateR payment_id, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), "mandate revoke", new_router_data.request, new_router_data.response, @@ -559,7 +594,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for MandateR router_data.customer_id = Some(customer_id); router_data.payment_id = payment_id .unwrap_or_else(|| { - common_utils::id_type::PaymentId::get_irrelevant_id("mandate revoke") + id_type::PaymentId::get_irrelevant_id("mandate revoke") .get_string_repr() .to_owned() }) @@ -588,6 +623,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PayoutFl quote_id: old_router_data.quote_id.clone(), }; Ok(RouterDataV2 { + tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), @@ -613,8 +649,12 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PayoutFl payout_method_data, quote_id, } = new_router_data.resource_common_data; - let mut router_data = - get_default_router_data("payout", new_router_data.request, new_router_data.response); + let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "payout", + new_router_data.request, + new_router_data.response, + ); router_data.merchant_id = merchant_id; router_data.customer_id = customer_id; router_data.connector_customer = connector_customer; @@ -642,6 +682,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> address: old_router_data.address.clone(), }; Ok(RouterDataV2 { + tenant_id: old_router_data.tenant_id.clone(), flow: std::marker::PhantomData, resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), @@ -662,6 +703,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> address, } = new_router_data.resource_common_data; let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), "external authentication", new_router_data.request, new_router_data.response, @@ -692,6 +734,7 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowD }; Ok(RouterDataV2 { flow: std::marker::PhantomData, + tenant_id: old_router_data.tenant_id.clone(), resource_common_data, connector_auth_type: old_router_data.connector_auth_type.clone(), request: old_router_data.request.clone(), @@ -709,8 +752,12 @@ impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowD authenticate_by, source_authentication_id, } = new_router_data.resource_common_data; - let mut router_data = - get_default_router_data("uas", new_router_data.request, new_router_data.response); + let mut router_data = get_default_router_data( + new_router_data.tenant_id.clone(), + "uas", + new_router_data.request, + new_router_data.response, + ); router_data.connector = authenticate_by; router_data.authentication_id = Some(source_authentication_id); Ok(router_data) diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index f9c9e6edb26..2ae2af92478 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -914,6 +914,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2) merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), + tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, connector_auth_type: data.connector_auth_type.clone(), @@ -983,6 +984,7 @@ impl<F1, F2> merchant_id: data.merchant_id.clone(), connector: data.connector.clone(), attempt_id: data.attempt_id.clone(), + tenant_id: data.tenant_id.clone(), status: data.status, payment_method: data.payment_method, connector_auth_type: data.connector_auth_type.clone(), diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 47d8add58c3..4d248bbf0b4 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -65,6 +65,7 @@ impl VerifyConnectorData { fn get_router_data<F, R1, R2>( &self, + state: &SessionState, request_data: R1, access_token: Option<types::AccessToken>, ) -> types::RouterData<F, R1, R2> { @@ -81,6 +82,7 @@ impl VerifyConnectorData { attempt_id: attempt_id.clone(), description: None, customer_id: None, + tenant_id: state.tenant.tenant_id.clone(), merchant_id: common_utils::id_type::MerchantId::default(), reference_id: None, access_token, @@ -132,7 +134,7 @@ pub trait VerifyConnector { ) -> errors::RouterResponse<()> { let authorize_data = connector_data.get_payment_authorize_data(); let access_token = Self::get_access_token(state, connector_data.clone()).await?; - let router_data = connector_data.get_router_data(authorize_data, access_token); + let router_data = connector_data.get_router_data(state, authorize_data, access_token); let request = connector_data .connector diff --git a/crates/router/src/types/api/verify_connector/paypal.rs b/crates/router/src/types/api/verify_connector/paypal.rs index f7de86ceebd..d7c4fca748e 100644 --- a/crates/router/src/types/api/verify_connector/paypal.rs +++ b/crates/router/src/types/api/verify_connector/paypal.rs @@ -17,7 +17,7 @@ impl VerifyConnector for connector::Paypal { ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { let token_data: types::AccessTokenRequestData = connector_data.connector_auth.clone().try_into()?; - let router_data = connector_data.get_router_data(token_data, None); + let router_data = connector_data.get_router_data(state, token_data, None); let request = connector_data .connector diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 645b81e7069..8b3372d7dec 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -27,6 +27,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { flow: PhantomData, merchant_id, customer_id: Some(id_type::CustomerId::try_from(Cow::from("aci")).unwrap()), + tenant_id: id_type::TenantId::try_from_string("public".to_string()).unwrap(), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), @@ -145,6 +146,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { flow: PhantomData, merchant_id, customer_id: Some(id_type::CustomerId::try_from(Cow::from("aci")).unwrap()), + tenant_id: id_type::TenantId::try_from_string("public".to_string()).unwrap(), connector: "aci".to_string(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 03ea1f42e83..2cf3dc965fd 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -490,6 +490,8 @@ pub trait ConnectorActions: Connector { merchant_id, customer_id: Some(common_utils::generate_customer_id_of_default_length()), connector: self.get_name(), + tenant_id: common_utils::id_type::TenantId::try_from_string("public".to_string()) + .unwrap(), payment_id: uuid::Uuid::new_v4().to_string(), attempt_id: uuid::Uuid::new_v4().to_string(), status: enums::AttemptStatus::default(),
2025-01-08T08:03:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix ## Description <!-- Describe your changes in detail --> Add tenant id in dummy connector requests ## 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). --> Dummy connector calls `http://localhost:8080` plus respective endpoints. But when multi tenancy is enabled app server expects the requests to have `x-tenant-id` header in the request. Absence of this would call the dummy connector requests to fail. This PR addresses that ## 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 `stripe_test` PaymentsConnector ```bash curl --location 'http://localhost:8080/account/1736322673/connectors' \ --header 'cache-control: no-cache' \ --header 'content-type: application/json' \ --header 'x-tenant-id: public' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "stripe_test", "connector_label": "stripe_test_default", "disabled": false, "test_mode": true, "payment_methods_enabled": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "debit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Mastercard" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Visa" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Interac" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "AmericanExpress" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "JCB" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "DinersClub" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "Discover" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "CartesBancaires" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false }, { "payment_method_type": "credit", "card_networks": [ "UnionPay" ], "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "metadata": {}, "connector_account_details": { "api_key": "test_key", "auth_type": "HeaderKey" }, "additional_merchant_data": null, "status": "active", "pm_auth_config": null, "connector_wallets_details": null }' ``` 2. Create a Payment with `stripe_test` as the connector ```bash curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: public' \ --header 'api-key: dev_Pkb2Z4Lk00hQnSOtWXWxGL7NjZ41ySJ1KRLrmMRnbNCChaPnj0m8Uc9EnYE9SW86' \ --data-raw '{ "amount": 600, "currency": "USD", "confirm": true, "capture_method": "automatic", "customer_id": "HScustomer1234", "email": "[email protected]", "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", "connector": ["stripe_test"], "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" } }, "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" } }' ``` This should return status code 200 <img width="1284" alt="Screenshot 2025-01-08 at 1 32 46 PM" src="https://github.com/user-attachments/assets/6863c4fb-534c-4b64-9ceb-dcf216e163ee" /> ## 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
d594173de2aefaedce0c808f5d4903d0ad7eb447
juspay/hyperswitch
juspay__hyperswitch-7018
Bug: [BUG] connector's txn ID exceeding 512 characters are not being stored in DB ### Bug Description Worldpay's payment flows generate a txn identifier which is quite long - as it's a JWE. This is stored in DB for querying or performing any other processor related operation on the payment. DB schema for storing such long identifiers has been 512 characters. Recently, we started to see a txn ID being returned exceeding 512 characters due to which the application started throwing errors on DB update operations. ### Expected Behavior DB should respect and store Worldpay IDs exceeding 512 characters. ### Actual Behavior DB is not storing Worldpay IDs. ### Steps To Reproduce Route a payment through Worldpay connector. ### Possible solution For keeping backwards compatibility in mind, and wanting to ensure that query plan related errors are not encountered, the straightforward approach for handling this is to add a new column with required type and migrate any existing data to this column. ### 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`): `rustc 1.80.1 (3f5fd8dd4 2024-08-06)` 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/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 4e88d5c0fde..0377a3e8183 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1420,7 +1420,7 @@ crate::impl_to_sql_from_sql_json!(BrowserInformation); /// 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. +/// processor_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 { @@ -1438,7 +1438,7 @@ impl ConnectorTransactionId { } } - /// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and connector_transaction_data + /// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and processor_transaction_data pub fn form_id_and_data(src: String) -> (Self, Option<String>) { let txn_id = Self::from(src.clone()); match txn_id { @@ -1456,10 +1456,10 @@ impl ConnectorTransactionId { (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(), + message: "processor_transaction_data is empty for HashedData variant".to_string(), }) .attach_printable(format!( - "connector_transaction_data is empty for connector_transaction_id {}", + "processor_transaction_data is empty for connector_transaction_id {}", id ))), } diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs index d6272c34060..367382b98bf 100644 --- a/crates/diesel_models/src/capture.rs +++ b/crates/diesel_models/src/capture.rs @@ -30,7 +30,9 @@ pub struct Capture { pub capture_sequence: i16, // reference to the capture at connector side pub connector_response_reference_id: Option<String>, + /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, + pub processor_capture_data: Option<String>, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize)] @@ -55,7 +57,9 @@ pub struct CaptureNew { pub connector_capture_id: Option<ConnectorTransactionId>, pub capture_sequence: i16, pub connector_response_reference_id: Option<String>, + /// INFO: This field is deprecated and replaced by processor_capture_data pub connector_capture_data: Option<String>, + pub processor_capture_data: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -64,7 +68,7 @@ pub enum CaptureUpdate { status: storage_enums::CaptureStatus, connector_capture_id: Option<ConnectorTransactionId>, connector_response_reference_id: Option<String>, - connector_capture_data: Option<String>, + processor_capture_data: Option<String>, }, ErrorUpdate { status: storage_enums::CaptureStatus, @@ -84,7 +88,7 @@ pub struct CaptureUpdateInternal { pub modified_at: Option<PrimitiveDateTime>, pub connector_capture_id: Option<ConnectorTransactionId>, pub connector_response_reference_id: Option<String>, - pub connector_capture_data: Option<String>, + pub processor_capture_data: Option<String>, } impl CaptureUpdate { @@ -97,7 +101,7 @@ impl CaptureUpdate { modified_at: _, connector_capture_id, connector_response_reference_id, - connector_capture_data, + processor_capture_data, } = self.into(); Capture { status: status.unwrap_or(source.status), @@ -108,7 +112,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), + processor_capture_data: processor_capture_data.or(source.processor_capture_data), ..source } } @@ -122,13 +126,13 @@ impl From<CaptureUpdate> for CaptureUpdateInternal { status, connector_capture_id: connector_transaction_id, connector_response_reference_id, - connector_capture_data, + processor_capture_data, } => Self { status: Some(status), connector_capture_id: connector_transaction_id, modified_at: now, connector_response_reference_id, - connector_capture_data, + processor_capture_data, ..Self::default() }, CaptureUpdate::ErrorUpdate { diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs index 94dcf00f755..54e60891532 100644 --- a/crates/diesel_models/src/kv.rs +++ b/crates/diesel_models/src/kv.rs @@ -227,7 +227,7 @@ pub enum Insertable { pub enum Updateable { PaymentIntentUpdate(Box<PaymentIntentUpdateMems>), PaymentAttemptUpdate(Box<PaymentAttemptUpdateMems>), - RefundUpdate(RefundUpdateMems), + RefundUpdate(Box<RefundUpdateMems>), CustomerUpdate(CustomerUpdateMems), AddressUpdate(Box<AddressUpdateMems>), PayoutsUpdate(PayoutsUpdateMems), diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index eab95f81316..b3b3f44f3c9 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -171,8 +171,10 @@ pub struct PaymentAttempt { pub card_network: Option<String>, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, + /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, + pub processor_transaction_data: Option<String>, pub card_discovery: Option<storage_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, } @@ -183,7 +185,7 @@ impl ConnectorTransactionIdTrait for PaymentAttempt { match self .connector_transaction_id .as_ref() - .map(|txn_id| txn_id.get_txn_id(self.connector_transaction_data.as_ref())) + .map(|txn_id| txn_id.get_txn_id(self.processor_transaction_data.as_ref())) .transpose() { Ok(txn_id) => txn_id, @@ -871,8 +873,8 @@ 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>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, + pub processor_transaction_data: Option<String>, pub card_discovery: Option<common_enums::CardDiscovery>, pub charges: Option<common_types::payments::ConnectorChargeResponseData>, } @@ -1055,7 +1057,7 @@ impl PaymentAttemptUpdate { card_network, shipping_cost, order_tax_amount, - connector_transaction_data, + processor_transaction_data, connector_mandate_detail, card_discovery, charges, @@ -1113,8 +1115,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), + processor_transaction_data: processor_transaction_data + .or(source.processor_transaction_data), connector_mandate_detail: connector_mandate_detail.or(source.connector_mandate_detail), card_discovery: card_discovery.or(source.card_discovery), charges: charges.or(source.charges), @@ -1483,7 +1485,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { // card_network: None, // shipping_cost: None, // order_tax_amount: None, - // connector_transaction_data: None, + // processor_transaction_data: None, // connector_mandate_detail, // }, // PaymentAttemptUpdate::ConnectorMandateDetailUpdate { @@ -2167,7 +2169,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2224,7 +2226,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2313,7 +2315,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost, order_tax_amount, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail, card_discovery, charges: None, @@ -2371,7 +2373,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2430,7 +2432,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2489,7 +2491,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2546,7 +2548,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail, card_discovery: None, charges: None, @@ -2603,7 +2605,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2631,7 +2633,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_mandate_detail, charges, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2657,7 +2659,9 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_code, unified_message, payment_method_data, - connector_transaction_data, + processor_transaction_data, + connector_mandate_detail, + charges, amount: None, net_amount: None, currency: None, @@ -2686,9 +2690,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_mandate_detail, card_discovery: None, - charges, } } PaymentAttemptUpdate::ErrorUpdate { @@ -2705,7 +2707,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { payment_method_data, authentication_type, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2724,7 +2726,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, payment_method_data, authentication_type, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -2814,7 +2816,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2877,7 +2879,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -2893,7 +2895,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_response_reference_id, updated_by, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2909,7 +2911,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { error_reason, connector_response_reference_id, updated_by, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -2962,7 +2964,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_response_reference_id, updated_by, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -2976,7 +2978,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector_transaction_id, connector_response_reference_id, updated_by, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -3075,7 +3077,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3133,7 +3135,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3146,7 +3148,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { updated_by, charges, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -3158,7 +3160,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { connector: connector.map(Some), modified_at: common_utils::date_time::now(), updated_by, - connector_transaction_data, + processor_transaction_data, + charges, amount: None, net_amount: None, currency: None, @@ -3203,7 +3206,6 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { order_tax_amount: None, connector_mandate_detail: None, card_discovery: None, - charges, } } PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate { @@ -3258,7 +3260,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3318,7 +3320,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, @@ -3333,7 +3335,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_message, connector_transaction_id, } => { - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -3348,7 +3350,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { unified_code: unified_code.map(Some), unified_message: unified_message.map(Some), connector_transaction_id, - connector_transaction_data, + processor_transaction_data, amount: None, net_amount: None, currency: None, @@ -3445,7 +3447,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { card_network: None, shipping_cost: None, order_tax_amount: None, - connector_transaction_data: None, + processor_transaction_data: None, connector_mandate_detail: None, card_discovery: None, charges: None, diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs index 7a32e410961..3f02948d2a4 100644 --- a/crates/diesel_models/src/query/capture.rs +++ b/crates/diesel_models/src/query/capture.rs @@ -74,7 +74,7 @@ impl ConnectorTransactionIdTrait for Capture { match self .connector_capture_id .as_ref() - .map(|capture_id| capture_id.get_txn_id(self.connector_capture_data.as_ref())) + .map(|capture_id| capture_id.get_txn_id(self.processor_capture_data.as_ref())) .transpose() { Ok(capture_id) => capture_id, diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index b929481d64d..f19c3252c60 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -51,11 +51,15 @@ 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, + /// INFO: This field is deprecated and replaced by processor_refund_data pub connector_refund_data: Option<String>, + /// INFO: This field is deprecated and replaced by processor_transaction_data pub connector_transaction_data: Option<String>, pub split_refunds: Option<common_types::refunds::SplitRefund>, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub processor_refund_data: Option<String>, + pub processor_transaction_data: Option<String>, } #[derive( @@ -99,9 +103,9 @@ 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>, pub split_refunds: Option<common_types::refunds::SplitRefund>, + pub processor_refund_data: Option<String>, + pub processor_transaction_data: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -113,7 +117,7 @@ pub enum RefundUpdate { refund_error_message: Option<String>, refund_arn: String, updated_by: String, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, }, MetadataAndReasonUpdate { metadata: Option<pii::SecretSerdeValue>, @@ -125,7 +129,7 @@ pub enum RefundUpdate { sent_to_gateway: bool, refund_status: storage_enums::RefundStatus, updated_by: String, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, }, ErrorUpdate { refund_status: Option<storage_enums::RefundStatus>, @@ -133,7 +137,7 @@ pub enum RefundUpdate { refund_error_code: Option<String>, updated_by: String, connector_refund_id: Option<ConnectorTransactionId>, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, }, @@ -158,7 +162,7 @@ pub struct RefundUpdateInternal { refund_error_code: Option<String>, updated_by: String, modified_at: PrimitiveDateTime, - connector_refund_data: Option<String>, + processor_refund_data: Option<String>, unified_code: Option<String>, unified_message: Option<String>, } @@ -176,7 +180,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, + processor_refund_data: self.processor_refund_data, unified_code: self.unified_code, unified_message: self.unified_message, ..source @@ -194,7 +198,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_arn, updated_by, - connector_refund_data, + processor_refund_data, } => Self { connector_refund_id: Some(connector_refund_id), refund_status: Some(refund_status), @@ -202,7 +206,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_error_message, refund_arn: Some(refund_arn), updated_by, - connector_refund_data, + processor_refund_data, metadata: None, refund_reason: None, refund_error_code: None, @@ -225,7 +229,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { refund_arn: None, refund_error_code: None, modified_at: common_utils::date_time::now(), - connector_refund_data: None, + processor_refund_data: None, unified_code: None, unified_message: None, }, @@ -234,13 +238,13 @@ impl From<RefundUpdate> for RefundUpdateInternal { sent_to_gateway, refund_status, updated_by, - connector_refund_data, + processor_refund_data, } => Self { connector_refund_id, sent_to_gateway: Some(sent_to_gateway), refund_status: Some(refund_status), updated_by, - connector_refund_data, + processor_refund_data, refund_error_message: None, refund_arn: None, metadata: None, @@ -258,14 +262,14 @@ impl From<RefundUpdate> for RefundUpdateInternal { unified_message, updated_by, connector_refund_id, - connector_refund_data, + processor_refund_data, } => Self { refund_status, refund_error_message, refund_error_code, updated_by, connector_refund_id, - connector_refund_data, + processor_refund_data, sent_to_gateway: None, refund_arn: None, metadata: None, @@ -290,7 +294,7 @@ impl From<RefundUpdate> for RefundUpdateInternal { metadata: None, refund_reason: None, modified_at: common_utils::date_time::now(), - connector_refund_data: None, + processor_refund_data: None, unified_code: None, unified_message: None, }, @@ -311,7 +315,7 @@ impl RefundUpdate { refund_error_code, updated_by, modified_at: _, - connector_refund_data, + processor_refund_data, unified_code, unified_message, } = self.into(); @@ -326,7 +330,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), + processor_refund_data: processor_refund_data.or(source.processor_refund_data), unified_code: unified_code.or(source.unified_code), unified_message: unified_message.or(source.unified_message), ..source @@ -340,7 +344,7 @@ pub struct RefundCoreWorkflow { 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>, + pub processor_transaction_data: Option<String>, } #[cfg(feature = "v1")] @@ -358,7 +362,7 @@ impl ConnectorTransactionIdTrait for Refund { match self .connector_refund_id .as_ref() - .map(|refund_id| refund_id.get_txn_id(self.connector_refund_data.as_ref())) + .map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref())) .transpose() { Ok(refund_id) => refund_id, @@ -374,7 +378,7 @@ impl ConnectorTransactionIdTrait for Refund { fn get_connector_transaction_id(&self) -> &String { match self .connector_transaction_id - .get_txn_id(self.connector_transaction_data.as_ref()) + .get_txn_id(self.processor_transaction_data.as_ref()) { Ok(txn_id) => txn_id, @@ -418,6 +422,7 @@ mod tests { "connector_transaction_data": null "unified_code": null, "unified_message": null, + "processor_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 bbde92ea040..2e8219c5ab4 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -271,6 +271,7 @@ diesel::table! { connector_response_reference_id -> Nullable<Varchar>, #[max_length = 512] connector_capture_data -> Nullable<Varchar>, + processor_capture_data -> Nullable<Text>, } } @@ -909,6 +910,7 @@ diesel::table! { #[max_length = 512] connector_transaction_data -> Nullable<Varchar>, connector_mandate_detail -> Nullable<Jsonb>, + processor_transaction_data -> Nullable<Text>, card_discovery -> Nullable<CardDiscovery>, charges -> Nullable<Jsonb>, } @@ -1261,6 +1263,8 @@ diesel::table! { unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, + processor_refund_data -> Nullable<Text>, + processor_transaction_data -> Nullable<Text>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index d17d4f8478a..ab2195526f5 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -278,8 +278,7 @@ diesel::table! { capture_sequence -> Int2, #[max_length = 128] connector_response_reference_id -> Nullable<Varchar>, - #[max_length = 512] - connector_capture_data -> Nullable<Varchar>, + processor_capture_data -> Nullable<Text>, } } @@ -872,8 +871,7 @@ diesel::table! { tax_on_surcharge -> Nullable<Int8>, payment_method_billing_address -> Nullable<Bytea>, redirection_data -> Nullable<Jsonb>, - #[max_length = 512] - connector_payment_data -> Nullable<Varchar>, + connector_payment_data -> Nullable<Text>, connector_token_details -> Nullable<Jsonb>, #[max_length = 64] id -> Varchar, @@ -1198,15 +1196,13 @@ 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>, split_refunds -> Nullable<Jsonb>, #[max_length = 255] unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, + processor_refund_data -> Nullable<Text>, + processor_transaction_data -> Nullable<Text>, } } diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs index c063545d81f..27085424083 100644 --- a/crates/diesel_models/src/user/sample_data.rs +++ b/crates/diesel_models/src/user/sample_data.rs @@ -201,7 +201,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>, + pub processor_transaction_data: Option<String>, pub connector_mandate_detail: Option<ConnectorMandateReferenceId>, pub card_discovery: Option<common_enums::CardDiscovery>, } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs index 6e19c20edab..a43ffb7cfa1 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs @@ -149,14 +149,12 @@ pub struct ExpiryDate { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BillingAddress { - #[serde(skip_serializing_if = "Option::is_none")] - pub address1: Option<Secret<String>>, + pub address1: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub address2: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub address3: Option<Secret<String>>, - #[serde(skip_serializing_if = "Option::is_none")] - pub city: Option<String>, + pub city: String, #[serde(skip_serializing_if = "Option::is_none")] pub state: Option<Secret<String>>, pub postal_code: Secret<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index 28cbca418a3..65c884601de 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -90,10 +90,16 @@ fn fetch_payment_instrument( billing_address.and_then(|addr| addr.address.clone()) { Some(BillingAddress { - address1: address.line1, + address1: address.line1.get_required_value("line1").change_context( + errors::ConnectorError::MissingRequiredField { + field_name: "line1", + }, + )?, address2: address.line2, address3: address.line3, - city: address.city, + city: address.city.get_required_value("city").change_context( + errors::ConnectorError::MissingRequiredField { field_name: "city" }, + )?, state: address.state, postal_code: address.zip.get_required_value("zip").change_context( errors::ConnectorError::MissingRequiredField { field_name: "zip" }, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 361973daf94..d2eb8e44e87 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -1503,7 +1503,7 @@ 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 + let (connector_transaction_id, processor_transaction_data) = self .connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -1570,12 +1570,14 @@ 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(), connector_mandate_detail: self.connector_mandate_detail, + processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + // Below fields are deprecated. Please add any new fields above this line. + connector_transaction_data: None, }) } diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index c5b9b9a0430..a9f5ae59493 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -13514,5 +13514,14 @@ pub fn get_worldpay_billing_required_fields() -> HashMap<String, RequiredFieldIn value: None, }, ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserAddressPincode, + value: None, + }, + ), ]) } diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 4616be81a5f..25ae8c84c39 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1663,7 +1663,7 @@ 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) = + let (connector_capture_id, processor_capture_data) = match resource_id { types::ResponseId::NoResponseId => (None, None), types::ResponseId::ConnectorTransactionId(id) @@ -1679,7 +1679,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( )?, connector_capture_id: connector_capture_id.clone(), connector_response_reference_id, - connector_capture_data: connector_capture_data.clone(), + processor_capture_data: processor_capture_data.clone(), }; let capture_update_list = vec![( multiple_capture_data.get_latest_capture().clone(), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index e2967e4ba59..5659fef6296 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -3839,7 +3839,7 @@ impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { connector_response_reference_id, .. } => { - let (connector_capture_id, connector_capture_data) = match resource_id { + let (connector_capture_id, processor_capture_data) = match resource_id { types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => { (None, None) } @@ -3853,7 +3853,7 @@ impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate { status: enums::CaptureStatus::foreign_try_from(status)?, connector_capture_id, connector_response_reference_id, - connector_capture_data, + processor_capture_data, }) } types::CaptureSyncResponse::Error { diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 4d8cc195693..938bf1a8369 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -235,7 +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, + processor_refund_data: None, unified_code: None, unified_message: None, }) @@ -249,7 +249,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, + processor_refund_data: None, unified_code: None, unified_message: None, }) @@ -332,7 +332,7 @@ 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, + processor_refund_data: None, unified_code: Some(unified_code), unified_message: Some(unified_message), } @@ -341,7 +341,7 @@ pub async fn trigger_refund_to_gateway( // match on connector integrity checks match router_data_res.integrity_check.clone() { Err(err) => { - let (refund_connector_transaction_id, connector_refund_data) = + let (refund_connector_transaction_id, processor_refund_data) = err.connector_transaction_id.map_or((None, None), |txn_id| { let (refund_id, refund_data) = ConnectorTransactionId::form_id_and_data(txn_id); @@ -363,7 +363,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, + processor_refund_data, unified_code: None, unified_message: None, } @@ -378,7 +378,7 @@ pub async fn trigger_refund_to_gateway( )), ) } - let (connector_refund_id, connector_refund_data) = + let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); storage::RefundUpdate::Update { connector_refund_id, @@ -387,7 +387,7 @@ pub async fn trigger_refund_to_gateway( refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), - connector_refund_data, + processor_refund_data, } } } @@ -677,7 +677,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, + processor_refund_data: None, unified_code: None, unified_message: None, } @@ -691,7 +691,7 @@ pub async fn sync_refund_with_gateway( ("merchant_id", merchant_account.get_id().clone()), ), ); - let (refund_connector_transaction_id, connector_refund_data) = err + let (refund_connector_transaction_id, processor_refund_data) = err .connector_transaction_id .map_or((None, None), |refund_id| { let (refund_id, refund_data) = @@ -707,13 +707,13 @@ 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, + processor_refund_data, unified_code: None, unified_message: None, } } Ok(()) => { - let (connector_refund_id, connector_refund_data) = + let (connector_refund_id, processor_refund_data) = ConnectorTransactionId::form_id_and_data(response.connector_refund_id); storage::RefundUpdate::Update { connector_refund_id, @@ -722,7 +722,7 @@ pub async fn sync_refund_with_gateway( refund_error_message: None, refund_arn: "".to_string(), updated_by: storage_scheme.to_string(), - connector_refund_data, + processor_refund_data, } } }, @@ -882,7 +882,7 @@ 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) = + let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(connector_transaction_id); let refund_create_req = storage::RefundNew { refund_id: refund_id.to_string(), @@ -912,8 +912,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, + processor_transaction_data, + processor_refund_data: None, }; let refund = match db @@ -1584,7 +1584,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(), + processor_transaction_data: refund.processor_transaction_data.clone(), } } diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 2c0d9b5b5c5..8b562978804 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -1023,7 +1023,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, + processor_refund_data: None, }; db.update_refund( refund.to_owned(), diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs index cbc27f918d4..a2e4a90d66d 100644 --- a/crates/router/src/db/capture.rs +++ b/crates/router/src/db/capture.rs @@ -198,7 +198,9 @@ 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, + processor_capture_data: capture.processor_capture_data, + // Below fields are deprecated. Please add any new fields above this line. + connector_capture_data: None, }; captures.push(capture.clone()); Ok(capture) diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index e07821cd9a8..07bdfa3f77d 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -435,10 +435,13 @@ mod storage { charges: new.charges.clone(), split_refunds: new.split_refunds.clone(), organization_id: new.organization_id.clone(), - connector_refund_data: new.connector_refund_data.clone(), - connector_transaction_data: new.connector_transaction_data.clone(), unified_code: None, unified_message: None, + processor_refund_data: new.processor_refund_data.clone(), + processor_transaction_data: new.processor_transaction_data.clone(), + // Below fields are deprecated. Please add any new fields above this line. + connector_refund_data: None, + connector_transaction_data: None, }; let field = format!( @@ -620,12 +623,12 @@ mod storage { let redis_entry = kv::TypedSql { op: kv::DBOperation::Update { - updatable: Box::new(kv::Updateable::RefundUpdate( + updatable: Box::new(kv::Updateable::RefundUpdate(Box::new( kv::RefundUpdateMems { orig: this, update_data: refund, }, - )), + ))), }, }; @@ -932,10 +935,13 @@ impl RefundInterface for MockDb { charges: new.charges, split_refunds: new.split_refunds, organization_id: new.organization_id, - connector_refund_data: new.connector_refund_data, - connector_transaction_data: new.connector_transaction_data, unified_code: None, unified_message: None, + processor_refund_data: new.processor_refund_data.clone(), + processor_transaction_data: new.processor_transaction_data.clone(), + // Below fields are deprecated. Please add any new fields above this line. + connector_refund_data: None, + connector_transaction_data: None, }; refunds.push(refund.clone()); Ok(refund) diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs index 1773d7f3a17..c82a921fe17 100644 --- a/crates/router/src/types/storage/payment_attempt.rs +++ b/crates/router/src/types/storage/payment_attempt.rs @@ -63,6 +63,8 @@ impl PaymentAttemptExt for PaymentAttempt { capture_sequence, connector_capture_id: None, connector_response_reference_id: None, + processor_capture_data: None, + // Below fields are deprecated. Please add any new fields above this line. connector_capture_data: None, }) } diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index c5652e6cbfa..e189deb9487 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -277,7 +277,7 @@ pub async fn generate_sample_data( psd2_sca_exemption_type: None, platform_merchant_id: None, }; - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), @@ -359,14 +359,14 @@ pub async fn generate_sample_data( organization_id: org_id.clone(), shipping_cost: None, order_tax_amount: None, - connector_transaction_data, + processor_transaction_data, connector_mandate_detail: None, card_discovery: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { refunds_count += 1; - let (connector_transaction_id, connector_transaction_data) = + let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); Some(RefundNew { refund_id: common_utils::generate_id_with_default_len("test"), @@ -401,8 +401,8 @@ pub async fn generate_sample_data( charges: None, split_refunds: None, organization_id: org_id.clone(), - connector_refund_data: None, - connector_transaction_data, + processor_refund_data: None, + processor_transaction_data, }) } else { None diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 8a8e8d4e4a8..847e9c14da0 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1434,7 +1434,7 @@ impl DataModelExt for PaymentAttempt { type StorageModel = DieselPaymentAttempt; fn to_storage_model(self) -> Self::StorageModel { - let (connector_transaction_id, connector_transaction_data) = self + let (connector_transaction_id, processor_transaction_data) = self .connector_transaction_id .map(ConnectorTransactionId::form_id_and_data) .map(|(txn_id, txn_data)| (Some(txn_id), txn_data)) @@ -1509,12 +1509,14 @@ 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(), connector_mandate_detail: self.connector_mandate_detail, + processor_transaction_data, card_discovery: self.card_discovery, charges: self.charges, + // Below fields are deprecated. Please add any new fields above this line. + connector_transaction_data: None, } } diff --git a/migrations/2025-01-09-135057_add_processor_transaction_data/down.sql b/migrations/2025-01-09-135057_add_processor_transaction_data/down.sql new file mode 100644 index 00000000000..bbba634e6e2 --- /dev/null +++ b/migrations/2025-01-09-135057_add_processor_transaction_data/down.sql @@ -0,0 +1,8 @@ +ALTER TABLE payment_attempt +DROP COLUMN IF EXISTS processor_transaction_data; + +ALTER TABLE refund DROP COLUMN IF EXISTS processor_refund_data; + +ALTER TABLE refund DROP COLUMN IF EXISTS processor_transaction_data; + +ALTER TABLE captures DROP COLUMN IF EXISTS processor_capture_data; \ No newline at end of file diff --git a/migrations/2025-01-09-135057_add_processor_transaction_data/up.sql b/migrations/2025-01-09-135057_add_processor_transaction_data/up.sql new file mode 100644 index 00000000000..81e9cdcd074 --- /dev/null +++ b/migrations/2025-01-09-135057_add_processor_transaction_data/up.sql @@ -0,0 +1,11 @@ +ALTER TABLE payment_attempt +ADD COLUMN IF NOT EXISTS processor_transaction_data TEXT; + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS processor_refund_data TEXT; + +ALTER TABLE refund +ADD COLUMN IF NOT EXISTS processor_transaction_data TEXT; + +ALTER TABLE captures +ADD COLUMN IF NOT EXISTS processor_capture_data TEXT; \ No newline at end of file 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 3926a02afa6..03059985875 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 @@ -51,7 +51,7 @@ ADD COLUMN payment_method_type_v2 VARCHAR, ADD COLUMN tax_on_surcharge BIGINT, ADD COLUMN payment_method_billing_address BYTEA, ADD COLUMN redirection_data JSONB, - ADD COLUMN connector_payment_data VARCHAR(512), + ADD COLUMN connector_payment_data TEXT, ADD COLUMN connector_token_details JSONB; -- Change the type of the column from JSON to JSONB diff --git a/v2_migrations/2024-11-08-081847_drop_v1_columns/down.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql similarity index 98% rename from v2_migrations/2024-11-08-081847_drop_v1_columns/down.sql rename to v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql index f67b9b2e7ac..8d0fedce089 100644 --- a/v2_migrations/2024-11-08-081847_drop_v1_columns/down.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/down.sql @@ -76,7 +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 connector_transaction_data TEXT, ADD COLUMN capture_method "CaptureMethod", ADD COLUMN capture_on TIMESTAMP, ADD COLUMN mandate_id VARCHAR(64), diff --git a/v2_migrations/2024-11-08-081847_drop_v1_columns/up.sql b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql similarity index 92% rename from v2_migrations/2024-11-08-081847_drop_v1_columns/up.sql rename to v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql index e19f8631f62..caac00abd0f 100644 --- a/v2_migrations/2024-11-08-081847_drop_v1_columns/up.sql +++ b/v2_migrations/2025-01-13-081847_drop_v1_columns/up.sql @@ -75,6 +75,7 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN payment_method, DROP COLUMN connector_transaction_id, DROP COLUMN connector_transaction_data, + DROP COLUMN processor_transaction_data, DROP COLUMN capture_method, DROP COLUMN capture_on, DROP COLUMN mandate_id, @@ -89,3 +90,10 @@ ALTER TABLE payment_attempt DROP COLUMN attempt_id, DROP COLUMN payment_method_billing_address_id, DROP COLUMN connector_mandate_detail, DROP COLUMN charge_id; + +-- Run below queries only when V1 is deprecated +ALTER TABLE refund DROP COLUMN connector_refund_data, + DROP COLUMN connector_transaction_data; + +-- Run below queries only when V1 is deprecated +ALTER TABLE captures DROP COLUMN connector_capture_data;
2025-01-09T14:03:34Z
## 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 introduces below changes around Worldpay connector ### Core changes - add new columns (TEXT) for storing the JWE based connector transaction ID - `payment_attempt` - `processor_transaction_data` - `refund` - `processor_transaction_data` and `processor_refund_data` - `captures` - `processor_capture_data` ### Connector integration changes (Worldpay only) - make `line1` and `city` non optional in payment request - add `zip` in dynamic required fields for Worldpay cards ### QA - add cypress test cases for dynamic fields for Worldpay ### Additional Changes - [ ] This PR modifies the API contract - [x] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables ## Motivation and Context This PR keeps Worldpay's payments integration intact. ## How did you test it? <details> <summary>1. Route a payment through Worldpay</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Wc9lMS2KJ6l35ehmlSsR3dwwiOvGZaWLmkk3BqRLRe6vqa1rkiNJ3mVza3U1EdWh' \ --data-raw '{"amount":100,"currency":"USD","confirm":true,"capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","customer_id":"cus_JgZZwioWal2CoKgsLXEb","email":"[email protected]","name":"John Doe","phone":"999999999","profile_id":"pro_NyQDoa1SRAC4rZ5QjDv9","phone_country_code":"+65","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://hyperswitch.io","setup_future_usage":"off_session","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector":["worldpay"],"payment_method":"card","payment_method_data":{"card":{"card_number":"4917610000000000","card_exp_month":"03","card_exp_year":"2030","card_cvc":"737","nick_name":"JD"},"billing":{"email":"[email protected]","address":{"first_name":"John","last_name":"US"}}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"US","first_name":"John","last_name":"US"}},"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true}}' Response {"payment_id":"pay_wY8cJE6MgvO13EE0vIyx","merchant_id":"merchant_1736497521","status":"succeeded","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":0,"amount_received":100,"connector":"worldpay","client_secret":"pay_wY8cJE6MgvO13EE0vIyx_secret_42yawtMDmMbJf15nP8TP","created":"2025-01-10T09:35:51.576Z","currency":"USD","customer_id":"cus_JgZZwioWal2CoKgsLXEb","customer":{"id":"cus_JgZZwioWal2CoKgsLXEb","name":"John Doe","email":"[email protected]","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":"0000","card_type":"CREDIT","card_network":"Visa","card_issuer":"BANKPOLSKAKASAOPIEKIS.A.(BANKPEKAOSA)","card_issuing_country":"POLAND","card_isin":"491761","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John US","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":null,"country":null,"line1":null,"line2":null,"line3":null,"zip":null,"state":null,"first_name":"John","last_name":"US"},"phone":null,"email":"[email protected]"}},"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":"John","last_name":"US"},"phone":null,"email":null},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://hyperswitch.io/","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":"cus_JgZZwioWal2CoKgsLXEb","created_at":1736501751,"expires":1736505351,"secret":"epk_d47f022a1de246bebe54d6898c408836"},"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNi4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLJDIunO0DhjaUi3niPBfv98:VUQcO2wyJ4EGywR:l4ssCpZY8cZeCeMgt1ol:GABqQG6u+T:u3sfHv3ezSOJxioRTixsThPEhzFW4ZZ6mObj3CK0rnFndcM0swvZMqgQwSEj5tBsydfzM4XKX20O6Nme96ha9twqxTSQIfr1rtl9V3q7fw3w5O9UZT4vQi9BMyCcaHkWSD:RbCWCcmiQqa5EPu9d6p6Bt0lCYl:Np4aWZ0pJCEaV4g9uGTAlKDtig0jKl6MU3ArZWtDWm7LKjrd+hQ9RR:Z491q0vLPK+etFBNqgwjiceXMDUvG7lafYHHR5Ak5lI+Sa7YaesgGkXXzgiDTOQzNK9UH+W9rzqFt6t5VcedliH8B9MKI3IKaPyVavYo4YzMmVfRID7seWtakAYMzGq+YEqwioSKkuPXbo=","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"95f4583f-a8ee-426c-acd8-f475d85b0bef","payment_link":null,"profile_id":"pro_NyQDoa1SRAC4rZ5QjDv9","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_jJbWUjL9iGOEfQo8Uw8P","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-01-10T09:50:51.576Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_xeVtmDykRQKg3pvt4EI5","payment_method_status":"active","updated":"2025-01-10T09:35:52.981Z","split_payments":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":"https://try.access.worldpay.com/tokens/eyJrIjoxLCJkIjoiWndnc0NNQjJXNkZFTkl4TUZUZFBKdzhQdm9OS3JjYnFnT0haOThuOVE4RT0ifQ"} </details> <details> <summary>2. Create a payment link without passing in details</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_Wc9lMS2KJ6l35ehmlSsR3dwwiOvGZaWLmkk3BqRLRe6vqa1rkiNJ3mVza3U1EdWh' \ --data-raw '{"authentication_type":"three_ds","customer_id":"cus_JgZZwioWal2CoKgsLXEb","profile_id":"pro_NyQDoa1SRAC4rZ5QjDv9","amount":100,"currency":"USD","payment_link":true,"connector":["worldpay"],"description":"This is my description of why this payment was requested.","capture_method":"automatic","billing":{"address":{"line2":"Harrison Street","line3":"Harrison Street","state":"CA","first_name":"John","last_name":"Doe"},"phone":{"number":"8056594427","country_code":"+91"}},"email":"[email protected]","session_expiry":100000,"return_url":"https://example.com","payment_link_config":{"theme":"#0E103D","logo":"https://hyperswitch.io/favicon.ico","seller_name":"Hyperswitch Inc.","enabled_saved_payment_method":true,"hide_card_nickname_field":true,"show_card_form_by_default":true,"transaction_details":[{"key":"Policy Number","value":"938478327648","ui_configuration":{"is_key_bold":false,"is_value_bold":false,"position":2}},{"key":"Business Country","value":"Germany","ui_configuration":{"is_key_bold":false,"is_value_bold":false,"position":1}},{"key":"Product Name","value":"Life Insurance Elite","ui_configuration":{"is_key_bold":false,"is_value_bold":false,"position":3}}]}}' - Open payment link <img width="599" alt="Screenshot 2025-01-10 at 3 08 50 PM" src="https://github.com/user-attachments/assets/8a3b0a75-ff52-4f5e-b889-460e5261556b" /> </details> <details> <summary>3. Dynamic field tests</summary> <img width="642" alt="Screenshot 2025-01-10 at 3 10 29 PM" src="https://github.com/user-attachments/assets/5929d89e-341c-4a86-a488-5a77d983a08e" /> </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
bfcaf003427caf9580a2520b3f2efc8773818905
juspay/hyperswitch
juspay__hyperswitch-7000
Bug: test(cypress): add a test for in memory cache
2024-12-30T11:36:48Z
## 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 --> Add Test Cases for testing In Memory Cache ### 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). --> Currently test cases were not present. ## 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="1025" alt="Screenshot 2024-12-30 at 3 28 02 PM" src="https://github.com/user-attachments/assets/8059ee3c-f695-452f-ac74-3909849559d3" /> <img width="1028" alt="Screenshot 2024-12-30 at 3 28 10 PM" src="https://github.com/user-attachments/assets/d6d12ca8-3802-4a3a-94d8-0382bf8e1fb2" /> ## 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
c4d36b506e159f39acff17e13f72b5c53edec184
juspay/hyperswitch
juspay__hyperswitch-6987
Bug: [FEATURE] Integrate global SR ### Feature Description In dynamic routing, we need to keep track of global success rates as well. We need to support the integration for tracking global SR ### Possible Implementation The dynamic routing modules and corresponding proto file would need to be 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 ### 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/routing.rs b/crates/api_models/src/routing.rs index 2e570816ab4..8e502767575 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -779,6 +779,7 @@ impl Default for SuccessBasedRoutingConfig { duration_in_mins: Some(5), max_total_count: Some(2), }), + specificity_level: SuccessRateSpecificityLevel::default(), }), } } @@ -801,6 +802,8 @@ pub struct SuccessBasedRoutingConfigBody { pub default_success_rate: Option<f64>, pub max_aggregates_size: Option<u32>, pub current_block_threshold: Option<CurrentBlockThreshold>, + #[serde(default)] + pub specificity_level: SuccessRateSpecificityLevel, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] @@ -809,6 +812,14 @@ pub struct CurrentBlockThreshold { pub max_total_count: Option<u64>, } +#[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum SuccessRateSpecificityLevel { + #[default] + Merchant, + Global, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedRoutingPayloadWrapper { pub updated_config: SuccessBasedRoutingConfig, @@ -849,6 +860,7 @@ impl SuccessBasedRoutingConfigBody { .as_mut() .map(|threshold| threshold.update(current_block_threshold)); } + self.specificity_level = new.specificity_level } } diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rs index c055359d8b0..90cf4689080 100644 --- a/crates/diesel_models/src/dynamic_routing_stats.rs +++ b/crates/diesel_models/src/dynamic_routing_stats.rs @@ -20,6 +20,7 @@ pub struct DynamicRoutingStatsNew { pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, pub payment_method_type: Option<common_enums::PaymentMethodType>, + pub global_success_based_connector: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Queryable, Selectable, Insertable)] @@ -40,4 +41,5 @@ pub struct DynamicRoutingStats { pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, pub payment_method_type: Option<common_enums::PaymentMethodType>, + pub global_success_based_connector: Option<String>, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index dfe3d5acc23..7930ad5d9ae 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -435,6 +435,8 @@ diesel::table! { created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, + #[max_length = 64] + global_success_based_connector -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index b5361f4c95c..13abf8ee64b 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -447,6 +447,8 @@ diesel::table! { created_at -> Timestamp, #[max_length = 64] payment_method_type -> Nullable<Varchar>, + #[max_length = 64] + global_success_based_connector -> Nullable<Varchar>, } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs index fca4ff61fcc..278a2b50d15 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs @@ -1,15 +1,17 @@ use api_models::routing::{ CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus, - SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, + SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody, SuccessRateSpecificityLevel, }; use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom}; use error_stack::ResultExt; use router_env::{instrument, logger, tracing}; pub use success_rate::{ - success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig, + success_rate_calculator_client::SuccessRateCalculatorClient, CalGlobalSuccessRateConfig, + CalGlobalSuccessRateRequest, CalGlobalSuccessRateResponse, CalSuccessRateConfig, CalSuccessRateRequest, CalSuccessRateResponse, CurrentBlockThreshold as DynamicCurrentThreshold, InvalidateWindowsRequest, - InvalidateWindowsResponse, LabelWithStatus, UpdateSuccessRateWindowConfig, + InvalidateWindowsResponse, LabelWithStatus, + SuccessRateSpecificityLevel as ProtoSpecificityLevel, UpdateSuccessRateWindowConfig, UpdateSuccessRateWindowRequest, UpdateSuccessRateWindowResponse, }; #[allow( @@ -51,6 +53,15 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { id: String, headers: GrpcHeaders, ) -> DynamicRoutingResult<InvalidateWindowsResponse>; + /// To calculate both global and merchant specific success rate for the list of chosen connectors + async fn calculate_entity_and_global_success_rate( + &self, + id: String, + success_rate_based_config: SuccessBasedRoutingConfig, + params: String, + label_input: Vec<RoutableConnectorChoice>, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<CalGlobalSuccessRateResponse>; } #[async_trait::async_trait] @@ -113,6 +124,7 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { .transpose()?; let labels_with_status = label_input + .clone() .into_iter() .map(|conn_choice| LabelWithStatus { label: conn_choice.routable_connector_choice.to_string(), @@ -120,12 +132,21 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { }) .collect(); + let global_labels_with_status = label_input + .into_iter() + .map(|conn_choice| LabelWithStatus { + label: conn_choice.routable_connector_choice.connector.to_string(), + status: conn_choice.status, + }) + .collect(); + let request = grpc_client::create_grpc_request( UpdateSuccessRateWindowRequest { id, params, labels_with_status, config, + global_labels_with_status, }, headers, ); @@ -165,6 +186,55 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { Ok(response) } + + async fn calculate_entity_and_global_success_rate( + &self, + id: String, + success_rate_based_config: SuccessBasedRoutingConfig, + params: String, + label_input: Vec<RoutableConnectorChoice>, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<CalGlobalSuccessRateResponse> { + let labels = label_input + .clone() + .into_iter() + .map(|conn_choice| conn_choice.to_string()) + .collect::<Vec<_>>(); + + let global_labels = label_input + .into_iter() + .map(|conn_choice| conn_choice.connector.to_string()) + .collect::<Vec<_>>(); + + let config = success_rate_based_config + .config + .map(ForeignTryFrom::foreign_try_from) + .transpose()?; + + let request = grpc_client::create_grpc_request( + CalGlobalSuccessRateRequest { + entity_id: id, + entity_params: params, + entity_labels: labels, + global_labels, + config, + }, + headers, + ); + + let response = self + .clone() + .fetch_entity_and_global_success_rate(request) + .await + .change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure( + "Failed to fetch the entity and global success rate".to_string(), + ))? + .into_inner(); + + logger::info!(dynamic_routing_response=?response); + + Ok(response) + } } impl ForeignTryFrom<CurrentBlockThreshold> for DynamicCurrentThreshold { @@ -216,6 +286,30 @@ impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalSuccessRateConfig { .change_context(DynamicRoutingError::MissingRequiredField { field: "default_success_rate".to_string(), })?, + specificity_level: match config.specificity_level { + SuccessRateSpecificityLevel::Merchant => Some(ProtoSpecificityLevel::Entity.into()), + SuccessRateSpecificityLevel::Global => Some(ProtoSpecificityLevel::Global.into()), + }, + }) + } +} + +impl ForeignTryFrom<SuccessBasedRoutingConfigBody> for CalGlobalSuccessRateConfig { + type Error = error_stack::Report<DynamicRoutingError>; + fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> { + Ok(Self { + entity_min_aggregates_size: config + .min_aggregates_size + .get_required_value("min_aggregate_size") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "min_aggregates_size".to_string(), + })?, + entity_default_success_rate: config + .default_success_rate + .get_required_value("default_success_rate") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "default_success_rate".to_string(), + })?, }) } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 32c2402e108..9ad89500eb9 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -624,6 +624,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::StraightThroughAlgorithm, api_models::routing::ConnectorVolumeSplit, api_models::routing::ConnectorSelection, + api_models::routing::SuccessRateSpecificityLevel, api_models::routing::ToggleDynamicRoutingQuery, api_models::routing::ToggleDynamicRoutingPath, api_models::routing::ast::RoutableChoiceKind, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 1395563a30a..ca14e3e7e48 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -714,7 +714,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( ); let success_based_connectors = client - .calculate_success_rate( + .calculate_entity_and_global_success_rate( business_profile.get_id().get_string_repr().into(), success_based_routing_configs.clone(), success_based_routing_config_params.clone(), @@ -730,28 +730,34 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( let payment_status_attribute = get_desired_payment_status_for_success_routing_metrics(payment_attempt.status); - let first_success_based_connector_label = &success_based_connectors - .labels_with_score + let first_merchant_success_based_connector = &success_based_connectors + .entity_scores_with_labels .first() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable( "unable to fetch the first connector from list of connectors obtained from dynamic routing service", - )? - .label - .to_string(); + )?; - let (first_success_based_connector, _) = first_success_based_connector_label + let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label .split_once(':') .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable(format!( "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service", - first_success_based_connector_label + first_merchant_success_based_connector.label ))?; + let first_global_success_based_connector = &success_based_connectors + .global_scores_with_labels + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to fetch the first global connector from list of connectors obtained from dynamic routing service", + )?; + let outcome = get_success_based_metrics_outcome_for_payment( payment_status_attribute, payment_connector.to_string(), - first_success_based_connector.to_string(), + first_merchant_success_based_connector_label.to_string(), ); let dynamic_routing_stats = DynamicRoutingStatsNew { @@ -760,7 +766,8 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( merchant_id: payment_attempt.merchant_id.to_owned(), profile_id: payment_attempt.profile_id.to_owned(), amount: payment_attempt.get_total_amount(), - success_based_routing_connector: first_success_based_connector.to_string(), + success_based_routing_connector: first_merchant_success_based_connector_label + .to_string(), payment_connector: payment_connector.to_string(), payment_method_type: payment_attempt.payment_method_type, currency: payment_attempt.currency, @@ -770,6 +777,9 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( payment_status: payment_attempt.status, conclusive_classification: outcome, created_at: common_utils::date_time::now(), + global_success_based_connector: Some( + first_global_success_based_connector.label.to_string(), + ), }; core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add( @@ -788,8 +798,20 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( ), ), ( - "success_based_routing_connector", - first_success_based_connector.to_string(), + "merchant_specific_success_based_routing_connector", + first_merchant_success_based_connector_label.to_string(), + ), + ( + "merchant_specific_success_based_routing_connector_score", + first_merchant_success_based_connector.score.to_string(), + ), + ( + "global_success_based_routing_connector", + first_global_success_based_connector.label.to_string(), + ), + ( + "global_success_based_routing_connector_score", + first_global_success_based_connector.score.to_string(), ), ("payment_connector", payment_connector.to_string()), ( diff --git a/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/down.sql b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/down.sql new file mode 100644 index 00000000000..c99db9a384d --- /dev/null +++ b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE dynamic_routing_stats +DROP COLUMN IF EXISTS global_success_based_connector; \ No newline at end of file diff --git a/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/up.sql b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/up.sql new file mode 100644 index 00000000000..81e00a9753c --- /dev/null +++ b/migrations/2025-01-07-101337_global_sr_connector_dynamic_routing/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE dynamic_routing_stats +ADD COLUMN IF NOT EXISTS global_success_based_connector VARCHAR(64); \ No newline at end of file diff --git a/proto/success_rate.proto b/proto/success_rate.proto index f49618bc4b6..17d566af356 100644 --- a/proto/success_rate.proto +++ b/proto/success_rate.proto @@ -7,6 +7,8 @@ service SuccessRateCalculator { rpc UpdateSuccessRateWindow (UpdateSuccessRateWindowRequest) returns (UpdateSuccessRateWindowResponse); rpc InvalidateWindows (InvalidateWindowsRequest) returns (InvalidateWindowsResponse); + + rpc FetchEntityAndGlobalSuccessRate (CalGlobalSuccessRateRequest) returns (CalGlobalSuccessRateResponse); } // API-1 types @@ -20,6 +22,12 @@ message CalSuccessRateRequest { message CalSuccessRateConfig { uint32 min_aggregates_size = 1; double default_success_rate = 2; + optional SuccessRateSpecificityLevel specificity_level = 3; +} + +enum SuccessRateSpecificityLevel { + ENTITY = 0; + GLOBAL = 1; } message CalSuccessRateResponse { @@ -31,12 +39,13 @@ message LabelWithScore { string label = 2; } - // API-2 types +// API-2 types message UpdateSuccessRateWindowRequest { string id = 1; string params = 2; repeated LabelWithStatus labels_with_status = 3; UpdateSuccessRateWindowConfig config = 4; + repeated LabelWithStatus global_labels_with_status = 5; } message LabelWithStatus { @@ -68,9 +77,28 @@ message InvalidateWindowsRequest { } message InvalidateWindowsResponse { - enum InvalidationStatus { + enum InvalidationStatus { WINDOW_INVALIDATION_SUCCEEDED = 0; WINDOW_INVALIDATION_FAILED = 1; } InvalidationStatus status = 1; +} + +// API-4 types +message CalGlobalSuccessRateRequest { + string entity_id = 1; + string entity_params = 2; + repeated string entity_labels = 3; + repeated string global_labels = 4; + CalGlobalSuccessRateConfig config = 5; +} + +message CalGlobalSuccessRateConfig { + uint32 entity_min_aggregates_size = 1; + double entity_default_success_rate = 2; +} + +message CalGlobalSuccessRateResponse { + repeated LabelWithScore entity_scores_with_labels = 1; + repeated LabelWithScore global_scores_with_labels = 2; } \ No newline at end of file
2024-12-26T13:46:40Z
## 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 --> Integrate global Success rates for dynamic routing ### 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. toggle success based routing with dynamic connector selection enabled ``` curl --location --request POST 'http://localhost:8080/account/sarthak2/business_profile/pro_F5mC1GGXHPLTtfcBnZEP/dynamic_routing/success_based/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_RQxKf8JqHb5tTfTp13JMnI7TyWgXIHaa2AP5VkjLtst1CRJPArSfqasfGQI1oIAQ' ``` 2. Set volume split for dynamic routing ``` curl --location --request POST 'http://localhost:8080/account/sarthak2/business_profile/pro_F5mC1GGXHPLTtfcBnZEP/dynamic_routing/set_volume_split?split=80' \ --header 'api-key: dev_RQxKf8JqHb5tTfTp13JMnI7TyWgXIHaa2AP5VkjLtst1CRJPArSfqasfGQI1oIAQ' ``` 3. Make a payment 4. Global SR connector should be populated in DB <img width="639" alt="image" src="https://github.com/user-attachments/assets/1fadcb60-21d1-4958-8511-9a3872bb3daf" /> ## 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
72904842ed0092e16e2d9980e1d4968df03cafb6
juspay/hyperswitch
juspay__hyperswitch-6999
Bug: feat(roles): edge cases for multi-tenancy - I Add tenant_id in custom roles Add generic query to search across all tenants Close https://github.com/juspay/hyperswitch-cloud/issues/7998 Close https://github.com/juspay/hyperswitch-cloud/issues/7998 Close https://github.com/juspay/hyperswitch-cloud/issues/8026
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs index 6f6a1404ee2..2ab58ec2382 100644 --- a/crates/diesel_models/src/query/role.rs +++ b/crates/diesel_models/src/query/role.rs @@ -32,14 +32,18 @@ impl Role { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, - dsl::role_id.eq(role_id.to_owned()).and( - dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id - .eq(org_id.to_owned()) - .and(dsl::scope.eq(RoleScope::Organization))), - ), + dsl::role_id + .eq(role_id.to_owned()) + .and(dsl::tenant_id.eq(tenant_id.to_owned())) + .and( + dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id + .eq(org_id.to_owned()) + .and(dsl::scope.eq(RoleScope::Organization))), + ), ) .await } @@ -49,11 +53,13 @@ impl Role { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) + .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())) .and( dsl::scope.eq(RoleScope::Organization).or(dsl::merchant_id @@ -64,15 +70,17 @@ impl Role { .await } - pub async fn find_by_role_id_and_org_id( + pub async fn find_by_role_id_org_id_tenant_id( conn: &PgPooledConn, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::role_id .eq(role_id.to_owned()) + .and(dsl::tenant_id.eq(tenant_id.to_owned())) .and(dsl::org_id.eq(org_id.to_owned())), ) .await @@ -108,12 +116,16 @@ impl Role { conn: &PgPooledConn, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> StorageResult<Vec<Self>> { - let predicate = dsl::org_id.eq(org_id.to_owned()).and( - dsl::scope.eq(RoleScope::Organization).or(dsl::merchant_id - .eq(merchant_id.to_owned()) - .and(dsl::scope.eq(RoleScope::Merchant))), - ); + let predicate = dsl::tenant_id + .eq(tenant_id.to_owned()) + .and(dsl::org_id.eq(org_id.to_owned())) + .and( + dsl::scope.eq(RoleScope::Organization).or(dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::scope.eq(RoleScope::Merchant))), + ); generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, @@ -127,13 +139,14 @@ impl Role { pub async fn generic_roles_list_for_org( conn: &PgPooledConn, + tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, entity_type: Option<common_enums::EntityType>, limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() - .filter(dsl::org_id.eq(org_id)) + .filter(dsl::tenant_id.eq(tenant_id).and(dsl::org_id.eq(org_id))) .into_boxed(); if let Some(merchant_id) = merchant_id { diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index bb07f671824..01fa05e925a 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -294,4 +294,34 @@ impl UserRole { }, } } + + pub async fn list_user_roles_by_user_id_across_tenants( + conn: &PgPooledConn, + user_id: String, + limit: Option<u32>, + ) -> StorageResult<Vec<Self>> { + let mut query = <Self as HasTable>::table() + .filter(dsl::user_id.eq(user_id)) + .into_boxed(); + 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, _, _>( + query.get_results_async(conn), + generics::db_metrics::DatabaseOperation::Filter, + ) + .await + { + Ok(value) => Ok(value), + Err(err) => match err { + DieselError::NotFound => { + Err(report!(err)).change_context(errors::DatabaseError::NotFound) + } + _ => Err(report!(err)).change_context(errors::DatabaseError::Others), + }, + } + } } diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index 8199bd3979c..16728801933 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -19,6 +19,7 @@ pub struct Role { pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, + pub tenant_id: id_type::TenantId, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -36,6 +37,7 @@ pub struct RoleNew { pub last_modified_at: PrimitiveDateTime, pub last_modified_by: String, pub entity_type: enums::EntityType, + pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 37a39cb731a..f5b10e091ce 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1308,6 +1308,8 @@ diesel::table! { last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, + #[max_length = 64] + tenant_id -> Varchar, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 3e27f29427b..2de2309ba20 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1255,6 +1255,8 @@ diesel::table! { last_modified_by -> Varchar, #[max_length = 64] entity_type -> Varchar, + #[max_length = 64] + tenant_id -> Varchar, } } diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 8fe30aa59d4..8fb4f2ac2c1 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1925,32 +1925,57 @@ 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_and_org_id(&state, &role_id, &auth.org_id) - .await - .change_context(UserErrors::InternalServerError) - .change_context(OpenSearchError::UnknownError)?; + let role_info = RoleInfo::from_role_id_org_id_tenant_id( + &state, + &role_id, + &auth.org_id, + auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), + ) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; 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 - .global_store - .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { - user_id: &auth.user_id, - tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_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 user_roles: HashSet<UserRole> = match role_info.get_entity_type() { + EntityType::Tenant => state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &auth.user_id, + tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), + org_id: None, + 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(), + EntityType::Organization | EntityType::Merchant | EntityType::Profile => state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &auth.user_id, + tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_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 @@ -1959,12 +1984,15 @@ pub mod routes { let state = Arc::clone(&state); let role_id = user_role.role_id.clone(); let org_id = user_role.org_id.clone().unwrap_or_default(); + let tenant_id = &user_role.tenant_id; async move { - RoleInfo::from_role_id_and_org_id(&state, &role_id, &org_id) - .await - .change_context(UserErrors::InternalServerError) - .change_context(OpenSearchError::UnknownError) - .map(|role_info| (role_id, role_info)) + RoleInfo::from_role_id_org_id_tenant_id( + &state, &role_id, &org_id, tenant_id, + ) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError) + .map(|role_info| (role_id, role_info)) } }) .collect::<FuturesUnordered<_>>() @@ -2047,32 +2075,57 @@ pub mod routes { indexed_req, |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; - let role_info = RoleInfo::from_role_id_and_org_id(&state, &role_id, &auth.org_id) - .await - .change_context(UserErrors::InternalServerError) - .change_context(OpenSearchError::UnknownError)?; + let role_info = RoleInfo::from_role_id_org_id_tenant_id( + &state, + &role_id, + &auth.org_id, + auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), + ) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; 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 - .global_store - .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { - user_id: &auth.user_id, - tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_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 user_roles: HashSet<UserRole> = match role_info.get_entity_type() { + EntityType::Tenant => state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &auth.user_id, + tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), + org_id: None, + 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(), + EntityType::Organization | EntityType::Merchant | EntityType::Profile => state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &auth.user_id, + tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_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() @@ -2080,12 +2133,15 @@ pub mod routes { let state = Arc::clone(&state); let role_id = user_role.role_id.clone(); let org_id = user_role.org_id.clone().unwrap_or_default(); + let tenant_id = &user_role.tenant_id; async move { - RoleInfo::from_role_id_and_org_id(&state, &role_id, &org_id) - .await - .change_context(UserErrors::InternalServerError) - .change_context(OpenSearchError::UnknownError) - .map(|role_info| (role_id, role_info)) + RoleInfo::from_role_id_org_id_tenant_id( + &state, &role_id, &org_id, tenant_id, + ) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError) + .map(|role_info| (role_id, role_info)) } }) .collect::<FuturesUnordered<_>>() diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index a7c60f33ff7..52d7d6a252e 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -116,10 +116,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_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -633,6 +637,10 @@ async fn handle_invitation( &request.role_id, &user_from_token.merchant_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; @@ -1155,10 +1163,14 @@ pub async fn resend_invite( .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; - let invitee_role_info = roles::RoleInfo::from_role_id_and_org_id( + let invitee_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -1401,7 +1413,7 @@ pub async fn create_tenant_user( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get merchants list for org")? .pop() - .ok_or(UserErrors::InternalServerError) + .ok_or(UserErrors::InvalidRoleOperation) .attach_printable("No merchants found in the tenancy")?; let new_user = domain::NewUser::try_from(( @@ -1490,10 +1502,14 @@ pub async fn list_user_roles_details( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; - let requestor_role_info = roles::RoleInfo::from_role_id_and_org_id( + let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InternalServerError) @@ -1644,10 +1660,14 @@ pub async fn list_user_roles_details( .collect::<HashSet<_>>() .into_iter() .map(|role_id| async { - let role_info = roles::RoleInfo::from_role_id_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -2757,10 +2777,14 @@ 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_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -2834,10 +2858,14 @@ 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_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -2909,10 +2937,14 @@ 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_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -3001,10 +3033,14 @@ pub async fn switch_org_for_user( .into()); } - let role_info = roles::RoleInfo::from_role_id_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) @@ -3092,12 +3128,20 @@ pub async fn switch_org_for_user( request.org_id.clone(), role_id.clone(), profile_id.clone(), - user_from_token.tenant_id, + user_from_token.tenant_id.clone(), ) .await?; - utils::user_role::set_role_info_in_cache_by_role_id_org_id(&state, &role_id, &request.org_id) - .await; + utils::user_role::set_role_info_in_cache_by_role_id_org_id( + &state, + &role_id, + &request.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await; let response = user_api::TokenResponse { token: token.clone(), @@ -3120,10 +3164,14 @@ pub async fn switch_merchant_for_user_in_org( } let key_manager_state = &(&state).into(); - let role_info = roles::RoleInfo::from_role_id_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) @@ -3275,11 +3323,20 @@ pub async fn switch_merchant_for_user_in_org( org_id.clone(), role_id.clone(), profile_id, - user_from_token.tenant_id, + user_from_token.tenant_id.clone(), ) .await?; - utils::user_role::set_role_info_in_cache_by_role_id_org_id(&state, &role_id, &org_id).await; + utils::user_role::set_role_info_in_cache_by_role_id_org_id( + &state, + &role_id, + &org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await; let response = user_api::TokenResponse { token: token.clone(), @@ -3302,10 +3359,14 @@ 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_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) @@ -3378,7 +3439,7 @@ pub async fn switch_profile_for_user_in_org_and_merchant( user_from_token.org_id.clone(), role_id.clone(), profile_id, - user_from_token.tenant_id, + user_from_token.tenant_id.clone(), ) .await?; @@ -3386,6 +3447,10 @@ pub async fn switch_profile_for_user_in_org_and_merchant( &state, &role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index d8fdff0e623..19d91b14f01 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -83,10 +83,14 @@ pub async fn get_parent_group_info( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<role_api::ParentGroupInfo>> { - let role_info = roles::RoleInfo::from_role_id_and_org_id( + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; @@ -123,6 +127,10 @@ pub async fn update_user_role( &req.role_id, &user_from_token.merchant_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleId)?; @@ -143,10 +151,14 @@ pub async fn update_user_role( .attach_printable("User Changing their own role"); } - let updator_role = roles::RoleInfo::from_role_id_and_org_id( + let updator_role = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -179,10 +191,14 @@ 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_and_org_id( + let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -259,10 +275,14 @@ 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_and_org_id( + let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -485,10 +505,14 @@ pub async fn delete_user_role( .attach_printable("User deleting himself"); } - let deletion_requestor_role_info = roles::RoleInfo::from_role_id_and_org_id( + let deletion_requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -527,6 +551,10 @@ pub async fn delete_user_role( &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -597,6 +625,10 @@ pub async fn delete_user_role( &role_to_be_deleted.role_id, &user_from_token.merchant_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -680,10 +712,14 @@ pub async fn list_users_in_lineage( 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_and_org_id( + let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_from_token.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError)?; @@ -692,7 +728,49 @@ pub async fn list_users_in_lineage( requestor_role_info.get_entity_type(), request.entity_type, )? { - EntityType::Tenant | EntityType::Organization => { + EntityType::Tenant => { + let mut org_users = utils::user_role::fetch_user_roles_by_payload( + &state, + ListUserRolesByOrgIdPayload { + user_id: None, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + org_id: &user_from_token.org_id, + merchant_id: None, + profile_id: None, + version: None, + limit: None, + }, + request.entity_type, + ) + .await?; + + // Fetch tenant user + let tenant_user = state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &user_from_token.user_id, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + org_id: None, + merchant_id: None, + profile_id: None, + entity_id: None, + version: None, + status: None, + limit: None, + }) + .await + .change_context(UserErrors::InternalServerError)?; + + org_users.extend(tenant_user); + org_users + } + EntityType::Organization => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { @@ -777,10 +855,14 @@ pub async fn list_users_in_lineage( let role_info_map = futures::future::try_join_all(user_roles_set.iter().map(|user_role| async { - roles::RoleInfo::from_role_id_and_org_id( + roles::RoleInfo::from_role_id_org_id_tenant_id( &state, &user_role.role_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .map(|role_info| { diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index e897e1b336a..ca4c062244c 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -73,16 +73,21 @@ pub async fn create_role( &role_name, &user_from_token.merchant_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await?; let user_role_info = user_from_token.get_role_info_from_db(&state).await?; if matches!(req.role_scope, RoleScope::Organization) - && user_role_info.get_entity_type() != EntityType::Organization + && user_role_info.get_entity_type() < EntityType::Organization { - return Err(report!(UserErrors::InvalidRoleOperation)) - .attach_printable("Non org admin user creating org level role"); + return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable( + "User does not have sufficient privileges to perform organization-level role operation", + ); } let role = state @@ -99,6 +104,7 @@ pub async fn create_role( last_modified_by: user_from_token.user_id, created_at: now, last_modified_at: now, + tenant_id: user_from_token.tenant_id.unwrap_or(state.tenant.tenant_id), }) .await .to_duplicate_response(UserErrors::RoleNameAlreadyExists)?; @@ -118,10 +124,17 @@ 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_and_org_id(&state, &role.role_id, &user_from_token.org_id) - .await - .to_not_found_response(UserErrors::InvalidRoleId)?; + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( + &state, + &role.role_id, + &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleId.into()); @@ -142,10 +155,17 @@ pub async fn get_parent_info_for_role( user_from_token: UserFromToken, role: role_api::GetRoleRequest, ) -> UserResponse<role_api::RoleInfoWithParents> { - let role_info = - roles::RoleInfo::from_role_id_and_org_id(&state, &role.role_id, &user_from_token.org_id) - .await - .to_not_found_response(UserErrors::InvalidRoleId)?; + let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id( + &state, + &role.role_id, + &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + ) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleId.into()); @@ -193,6 +213,10 @@ pub async fn update_role( role_name, &user_from_token.merchant_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await?; } @@ -206,6 +230,10 @@ pub async fn update_role( role_id, &user_from_token.merchant_id, &user_from_token.org_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), ) .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; @@ -273,6 +301,10 @@ pub async fn list_roles_with_info( EntityType::Tenant | EntityType::Organization => state .global_store .list_roles_for_org_by_parameters( + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, None, request.entity_type, @@ -284,6 +316,10 @@ pub async fn list_roles_with_info( EntityType::Merchant => state .global_store .list_roles_for_org_by_parameters( + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), request.entity_type, @@ -346,6 +382,10 @@ pub async fn list_roles_at_entity_level( EntityType::Tenant | EntityType::Organization => state .global_store .list_roles_for_org_by_parameters( + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, None, Some(req.entity_type), @@ -358,6 +398,10 @@ pub async fn list_roles_at_entity_level( EntityType::Merchant => state .global_store .list_roles_for_org_by_parameters( + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(req.entity_type), diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 8eec7f04169..cbced16bdcd 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3209,6 +3209,16 @@ impl UserRoleInterface for KafkaStore { self.diesel_store.list_user_roles_by_user_id(payload).await } + async fn list_user_roles_by_user_id_across_tenants( + &self, + user_id: &str, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { + self.diesel_store + .list_user_roles_by_user_id_across_tenants(user_id, limit) + .await + } + async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, @@ -3606,9 +3616,10 @@ impl RoleInterface for KafkaStore { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store - .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id, tenant_id) .await } @@ -3617,19 +3628,21 @@ impl RoleInterface for KafkaStore { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store - .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id) + .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id, tenant_id) .await } - async fn find_by_role_id_and_org_id( + async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { self.diesel_store - .find_by_role_id_and_org_id(role_id, org_id) + .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await } @@ -3654,19 +3667,23 @@ impl RoleInterface for KafkaStore { &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { - self.diesel_store.list_all_roles(merchant_id, org_id).await + self.diesel_store + .list_all_roles(merchant_id, org_id, tenant_id) + .await } async fn list_roles_for_org_by_parameters( &self, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<enums::EntityType>, limit: Option<u32>, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { self.diesel_store - .list_roles_for_org_by_parameters(org_id, merchant_id, entity_type, limit) + .list_roles_for_org_by_parameters(tenant_id, org_id, merchant_id, entity_type, limit) .await } } diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index 877a4c54077..1006c33aaa0 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -29,6 +29,7 @@ pub trait RoleInterface { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn find_role_by_role_id_in_lineage( @@ -36,12 +37,14 @@ pub trait RoleInterface { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; - async fn find_by_role_id_and_org_id( + async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError>; async fn update_role_by_role_id( @@ -59,10 +62,12 @@ pub trait RoleInterface { &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError>; async fn list_roles_for_org_by_parameters( &self, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<enums::EntityType>, @@ -101,11 +106,18 @@ impl RoleInterface for Store { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { 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))) + storage::Role::find_by_role_id_in_merchant_scope( + &conn, + role_id, + merchant_id, + org_id, + tenant_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] @@ -114,21 +126,23 @@ impl RoleInterface for Store { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::Role::find_by_role_id_in_lineage(&conn, role_id, merchant_id, org_id) + storage::Role::find_by_role_id_in_lineage(&conn, role_id, merchant_id, org_id, tenant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } #[instrument(skip_all)] - async fn find_by_role_id_and_org_id( + async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::Role::find_by_role_id_and_org_id(&conn, role_id, org_id) + storage::Role::find_by_role_id_org_id_tenant_id(&conn, role_id, org_id, tenant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -161,9 +175,10 @@ impl RoleInterface for Store { &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::Role::list_roles(&conn, merchant_id, org_id) + storage::Role::list_roles(&conn, merchant_id, org_id, tenant_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -171,6 +186,7 @@ impl RoleInterface for Store { #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<enums::EntityType>, @@ -179,6 +195,7 @@ impl RoleInterface for Store { let conn = connection::pg_connection_read(self).await?; storage::Role::generic_roles_list_for_org( &conn, + tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), entity_type, @@ -217,6 +234,7 @@ impl RoleInterface for MockDb { created_at: role.created_at, last_modified_at: role.last_modified_at, last_modified_by: role.last_modified_by, + tenant_id: role.tenant_id, }; roles.push(role.clone()); Ok(role) @@ -245,12 +263,14 @@ impl RoleInterface for MockDb { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id + && (role.tenant_id == *tenant_id) && (role.merchant_id == *merchant_id || (role.org_id == *org_id && role.scope == enums::RoleScope::Organization)) }) @@ -269,12 +289,14 @@ impl RoleInterface for MockDb { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<storage::Role, errors::StorageError> { let roles = self.roles.lock().await; roles .iter() .find(|role| { role.role_id == role_id + && (role.tenant_id == *tenant_id) && role.org_id == *org_id && ((role.scope == enums::RoleScope::Organization) || (role.merchant_id == *merchant_id @@ -290,15 +312,18 @@ impl RoleInterface for MockDb { ) } - async fn find_by_role_id_and_org_id( + async fn find_by_role_id_org_id_tenant_id( &self, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> 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) + .find(|role| { + role.role_id == role_id && role.org_id == *org_id && role.tenant_id == *tenant_id + }) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( @@ -361,15 +386,17 @@ impl RoleInterface for MockDb { &self, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<Vec<storage::Role>, errors::StorageError> { let roles = self.roles.lock().await; let roles_list: Vec<_> = roles .iter() .filter(|role| { - role.merchant_id == *merchant_id - || (role.org_id == *org_id - && role.scope == diesel_models::enums::RoleScope::Organization) + role.tenant_id == *tenant_id + && (role.merchant_id == *merchant_id + || (role.org_id == *org_id + && role.scope == diesel_models::enums::RoleScope::Organization)) }) .cloned() .collect(); @@ -388,6 +415,7 @@ impl RoleInterface for MockDb { #[instrument(skip_all)] async fn list_roles_for_org_by_parameters( &self, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, entity_type: Option<enums::EntityType>, @@ -403,7 +431,10 @@ impl RoleInterface for MockDb { None => true, }; - matches_merchant && role.org_id == *org_id && Some(role.entity_type) == entity_type + matches_merchant + && role.org_id == *org_id + && role.tenant_id == *tenant_id + && Some(role.entity_type) == entity_type }) .take(limit_usize) .cloned() diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index 0da51898326..1df6160f81e 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -79,6 +79,12 @@ pub trait UserRoleInterface { payload: ListUserRolesByUserIdPayload<'a>, ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; + async fn list_user_roles_by_user_id_across_tenants( + &self, + user_id: &str, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>; + async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, @@ -195,6 +201,21 @@ impl UserRoleInterface for Store { .map_err(|error| report!(errors::StorageError::from(error))) } + async fn list_user_roles_by_user_id_across_tenants( + &self, + user_id: &str, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::UserRole::list_user_roles_by_user_id_across_tenants( + &conn, + user_id.to_owned(), + limit, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, @@ -472,6 +493,26 @@ impl UserRoleInterface for MockDb { Ok(filtered_roles) } + async fn list_user_roles_by_user_id_across_tenants( + &self, + user_id: &str, + limit: Option<u32>, + ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> { + let user_roles = self.user_roles.lock().await; + + let filtered_roles: Vec<_> = user_roles + .iter() + .filter(|role| role.user_id == user_id) + .cloned() + .collect(); + + if let Some(Ok(limit)) = limit.map(|val| val.try_into()) { + return Ok(filtered_roles.into_iter().take(limit).collect()); + } + + Ok(filtered_roles) + } + async fn list_user_roles_by_org_id<'a>( &self, payload: ListUserRolesByOrgIdPayload<'a>, diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index da296373d80..db3483f8164 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -33,7 +33,16 @@ where return Ok(role_info.clone()); } - let role_info = get_role_info_from_db(state, &token.role_id, &token.org_id).await?; + let role_info = get_role_info_from_db( + state, + &token.role_id, + &token.org_id, + token + .tenant_id + .as_ref() + .unwrap_or(&state.session_state().tenant.tenant_id), + ) + .await?; let token_expiry = i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; @@ -68,6 +77,7 @@ async fn get_role_info_from_db<A>( state: &A, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> RouterResult<roles::RoleInfo> where A: SessionStateInfo + Sync, @@ -75,7 +85,7 @@ where state .session_state() .global_store - .find_by_role_id_and_org_id(role_id, org_id) + .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await .map(roles::RoleInfo::from) .to_not_found_response(ApiErrorResponse::InvalidJwtToken) diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index c9c64b76143..df2a14a1a1a 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -121,29 +121,32 @@ impl RoleInfo { role_id: &str, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<Self, errors::StorageError> { if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { Ok(role.clone()) } else { state .global_store - .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id) + .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id, tenant_id) .await .map(Self::from) } } - pub async fn from_role_id_and_org_id( + // TODO: To evaluate whether we can omit org_id and tenant_id for this function + pub async fn from_role_id_org_id_tenant_id( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> CustomResult<Self, errors::StorageError> { if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) { Ok(role.clone()) } else { state .global_store - .find_by_role_id_and_org_id(role_id, org_id) + .find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id) .await .map(Self::from) } diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index b8ffcf836d7..ef06531b421 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -77,9 +77,14 @@ impl UserFromToken { } pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> { - RoleInfo::from_role_id_and_org_id(state, &self.role_id, &self.org_id) - .await - .change_context(UserErrors::InternalServerError) + RoleInfo::from_role_id_org_id_tenant_id( + state, + &self.role_id, + &self.org_id, + self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_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 ac8ee11fc6a..7413e66070f 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -48,6 +48,7 @@ pub async fn validate_role_name( role_name: &domain::RoleName, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> UserResult<()> { let role_name_str = role_name.clone().get_role_name(); @@ -58,7 +59,7 @@ pub async fn validate_role_name( // TODO: Create and use find_by_role_name to make this efficient let is_present_in_custom_roles = state .global_store - .list_all_roles(merchant_id, org_id) + .list_all_roles(merchant_id, org_id, tenant_id) .await .change_context(UserErrors::InternalServerError)? .iter() @@ -78,18 +79,24 @@ pub async fn set_role_info_in_cache_by_user_role( let Some(ref org_id) = user_role.org_id else { return false; }; - set_role_info_in_cache_if_required(state, user_role.role_id.as_str(), org_id) - .await - .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) - .is_ok() + set_role_info_in_cache_if_required( + state, + user_role.role_id.as_str(), + org_id, + &user_role.tenant_id, + ) + .await + .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) + .is_ok() } pub async fn set_role_info_in_cache_by_role_id_org_id( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> bool { - set_role_info_in_cache_if_required(state, role_id, org_id) + set_role_info_in_cache_if_required(state, role_id, org_id, tenant_id) .await .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) .is_ok() @@ -99,15 +106,17 @@ pub async fn set_role_info_in_cache_if_required( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, + tenant_id: &id_type::TenantId, ) -> UserResult<()> { if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) { return Ok(()); } - let role_info = roles::RoleInfo::from_role_id_and_org_id(state, role_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_org_id_tenant_id(state, role_id, org_id, tenant_id) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error getting role_info from role_id")?; authz::set_role_info_in_cache( state, diff --git a/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/down.sql b/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/down.sql new file mode 100644 index 00000000000..58d6b900e2d --- /dev/null +++ b/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE roles DROP COLUMN IF EXISTS tenant_id; \ No newline at end of file diff --git a/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/up.sql b/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/up.sql new file mode 100644 index 00000000000..13ec3cf48b7 --- /dev/null +++ b/migrations/2024-12-28-121104_add_column_tenant_id_to_roles/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE roles ADD COLUMN IF NOT EXISTS tenant_id VARCHAR(64) NOT NULL DEFAULT 'public'; \ No newline at end of file
2025-01-05T20:12:09Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR - add tenant_id in roles table - add support for genenric query to serach user across all tenancies - Fixes custom roles creates by tenant_level user - List view for tenant level user - Fix bug to search across envs for tenant admin ### 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 [#6999](https://github.com/juspay/hyperswitch/issues/6999) ## How did you test it? Tenant admin able to create custom org level role ``` curl --location 'http://localhost:8080/user/role' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "role_name": "custom_role_7", "groups": ["users_view"], "role_scope": "organization" }' ``` Response ``` { "role_id": "role_KQxGGeCs6usRwxubnU2Y", "groups": [ "users_view" ], "role_name": "custom_role_7", "role_scope": "organization" } ``` For tenant level user, list api is showing that user in list, if we don't pass query, its coming with remaning org users ``` curl --location 'http://localhost:8080/user/user/list?entity_type=tenant' \ --header 'x-tenant-id: test' \ --header 'Authorization: Bearer JWT' \ ``` Response ``` [ { "email": "[email protected]", "roles": [ { "role_id": "tenant_admin", "role_name": "tenant_admin" } ] } ] ``` For global search now, we are getting org_id in the query <img width="1146" alt="Screenshot 2025-01-07 at 3 23 14 PM" src="https://github.com/user-attachments/assets/2cc0c6d9-1377-4fb6-883c-540845307d51" /> ## 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
79013024ff371efc6062310564b8b56e9bb22701
juspay/hyperswitch
juspay__hyperswitch-6983
Bug: [CHORE] remove redundant variants from PermissionGroup ### Feature Description Few variants in `PermissionGroup` enum were kept in the application code for backwards compatibility. These variants are directly stored as TEXT in DB which forces the application to ensure backwards compatibility during staggered releases. Since new variants were added and deployed, old variants can be removed post running the DB migrations. ### Possible Implementation 1. Add DB migration for updating any existing values from older variants to new variants 2. Remove variants from application code 3. Deploy This still leaves a small time window where users can make use of older variants during staggered deployment once the migrations have run, that can be manually avoided by running migrations several times during staggered release, if required. ### 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_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 0234fbea6d5..1faa3b90aa8 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2936,8 +2936,6 @@ pub enum PermissionGroup { ReconReportsManage, ReconOpsView, ReconOpsManage, - // TODO: To be deprecated, make sure DB is migrated before removing - ReconOps, } #[derive(Clone, Debug, serde::Serialize, PartialEq, Eq, Hash, strum::EnumIter)] diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs index e02838b3e00..b4413dfa3b3 100644 --- a/crates/router/src/services/authorization/info.rs +++ b/crates/router/src/services/authorization/info.rs @@ -40,10 +40,10 @@ fn get_group_description(group: PermissionGroup) -> &'static str { PermissionGroup::MerchantDetailsView | PermissionGroup::AccountView => "View Merchant Details", PermissionGroup::MerchantDetailsManage | PermissionGroup::AccountManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc", PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc", - PermissionGroup::ReconReportsView => "View and access reconciliation reports and analytics", + PermissionGroup::ReconReportsView => "View reconciliation reports and analytics", PermissionGroup::ReconReportsManage => "Manage reconciliation reports", - PermissionGroup::ReconOpsView => "View and access reconciliation operations", - PermissionGroup::ReconOpsManage | PermissionGroup::ReconOps => "Manage reconciliation operations", + PermissionGroup::ReconOpsView => "View and access all reconciliation operations including reports and analytics", + PermissionGroup::ReconOpsManage => "Manage all reconciliation operations including reports and analytics", } } diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index ceb943950d5..0cdb68ec8d7 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -33,7 +33,6 @@ impl PermissionGroupExt for PermissionGroup { | Self::OrganizationManage | Self::AccountManage | Self::ReconOpsManage - | Self::ReconOps | Self::ReconReportsManage => PermissionScope::Write, } } @@ -50,7 +49,7 @@ impl PermissionGroupExt for PermissionGroup { | Self::MerchantDetailsManage | Self::AccountView | Self::AccountManage => ParentGroup::Account, - Self::ReconOpsView | Self::ReconOpsManage | Self::ReconOps => ParentGroup::ReconOps, + Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps, Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports, } } @@ -86,7 +85,7 @@ impl PermissionGroupExt for PermissionGroup { } Self::ReconOpsView => vec![Self::ReconOpsView], - Self::ReconOpsManage | Self::ReconOps => vec![Self::ReconOpsView, Self::ReconOpsManage], + Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage], Self::ReconReportsView => vec![Self::ReconReportsView], Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage], diff --git a/migrations/2025-01-03-104019_migrate_permission_group_for_recon/down.sql b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/down.sql new file mode 100644 index 00000000000..e0ac49d1ecf --- /dev/null +++ b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/down.sql @@ -0,0 +1 @@ +SELECT 1; diff --git a/migrations/2025-01-03-104019_migrate_permission_group_for_recon/up.sql b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/up.sql new file mode 100644 index 00000000000..0fa04632dce --- /dev/null +++ b/migrations/2025-01-03-104019_migrate_permission_group_for_recon/up.sql @@ -0,0 +1,3 @@ +UPDATE roles +SET groups = array_replace(groups, 'recon_ops', 'recon_ops_manage') +WHERE 'recon_ops' = ANY(groups);
2025-01-03T10:45:05Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This removes the redundant `ReconOps` variant from `PermissionGroup` enum which is stored in DB. This was kept back in application for backwards compatibility. Migrations are added for this and this will not be needed anymore. ### 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 in keeping a clean permission view on HS dashboard. ## How did you test it? Locally by running migrations and viewing permission view in dashboard. ## 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
22072fd750940ac7fec6ea971737409518600891
juspay/hyperswitch
juspay__hyperswitch-6986
Bug: refactor(currency_conversion): re-frame the crate to make api calls on background thread
diff --git a/config/config.example.toml b/config/config.example.toml index c860420da38..ecc2d2127ce 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -74,13 +74,10 @@ max_feed_count = 200 # The maximum number of frames that will be fe # This section provides configs for currency conversion api [forex_api] -call_delay = 21600 # Api calls are made after every 6 hrs -local_fetch_retry_count = 5 # Fetch from Local cache has retry count as 5 -local_fetch_retry_delay = 1000 # Retry delay for checking write condition -api_timeout = 20000 # Api timeouts once it crosses 20000 ms -api_key = "YOUR API KEY HERE" # Api key for making request to foreign exchange Api -fallback_api_key = "YOUR API KEY" # Api key for the fallback service -redis_lock_timeout = 26000 # Redis remains write locked for 26000 ms once the acquire_redis_lock is called +call_delay = 21600 # Expiration time for data in cache as well as redis in seconds +api_key = "" # Api key for making request to foreign exchange Api +fallback_api_key = "" # Api key for the fallback service +redis_lock_timeout = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called # Logging configuration. Logging can be either to file or console or both. diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 84550922d4a..8c846ff422e 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -101,13 +101,10 @@ bucket_name = "bucket" # The AWS S3 bucket name for file storage # This section provides configs for currency conversion api [forex_api] -call_delay = 21600 # Api calls are made after every 6 hrs -local_fetch_retry_count = 5 # Fetch from Local cache has retry count as 5 -local_fetch_retry_delay = 1000 # Retry delay for checking write condition -api_timeout = 20000 # Api timeouts once it crosses 20000 ms -api_key = "YOUR API KEY HERE" # Api key for making request to foreign exchange Api -fallback_api_key = "YOUR API KEY" # Api key for the fallback service -redis_lock_timeout = 26000 # Redis remains write locked for 26000 ms once the acquire_redis_lock is called +call_delay = 21600 # Expiration time for data in cache as well as redis in seconds +api_key = "" # Api key for making request to foreign exchange Api +fallback_api_key = "" # Api key for the fallback service +redis_lock_timeout = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called [jwekey] # 3 priv/pub key pair vault_encryption_key = "" # public key in pem format, corresponding private key in rust locker diff --git a/config/development.toml b/config/development.toml index a32102aeebf..6bce5cb89d7 100644 --- a/config/development.toml +++ b/config/development.toml @@ -78,12 +78,9 @@ ttl_for_storage_in_secs = 220752000 [forex_api] call_delay = 21600 -local_fetch_retry_count = 5 -local_fetch_retry_delay = 1000 -api_timeout = 20000 -api_key = "YOUR API KEY HERE" -fallback_api_key = "YOUR API KEY HERE" -redis_lock_timeout = 26000 +api_key = "" +fallback_api_key = "" +redis_lock_timeout = 100 [jwekey] vault_encryption_key = "" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 4296a5931dc..293e9a313e9 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -31,12 +31,9 @@ pool_size = 5 [forex_api] call_delay = 21600 -local_fetch_retry_count = 5 -local_fetch_retry_delay = 1000 -api_timeout = 20000 -api_key = "YOUR API KEY HERE" -fallback_api_key = "YOUR API KEY HERE" -redis_lock_timeout = 26000 +api_key = "" +fallback_api_key = "" +redis_lock_timeout = 100 [replica_database] username = "db_user" diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md index e24dc6c5af7..71190613a10 100644 --- a/crates/analytics/docs/README.md +++ b/crates/analytics/docs/README.md @@ -115,8 +115,8 @@ To configure the Forex APIs, update the `config/development.toml` or `config/doc ```toml [forex_api] -api_key = "YOUR API KEY HERE" # Replace the placeholder with your Primary API Key -fallback_api_key = "YOUR API KEY HERE" # Replace the placeholder with your Fallback API Key +api_key = "" +fallback_api_key = "" ``` ### Important Note ```bash @@ -159,4 +159,4 @@ To view the data on the OpenSearch dashboard perform the following steps: - Select a time field that will be used for time-based queries - Save the index pattern -Now, head on to `Discover` under the `OpenSearch Dashboards` tab, to select the newly created index pattern and query the data \ No newline at end of file +Now, head on to `Discover` under the `OpenSearch Dashboards` tab, to select the newly created index pattern and query the data diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 577b29b0534..fa3d004aada 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -303,16 +303,11 @@ pub struct PaymentLink { #[derive(Debug, Deserialize, Clone, Default)] #[serde(default)] pub struct ForexApi { - pub local_fetch_retry_count: u64, pub api_key: Secret<String>, pub fallback_api_key: Secret<String>, - /// in ms + /// in s pub call_delay: i64, - /// in ms - pub local_fetch_retry_delay: u64, - /// in ms - pub api_timeout: u64, - /// in ms + /// in s pub redis_lock_timeout: u64, } diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs index 912484b014a..8c1a8512892 100644 --- a/crates/router/src/core/currency.rs +++ b/crates/router/src/core/currency.rs @@ -15,16 +15,11 @@ pub async fn retrieve_forex( ) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> { let forex_api = state.conf.forex_api.get_inner(); Ok(ApplicationResponse::Json( - get_forex_rates( - &state, - forex_api.call_delay, - forex_api.local_fetch_retry_delay, - forex_api.local_fetch_retry_count, - ) - .await - .change_context(ApiErrorResponse::GenericNotFoundError { - message: "Unable to fetch forex rates".to_string(), - })?, + get_forex_rates(&state, forex_api.call_delay) + .await + .change_context(ApiErrorResponse::GenericNotFoundError { + message: "Unable to fetch forex rates".to_string(), + })?, )) } @@ -53,14 +48,9 @@ pub async fn get_forex_exchange_rates( state: SessionState, ) -> CustomResult<ExchangeRates, AnalyticsError> { let forex_api = state.conf.forex_api.get_inner(); - let rates = get_forex_rates( - &state, - forex_api.call_delay, - forex_api.local_fetch_retry_delay, - forex_api.local_fetch_retry_count, - ) - .await - .change_context(AnalyticsError::ForexFetchFailed)?; + let rates = get_forex_rates(&state, forex_api.call_delay) + .await + .change_context(AnalyticsError::ForexFetchFailed)?; Ok((*rates.data).clone()) } diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 9ab2780da73..c10ebf3dac1 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, ops::Deref, str::FromStr, sync::Arc, time::Duration}; +use std::{collections::HashMap, ops::Deref, str::FromStr, sync::Arc}; use api_models::enums; use common_utils::{date_time, errors::CustomResult, events::ApiEventMetric, ext_traits::AsyncExt}; @@ -10,7 +10,8 @@ use redis_interface::DelReply; use router_env::{instrument, tracing}; use rust_decimal::Decimal; use strum::IntoEnumIterator; -use tokio::{sync::RwLock, time::sleep}; +use tokio::sync::RwLock; +use tracing_futures::Instrument; use crate::{ logger, @@ -50,10 +51,14 @@ pub enum ForexCacheError { CouldNotAcquireLock, #[error("Provided currency not acceptable")] CurrencyNotAcceptable, + #[error("Forex configuration error: {0}")] + ConfigurationError(String), #[error("Incorrect entries in default Currency response")] DefaultCurrencyParsingError, #[error("Entry not found in cache")] EntryNotFound, + #[error("Forex data unavailable")] + ForexDataUnavailable, #[error("Expiration time invalid")] InvalidLogExpiry, #[error("Error reading local")] @@ -107,44 +112,19 @@ impl FxExchangeRatesCacheEntry { } } -async fn retrieve_forex_from_local() -> Option<FxExchangeRatesCacheEntry> { +async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> { FX_EXCHANGE_RATES_CACHE.read().await.clone() } -async fn save_forex_to_local( +async fn save_forex_data_to_local_cache( exchange_rates_cache_entry: FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexCacheError> { let mut local = FX_EXCHANGE_RATES_CACHE.write().await; *local = Some(exchange_rates_cache_entry); + logger::debug!("forex_log: forex saved in cache"); Ok(()) } -// Alternative handler for handling the case, When no data in local as well as redis -#[allow(dead_code)] -async fn waited_fetch_and_update_caches( - state: &SessionState, - local_fetch_retry_delay: u64, - local_fetch_retry_count: u64, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - for _n in 1..local_fetch_retry_count { - sleep(Duration::from_millis(local_fetch_retry_delay)).await; - //read from redis and update local plus break the loop and return - match retrieve_forex_from_redis(state).await { - Ok(Some(rates)) => { - save_forex_to_local(rates.clone()).await?; - return Ok(rates.clone()); - } - Ok(None) => continue, - Err(error) => { - logger::error!(?error); - continue; - } - } - } - //acquire lock one last time and try to fetch and update local & redis - successive_fetch_and_save_forex(state, None).await -} - impl TryFrom<DefaultExchangeRates> for ExchangeRates { type Error = error_stack::Report<ForexCacheError>; fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> { @@ -178,102 +158,108 @@ impl From<Conversion> for CurrencyFactors { pub async fn get_forex_rates( state: &SessionState, call_delay: i64, - local_fetch_retry_delay: u64, - local_fetch_retry_count: u64, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - if let Some(local_rates) = retrieve_forex_from_local().await { + if let Some(local_rates) = retrieve_forex_from_local_cache().await { if local_rates.is_expired(call_delay) { // expired local data - handler_local_expired(state, call_delay, local_rates).await + logger::debug!("forex_log: Forex stored in cache is expired"); + call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await } else { // Valid data present in local + logger::debug!("forex_log: forex found in cache"); Ok(local_rates) } } else { // No data in local - handler_local_no_data( - state, - call_delay, - local_fetch_retry_delay, - local_fetch_retry_count, - ) - .await + call_api_if_redis_forex_data_expired(state, call_delay).await } } -async fn handler_local_no_data( +async fn call_api_if_redis_forex_data_expired( state: &SessionState, call_delay: i64, - _local_fetch_retry_delay: u64, - _local_fetch_retry_count: u64, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - match retrieve_forex_from_redis(state).await { - Ok(Some(data)) => fallback_forex_redis_check(state, data, call_delay).await, + match retrieve_forex_data_from_redis(state).await { + Ok(Some(data)) => call_forex_api_if_redis_data_expired(state, data, call_delay).await, Ok(None) => { // No data in local as well as redis - Ok(successive_fetch_and_save_forex(state, None).await?) + call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; + Err(ForexCacheError::ForexDataUnavailable.into()) } Err(error) => { - logger::error!(?error); - Ok(successive_fetch_and_save_forex(state, None).await?) + // Error in deriving forex rates from redis + logger::error!("forex_error: {:?}", error); + call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; + Err(ForexCacheError::ForexDataUnavailable.into()) } } } -async fn successive_fetch_and_save_forex( +async fn call_forex_api_and_save_data_to_cache_and_redis( state: &SessionState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - match acquire_redis_lock(state).await { - Ok(lock_acquired) => { - if !lock_acquired { - return stale_redis_data.ok_or(ForexCacheError::CouldNotAcquireLock.into()); + // spawn a new thread and do the api fetch and write operations on redis. + let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); + if forex_api_key.is_empty() { + Err(ForexCacheError::ConfigurationError("api_keys not provided".into()).into()) + } else { + let state = state.clone(); + tokio::spawn( + async move { + acquire_redis_lock_and_call_forex_api(&state) + .await + .map_err(|err| { + logger::error!(forex_error=?err); + }) + .ok(); } - let api_rates = fetch_forex_rates(state).await; - match api_rates { - Ok(rates) => successive_save_data_to_redis_local(state, rates).await, - Err(error) => { - // API not able to fetch data call secondary service - logger::error!(?error); - let secondary_api_rates = fallback_fetch_forex_rates(state).await; - match secondary_api_rates { - Ok(rates) => Ok(successive_save_data_to_redis_local(state, rates).await?), - Err(error) => stale_redis_data.ok_or({ - logger::error!(?error); - release_redis_lock(state).await?; - ForexCacheError::ApiUnresponsive.into() - }), + .in_current_span(), + ); + stale_redis_data.ok_or(ForexCacheError::EntryNotFound.into()) + } +} + +async fn acquire_redis_lock_and_call_forex_api( + state: &SessionState, +) -> CustomResult<(), ForexCacheError> { + let lock_acquired = acquire_redis_lock(state).await?; + if !lock_acquired { + Err(ForexCacheError::CouldNotAcquireLock.into()) + } else { + logger::debug!("forex_log: redis lock acquired"); + let api_rates = fetch_forex_rates_from_primary_api(state).await; + match api_rates { + Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, + Err(error) => { + logger::error!(forex_error=?error,"primary_forex_error"); + // API not able to fetch data call secondary service + let secondary_api_rates = fetch_forex_rates_from_fallback_api(state).await; + match secondary_api_rates { + Ok(rates) => save_forex_data_to_cache_and_redis(state, rates).await, + Err(error) => { + release_redis_lock(state).await?; + Err(error) } } } } - Err(error) => stale_redis_data.ok_or({ - logger::error!(?error); - ForexCacheError::ApiUnresponsive.into() - }), } } -async fn successive_save_data_to_redis_local( +async fn save_forex_data_to_cache_and_redis( state: &SessionState, forex: FxExchangeRatesCacheEntry, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - Ok(save_forex_to_redis(state, &forex) +) -> CustomResult<(), ForexCacheError> { + save_forex_data_to_redis(state, &forex) .await .async_and_then(|_rates| release_redis_lock(state)) .await - .async_and_then(|_val| save_forex_to_local(forex.clone())) + .async_and_then(|_val| save_forex_data_to_local_cache(forex.clone())) .await - .map_or_else( - |error| { - logger::error!(?error); - forex.clone() - }, - |_| forex.clone(), - )) } -async fn fallback_forex_redis_check( +async fn call_forex_api_if_redis_data_expired( state: &SessionState, redis_data: FxExchangeRatesCacheEntry, call_delay: i64, @@ -282,57 +268,30 @@ async fn fallback_forex_redis_check( Some(redis_forex) => { // Valid data present in redis let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone()); - save_forex_to_local(exchange_rates.clone()).await?; + logger::debug!("forex_log: forex response found in redis"); + save_forex_data_to_local_cache(exchange_rates.clone()).await?; Ok(exchange_rates) } None => { // redis expired - successive_fetch_and_save_forex(state, Some(redis_data)).await - } - } -} - -async fn handler_local_expired( - state: &SessionState, - call_delay: i64, - local_rates: FxExchangeRatesCacheEntry, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - match retrieve_forex_from_redis(state).await { - Ok(redis_data) => { - match is_redis_expired(redis_data.as_ref(), call_delay).await { - Some(redis_forex) => { - // Valid data present in redis - let exchange_rates = - FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone()); - save_forex_to_local(exchange_rates.clone()).await?; - Ok(exchange_rates) - } - None => { - // Redis is expired going for API request - successive_fetch_and_save_forex(state, Some(local_rates)).await - } - } - } - Err(error) => { - // data not present in redis waited fetch - logger::error!(?error); - successive_fetch_and_save_forex(state, Some(local_rates)).await + call_forex_api_and_save_data_to_cache_and_redis(state, Some(redis_data)).await } } } -async fn fetch_forex_rates( +async fn fetch_forex_rates_from_primary_api( state: &SessionState, ) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexCacheError>> { let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); + logger::debug!("forex_log: Primary api call for forex fetch"); let forex_url: String = format!("{}{}{}", FOREX_BASE_URL, forex_api_key, FOREX_BASE_CURRENCY); let forex_request = services::RequestBuilder::new() .method(services::Method::Get) .url(&forex_url) .build(); - logger::info!(?forex_request); + logger::info!(primary_forex_request=?forex_request,"forex_log: Primary api call for forex fetch"); let response = state .api_client .send_request( @@ -352,7 +311,7 @@ async fn fetch_forex_rates( "Unable to parse response received from primary api into ForexResponse", )?; - logger::info!("{:?}", forex_response); + logger::info!(primary_forex_response=?forex_response,"forex_log"); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { @@ -361,7 +320,10 @@ async fn fetch_forex_rates( let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { - logger::error!("Rates for {} not received from API", &enum_curr); + logger::error!( + "forex_error: Rates for {} not received from API", + &enum_curr + ); continue; } }; @@ -369,7 +331,10 @@ async fn fetch_forex_rates( conversions.insert(enum_curr, currency_factors); } None => { - logger::error!("Rates for {} not received from API", &enum_curr); + logger::error!( + "forex_error: Rates for {} not received from API", + &enum_curr + ); } }; } @@ -380,7 +345,7 @@ async fn fetch_forex_rates( ))) } -pub async fn fallback_fetch_forex_rates( +pub async fn fetch_forex_rates_from_fallback_api( state: &SessionState, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); @@ -392,7 +357,7 @@ pub async fn fallback_fetch_forex_rates( .url(&fallback_forex_url) .build(); - logger::info!(?fallback_forex_request); + logger::info!(fallback_forex_request=?fallback_forex_request,"forex_log: Fallback api call for forex fetch"); let response = state .api_client .send_request( @@ -413,7 +378,8 @@ pub async fn fallback_fetch_forex_rates( "Unable to parse response received from falback api into ForexResponse", )?; - logger::info!("{:?}", fallback_forex_response); + logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log"); + let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { match fallback_forex_response.quotes.get( @@ -428,7 +394,10 @@ pub async fn fallback_fetch_forex_rates( let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { - logger::error!("Rates for {} not received from API", &enum_curr); + logger::error!( + "forex_error: Rates for {} not received from API", + &enum_curr + ); continue; } }; @@ -441,7 +410,10 @@ pub async fn fallback_fetch_forex_rates( CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); conversions.insert(enum_curr, currency_factors); } else { - logger::error!("Rates for {} not received from API", &enum_curr); + logger::error!( + "forex_error: Rates for {} not received from API", + &enum_curr + ); } } }; @@ -450,17 +422,18 @@ pub async fn fallback_fetch_forex_rates( let rates = FxExchangeRatesCacheEntry::new(ExchangeRates::new(enums::Currency::USD, conversions)); match acquire_redis_lock(state).await { - Ok(_) => Ok(successive_save_data_to_redis_local(state, rates).await?), - Err(e) => { - logger::error!(?e); + Ok(_) => { + save_forex_data_to_cache_and_redis(state, rates.clone()).await?; Ok(rates) } + Err(e) => Err(e), } } async fn release_redis_lock( state: &SessionState, ) -> Result<DelReply, error_stack::Report<ForexCacheError>> { + logger::debug!("forex_log: Releasing redis lock"); state .store .get_redis_conn() @@ -473,6 +446,7 @@ async fn release_redis_lock( async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCacheError> { let forex_api = state.conf.forex_api.get_inner(); + logger::debug!("forex_log: Acquiring redis lock"); state .store .get_redis_conn() @@ -481,11 +455,8 @@ async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCac REDIX_FOREX_CACHE_KEY, "", Some( - i64::try_from( - forex_api.local_fetch_retry_count * forex_api.local_fetch_retry_delay - + forex_api.api_timeout, - ) - .change_context(ForexCacheError::ConversionError)?, + i64::try_from(forex_api.redis_lock_timeout) + .change_context(ForexCacheError::ConversionError)?, ), ) .await @@ -494,10 +465,11 @@ async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCac .attach_printable("Unable to acquire redis lock") } -async fn save_forex_to_redis( +async fn save_forex_data_to_redis( app_state: &SessionState, forex_exchange_cache_entry: &FxExchangeRatesCacheEntry, ) -> CustomResult<(), ForexCacheError> { + logger::debug!("forex_log: Saving forex to redis"); app_state .store .get_redis_conn() @@ -508,9 +480,10 @@ async fn save_forex_to_redis( .attach_printable("Unable to save forex data to redis") } -async fn retrieve_forex_from_redis( +async fn retrieve_forex_data_from_redis( app_state: &SessionState, ) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexCacheError> { + logger::debug!("forex_log: Retrieving forex from redis"); app_state .store .get_redis_conn() @@ -529,6 +502,7 @@ async fn is_redis_expired( if cache.timestamp + call_delay > date_time::now_unix_timestamp() { Some(cache.data.clone()) } else { + logger::debug!("forex_log: Forex stored in redis is expired"); None } }) @@ -542,14 +516,9 @@ pub async fn convert_currency( from_currency: String, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> { let forex_api = state.conf.forex_api.get_inner(); - let rates = get_forex_rates( - &state, - forex_api.call_delay, - forex_api.local_fetch_retry_delay, - forex_api.local_fetch_retry_count, - ) - .await - .change_context(ForexCacheError::ApiError)?; + let rates = get_forex_rates(&state, forex_api.call_delay) + .await + .change_context(ForexCacheError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) .change_context(ForexCacheError::CurrencyNotAcceptable) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index e90eb16ab61..61f5debb4d0 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -48,12 +48,9 @@ ttl_for_storage_in_secs = 220752000 [forex_api] call_delay = 21600 -local_fetch_retry_count = 5 -local_fetch_retry_delay = 1000 -api_timeout = 20000 -api_key = "YOUR API KEY HERE" -fallback_api_key = "YOUR API KEY HERE" -redis_lock_timeout = 26000 +api_key = "" +fallback_api_key = "" +redis_lock_timeout = 100 [eph_key] validity = 1
2024-12-20T06:29:50Z
## 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 --> Due to redis lock being held for a long time, which made the forex api-calls synchronous, we had to re-frame the way how things were being operated for forex rates fetch, The changes includes: 1. Acquiring redis lock, just before api-call and releasing it once data is written on redis. 2. Always responding back with stale-data and operating everything (redis-write, update, api call) on background thread. 3. Throwing error, if api_keys are missing in configs, whenever call is being made. 4. Greater log coverage. ### 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` 5. `crates/router/src/configs` 6. `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. Testing for first call when there is no data present in cache as well as redis: ![Screenshot 2025-01-03 at 4 35 53 PM](https://github.com/user-attachments/assets/d60ddc98-59c1-43e7-b99c-3eca9117ad60) ``` curl --location 'http://127.0.0.1:8080/forex/rates' \ --header 'api-key: xxxxxxx' \ --data '' ``` <img width="822" alt="Screenshot 2025-01-03 at 5 13 35 PM" src="https://github.com/user-attachments/assets/ad2f4104-98cd-42d8-beba-305a5ba096e9" /> 2. Testing for the case, when data is present in cache and/or redis: <img width="821" alt="Screenshot 2025-01-03 at 5 14 59 PM" src="https://github.com/user-attachments/assets/13a7e292-bff5-4b2a-a32d-985a3a7e1066" /> 3. For cases when data is expired in cache, it will provide us with the stale data and a background thread will be spun which will update the data on cache as well as redis. Full response: ``` { "data": { "base_currency": "USD", "conversion": { "TWD": { "to_factor": "32.939501", "from_factor": "0.0303586869758591667797274767" }, ...... "MOP": { "to_factor": "8.011576", "from_factor": "0.1248193863479545098242842607" } } }, "timestamp": 1735904610 } ``` ## 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
3fdc41e6c946609461db6b5459e10e6351694d4c
juspay/hyperswitch
juspay__hyperswitch-6993
Bug: [REFACTOR] reduce duplicate code in config in cypress - too much chaos and confusion - boiler plate and duplicate code - move memory cache test out of payments and make it a separate service
2025-01-06T09:12:46Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> This PR aims at refactoring: - `cypress-tests` folder structure to reduce confusion and chaos in within `e2e` directory - previous: ```sh . └── cypress ├── e2e │   ├── PaymentMethodListTest │   ├── PaymentMethodListUtils │   ├── PaymentTest │   ├── PaymentUtils │   ├── PayoutTest │   ├── PayoutUtils │   ├── RoutingTest │   └── RoutingUtils ├── fixtures ├── support └── utils ``` - present: ```sh . └── cypress ├── e2e │   ├── configs │   │   ├── Payment │   │   ├── PaymentMethodList │   │   ├── Payout │   │   └── Routing │   └── spec │   ├── Misc <- memory cache tests have been moved here │   ├── Payment │   ├── PaymentMethodList │   ├── Payout │   └── Routing ├── fixtures ├── support └── utils ``` - reduce / remove duplicate commands in memory cache (config calls) by unifying them - #6961 introduces the memory cache test, but does not aim at optimising things. this pr is intended to address that - additionally, memory cache test have been moved out of `payments` service to `misc` just so that, tests that are independent of business profile, mca, merchant account can be added here in the future - new command addition to miscellaneous tests: `npm run cypress:misc` - slight security improvement by forcing the api key to expire within `24` hours closes #6993 documentation will be updated later ### 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). --> Too many boiler plates, too many useless code ## 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)? --> ```sh # executed below command to cherry-pick cookie changes just so that userlogin work git cherry-pick -n ..fix-cookie-cypress # started cypress against stripe CYPRESS_CONNECTOR=stripe npm run cypress ``` stripe: <img width="556" alt="image" src="https://github.com/user-attachments/assets/df8c443f-d0ba-4f8b-ac65-a68ad5f7c89e" /> memory cache: <img width="554" alt="image" src="https://github.com/user-attachments/assets/10545633-7691-4841-831a-38f04ca9a91a" /> health check: <img width="467" alt="image" src="https://github.com/user-attachments/assets/3e14bd10-4f05-42c9-84f9-c925beae15e3" /> ci: ![image](https://github.com/user-attachments/assets/d48820dc-a102-4475-867e-4783c0430272) ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `npm run format` - [x] I addressed lints thrown by `npm run lint` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
cf82861e855bbd055fcbfc2367b23eaa58d8f842
juspay/hyperswitch
juspay__hyperswitch-6977
Bug: [BUG - Cypress] Cookie not passed in user APIs we need to pass cookies in user apis
2025-01-02T15:58:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> this pr fixes the issue where cookies are not being set when hitting user apis. - we need to set cookies. but cypress does not directly support that - `cy.setCookie()` method does not persist outside of the `it()` block - in order to make it persist, we need to set session using `cy.session()` method in the `beforeEach()` hook closes #6977 this pr, of course, does not fix the hooks (caching) issue. ### 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). --> NA ## 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="540" alt="image" src="https://github.com/user-attachments/assets/5d1f0463-e9a2-4ee7-9597-65151c85539e" /> every failure here is related to assertion and `globalState` where `connectorId` and `mcaId` not getting updated. This can be picked up a separate PR since the fix done in this PR is `P0` ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `npm run format && npm run lint -- --fix` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
7d00583a8076ef2f996345549b5e81c7f90361dc
juspay/hyperswitch
juspay__hyperswitch-6973
Bug: refactor(redis_interface): make the redis command for using scripts to write into redis Generic make the redis command for using scripts to write into redis as Generic
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 3c7ffa16ada..56e9ab98104 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -849,20 +849,23 @@ impl super::RedisConnectionPool { } #[instrument(level = "DEBUG", skip(self))] - pub async fn incr_keys_using_script<V>( + pub async fn evaluate_redis_script<V, T>( &self, lua_script: &'static str, key: Vec<String>, values: V, - ) -> CustomResult<(), errors::RedisError> + ) -> CustomResult<T, errors::RedisError> where V: TryInto<MultipleValues> + Debug + Send + Sync, V::Error: Into<fred::error::RedisError> + Send + Sync, + T: serde::de::DeserializeOwned + FromRedis, { - self.pool + let val: T = self + .pool .eval(lua_script, key, values) .await - .change_context(errors::RedisError::IncrementHashFieldFailed) + .change_context(errors::RedisError::IncrementHashFieldFailed)?; + Ok(val) } } @@ -955,11 +958,10 @@ mod tests { .await .expect("failed to create redis connection pool"); let lua_script = r#" - local results = {} for i = 1, #KEYS do - results[i] = redis.call("INCRBY", KEYS[i], ARGV[i]) + redis.call("INCRBY", KEYS[i], ARGV[i]) end - return results + return "#; let mut keys_and_values = HashMap::new(); for i in 0..10 { @@ -973,7 +975,45 @@ mod tests { .collect::<Vec<String>>(); // Act - let result = pool.incr_keys_using_script(lua_script, key, values).await; + let result = pool + .evaluate_redis_script::<_, ()>(lua_script, key, values) + .await; + + // Assert Setup + result.is_ok() + }) + }) + .await + .expect("Spawn block failure"); + + assert!(is_success); + } + #[tokio::test] + async fn test_getting_keys_using_scripts() { + let is_success = tokio::task::spawn_blocking(move || { + futures::executor::block_on(async { + // Arrange + let pool = RedisConnectionPool::new(&RedisSettings::default()) + .await + .expect("failed to create redis connection pool"); + let lua_script = r#" + local results = {} + for i = 1, #KEYS do + results[i] = redis.call("GET", KEYS[i]) + end + return results + "#; + let mut keys_and_values = HashMap::new(); + for i in 0..10 { + keys_and_values.insert(format!("key{}", i), i); + } + + let key = keys_and_values.keys().cloned().collect::<Vec<_>>(); + + // Act + let result = pool + .evaluate_redis_script::<_, String>(lua_script, key, 0) + .await; // Assert Setup result.is_ok()
2025-01-02T08:33:31Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description make the redis command for using scripts to write into redis Generic, for allowing the flexibility to update the redis ### 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? wrote a unit test for it ## 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
638e1f230a543a1ff2b7712d04b937a9a9db1969
juspay/hyperswitch
juspay__hyperswitch-6975
Bug: add support for relay refund incoming webhooks Some connectors, like Adyen, do not support a refund sync API, so we need to rely on refund webhooks for the status. To address this, support for relay refund webhooks needs to be added. To support this use case, a new webhook endpoint needs to be introduced for relay webhooks: `/webhooks/relay/{merchant_id}/{connector_id_or_name}` Once the webhook is identified as a relay webhook, it should be handled based on the flow type, such as refunds, payments, etc. For now, only support for relay refund webhooks has been added.
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index e6f4065eb7a..f99e3a450b2 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -120,6 +120,10 @@ pub enum WebhookResponseTracker { status: common_enums::MandateStatus, }, NoEffect, + Relay { + relay_id: common_utils::id_type::RelayId, + status: common_enums::RelayStatus, + }, } impl WebhookResponseTracker { @@ -132,6 +136,7 @@ impl WebhookResponseTracker { Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, + Self::Relay { .. } => None, } } @@ -144,6 +149,7 @@ impl WebhookResponseTracker { Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, + Self::Relay { .. } => None, } } } diff --git a/crates/common_utils/src/id_type/relay.rs b/crates/common_utils/src/id_type/relay.rs index 3ad64729fb7..c818671e0e5 100644 --- a/crates/common_utils/src/id_type/relay.rs +++ b/crates/common_utils/src/id_type/relay.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + crate::id_type!( RelayId, "A type for relay_id that can be used for relay ids" @@ -11,3 +13,12 @@ crate::impl_queryable_id_type!(RelayId); crate::impl_to_sql_from_sql_id_type!(RelayId); crate::impl_debug_id_type!(RelayId); + +impl FromStr for RelayId { + type Err = error_stack::Report<crate::errors::ValidationError>; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + let cow_string = std::borrow::Cow::Owned(s.to_string()); + Self::try_from(cow_string) + } +} diff --git a/crates/diesel_models/src/query/relay.rs b/crates/diesel_models/src/query/relay.rs index 034446fe6b5..217f6fd734d 100644 --- a/crates/diesel_models/src/query/relay.rs +++ b/crates/diesel_models/src/query/relay.rs @@ -1,4 +1,4 @@ -use diesel::{associations::HasTable, ExpressionMethods}; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods}; use super::generics; use crate::{ @@ -46,4 +46,18 @@ impl Relay { ) .await } + + pub async fn find_by_profile_id_connector_reference_id( + conn: &PgPooledConn, + profile_id: &common_utils::id_type::ProfileId, + connector_reference_id: &str, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::profile_id + .eq(profile_id.to_owned()) + .and(dsl::connector_reference_id.eq(connector_reference_id.to_owned())), + ) + .await + } } diff --git a/crates/hyperswitch_domain_models/src/relay.rs b/crates/hyperswitch_domain_models/src/relay.rs index 959ac8e7f61..8af58265c39 100644 --- a/crates/hyperswitch_domain_models/src/relay.rs +++ b/crates/hyperswitch_domain_models/src/relay.rs @@ -81,7 +81,7 @@ impl RelayUpdate { match response { Err(error) => Self::ErrorUpdate { error_code: error.code, - error_message: error.message, + error_message: error.reason.unwrap_or(error.message), status: common_enums::RelayStatus::Failure, }, Ok(response) => Self::StatusUpdate { diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index ff9849958b5..c29c5ff02c0 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -22,9 +22,9 @@ use crate::{ core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, - metrics, payments, - payments::tokenization, - refunds, utils as core_utils, + metrics, + payments::{self, tokenization}, + refunds, relay, utils as core_utils, webhooks::utils::construct_webhook_router_data, }, db::StorageInterface, @@ -62,6 +62,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, + is_relay_webhook: bool, ) -> RouterResponse<serde_json::Value> { let start_instant = Instant::now(); let (application_response, webhooks_response_tracker, serialized_req) = @@ -73,6 +74,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( key_store, connector_name_or_mca_id, body.clone(), + is_relay_webhook, )) .await?; @@ -118,6 +120,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( Ok(application_response) } +#[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( state: SessionState, @@ -127,6 +130,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( key_store: domain::MerchantKeyStore, connector_name_or_mca_id: &str, body: actix_web::web::Bytes, + is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, @@ -361,120 +365,162 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( id: profile_id.get_string_repr().to_owned(), })?; - let result_response = match flow_type { - api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( + // If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow + let result_response = if is_relay_webhook { + let relay_webhook_response = Box::pin(relay_incoming_webhook_flow( state.clone(), - req_state, merchant_account, business_profile, key_store, webhook_details, - source_verified, - &connector, - &request_details, event_type, - )) - .await - .attach_printable("Incoming webhook flow for payments failed"), - - api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - connector_name.as_str(), source_verified, - event_type, )) .await - .attach_printable("Incoming webhook flow for refunds failed"), + .attach_printable("Incoming webhook flow for relay failed"); - api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - source_verified, - &connector, - &request_details, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for disputes failed"), + // Using early return ensures unsupported webhooks are acknowledged to the connector + if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response + .as_ref() + .err() + .map(|a| a.current_context()) + { + logger::error!( + webhook_payload =? request_details.body, + "Failed while identifying the event type", + ); - api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( - state.clone(), - req_state, - merchant_account, - business_profile, - key_store, - webhook_details, - source_verified, - )) - .await - .attach_printable("Incoming bank-transfer webhook flow failed"), + let response = connector + .get_webhook_api_response(&request_details, None) + .switch() + .attach_printable( + "Failed while early return in case of not supported event type in relay webhooks", + )?; + + return Ok(( + response, + WebhookResponseTracker::NoEffect, + serde_json::Value::Null, + )); + }; - api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect), + relay_webhook_response + } else { + match flow_type { + api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow( + state.clone(), + req_state, + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + &connector, + &request_details, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for payments failed"), - api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - source_verified, - event_type, - )) - .await - .attach_printable("Incoming webhook flow for mandates failed"), + api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + connector_name.as_str(), + source_verified, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for refunds failed"), - api::WebhookFlow::ExternalAuthentication => { - Box::pin(external_authentication_incoming_webhook_flow( + api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + &connector, + &request_details, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for disputes failed"), + + api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow( + state.clone(), + req_state, + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + )) + .await + .attach_printable("Incoming bank-transfer webhook flow failed"), + + api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect), + + api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + source_verified, + event_type, + )) + .await + .attach_printable("Incoming webhook flow for mandates failed"), + + api::WebhookFlow::ExternalAuthentication => { + Box::pin(external_authentication_incoming_webhook_flow( + state.clone(), + req_state, + merchant_account, + key_store, + source_verified, + event_type, + &request_details, + &connector, + object_ref_id, + business_profile, + merchant_connector_account, + )) + .await + .attach_printable("Incoming webhook flow for external authentication failed") + } + api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( state.clone(), req_state, merchant_account, key_store, source_verified, event_type, - &request_details, - &connector, object_ref_id, business_profile, - merchant_connector_account, )) .await - .attach_printable("Incoming webhook flow for external authentication failed") - } - api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow( - state.clone(), - req_state, - merchant_account, - key_store, - source_verified, - event_type, - object_ref_id, - business_profile, - )) - .await - .attach_printable("Incoming webhook flow for fraud check failed"), + .attach_printable("Incoming webhook flow for fraud check failed"), - #[cfg(feature = "payouts")] - api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( - state.clone(), - merchant_account, - business_profile, - key_store, - webhook_details, - event_type, - source_verified, - )) - .await - .attach_printable("Incoming webhook flow for payouts failed"), + #[cfg(feature = "payouts")] + api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow( + state.clone(), + merchant_account, + business_profile, + key_store, + webhook_details, + event_type, + source_verified, + )) + .await + .attach_printable("Incoming webhook flow for payouts failed"), - _ => Err(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Unsupported Flow Type received in incoming webhooks"), + _ => Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unsupported Flow Type received in incoming webhooks"), + } }; match result_response { @@ -836,6 +882,97 @@ async fn payouts_incoming_webhook_flow( } } +async fn relay_refunds_incoming_webhook_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: domain::Profile, + merchant_key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + event_type: webhooks::IncomingWebhookEvent, + source_verified: bool, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + let db = &*state.store; + let key_manager_state = &(&state).into(); + + let relay_record = match webhook_details.object_reference_id { + webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type { + webhooks::RefundIdType::RefundId(refund_id) => { + let relay_id = common_utils::id_type::RelayId::from_str(&refund_id) + .change_context(errors::ValidationError::IncorrectValueProvided { + field_name: "relay_id", + }) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + db.find_relay_by_id(key_manager_state, &merchant_key_store, &relay_id) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the relay record")? + } + webhooks::RefundIdType::ConnectorRefundId(connector_refund_id) => db + .find_relay_by_profile_id_connector_reference_id( + key_manager_state, + &merchant_key_store, + business_profile.get_id(), + &connector_refund_id, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the relay record")?, + }, + _ => Err(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("received a non-refund id when processing relay refund webhooks")?, + }; + + // if source_verified then update relay status else trigger relay force sync + let relay_response = if source_verified { + let relay_update = hyperswitch_domain_models::relay::RelayUpdate::StatusUpdate { + connector_reference_id: None, + status: common_enums::RelayStatus::foreign_try_from(event_type) + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("failed relay refund status mapping from event type")?, + }; + db.update_relay( + key_manager_state, + &merchant_key_store, + relay_record, + relay_update, + ) + .await + .map(api_models::relay::RelayResponse::from) + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to update relay")? + } else { + let relay_retrieve_request = api_models::relay::RelayRetrieveRequest { + force_sync: true, + id: relay_record.id, + }; + let relay_force_sync_response = Box::pin(relay::relay_retrieve( + state, + merchant_account, + Some(business_profile.get_id().clone()), + merchant_key_store, + relay_retrieve_request, + )) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to force sync relay")?; + + if let hyperswitch_domain_models::api::ApplicationResponse::Json(response) = + relay_force_sync_response + { + response + } else { + Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unexpected response from force sync relay")? + } + }; + + Ok(WebhookResponseTracker::Relay { + relay_id: relay_response.id, + status: relay_response.status, + }) +} + #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn refunds_incoming_webhook_flow( @@ -938,6 +1075,44 @@ async fn refunds_incoming_webhook_flow( }) } +async fn relay_incoming_webhook_flow( + state: SessionState, + merchant_account: domain::MerchantAccount, + business_profile: domain::Profile, + merchant_key_store: domain::MerchantKeyStore, + webhook_details: api::IncomingWebhookDetails, + event_type: webhooks::IncomingWebhookEvent, + source_verified: bool, +) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + let flow_type: api::WebhookFlow = event_type.into(); + + let result_response = match flow_type { + webhooks::WebhookFlow::Refund => Box::pin(relay_refunds_incoming_webhook_flow( + state, + merchant_account, + business_profile, + merchant_key_store, + webhook_details, + event_type, + source_verified, + )) + .await + .attach_printable("Incoming webhook flow for relay refund failed")?, + webhooks::WebhookFlow::Payment + | webhooks::WebhookFlow::Payout + | webhooks::WebhookFlow::Dispute + | webhooks::WebhookFlow::Subscription + | webhooks::WebhookFlow::ReturnResponse + | webhooks::WebhookFlow::BankTransfer + | webhooks::WebhookFlow::Mandate + | webhooks::WebhookFlow::ExternalAuthentication + | webhooks::WebhookFlow::FraudCheck => Err(errors::ApiErrorResponse::NotSupported { + message: "Relay webhook flow types not supported".to_string(), + })?, + }; + Ok(result_response) +} + async fn get_payment_attempt_from_object_reference_id( state: &SessionState, object_reference_id: webhooks::ObjectReferenceId, diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs index 569cd330a07..5935c8d4979 100644 --- a/crates/router/src/core/webhooks/incoming_v2.rs +++ b/crates/router/src/core/webhooks/incoming_v2.rs @@ -56,6 +56,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( key_store: domain::MerchantKeyStore, connector_id: &common_utils::id_type::MerchantConnectorAccountId, body: actix_web::web::Bytes, + is_relay_webhook: bool, ) -> RouterResponse<serde_json::Value> { let start_instant = Instant::now(); let (application_response, webhooks_response_tracker, serialized_req) = @@ -68,6 +69,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( key_store, connector_id, body.clone(), + is_relay_webhook, )) .await?; @@ -124,6 +126,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( key_store: domain::MerchantKeyStore, connector_id: &common_utils::id_type::MerchantConnectorAccountId, body: actix_web::web::Bytes, + _is_relay_webhook: bool, ) -> errors::RouterResult<( services::ApplicationResponse<serde_json::Value>, WebhookResponseTracker, diff --git a/crates/router/src/db/relay.rs b/crates/router/src/db/relay.rs index 46259679c55..2ead84019d8 100644 --- a/crates/router/src/db/relay.rs +++ b/crates/router/src/db/relay.rs @@ -35,6 +35,14 @@ pub trait RelayInterface { merchant_key_store: &domain::MerchantKeyStore, relay_id: &common_utils::id_type::RelayId, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; + + async fn find_relay_by_profile_id_connector_reference_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + profile_id: &common_utils::id_type::ProfileId, + connector_reference_id: &str, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; } #[async_trait::async_trait] @@ -105,6 +113,30 @@ impl RelayInterface for Store { .await .change_context(errors::StorageError::DecryptionError) } + + async fn find_relay_by_profile_id_connector_reference_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + profile_id: &common_utils::id_type::ProfileId, + connector_reference_id: &str, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + diesel_models::relay::Relay::find_by_profile_id_connector_reference_id( + &conn, + profile_id, + connector_reference_id, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error)))? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } } #[async_trait::async_trait] @@ -136,6 +168,16 @@ impl RelayInterface for MockDb { ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } + + async fn find_relay_by_profile_id_connector_reference_id( + &self, + _key_manager_state: &KeyManagerState, + _merchant_key_store: &domain::MerchantKeyStore, + _profile_id: &common_utils::id_type::ProfileId, + _connector_reference_id: &str, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } } #[async_trait::async_trait] @@ -178,4 +220,21 @@ impl RelayInterface for KafkaStore { .find_relay_by_id(key_manager_state, merchant_key_store, relay_id) .await } + + async fn find_relay_by_profile_id_connector_reference_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + profile_id: &common_utils::id_type::ProfileId, + connector_reference_id: &str, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { + self.diesel_store + .find_relay_by_profile_id_connector_reference_id( + key_manager_state, + merchant_key_store, + profile_id, + connector_reference_id, + ) + .await + } } diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 4fe9318f64b..8c2bca5a82e 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -142,6 +142,7 @@ pub fn mk_app( .service(routes::Customers::server(state.clone())) .service(routes::Configs::server(state.clone())) .service(routes::MerchantConnectorAccount::server(state.clone())) + .service(routes::RelayWebhooks::server(state.clone())) .service(routes::Webhooks::server(state.clone())) .service(routes::Relay::server(state.clone())); diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs index 462861d331f..22f5983e4c3 100644 --- a/crates/router/src/routes.rs +++ b/crates/router/src/routes.rs @@ -69,7 +69,7 @@ pub use self::app::{ ApiKeys, AppState, ApplePayCertificatesMigration, Cache, Cards, Configs, ConnectorOnboarding, Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm, Health, Mandates, MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, - Profile, ProfileNew, Refunds, Relay, SessionState, User, Webhooks, + Profile, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState, User, Webhooks, }; #[cfg(feature = "olap")] pub use self::app::{Blocklist, Organization, Routing, Verify, WebhookEvents}; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f8b5ef44567..2a9561c06c8 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1515,6 +1515,20 @@ impl Webhooks { } } +pub struct RelayWebhooks; + +#[cfg(feature = "oltp")] +impl RelayWebhooks { + pub fn server(state: AppState) -> Scope { + use api_models::webhooks as webhook_type; + web::scope("/webhooks/relay") + .app_data(web::Data::new(state)) + .service(web::resource("/{merchant_id}/{connector_id}").route( + web::post().to(receive_incoming_relay_webhook::<webhook_type::OutgoingWebhook>), + )) + } +} + #[cfg(all(feature = "oltp", feature = "v2"))] impl Webhooks { pub fn server(config: AppState) -> Scope { diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 9d7ae1874c1..6550778619a 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -171,6 +171,7 @@ impl From<Flow> for ApiIdentifier { Flow::FrmFulfillment | Flow::IncomingWebhookReceive + | Flow::IncomingRelayWebhookReceive | Flow::WebhookEventInitialDeliveryAttemptList | Flow::WebhookEventDeliveryAttemptList | Flow::WebhookEventDeliveryRetry => Self::Webhooks, diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index 5427ac34b4e..1b3f28fd256 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -36,6 +36,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( auth.key_store, &connector_id_or_name, body.clone(), + false, ) }, &auth::MerchantIdAuth(merchant_id), @@ -44,6 +45,89 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))] +pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>( + state: web::Data<AppState>, + req: HttpRequest, + body: web::Bytes, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::MerchantConnectorAccountId, + )>, +) -> impl Responder { + let flow = Flow::IncomingWebhookReceive; + let (merchant_id, connector_id) = path.into_inner(); + let is_relay_webhook = true; + + Box::pin(api::server_wrap( + flow.clone(), + state, + &req, + (), + |state, auth, _, req_state| { + webhooks::incoming_webhooks_wrapper::<W>( + &flow, + state.to_owned(), + req_state, + &req, + auth.merchant_account, + auth.key_store, + connector_id.get_string_repr(), + body.clone(), + is_relay_webhook, + ) + }, + &auth::MerchantIdAuth(merchant_id), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::IncomingRelayWebhookReceive))] +pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>( + state: web::Data<AppState>, + req: HttpRequest, + body: web::Bytes, + path: web::Path<( + common_utils::id_type::MerchantId, + common_utils::id_type::ProfileId, + common_utils::id_type::MerchantConnectorAccountId, + )>, +) -> impl Responder { + let flow = Flow::IncomingWebhookReceive; + let (merchant_id, profile_id, connector_id) = path.into_inner(); + let is_relay_webhook = true; + + Box::pin(api::server_wrap( + flow.clone(), + state, + &req, + (), + |state, auth, _, req_state| { + webhooks::incoming_webhooks_wrapper::<W>( + &flow, + state.to_owned(), + req_state, + &req, + auth.merchant_account, + auth.profile, + auth.key_store, + &connector_id, + body.clone(), + is_relay_webhook, + ) + }, + &auth::MerchantIdAndProfileIdAuth { + merchant_id, + profile_id, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::IncomingWebhookReceive))] #[cfg(feature = "v2")] pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( @@ -75,6 +159,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( auth.key_store, &connector_id, body.clone(), + false, ) }, &auth::MerchantIdAndProfileIdAuth { diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index bbcdfc535df..cb7d3f78f78 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -662,6 +662,22 @@ impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enum } } +impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for api_enums::RelayStatus { + type Error = errors::ValidationError; + + fn foreign_try_from( + value: api_models::webhooks::IncomingWebhookEvent, + ) -> Result<Self, Self::Error> { + match value { + api_models::webhooks::IncomingWebhookEvent::RefundSuccess => Ok(Self::Success), + api_models::webhooks::IncomingWebhookEvent::RefundFailure => Ok(Self::Failure), + _ => Err(errors::ValidationError::IncorrectValueProvided { + field_name: "incoming_webhook_event_type", + }), + } + } +} + #[cfg(feature = "payouts")] impl ForeignTryFrom<api_models::webhooks::IncomingWebhookEvent> for storage_enums::PayoutStatus { type Error = errors::ValidationError; diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 10183f75d5b..935efa3c78b 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -537,6 +537,8 @@ pub enum Flow { Relay, /// Relay retrieve flow RelayRetrieve, + /// Incoming Relay Webhook Receive + IncomingRelayWebhookReceive, } /// Trait for providing generic behaviour to flow metric diff --git a/migrations/2025-01-07-105739_create_index_for_relay/down.sql b/migrations/2025-01-07-105739_create_index_for_relay/down.sql new file mode 100644 index 00000000000..8a75d445466 --- /dev/null +++ b/migrations/2025-01-07-105739_create_index_for_relay/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +DROP INDEX relay_profile_id_connector_reference_id_index; \ No newline at end of file diff --git a/migrations/2025-01-07-105739_create_index_for_relay/up.sql b/migrations/2025-01-07-105739_create_index_for_relay/up.sql new file mode 100644 index 00000000000..5ebe5983c74 --- /dev/null +++ b/migrations/2025-01-07-105739_create_index_for_relay/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +CREATE UNIQUE INDEX relay_profile_id_connector_reference_id_index ON relay (profile_id, connector_reference_id); \ No newline at end of file
2025-01-02T13:49: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 --> Some connectors, like Adyen, do not support a refund sync API, so we need to rely on refund webhooks for the status. To address this, support for relay refund webhooks is being added. To support this use case, a new webhook endpoint needs to be introduced for relay webhooks: /webhooks/relay/{merchant_id}/{connector_id_or_name} Once the webhook is identified as a relay webhook, it should be handled based on the flow type, such as refunds, payments, etc. For now, only support for relay refund webhooks has been added. ### 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). --> This change is to update the relay status when we have to rely on the connector webhooks for the refund status. ## 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 account for stripe -> Setup the webhook url in the stripe dashboard -> Relay webhook testing -> Make payment through stripe connector. As this relay webhooks can only handle relay refunds webhooks, we need to return 200 OK for the payments webhooks that we received. ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key:' \ --data-raw '{ "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1736430184", "return_url": "http://127.0.0.1:4040", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "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" }, "routing": { "type": "single", "data": { "connector": "cybersource", "merchant_connector_id": "mca_8W0CQfwE89J1BJBbpcnt" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_9IYMeErPOtFrHTxEundR", "merchant_id": "merchant_1736429319", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "stripe", "client_secret": "pay_9IYMeErPOtFrHTxEundR_secret_A9BwRKPAld2g2fPwpN0Z", "created": "2025-01-09T13:42:58.438Z", "currency": "USD", "customer_id": "cu_1736430178", "customer": { "id": "cu_1736430178", "name": "John Doe", "email": "[email protected]", "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": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "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": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "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": { "customer_id": "cu_1736430178", "created_at": 1736430178, "expires": 1736433778, "secret": "epk_54d28c2dcea8416fa84ce3ec9f960102" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3QfM0lD5R7gDAGff1L1eaicn", "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_3QfM0lD5R7gDAGff1L1eaicn", "payment_link": null, "profile_id": "pro_GhoiAnNpnyEAqAAbwULW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-09T13:57:58.438Z", "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": null, "payment_method_status": null, "updated": "2025-01-09T13:43:00.565Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` ![image](https://github.com/user-attachments/assets/8f422071-09fa-41a1-9ef3-096baed78c64) -> Create a relay refund ``` curl --location 'http://localhost:8080/relay' \ --header 'Content-Type: application/json' \ --header 'x-profile-id: pro_GhoiAnNpnyEAqAAbwULW' \ --header 'api-key:' \ --data '{ "connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "connector_resource_id": "pi_3QfM0lD5R7gDAGff1L1eaicn", "data": { "refund": { "amount": 1, "currency": "USD" } }, "type": "refund" }' ``` ``` { "id": "relay_WhRindDie9fcGbLRvE3G", "status": "success", "connector_resource_id": "pi_3QfM0lD5R7gDAGff1L1eaicn", "error": null, "connector_reference_id": "re_3QfM0lD5R7gDAGff1533tuY2", "connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "profile_id": "pro_GhoiAnNpnyEAqAAbwULW", "type": "refund", "data": { "refund": { "amount": 1, "currency": "USD", "reason": null } } } ``` ![image](https://github.com/user-attachments/assets/c9bca26d-2bf5-472b-b38c-686821b08b4a) -> Manually setting the db recording the pending to test relay status update by webhook ``` curl --location 'http://localhost:8080/relay/relay_WhRindDie9fcGbLRvE3G' \ --header 'Content-Type: application/json' \ --header 'X-Idempotency-Key: <x-idempotency-key>' \ --header 'X-Profile-Id: pro_GhoiAnNpnyEAqAAbwULW' \ --header 'api-key:' \ --data '' ``` ``` { "id": "relay_WhRindDie9fcGbLRvE3G", "status": "pending", "connector_resource_id": "pi_3QfM0lD5R7gDAGff1L1eaicn", "error": null, "connector_reference_id": "re_3QfM0lD5R7gDAGff1533tuY2", "connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "profile_id": "pro_GhoiAnNpnyEAqAAbwULW", "type": "refund", "data": { "refund": { "amount": 1, "currency": "USD", "reason": null } } } ``` -> Re trigger the relay webhook and when retrieved the status is expected to be succeeded ![image](https://github.com/user-attachments/assets/c860f611-7b81-49d8-85cd-55e7f52ad347) ``` curl --location 'http://localhost:8080/relay/relay_WhRindDie9fcGbLRvE3G' \ --header 'Content-Type: application/json' \ --header 'X-Idempotency-Key: <x-idempotency-key>' \ --header 'X-Profile-Id: pro_GhoiAnNpnyEAqAAbwULW' \ --header 'api-key:' \ --data '' ``` ``` { "id": "relay_WhRindDie9fcGbLRvE3G", "status": "success", "connector_resource_id": "pi_3QfM0lD5R7gDAGff1L1eaicn", "error": null, "connector_reference_id": "re_3QfM0lD5R7gDAGff1533tuY2", "connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "profile_id": "pro_GhoiAnNpnyEAqAAbwULW", "type": "refund", "data": { "refund": { "amount": 1, "currency": "USD", "reason": null } } } ``` -> Test stripe normal payments webhooks to ensure that the webhook behaviour is not affected for all other events -> Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-tenant-id: hyperswitch' \ --header 'api-key:' \ --data-raw '{ "amount": 100, "amount_to_capture": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "customer_id": "cu_1736432186", "return_url": "http://127.0.0.1:4040", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4111111111111111", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX", "last_name": "ss" }, "email": "[email protected]" }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "PiX" } }, "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" }, "routing": { "type": "single", "data": { "connector": "cybersource", "merchant_connector_id": "mca_8W0CQfwE89J1BJBbpcnt" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` ``` { "payment_id": "pay_bnl7rTJB6WUbfsQRTRU3", "merchant_id": "merchant_1736429319", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "stripe", "client_secret": "pay_bnl7rTJB6WUbfsQRTRU3_secret_YRCZCEKKcDxD6VnbtBGl", "created": "2025-01-09T14:07:10.134Z", "currency": "USD", "customer_id": "cu_1736431630", "customer": { "id": "cu_1736431630", "name": "John Doe", "email": "[email protected]", "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": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "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": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "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": { "customer_id": "cu_1736431630", "created_at": 1736431630, "expires": 1736435230, "secret": "epk_bf70a02d2bb64f5c81712679dedac0aa" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3QfMOBD5R7gDAGff0l6jmTHK", "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_3QfMOBD5R7gDAGff0l6jmTHK", "payment_link": null, "profile_id": "pro_GhoiAnNpnyEAqAAbwULW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-09T14:22:10.134Z", "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": null, "payment_method_status": null, "updated": "2025-01-09T14:07:12.259Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Manually set the status to pending in the db to test webhooks flow ``` curl --location 'http://localhost:8080/payments/pay_bnl7rTJB6WUbfsQRTRU3' \ --header 'Accept: application/json' \ --header 'api-key:' ``` ``` { "payment_id": "pay_bnl7rTJB6WUbfsQRTRU3", "merchant_id": "merchant_1736429319", "status": "processing", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "stripe", "client_secret": "pay_bnl7rTJB6WUbfsQRTRU3_secret_YRCZCEKKcDxD6VnbtBGl", "created": "2025-01-09T14:07:10.134Z", "currency": "USD", "customer_id": "cu_1736431630", "customer": { "id": "cu_1736431630", "name": "John Doe", "email": "[email protected]", "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": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "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": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "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": false, "connector_transaction_id": "pi_3QfMOBD5R7gDAGff0l6jmTHK", "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_3QfMOBD5R7gDAGff0l6jmTHK", "payment_link": null, "profile_id": "pro_GhoiAnNpnyEAqAAbwULW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-09T14:22:10.134Z", "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_2aJAicSBjlanyP8w6jYQ", "payment_method_status": "active", "updated": "2025-01-09T14:15:56.696Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> resend the webhook and when retrieved the payment status is expected to be succeeded ``` curl --location 'http://localhost:8080/payments/pay_bnl7rTJB6WUbfsQRTRU3' \ --header 'Accept: application/json' \ --header 'api-key:' ``` ``` { "payment_id": "pay_bnl7rTJB6WUbfsQRTRU3", "merchant_id": "merchant_1736429319", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "stripe", "client_secret": "pay_bnl7rTJB6WUbfsQRTRU3_secret_YRCZCEKKcDxD6VnbtBGl", "created": "2025-01-09T14:07:10.134Z", "currency": "USD", "customer_id": "cu_1736431630", "customer": { "id": "cu_1736431630", "name": "John Doe", "email": "[email protected]", "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": "1111", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "411111", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "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": "San Fransico", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": null }, "phone": null, "email": null }, "billing": { "address": { "city": "San", "country": "US", "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "zip": "94122", "state": "California", "first_name": "PiX", "last_name": "ss" }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "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": false, "connector_transaction_id": "pi_3QfMOBD5R7gDAGff0l6jmTHK", "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_3QfMOBD5R7gDAGff0l6jmTHK", "payment_link": null, "profile_id": "pro_GhoiAnNpnyEAqAAbwULW", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_YhBV1Nr6PXdkkG7md9ro", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-09T14:22:10.134Z", "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_2aJAicSBjlanyP8w6jYQ", "payment_method_status": "active", "updated": "2025-01-09T14:21:04.293Z", "split_payments": 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
c4d36b506e159f39acff17e13f72b5c53edec184
juspay/hyperswitch
juspay__hyperswitch-6972
Bug: [feat] add multitenancy support to keymanager
diff --git a/config/config.example.toml b/config/config.example.toml index 99926632114..eb30435d5f8 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -762,7 +762,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants.public] base_url = "http://localhost:8080" # URL of the tenant diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 967b847dae5..809edf1bac6 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -303,7 +303,7 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants.public] base_url = "http://localhost:8080" diff --git a/config/development.toml b/config/development.toml index 4c9b8516b5a..e3631b96b17 100644 --- a/config/development.toml +++ b/config/development.toml @@ -794,7 +794,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +global_tenant = { tenant_id = "global" ,schema = "public", redis_key_prefix = "global", clickhouse_database = "default"} [multitenancy.tenants.public] base_url = "http://localhost:8080" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 75699d0a967..6f95380d2db 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -635,7 +635,7 @@ sdk_eligible_payment_methods = "card" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default" } +global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } [multitenancy.tenants.public] base_url = "http://localhost:8080" diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 3b437b703be..fdda26cc77c 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -149,3 +149,6 @@ pub const APPLEPAY_VALIDATION_URL: &str = /// Request ID pub const X_REQUEST_ID: &str = "x-request-id"; + +/// Default Tenant ID for the `Global` tenant +pub const DEFAULT_GLOBAL_TENANT_ID: &str = "global"; diff --git a/crates/common_utils/src/id_type/tenant.rs b/crates/common_utils/src/id_type/tenant.rs index 953bf82287a..0584496332a 100644 --- a/crates/common_utils/src/id_type/tenant.rs +++ b/crates/common_utils/src/id_type/tenant.rs @@ -1,4 +1,7 @@ -use crate::errors::{CustomResult, ValidationError}; +use crate::{ + consts::DEFAULT_GLOBAL_TENANT_ID, + errors::{CustomResult, ValidationError}, +}; crate::id_type!( TenantId, @@ -15,6 +18,13 @@ crate::impl_queryable_id_type!(TenantId); crate::impl_to_sql_from_sql_id_type!(TenantId); impl TenantId { + /// Get the default global tenant ID + pub fn get_default_global_tenant_id() -> Self { + Self(super::LengthId::new_unchecked( + super::AlphaNumericId::new_unchecked(DEFAULT_GLOBAL_TENANT_ID.to_string()), + )) + } + /// Get tenant id from String pub fn try_from_string(tenant_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(tenant_id)) diff --git a/crates/common_utils/src/keymanager.rs b/crates/common_utils/src/keymanager.rs index 53761951791..0dc05b22fd7 100644 --- a/crates/common_utils/src/keymanager.rs +++ b/crates/common_utils/src/keymanager.rs @@ -11,11 +11,11 @@ use once_cell::sync::OnceCell; use router_env::{instrument, logger, tracing}; use crate::{ - consts::BASE64_ENGINE, + consts::{BASE64_ENGINE, TENANT_HEADER}, errors, types::keymanager::{ BatchDecryptDataRequest, DataKeyCreateResponse, DecryptDataRequest, - EncryptionCreateRequest, EncryptionTransferRequest, KeyManagerState, + EncryptionCreateRequest, EncryptionTransferRequest, GetKeymanagerTenant, KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest, }, }; @@ -100,7 +100,7 @@ pub async fn call_encryption_service<T, R>( request_body: T, ) -> errors::CustomResult<R, errors::KeyManagerClientError> where - T: ConvertRaw + Send + Sync + 'static + Debug, + T: GetKeymanagerTenant + ConvertRaw + Send + Sync + 'static + Debug, R: serde::de::DeserializeOwned, { let url = format!("{}/{endpoint}", &state.url); @@ -122,6 +122,15 @@ where .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, )) } + + //Add Tenant ID + header.push(( + HeaderName::from_str(TENANT_HEADER) + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + HeaderValue::from_str(request_body.get_tenant_id(state).get_string_repr()) + .change_context(errors::KeyManagerClientError::FailedtoConstructHeader)?, + )); + let response = send_encryption_request( state, HeaderMap::from_iter(header.into_iter()), diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs index 09d26bd91ef..f18c6656207 100644 --- a/crates/common_utils/src/types/keymanager.rs +++ b/crates/common_utils/src/types/keymanager.rs @@ -23,8 +23,23 @@ use crate::{ transformers::{ForeignFrom, ForeignTryFrom}, }; +macro_rules! impl_get_tenant_for_request { + ($ty:ident) => { + impl GetKeymanagerTenant for $ty { + fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId { + match self.identifier { + Identifier::User(_) | Identifier::UserAuth(_) => state.global_tenant_id.clone(), + Identifier::Merchant(_) => state.tenant_id.clone(), + } + } + } + }; +} + #[derive(Debug, Clone)] pub struct KeyManagerState { + pub tenant_id: id_type::TenantId, + pub global_tenant_id: id_type::TenantId, pub enabled: bool, pub url: String, pub client_idle_timeout: Option<u64>, @@ -35,6 +50,11 @@ pub struct KeyManagerState { #[cfg(feature = "keymanager_mtls")] pub cert: Secret<String>, } + +pub trait GetKeymanagerTenant { + fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId; +} + #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)] #[serde(tag = "data_identifier", content = "key_identifier")] pub enum Identifier { @@ -70,6 +90,10 @@ pub struct BatchEncryptDataRequest { pub data: DecryptedDataGroup, } +impl_get_tenant_for_request!(EncryptionCreateRequest); +impl_get_tenant_for_request!(EncryptionTransferRequest); +impl_get_tenant_for_request!(BatchEncryptDataRequest); + impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest where S: Strategy<Vec<u8>>, @@ -219,6 +243,12 @@ pub struct DecryptDataRequest { pub data: StrongSecret<String>, } +impl_get_tenant_for_request!(EncryptDataRequest); +impl_get_tenant_for_request!(TransientBatchDecryptDataRequest); +impl_get_tenant_for_request!(TransientDecryptDataRequest); +impl_get_tenant_for_request!(BatchDecryptDataRequest); +impl_get_tenant_for_request!(DecryptDataRequest); + impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)> for FxHashMap<String, Encryptable<Secret<T, S>>> where diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 74f6502159d..3c38fa2a775 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -1,6 +1,7 @@ use std::collections::{HashMap, HashSet}; use api_models::{enums, payment_methods::RequiredFieldInfo}; +use common_utils::id_type; #[cfg(feature = "payouts")] pub mod payout_required_fields; @@ -138,6 +139,17 @@ impl Default for super::settings::KvConfig { } } +impl Default for super::settings::GlobalTenant { + fn default() -> Self { + Self { + tenant_id: id_type::TenantId::get_default_global_tenant_id(), + schema: String::from("global"), + redis_key_prefix: String::from("global"), + clickhouse_database: String::from("global"), + } + } +} + #[allow(clippy::derivable_impls)] impl Default for super::settings::ApiKeys { fn default() -> Self { diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index ad5d9e89aaa..737f8dfb980 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -137,7 +137,7 @@ pub struct Platform { pub enabled: bool, } -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Clone, Default, Deserialize)] pub struct Multitenancy { pub tenants: TenantConfig, pub enabled: bool, @@ -195,8 +195,10 @@ impl storage_impl::config::TenantConfig for Tenant { } } -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone)] pub struct GlobalTenant { + #[serde(default = "id_type::TenantId::get_default_global_tenant_id")] + pub tenant_id: id_type::TenantId, pub schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs index d4cd9ef62d7..bb123659060 100644 --- a/crates/router/src/types/domain/types.rs +++ b/crates/router/src/types/domain/types.rs @@ -7,6 +7,8 @@ impl From<&crate::SessionState> for KeyManagerState { fn from(state: &crate::SessionState) -> Self { let conf = state.conf.key_manager.get_inner(); Self { + global_tenant_id: state.conf.multitenancy.global_tenant.tenant_id.clone(), + tenant_id: state.tenant.tenant_id.clone(), enabled: conf.enabled, url: conf.url.clone(), client_idle_timeout: state.conf.proxy.idle_pool_connection_timeout, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index ec58ab08b87..b26b5b2e438 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -400,7 +400,7 @@ keys = "accept-language,user-agent,x-profile-id" [multitenancy] enabled = false -global_tenant = { schema = "public", redis_key_prefix = "" } +global_tenant = { tenant_id = "global", schema = "public", redis_key_prefix = "" } [multitenancy.tenants.public] base_url = "http://localhost:8080"
2025-01-02T09:46:41Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Enhancement ## Description <!-- Describe your changes in detail --> Adds tenant-id for every requests to keymanager ## 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). --> Added tenant id header for the keymanager service to classify key ids based on tenants. ## 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 Merchant Account with x-tenant-id as `public` ```bash curl --location 'http://localhost:8080/accounts' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'x-feature: integ-custom' \ --header 'x-tenant-id: public' \ --header 'api-key: test_admin' \ --data-raw '{ "merchant_id": "1735815159", "locker_id": "m0010", "merchant_name": "NewAge Retailer", "merchant_details": { "primary_contact_person": "John Test", "primary_email": "[email protected]", "primary_phone": "sunt laborum", "secondary_contact_person": "John Test2", "secondary_email": "[email protected]", "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://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": "default" } ] }' ``` - Get the `x-request-id` for the request and query it in grafana and see the if the tenant_id is `public` ![Screenshot 2025-01-02 at 4 24 01 PM](https://github.com/user-attachments/assets/eb9f2933-7390-4fa0-a9c7-33e6b522bc1e) ## 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
7d00583a8076ef2f996345549b5e81c7f90361dc
juspay/hyperswitch
juspay__hyperswitch-6979
Bug: [CHORE] extend Currency TYPE in DB with more variants ### Feature Description Below currencies to be added to the Currency type in DB AFN BTN CDF ERN IRR ISK KPW SDG SYP TJS TMT ZMW ZWL ### Possible Implementation Add diesel migrations ### 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/migrations/2025-01-03-084904_add_currencies/down.sql b/migrations/2025-01-03-084904_add_currencies/down.sql new file mode 100644 index 00000000000..e0ac49d1ecf --- /dev/null +++ b/migrations/2025-01-03-084904_add_currencies/down.sql @@ -0,0 +1 @@ +SELECT 1; diff --git a/migrations/2025-01-03-084904_add_currencies/up.sql b/migrations/2025-01-03-084904_add_currencies/up.sql new file mode 100644 index 00000000000..14167a32cfc --- /dev/null +++ b/migrations/2025-01-03-084904_add_currencies/up.sql @@ -0,0 +1,18 @@ +DO $$ + DECLARE currency TEXT; + BEGIN + FOR currency IN + SELECT + unnest( + ARRAY ['AFN', 'BTN', 'CDF', 'ERN', 'IRR', 'ISK', 'KPW', 'SDG', 'SYP', 'TJS', 'TMT', 'ZWL'] + ) AS currency + LOOP + IF NOT EXISTS ( + SELECT 1 + FROM pg_enum + WHERE enumlabel = currency + AND enumtypid = (SELECT oid FROM pg_type WHERE typname = 'Currency') + ) THEN EXECUTE format('ALTER TYPE "Currency" ADD VALUE %L', currency); + END IF; + END LOOP; +END $$; \ No newline at end of file
2025-01-03T08:54:40Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description This PR adds a diesel migration for including below variants in Currency ENUM in database ```AFN BTN CDF ERN IRR ISK KPW SDG SYP TJS TMT ZMW ZWL ``` ### 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? Ran migrations locally. ## 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
2aa14e7fec19b31d84745b524cbf835ff16b8ce8
juspay/hyperswitch
juspay__hyperswitch-6960
Bug: [REFACTOR] add info logs to log the grpc request and response
diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs index 404685025ed..7a627d3ab27 100644 --- a/crates/external_services/src/grpc_client.rs +++ b/crates/external_services/src/grpc_client.rs @@ -128,3 +128,13 @@ impl<T> AddHeaders for tonic::Request<T> { }); } } + +#[cfg(feature = "dynamic_routing")] +pub(crate) fn create_grpc_request<T: Debug>(message: T, headers: GrpcHeaders) -> tonic::Request<T> { + let mut request = tonic::Request::new(message); + request.add_headers_to_grpc_request(headers); + + logger::info!(dynamic_routing_request=?request); + + request +} diff --git a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs index bc5ce499727..17b332448e7 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs @@ -9,6 +9,7 @@ pub use elimination_rate::{ LabelWithBucketName, UpdateEliminationBucketRequest, UpdateEliminationBucketResponse, }; use error_stack::ResultExt; +use router_env::{instrument, logger, tracing}; #[allow( missing_docs, unused_qualifications, @@ -21,7 +22,7 @@ pub mod elimination_rate { } use super::{Client, DynamicRoutingError, DynamicRoutingResult}; -use crate::grpc_client::{AddHeaders, GrpcHeaders}; +use crate::grpc_client::{self, GrpcHeaders}; /// The trait Elimination Based Routing would have the functions required to support performance, calculation and invalidation bucket #[async_trait::async_trait] @@ -54,6 +55,7 @@ pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync { #[async_trait::async_trait] impl EliminationBasedRouting for EliminationAnalyserClient<Client> { + #[instrument(skip_all)] async fn perform_elimination_routing( &self, id: String, @@ -69,14 +71,15 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?; - let mut request = tonic::Request::new(EliminationRequest { - id, - params, - labels, - config, - }); - - request.add_headers_to_grpc_request(headers); + let request = grpc_client::create_grpc_request( + EliminationRequest { + id, + params, + labels, + config, + }, + headers, + ); let response = self .clone() @@ -87,9 +90,12 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { ))? .into_inner(); + logger::info!(dynamic_routing_response=?response); + Ok(response) } + #[instrument(skip_all)] async fn update_elimination_bucket_config( &self, id: String, @@ -110,14 +116,15 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { }) .collect::<Vec<_>>(); - let mut request = tonic::Request::new(UpdateEliminationBucketRequest { - id, - params, - labels_with_bucket_name, - config, - }); - - request.add_headers_to_grpc_request(headers); + let request = grpc_client::create_grpc_request( + UpdateEliminationBucketRequest { + id, + params, + labels_with_bucket_name, + config, + }, + headers, + ); let response = self .clone() @@ -127,16 +134,19 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { "Failed to update the elimination bucket".to_string(), ))? .into_inner(); + + logger::info!(dynamic_routing_response=?response); + Ok(response) } + + #[instrument(skip_all)] async fn invalidate_elimination_bucket( &self, id: String, headers: GrpcHeaders, ) -> DynamicRoutingResult<InvalidateBucketResponse> { - let mut request = tonic::Request::new(InvalidateBucketRequest { id }); - - request.add_headers_to_grpc_request(headers); + let request = grpc_client::create_grpc_request(InvalidateBucketRequest { id }, headers); let response = self .clone() @@ -146,6 +156,9 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { "Failed to invalidate the elimination bucket".to_string(), ))? .into_inner(); + + logger::info!(dynamic_routing_response=?response); + Ok(response) } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs index 3cf06ab63be..fca4ff61fcc 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs @@ -4,6 +4,7 @@ use api_models::routing::{ }; use common_utils::{ext_traits::OptionExt, transformers::ForeignTryFrom}; use error_stack::ResultExt; +use router_env::{instrument, logger, tracing}; pub use success_rate::{ success_rate_calculator_client::SuccessRateCalculatorClient, CalSuccessRateConfig, CalSuccessRateRequest, CalSuccessRateResponse, @@ -15,13 +16,14 @@ pub use success_rate::{ missing_docs, unused_qualifications, clippy::unwrap_used, - clippy::as_conversions + clippy::as_conversions, + clippy::use_self )] pub mod success_rate { tonic::include_proto!("success_rate"); } use super::{Client, DynamicRoutingError, DynamicRoutingResult}; -use crate::grpc_client::{AddHeaders, GrpcHeaders}; +use crate::grpc_client::{self, GrpcHeaders}; /// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window #[async_trait::async_trait] pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { @@ -53,6 +55,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { #[async_trait::async_trait] impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { + #[instrument(skip_all)] async fn calculate_success_rate( &self, id: String, @@ -71,14 +74,15 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { .map(ForeignTryFrom::foreign_try_from) .transpose()?; - let mut request = tonic::Request::new(CalSuccessRateRequest { - id, - params, - labels, - config, - }); - - request.add_headers_to_grpc_request(headers); + let request = grpc_client::create_grpc_request( + CalSuccessRateRequest { + id, + params, + labels, + config, + }, + headers, + ); let response = self .clone() @@ -89,9 +93,12 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { ))? .into_inner(); + logger::info!(dynamic_routing_response=?response); + Ok(response) } + #[instrument(skip_all)] async fn update_success_rate( &self, id: String, @@ -113,14 +120,15 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { }) .collect(); - let mut request = tonic::Request::new(UpdateSuccessRateWindowRequest { - id, - params, - labels_with_status, - config, - }); - - request.add_headers_to_grpc_request(headers); + let request = grpc_client::create_grpc_request( + UpdateSuccessRateWindowRequest { + id, + params, + labels_with_status, + config, + }, + headers, + ); let response = self .clone() @@ -131,16 +139,18 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { ))? .into_inner(); + logger::info!(dynamic_routing_response=?response); + Ok(response) } + + #[instrument(skip_all)] async fn invalidate_success_rate_routing_keys( &self, id: String, headers: GrpcHeaders, ) -> DynamicRoutingResult<InvalidateWindowsResponse> { - let mut request = tonic::Request::new(InvalidateWindowsRequest { id }); - - request.add_headers_to_grpc_request(headers); + let request = grpc_client::create_grpc_request(InvalidateWindowsRequest { id }, headers); let response = self .clone() @@ -150,6 +160,9 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { "Failed to invalidate the success rate routing keys".to_string(), ))? .into_inner(); + + logger::info!(dynamic_routing_response=?response); + Ok(response) } } diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 45bd0a6a015..271a5679282 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -37,6 +37,8 @@ use rand::{ distributions::{self, Distribution}, SeedableRng, }; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use router_env::{instrument, tracing}; use rustc_hash::FxHashMap; use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE}; @@ -1281,6 +1283,7 @@ pub fn make_dsl_input_for_surcharge( /// success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] pub async fn perform_success_based_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, diff --git a/proto/success_rate.proto b/proto/success_rate.proto index 38e56e36c0f..f49618bc4b6 100644 --- a/proto/success_rate.proto +++ b/proto/success_rate.proto @@ -55,7 +55,11 @@ message CurrentBlockThreshold { } message UpdateSuccessRateWindowResponse { - string message = 1; + enum UpdationStatus { + WINDOW_UPDATION_SUCCEEDED = 0; + WINDOW_UPDATION_FAILED = 1; + } + UpdationStatus status = 1; } // API-3 types @@ -64,5 +68,9 @@ message InvalidateWindowsRequest { } message InvalidateWindowsResponse { - string message = 1; + enum InvalidationStatus { + WINDOW_INVALIDATION_SUCCEEDED = 0; + WINDOW_INVALIDATION_FAILED = 1; + } + InvalidationStatus status = 1; } \ No newline at end of file
2024-12-30T16:03:02Z
## 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 the info logs to log the dynamic routing grpc requests and response objects. ### 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. Create merchant_account, api_key and mca (any connector) 2. Toggle dynamic routing ``` curl --location --request POST 'http://localhost:8080/account/merchant_1734609410/business_profile/pro_gPTjn9jLm0CxI8ZD1omL/dynamic_routing/success_based/toggle?enable=metrics' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K70Wr6zqJLbPECg8eEXrnZ43TW41JNUuXYHzRB50geiG0lViLExjxNUld6sgdNd0' \ --data '' ``` 3. Set 100% for dynamic_routing volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1734609410/business_profile/pro_gPTjn9jLm0CxI8ZD1omL/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: dev_GFInyC2oIihPleQ4CM8u8WOa02PxN5MHR5W1YAZyXxIYTHt8KDq2VPzRNn26JyJI' ``` 4. Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K70Wr6zqJLbPECg8eEXrnZ43TW41JNUuXYHzRB50geiG0lViLExjxNUld6sgdNd0' \ --data '{ "amount": 6540, "authentication_type": "no_three_ds", "confirm": true, "currency": "USD", "customer_acceptance": { "acceptance_type": "online" }, "customer_id": "cus_uYakn3OQTUtAgetLDOE1", "payment_method": "card", "payment_method_data": { "card": { "card_cvc": "123", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_number": "4242424242424242" } } }' ``` Check grafana logs for the payment matching keyword `dynamic_routing_request` and `dynamic_routing_response` Console request log - ![image](https://github.com/user-attachments/assets/cadec322-c22d-4288-b87b-c47976a8ac68) Console response log - ![image](https://github.com/user-attachments/assets/c0b81c33-70fb-4fae-a7c5-527ff7b1201d) ## 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
4664d4bc4b7e685ab6dfb9176a3309026d3032e9
juspay/hyperswitch
juspay__hyperswitch-6958
Bug: refactor(dynamic_routing): add non_deterministic value in SuccessBasedRoutingConclusiveState type ## Description <!-- Describe your changes in detail --> This will add a value `non_deterministic` in `SuccessBasedRoutingConclusiveState` type.
diff --git a/migrations/2024-12-18-124527_add_new_value_in_success_based_routing_conclusive_state/down.sql b/migrations/2024-12-18-124527_add_new_value_in_success_based_routing_conclusive_state/down.sql new file mode 100644 index 00000000000..2a3866c86d4 --- /dev/null +++ b/migrations/2024-12-18-124527_add_new_value_in_success_based_routing_conclusive_state/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +SELECT 1; diff --git a/migrations/2024-12-18-124527_add_new_value_in_success_based_routing_conclusive_state/up.sql b/migrations/2024-12-18-124527_add_new_value_in_success_based_routing_conclusive_state/up.sql new file mode 100644 index 00000000000..9e4a259c7ae --- /dev/null +++ b/migrations/2024-12-18-124527_add_new_value_in_success_based_routing_conclusive_state/up.sql @@ -0,0 +1,12 @@ +-- Your SQL goes here +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_enum + WHERE enumlabel = 'non_deterministic' + AND enumtypid = (SELECT oid FROM pg_type WHERE typname = 'SuccessBasedRoutingConclusiveState') + ) THEN + ALTER TYPE "SuccessBasedRoutingConclusiveState" ADD VALUE 'non_deterministic'; + END IF; +END $$;
2024-12-18T13:01:15Z
## 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 --> This will add a value `non_deterministic` in `SuccessBasedRoutingConclusiveState` type. ### Additional Changes - [ ] 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? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Toggle Success Based routing for the merchant. ``` curl --location --request POST 'http://localhost:8080/account/xxxxxx/business_profile/xxxxxxx/dynamic_routing/success_based/toggle?enable=metrics' \ --header 'api-key: xxxxxxx' ``` 2. Create a payment that goes in processing state or any non terminal state. 3. Check the `dynamic_routing_stats` table for the `payment_id` for the `non_determinisctic`. ## 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
db51ec43bc629dc20ceaa2bb57ede888d2d2fc2c
juspay/hyperswitch
juspay__hyperswitch-6951
Bug: refactor(payment_methods): update connector_mandate_details for card metadata changes Allow update of connector_mandate_details for card in case of metadata changes(in case of expiry changes). First the value is set as inactive and if a successful payment has been made then set it back to active
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 01a4e086091..e7101742676 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -200,6 +200,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor payment_method_billing_address, business_profile, connector_mandate_reference_id.clone(), + merchant_connector_id.clone(), )); let is_connector_mandate = resp.request.customer_acceptance.is_some() @@ -315,6 +316,7 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor payment_method_billing_address.as_ref(), &business_profile, connector_mandate_reference_id, + merchant_connector_id.clone(), )) .await; @@ -1099,6 +1101,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa payment_method_billing_address, business_profile, connector_mandate_reference_id, + merchant_connector_id.clone(), )) .await?; diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 89fb7752d1b..5f8d5fd8798 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -83,6 +83,7 @@ pub async fn save_payment_method<FData>( payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>, business_profile: &domain::Profile, mut original_connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, + merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, @@ -458,7 +459,41 @@ where resp.payment_method_id = payment_method_id; let existing_pm = match payment_method { - Ok(pm) => Ok(pm), + Ok(pm) => { + let mandate_details = pm + .connector_mandate_details + .clone() + .map(|val| { + val.parse_value::<diesel_models::PaymentsMandateReference>( + "PaymentsMandateReference", + ) + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; + if let Some((mandate_details, merchant_connector_id)) = + mandate_details.zip(merchant_connector_id) + { + let connector_mandate_details = + update_connector_mandate_details_status( + merchant_connector_id, + mandate_details, + ConnectorMandateStatus::Inactive, + )?; + payment_methods::cards::update_payment_method_connector_mandate_details( + state, + key_store, + db, + pm.clone(), + connector_mandate_details, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add payment method in db")?; + } + Ok(pm) + } Err(err) => { if err.current_context().is_db_not_found() { payment_methods::cards::create_payment_method( @@ -1252,3 +1287,37 @@ pub fn update_connector_mandate_details( Ok(connector_mandate_details) } + +#[cfg(feature = "v1")] +pub fn update_connector_mandate_details_status( + merchant_connector_id: id_type::MerchantConnectorAccountId, + mut payment_mandate_reference: diesel_models::PaymentsMandateReference, + status: ConnectorMandateStatus, +) -> RouterResult<Option<serde_json::Value>> { + let mandate_reference = { + payment_mandate_reference + .entry(merchant_connector_id) + .and_modify(|pm| { + let update_rec = diesel_models::PaymentsMandateReferenceRecord { + connector_mandate_id: pm.connector_mandate_id.clone(), + payment_method_type: pm.payment_method_type, + original_payment_authorized_amount: pm.original_payment_authorized_amount, + original_payment_authorized_currency: pm.original_payment_authorized_currency, + mandate_metadata: pm.mandate_metadata.clone(), + connector_mandate_status: Some(status), + connector_mandate_request_reference_id: pm + .connector_mandate_request_reference_id + .clone(), + }; + *pm = update_rec + }); + Some(payment_mandate_reference) + }; + let connector_mandate_details = mandate_reference + .map(|mandate| mandate.encode_to_value()) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to serialize customer acceptance to value")?; + + Ok(connector_mandate_details) +}
2024-12-16T10:09:23Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Allow update of `connector_mandate_details` for card in case of metadata changes(in case of expiry changes). First the value is set as inactive and if a successful payment has been made then set it back to active ### 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? - Nothreeds > - Create a MA and a MCA > - Make a off_Session save card payment > - Make a off_Session payment again with the same card just and changes expiry > - After a successful payment the Connector Mandate Details would be overriden <img width="1725" alt="Screenshot 2024-12-16 at 4 21 51 PM" src="https://github.com/user-attachments/assets/2c68dc5e-f27c-400d-9b16-3080029ccfb3" /> - Follow the same step for 3threeds > - Create a MA and a MCA > - Make a off_Session save card payment > - Make a off_Session payment again with the same card just and changed expiry > -Before a successful redirection ( the connector mandate is inactive) <img width="1725" alt="Screenshot 2024-12-16 at 4 23 50 PM" src="https://github.com/user-attachments/assets/69c74c67-f596-447e-baac-ea5191b3a7f0" /> > - After a successful redirection ( the connector mandate is active) <img width="1725" alt="Screenshot 2024-12-16 at 4 24 24 PM" src="https://github.com/user-attachments/assets/b141a8b1-2d91-4f68-b478-928d4f6149f2" /> ## 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
ed276ecc0017f7f98b6f8fa3841e6b8971f609f1
juspay/hyperswitch
juspay__hyperswitch-6948
Bug: rename `management_url` to `management_u_r_l` in the apple pay session response Parent issue describing the feature (https://github.com/juspay/hyperswitch/issues/6841) We need to rename `management_url` to `management_u_r_l` in the apple pay session response as our sdk converts the apple pay session request to camelCase before sending it to the apple pay team, after which `management_url` will be sent as `managementUrl`. But apple pay expects it to be passed as `managementURL`. Hence renaming it to `management_u_r_l` as that when it is converted to snake case it will be passed as `managementURL`.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 636723d808a..f1caede89cc 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3438,7 +3438,7 @@ "required": [ "payment_description", "regular_billing", - "management_url" + "management_u_r_l" ], "properties": { "payment_description": { @@ -3453,7 +3453,7 @@ "description": "A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment", "nullable": true }, - "management_url": { + "management_u_r_l": { "type": "string", "description": "A URL to a web page where the user can update or delete the payment method for the recurring payment", "example": "https://hyperswitch.io" diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index a1718944095..816c085b8fa 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6295,7 +6295,7 @@ pub struct ApplePayRecurringPaymentRequest { pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] - pub management_url: common_utils::types::Url, + pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index e532abaa7ea..79bcfb6a497 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -3480,7 +3480,7 @@ impl .recurring_payment_interval_count, }, billing_agreement: apple_pay_recurring_details.billing_agreement, - management_url: apple_pay_recurring_details.management_url, + management_u_r_l: apple_pay_recurring_details.management_url, } } }
2024-12-26T10:17:29Z
## 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 --> Parent issue describing the feature (https://github.com/juspay/hyperswitch/issues/6841) We need to rename `management_url` to `management_u_r_l` in the apple pay session response as our sdk converts the apple pay session request to camelCase before sending it to the apple pay team, after which `management_url` will be sent as `managementUrl`. But apple pay expects it to be passed as `managementURL`. Hence renaming it to `management_u_r_l` as that when it is converted to snake case it will be passed as `managementURL`. ### 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 account with apple pay enabled -> create a payment with recurring details passed in the `feature_metadata` ``` { "amount": 6500, "currency": "USD", "confirm": false, "amount_to_capture": 6500, "customer_id": "test_fb", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "three_ds", "return_url": "https://google.com", "email": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": { "payment_description": "this is the apple pay recurring payment", "regular_billing": { "label": "pay to hyperswitchs merchant", "recurring_payment_start_date": "2027-09-10T10:11:12.000Z", "recurring_payment_end_date": "2027-09-10T10:11:12.000Z", "recurring_payment_interval_unit": "year", "recurring_payment_interval_count": 1 }, "billing_agreement": "billing starts from the above mentioned start date", "management_url": "https://applepaydemo.apple.com/" } }, "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_id": "pay_IkF0eZObdRKHRaW2qPjP", "merchant_id": "merchant_1735037046", "status": "requires_payment_method", "amount": 6500, "net_amount": 6500, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_IkF0eZObdRKHRaW2qPjP_secret_NiGZ8jzWUD0Eul78MWKG", "created": "2024-12-26T10:11:17.687Z", "currency": "USD", "customer_id": "test_fb", "customer": { "id": "test_fb", "name": "Joseph Doe", "email": "[email protected]", "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": null, "payment_method_data": 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": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": "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": null, "connector_label": null, "business_country": null, "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "test_fb", "created_at": 1735207877, "expires": 1735211477, "secret": "epk_4a7844e8c4164df8806efc7aeda70607" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": { "payment_description": "this is the apple pay recurring payment", "regular_billing": { "label": "pay to hyperswitchs merchant", "recurring_payment_start_date": "2027-09-10T10:11:12.000Z", "recurring_payment_end_date": "2027-09-10T10:11:12.000Z", "recurring_payment_interval_unit": "year", "recurring_payment_interval_count": 1 }, "billing_agreement": "billing starts from the above mentioned start date", "management_url": "https://applepaydemo.apple.com/" } }, "reference_id": null, "payment_link": null, "profile_id": "pro_hyTvjhxF9uXvaibNrP0C", "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-12-26T10:26:17.687Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-26T10:11:17.740Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Make session call for above created payment ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_75f912a867024370a73d2e290b9f7623' \ --data '{ "payment_id": "pay_IkF0eZObdRKHRaW2qPjP", "wallets": [], "client_secret": "pay_IkF0eZObdRKHRaW2qPjP_secret_NiGZ8jzWUD0Eul78MWKG" }' ``` ``` { "payment_id": "pay_IkF0eZObdRKHRaW2qPjP", "client_secret": "pay_IkF0eZObdRKHRaW2qPjP_secret_NiGZ8jzWUD0Eul78MWKG", "session_token": [ { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1735207885750, "expires_at": 1735211485750, "merchant_session_identifier": "SSHABDD07E7A93F47A8AE218B19493987B6_CCE257A9D27B42513B2C3CA67DB49F602F3450D996C0811ED462EDCA0D7477FD", "nonce": "6a181236", "merchant_identifier": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813", "domain_name": "sdk-test-app.netlify.app", "display_name": "applepay", "signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018730820183020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313232363130313132355a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d010904312204209b43f7e26b7c35184723da6aa89977d89ebf53079f968db5b25d60ed379445b1300a06082a8648ce3d04030204463044022068fc0f182085841b99b8334ec5072017c4f32d93fdd8dac0b344a02f2c7797b3022024d835837764ddbf539c06781d2e41e37094d1c41f65c364da18aa6537e1ce17000000000000", "operational_analytics_identifier": "applepay:76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813", "retries": 0, "psp_id": "76B79A8E91F4D365B0B636C8F75CB207D52532E82C2C085DE79D6D8135EF3813" }, "payment_request_data": { "country_code": "US", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "65.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.com.hyperswitch.checkout", "recurring_payment_request": { "payment_description": "this is the apple pay recurring payment", "regular_billing": { "amount": "65.00", "label": "pay to hyperswitchs merchant", "payment_timing": "recurring", "recurring_payment_start_date": "2027-09-10T10:11:12.000Z", "recurring_payment_end_date": "2027-09-10T10:11:12.000Z", "recurring_payment_interval_unit": "year", "recurring_payment_interval_count": 1 }, "billing_agreement": "billing starts from the above mentioned start date", "management_u_r_l": "https://applepaydemo.apple.com/" } }, "connector": "stripe", "delayed_session_token": false, "sdk_next_action": { "next_action": "confirm" }, "connector_reference_id": null, "connector_sdk_public_key": null, "connector_merchant_id": null }, { "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": "65.00" }, "delayed_session_token": false, "connector": "stripe", "sdk_next_action": { "next_action": "confirm" }, "secrets": 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
b6249f226116a7cc96e602a8910e8b186eecda5b
juspay/hyperswitch
juspay__hyperswitch-6947
Bug: [BUG] Connector Required Fields for Mandates not present ### Bug Description Connector Required Fields for Mandates not present ### Expected Behavior Connector Required Fields for Mandates present ### Actual Behavior Connector Required Fields for Mandates not present ### 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/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 3eda9c2a91f..0a4d58c8ded 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -426,7 +426,8 @@ impl Default for settings::RequiredFields { enums::Connector::Bankofamerica, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::from( + non_mandate: HashMap::new(), + common: HashMap::from( [ ( "payment_method_data.card.card_number".to_string(), @@ -542,7 +543,6 @@ impl Default for settings::RequiredFields { ), ] ), - common: HashMap::new(), } ), ( @@ -9173,7 +9173,8 @@ impl Default for settings::RequiredFields { enums::Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::from( + non_mandate: HashMap::new(), + common: HashMap::from( [ ( "email".to_string(), @@ -9320,7 +9321,6 @@ impl Default for settings::RequiredFields { ), ] ), - common: HashMap::new(), } ), @@ -9600,7 +9600,9 @@ impl Default for settings::RequiredFields { enums::Connector::Multisafepay, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::from([ + non_mandate: HashMap::new(), + common: HashMap::from( + [ ( "billing.address.first_name".to_string(), RequiredFieldInfo { @@ -9676,8 +9678,8 @@ impl Default for settings::RequiredFields { field_type: enums::FieldType::UserAddressLine2, value: None, } - )]), - common: HashMap::new(), + )] + ), } ), ( @@ -9803,7 +9805,8 @@ impl Default for settings::RequiredFields { enums::Connector::Wellsfargo, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::from( + non_mandate: HashMap::new(), + common: HashMap::from( [ ( "email".to_string(), @@ -9950,7 +9953,6 @@ impl Default for settings::RequiredFields { ), ] ), - common: HashMap::new(), } ), ]),
2024-12-24T08:58:02Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The required fields were not added for mandates for some connectors. Those fields have been configured as `required` in this PR. Connectors I have checked for : Aci, Adyen, Authorizeddotnet, Globalpay, Multisafepay, Worldpay, Nexinets, Noon, Novalnet, Payme, Stripe, Bankofamerica, Cybersource, Wellsfargo ### 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. Worldpay** - **A) Create Payment** - Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_MA7DHjl9k4izCsQ42Vh7VJEKQeNy78RkGjIISOOrAbu78sRnpwuuuJmmipITEyae' \ --data-raw '{ "amount":1001, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1001, "customer_id": "StripeCustomer", "setup_future_usage": "off_session", "email": "[email protected]", "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": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "CA", "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": "CA", "line3": "CA", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "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, "ip_address": "127.2.2.0", "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true }, "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_HZXVkB3Sgivp05S4ZNb5", "merchant_id": "postman_merchant_GHAction_2df9b020-7ee8-4a4f-bbe8-fcfea85b6e97", "status": "requires_confirmation", "amount": 1001, "net_amount": 1001, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_HZXVkB3Sgivp05S4ZNb5_secret_vcAhY1ZDv6o3JUXQGD1O", "created": "2024-12-30T10:47:52.494Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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": "off_session", "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": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_mTYGZbORdGoUVjWd3HIB", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "CA", "line3": "CA", "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": "CA", "line3": "CA", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "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": "StripeCustomer", "created_at": 1735555672, "expires": 1735559272, "secret": "epk_598e7f9c98c5408bb9713a296458924e" }, "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_FXQzfrQDc9z2aCNJY9SG", "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-12-30T11:02:52.494Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.2.2.0", "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-12-30T10:47:52.525Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - **B) List Payment Method Merchant** - Request ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_HZXVkB3Sgivp05S4ZNb5_secret_vcAhY1ZDv6o3JUXQGD1O' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_6934f023b7e340578a6802a69b225f1e' ``` - Response ``` { "redirect_url": "https://duck.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] }, { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "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.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "94122" }, "billing.address.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "AF", "AU", "AW", "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", "DZ", "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" ] } }, "value": "US" }, "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_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "worldpay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "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.country": { "required_field": "billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "AF", "AU", "AW", "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", "DZ", "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" ] } }, "value": "US" }, "billing.address.zip": { "required_field": "billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "94122" } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` **2. Multisafepay** - **A) Create Payment** - Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_uaN1P2yDTIvML6tuSZabswFxSGfDz2xK63AoXpDeO6lEisiftVuZwXEpIxc4cGgH' \ --data-raw '{ "amount":1001, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 1001, "customer_id": "StripeCustomer", "setup_future_usage": "off_session", "email": "[email protected]", "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": "4242424242424242", "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": "joseph Doe", "card_cvc": "737" } }, "billing": { "address": { "line1": "1467", "line2": "CA", "line3": "CA", "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": "CA", "line3": "CA", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "joseph", "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, "ip_address": "127.2.2.0", "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled": true }, "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_CXaeXrSELBOHKt8WwrzN", "merchant_id": "postman_merchant_GHAction_4a25406a-bc96-4cfb-ae31-79d35d47eb57", "status": "requires_confirmation", "amount": 1001, "net_amount": 1001, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_CXaeXrSELBOHKt8WwrzN_secret_ZC42GH8feee79hkRIptR", "created": "2024-12-30T10:58:02.272Z", "currency": "USD", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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": "off_session", "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": "joseph Doe", "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_bFixxgfXyxtUjbRgGicv", "shipping": { "address": { "city": "San Fransico", "country": "US", "line1": "1467", "line2": "CA", "line3": "CA", "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": "CA", "line3": "CA", "zip": "94122", "state": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "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": "StripeCustomer", "created_at": 1735556282, "expires": 1735559882, "secret": "epk_c7c9dd7c672e45c1b61fbea9a77d0c2a" }, "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_wMwY5DYf61LpJu0wYwB1", "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-12-30T11:13:02.272Z", "fingerprint": null, "browser_info": { "language": "nl-NL", "time_zone": 0, "ip_address": "127.2.2.0", "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-12-30T10:58:02.310Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` - **B) List Payment Method Merchant** - Request ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_CXaeXrSELBOHKt8WwrzN_secret_ZC42GH8feee79hkRIptR' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_3bf61b76e332498a80708f11a3b017a2' ``` - Response ``` { "redirect_url": "https://duck.com/success", "currency": "USD", "payment_methods": [ { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": [ { "payment_experience_type": "redirect_to_url", "eligible_connectors": [ "multisafepay" ] } ], "card_networks": null, "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "San Fransico" }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "billing_last_name", "field_type": "user_billing_name", "value": "Doe" }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "94122" }, "billing.address.line2": { "required_field": "payment_method_data.billing.address.line2", "display_name": "line2", "field_type": "user_address_line2", "value": "CA" }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.state": { "required_field": "payment_method_data.billing.address.state", "display_name": "state", "field_type": "user_address_state", "value": "California" }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "1467" } }, "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": [ "multisafepay" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "multisafepay" ] } ], "bank_names": null, "bank_debits": null, "bank_transfers": null, "required_fields": { "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "San Fransico" }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.line2": { "required_field": "payment_method_data.billing.address.line2", "display_name": "line2", "field_type": "user_address_line2", "value": "CA" }, "billing.address.line1": { "required_field": "payment_method_data.billing.address.line1", "display_name": "line1", "field_type": "user_address_line1", "value": "1467" }, "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": "joseph" }, "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_cvc": { "required_field": "payment_method_data.card.card_cvc", "display_name": "card_cvc", "field_type": "user_card_cvc", "value": null }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "94122" }, "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 }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": "Doe" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "debit", "payment_experience": null, "card_networks": [ { "card_network": "Mastercard", "surcharge_details": null, "eligible_connectors": [ "multisafepay" ] }, { "card_network": "Visa", "surcharge_details": null, "eligible_connectors": [ "multisafepay" ] } ], "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": "1467" }, "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_number": { "required_field": "payment_method_data.card.card_number", "display_name": "card_number", "field_type": "user_card_number", "value": null }, "billing.address.city": { "required_field": "payment_method_data.billing.address.city", "display_name": "city", "field_type": "user_address_city", "value": "San Fransico" }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": "joseph" }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "94122" }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "card_holder_name", "field_type": "user_full_name", "value": "Doe" }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "ALL" ] } }, "value": "US" }, "billing.address.line2": { "required_field": "payment_method_data.billing.address.line2", "display_name": "line2", "field_type": "user_address_line2", "value": "CA" }, "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 } }, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "NewAge Retailer", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "is_tax_calculation_enabled": false } ``` **Cypress Tests** No3DSAutoCapture ![image](https://github.com/user-attachments/assets/361894d5-b8f8-4173-8d51-1de322f3ecbe) **No3DSManualCapture** ![image](https://github.com/user-attachments/assets/ccda8ba6-fb72-4aa5-b7d0-4462b0040626) **3DSAutoCapture** ![image](https://github.com/user-attachments/assets/0319f1b1-62f0-4e6a-98d7-2826e3e53726) **3DSManualCapture** ![image](https://github.com/user-attachments/assets/6b78ca67-e4b4-4252-82c9-a247126f2916) **SingleUseMandate** ![image](https://github.com/user-attachments/assets/08874e8e-cc70-4387-b911-9cfe6f3b46dc) **MultiUseMandate** ![image](https://github.com/user-attachments/assets/2a145d05-290f-44b5-afcd-f474e3d88e0e) ## 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
2b70c945406b1cf80831452b75e0c488eb60c86c
juspay/hyperswitch
juspay__hyperswitch-6955
Bug: [DOC] update cypress docs current docs are pretty much outdated
2024-12-28T17:24:37Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> Existing [docs](https://github.com/juspay/hyperswitch/tree/main/cypress-tests) are outdated to an extent and miss many feature updates. closes https://github.com/juspay/hyperswitch/issues/6955 ### 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). --> Update. ## 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)? --> Nah! ## Checklist <!-- Put an `x` in the boxes that apply --> - [x] I formatted the code `npm run format && npm run lint -- --fix` - [ ] I addressed lints thrown by `cargo clippy` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
e393a036fbde109d367e488807a53e919a12db90
juspay/hyperswitch
juspay__hyperswitch-6944
Bug: [REFACTOR] remove `tenant_id` prefix from `id` field in dynamic routing grpc requests
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 0a57819816f..8f3f40edf06 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1347,14 +1347,9 @@ pub async fn perform_success_based_routing( .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?, ); - let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id( - &state.tenant.redis_key_prefix, - business_profile.get_id().get_string_repr(), - ); - let success_based_connectors: CalSuccessRateResponse = client .calculate_success_rate( - tenant_business_profile_id, + business_profile.get_id().get_string_repr().into(), success_based_routing_configs, success_based_routing_config_params, routable_connectors, diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 5fc54fe96e5..717dfd0c6eb 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -1397,10 +1397,6 @@ pub async fn success_based_routing_update_configs( router_env::metric_attributes!(("profile_id", profile_id.clone())), ); - let prefix_of_dynamic_routing_keys = helpers::generate_tenant_business_profile_id( - &state.tenant.redis_key_prefix, - profile_id.get_string_repr(), - ); state .grpc_client .dynamic_routing @@ -1409,7 +1405,7 @@ pub async fn success_based_routing_update_configs( .async_map(|sr_client| async { sr_client .invalidate_success_rate_routing_keys( - prefix_of_dynamic_routing_keys, + profile_id.get_string_repr().into(), state.get_grpc_headers(), ) .await diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 489c3122a8e..0d66c3b6f17 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -699,11 +699,6 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("unable to retrieve success_rate based dynamic routing configs")?; - let tenant_business_profile_id = generate_tenant_business_profile_id( - &state.tenant.redis_key_prefix, - business_profile.get_id().get_string_repr(), - ); - let success_based_routing_config_params = success_based_routing_config_params_interpolator .get_string_val( success_based_routing_configs @@ -715,7 +710,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( let success_based_connectors = client .calculate_success_rate( - tenant_business_profile_id.clone(), + business_profile.get_id().get_string_repr().into(), success_based_routing_configs.clone(), success_based_routing_config_params.clone(), routable_connectors.clone(), @@ -841,7 +836,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( client .update_success_rate( - tenant_business_profile_id, + business_profile.get_id().get_string_repr().into(), success_based_routing_configs, success_based_routing_config_params, vec![routing_types::RoutableConnectorChoiceWithStatus::new( @@ -936,14 +931,6 @@ fn get_success_based_metrics_outcome_for_payment( } } -/// generates cache key with tenant's redis key prefix and profile_id -pub fn generate_tenant_business_profile_id( - redis_key_prefix: &str, - business_profile_id: &str, -) -> String { - format!("{}:{}", redis_key_prefix, business_profile_id) -} - #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn disable_dynamic_routing_algorithm( state: &SessionState,
2024-12-26T12:53:24Z
## 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 --> Since hyperswitch started sending tenant-id in headers of dynamic routing grpc requests, we can safely remove the tenant-id prefixed in `id` field ### 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. Create merchant_account, api_key and mca (any connector) 2. Toggle dynamic routing ``` curl --location --request POST 'http://localhost:8080/account/merchant_1734609410/business_profile/pro_gPTjn9jLm0CxI8ZD1omL/dynamic_routing/success_based/toggle?enable=metrics' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K70Wr6zqJLbPECg8eEXrnZ43TW41JNUuXYHzRB50geiG0lViLExjxNUld6sgdNd0' \ --data '' ``` 3. Set 100% for dynamic_routing volume split ``` curl --location --request POST 'http://localhost:8080/account/merchant_1734609410/business_profile/pro_gPTjn9jLm0CxI8ZD1omL/dynamic_routing/set_volume_split?split=100' \ --header 'api-key: dev_GFInyC2oIihPleQ4CM8u8WOa02PxN5MHR5W1YAZyXxIYTHt8KDq2VPzRNn26JyJI' ``` 4. Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K70Wr6zqJLbPECg8eEXrnZ43TW41JNUuXYHzRB50geiG0lViLExjxNUld6sgdNd0' \ --data '{ "amount": 6540, "authentication_type": "no_three_ds", "confirm": true, "currency": "USD", "customer_acceptance": { "acceptance_type": "online" }, "customer_id": "cus_uYakn3OQTUtAgetLDOE1", "payment_method": "card", "payment_method_data": { "card": { "card_cvc": "123", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_number": "4242424242424242" } } }' ``` Need to ssh into redis server for validating the key inserted from dynamo ## 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
295d3dde7749e7576dbdee4675528bb6dd6ffb70
juspay/hyperswitch
juspay__hyperswitch-6943
Bug: Update open-api spec of /relay request to make the data untagged enum Update open-api spec of /relay request to make the data untagged enum
diff --git a/crates/openapi/src/routes/relay.rs b/crates/openapi/src/routes/relay.rs index 9100bf47f75..180fed66492 100644 --- a/crates/openapi/src/routes/relay.rs +++ b/crates/openapi/src/routes/relay.rs @@ -13,8 +13,10 @@ "connector_id": "mca_5apGeP94tMts6rg3U3kR", "type": "refund", "data": { - "amount": 6540, - "currency": "USD" + "refund": { + "amount": 6540, + "currency": "USD" + } } }) )
2024-12-26T08:18:28Z
## 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 --> Update open-api spec of /relay request to make the data untagged enum. ### 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="1616" alt="image" src="https://github.com/user-attachments/assets/4ba7d3d6-9fcd-4a29-a7ff-62f0a5abda22" /> ## 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
b6249f226116a7cc96e602a8910e8b186eecda5b
juspay/hyperswitch
juspay__hyperswitch-6939
Bug: feat(users): Add email domain based restriction for dashboard entry APIs Currently Zurich uses okta and they use a specific `auth_id` to see the okta login method. If any user doesn't use `auth_id`, then the user will see the default auth methods that Hyperswitch has and they will be use them to login, which we should restrict for zurich users.
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 7b5911cf1a8..ea979bfe735 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -305,18 +305,26 @@ pub struct CreateUserAuthenticationMethodRequest { pub owner_type: common_enums::Owner, pub auth_method: AuthConfig, pub allow_signup: bool, + pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] -pub struct UpdateUserAuthenticationMethodRequest { - pub id: String, - // TODO: When adding more fields make config and new fields option - pub auth_method: AuthConfig, +#[serde(rename_all = "snake_case")] +pub enum UpdateUserAuthenticationMethodRequest { + AuthMethod { + id: String, + auth_config: AuthConfig, + }, + EmailDomain { + owner_id: String, + email_domain: String, + }, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserAuthenticationMethodsRequest { - pub auth_id: String, + pub auth_id: Option<String>, + pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/diesel_models/src/query/user_authentication_method.rs b/crates/diesel_models/src/query/user_authentication_method.rs index 14a28269cec..b9ed95e37c0 100644 --- a/crates/diesel_models/src/query/user_authentication_method.rs +++ b/crates/diesel_models/src/query/user_authentication_method.rs @@ -64,4 +64,18 @@ impl UserAuthenticationMethod { ) .await } + + pub async fn list_user_authentication_methods_for_email_domain( + conn: &PgPooledConn, + email_domain: &str, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( + conn, + dsl::email_domain.eq(email_domain.to_owned()), + None, + None, + Some(dsl::last_modified_at.asc()), + ) + .await + } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 178f5600542..01e21d7dd39 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1371,6 +1371,8 @@ diesel::table! { allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + email_domain -> Varchar, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index da2298d934b..da38c38ee2c 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1318,6 +1318,8 @@ diesel::table! { allow_signup -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + email_domain -> Varchar, } } diff --git a/crates/diesel_models/src/user_authentication_method.rs b/crates/diesel_models/src/user_authentication_method.rs index 76e1abe7575..7f3799aa7bf 100644 --- a/crates/diesel_models/src/user_authentication_method.rs +++ b/crates/diesel_models/src/user_authentication_method.rs @@ -17,6 +17,7 @@ pub struct UserAuthenticationMethod { pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub email_domain: String, } #[derive(router_derive::Setter, Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -32,6 +33,7 @@ pub struct UserAuthenticationMethodNew { pub allow_signup: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub email_domain: String, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] @@ -40,6 +42,7 @@ pub struct OrgAuthenticationMethodUpdateInternal { pub private_config: Option<Encryption>, pub public_config: Option<serde_json::Value>, pub last_modified_at: PrimitiveDateTime, + pub email_domain: Option<String>, } pub enum UserAuthenticationMethodUpdate { @@ -47,6 +50,9 @@ pub enum UserAuthenticationMethodUpdate { private_config: Option<Encryption>, public_config: Option<serde_json::Value>, }, + EmailDomain { + email_domain: String, + }, } impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInternal { @@ -60,6 +66,13 @@ impl From<UserAuthenticationMethodUpdate> for OrgAuthenticationMethodUpdateInter private_config, public_config, last_modified_at, + email_domain: None, + }, + UserAuthenticationMethodUpdate::EmailDomain { email_domain } => Self { + private_config: None, + public_config: None, + last_modified_at, + email_domain: Some(email_domain), }, } } diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index fa5f185ab82..6af269d916b 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -108,6 +108,8 @@ pub enum UserErrors { InvalidThemeLineage(String), #[error("Missing required field: email_config")] MissingEmailConfig, + #[error("Invalid Auth Method Operation: {0}")] + InvalidAuthMethodOperationWithMessage(String), } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -280,6 +282,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::MissingEmailConfig => { AER::BadRequest(ApiError::new(sub_code, 56, self.get_error_message(), None)) } + Self::InvalidAuthMethodOperationWithMessage(_) => { + AER::BadRequest(ApiError::new(sub_code, 57, self.get_error_message(), None)) + } } } } @@ -347,6 +352,9 @@ impl UserErrors { format!("Invalid field: {} in lineage", field_name) } Self::MissingEmailConfig => "Missing required field: email_config".to_string(), + Self::InvalidAuthMethodOperationWithMessage(operation) => { + format!("Invalid Auth Method Operation: {}", operation) + } } } } diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 642473bdf8e..b1d99e9e1d6 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -7,7 +7,7 @@ use api_models::{ payments::RedirectionResponse, user::{self as user_api, InviteMultipleUserResponse, NameIdUnit}, }; -use common_enums::EntityType; +use common_enums::{EntityType, UserAuthType}; use common_utils::{type_name, types::keymanager::Identifier}; #[cfg(feature = "email")] use diesel_models::user_role::UserRoleUpdate; @@ -22,6 +22,7 @@ use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "email")] use router_env::env; use router_env::logger; +use storage_impl::errors::StorageError; #[cfg(not(feature = "email"))] use user_api::dashboard_metadata::SetMetaDataRequest; @@ -151,6 +152,14 @@ pub async fn signup_token_only_flow( state: SessionState, request: user_api::SignUpRequest, ) -> UserResponse<user_api::TokenResponse> { + let user_email = domain::UserEmail::from_pii_email(request.email.clone())?; + utils::user::validate_email_domain_auth_type_using_db( + &state, + &user_email, + UserAuthType::Password, + ) + .await?; + let new_user = domain::NewUser::try_from(request)?; new_user .get_new_merchant() @@ -186,9 +195,18 @@ pub async fn signin_token_only_flow( state: SessionState, request: user_api::SignInRequest, ) -> UserResponse<user_api::TokenResponse> { + let user_email = domain::UserEmail::from_pii_email(request.email)?; + + utils::user::validate_email_domain_auth_type_using_db( + &state, + &user_email, + UserAuthType::Password, + ) + .await?; + let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) + .find_user_by_email(&user_email) .await .to_not_found_response(UserErrors::InvalidCredentials)? .into(); @@ -214,10 +232,16 @@ pub async fn connect_account( auth_id: Option<String>, theme_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { - let find_user = state - .global_store - .find_user_by_email(&domain::UserEmail::from_pii_email(request.email.clone())?) - .await; + let user_email = domain::UserEmail::from_pii_email(request.email.clone())?; + + utils::user::validate_email_domain_auth_type_using_db( + &state, + &user_email, + UserAuthType::MagicLink, + ) + .await?; + + let find_user = state.global_store.find_user_by_email(&user_email).await; if let Ok(found_user) = find_user { let user_from_db: domain::UserFromStorage = found_user.into(); @@ -408,6 +432,13 @@ pub async fn forgot_password( ) -> UserResponse<()> { let user_email = domain::UserEmail::from_pii_email(request.email)?; + utils::user::validate_email_domain_auth_type_using_db( + &state, + &user_email, + UserAuthType::Password, + ) + .await?; + let user_from_db = state .global_store .find_user_by_email(&user_email) @@ -1749,7 +1780,15 @@ pub async fn send_verification_mail( auth_id: Option<String>, theme_id: Option<String>, ) -> UserResponse<()> { - let user_email = domain::UserEmail::try_from(req.email)?; + let user_email = domain::UserEmail::from_pii_email(req.email)?; + + utils::user::validate_email_domain_auth_type_using_db( + &state, + &user_email, + UserAuthType::MagicLink, + ) + .await?; + let user = state .global_store .find_user_by_email(&user_email) @@ -2308,10 +2347,30 @@ pub async fn create_user_authentication_method( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get list of auth methods for the owner id")?; - let auth_id = auth_methods - .first() - .map(|auth_method| auth_method.auth_id.clone()) - .unwrap_or(uuid::Uuid::new_v4().to_string()); + let (auth_id, email_domain) = if let Some(auth_method) = auth_methods.first() { + let email_domain = match req.email_domain { + Some(email_domain) => { + if email_domain != auth_method.email_domain { + return Err(report!(UserErrors::InvalidAuthMethodOperationWithMessage( + "Email domain mismatch".to_string() + ))); + } + + email_domain + } + None => auth_method.email_domain.clone(), + }; + + (auth_method.auth_id.clone(), email_domain) + } else { + let email_domain = + req.email_domain + .ok_or(UserErrors::InvalidAuthMethodOperationWithMessage( + "Email domain not found".to_string(), + ))?; + + (uuid::Uuid::new_v4().to_string(), email_domain) + }; for db_auth_method in auth_methods { let is_type_same = db_auth_method.auth_type == (&req.auth_method).foreign_into(); @@ -2351,6 +2410,7 @@ pub async fn create_user_authentication_method( allow_signup: req.allow_signup, created_at: now, last_modified_at: now, + email_domain, }) .await .to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists)?; @@ -2374,25 +2434,71 @@ pub async fn update_user_authentication_method( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to decode DEK")?; - let (private_config, public_config) = utils::user::construct_public_and_private_db_configs( - &state, - &req.auth_method, - &user_auth_encryption_key, - req.id.clone(), - ) - .await?; + match req { + user_api::UpdateUserAuthenticationMethodRequest::AuthMethod { + id, + auth_config: auth_method, + } => { + let (private_config, public_config) = + utils::user::construct_public_and_private_db_configs( + &state, + &auth_method, + &user_auth_encryption_key, + id.clone(), + ) + .await?; + + state + .store + .update_user_authentication_method( + &id, + UserAuthenticationMethodUpdate::UpdateConfig { + private_config, + public_config, + }, + ) + .await + .map_err(|error| { + let user_error = match error.current_context() { + StorageError::ValueNotFound(_) => { + UserErrors::InvalidAuthMethodOperationWithMessage( + "Auth method not found".to_string(), + ) + } + StorageError::DuplicateValue { .. } => { + UserErrors::UserAuthMethodAlreadyExists + } + _ => UserErrors::InternalServerError, + }; + error.change_context(user_error) + })?; + } + user_api::UpdateUserAuthenticationMethodRequest::EmailDomain { + owner_id, + email_domain, + } => { + let auth_methods = state + .store + .list_user_authentication_methods_for_owner_id(&owner_id) + .await + .change_context(UserErrors::InternalServerError)?; + + futures::future::try_join_all(auth_methods.iter().map(|auth_method| async { + state + .store + .update_user_authentication_method( + &auth_method.id, + UserAuthenticationMethodUpdate::EmailDomain { + email_domain: email_domain.clone(), + }, + ) + .await + .to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists) + })) + .await?; + } + } - state - .store - .update_user_authentication_method( - &req.id, - UserAuthenticationMethodUpdate::UpdateConfig { - private_config, - public_config, - }, - ) - .await - .change_context(UserErrors::InvalidUserAuthMethodOperation)?; Ok(ApplicationResponse::StatusOk) } @@ -2400,18 +2506,28 @@ pub async fn list_user_authentication_methods( state: SessionState, req: user_api::GetUserAuthenticationMethodsRequest, ) -> UserResponse<Vec<user_api::UserAuthenticationMethodResponse>> { - let user_authentication_methods = state - .store - .list_user_authentication_methods_for_auth_id(&req.auth_id) - .await - .change_context(UserErrors::InternalServerError)?; + let user_authentication_methods = match (req.auth_id, req.email_domain) { + (Some(auth_id), None) => state + .store + .list_user_authentication_methods_for_auth_id(&auth_id) + .await + .change_context(UserErrors::InternalServerError)?, + (None, Some(email_domain)) => state + .store + .list_user_authentication_methods_for_email_domain(&email_domain) + .await + .change_context(UserErrors::InternalServerError)?, + (Some(_), Some(_)) | (None, None) => { + return Err(UserErrors::InvalidUserAuthMethodOperation.into()); + } + }; Ok(ApplicationResponse::Json( user_authentication_methods .into_iter() .map(|auth_method| { let auth_name = match (auth_method.auth_type, auth_method.public_config) { - (common_enums::UserAuthType::OpenIdConnect, config) => { + (UserAuthType::OpenIdConnect, config) => { let open_id_public_config: Option<user_api::OpenIdConnectPublicConfig> = config .map(|config| { @@ -2537,6 +2653,13 @@ pub async fn sso_sign( ) .await?; + utils::user::validate_email_domain_auth_type_using_db( + &state, + &email, + UserAuthType::OpenIdConnect, + ) + .await?; + // TODO: Use config to handle not found error let user_from_db: domain::UserFromStorage = state .global_store @@ -2585,14 +2708,20 @@ pub async fn terminate_auth_select( .change_context(UserErrors::InternalServerError)? .into(); - let user_authentication_method = if let Some(id) = &req.id { - state - .store - .get_user_authentication_method_by_id(id) - .await - .to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)? - } else { - DEFAULT_USER_AUTH_METHOD.clone() + let user_email = domain::UserEmail::from_pii_email(user_from_db.get_email())?; + let auth_methods = state + .store + .list_user_authentication_methods_for_email_domain(user_email.extract_domain()?) + .await + .change_context(UserErrors::InternalServerError)?; + + let user_authentication_method = match (req.id, auth_methods.is_empty()) { + (Some(id), _) => auth_methods + .into_iter() + .find(|auth_method| auth_method.id == id) + .ok_or(UserErrors::InvalidUserAuthMethodOperation)?, + (None, true) => DEFAULT_USER_AUTH_METHOD.clone(), + (None, false) => return Err(UserErrors::InvalidUserAuthMethodOperation.into()), }; let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?; diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index a7e71284aaf..1eba9dd0e3d 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3737,6 +3737,18 @@ impl UserAuthenticationMethodInterface for KafkaStore { .update_user_authentication_method(id, user_authentication_method_update) .await } + + async fn list_user_authentication_methods_for_email_domain( + &self, + email_domain: &str, + ) -> CustomResult< + Vec<diesel_models::user_authentication_method::UserAuthenticationMethod>, + errors::StorageError, + > { + self.diesel_store + .list_user_authentication_methods_for_email_domain(email_domain) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/user_authentication_method.rs b/crates/router/src/db/user_authentication_method.rs index a02e7bdb11f..cd918fe2060 100644 --- a/crates/router/src/db/user_authentication_method.rs +++ b/crates/router/src/db/user_authentication_method.rs @@ -36,6 +36,11 @@ pub trait UserAuthenticationMethodInterface { id: &str, user_authentication_method_update: storage::UserAuthenticationMethodUpdate, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>; + + async fn list_user_authentication_methods_for_email_domain( + &self, + email_domain: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>; } #[async_trait::async_trait] @@ -57,7 +62,7 @@ impl UserAuthenticationMethodInterface for Store { &self, id: &str, ) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::get_user_authentication_method_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) @@ -68,7 +73,7 @@ impl UserAuthenticationMethodInterface for Store { &self, auth_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_auth_id( &conn, auth_id, ) @@ -81,7 +86,7 @@ impl UserAuthenticationMethodInterface for Store { &self, owner_id: &str, ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { - let conn = connection::pg_connection_write(self).await?; + let conn = connection::pg_connection_read(self).await?; storage::UserAuthenticationMethod::list_user_authentication_methods_for_owner_id( &conn, owner_id, ) @@ -104,6 +109,20 @@ impl UserAuthenticationMethodInterface for Store { .await .map_err(|error| report!(errors::StorageError::from(error))) } + + #[instrument(skip_all)] + async fn list_user_authentication_methods_for_email_domain( + &self, + email_domain: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::UserAuthenticationMethod::list_user_authentication_methods_for_email_domain( + &conn, + email_domain, + ) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } } #[async_trait::async_trait] @@ -130,6 +149,7 @@ impl UserAuthenticationMethodInterface for MockDb { allow_signup: user_authentication_method.allow_signup, created_at: user_authentication_method.created_at, last_modified_at: user_authentication_method.last_modified_at, + email_domain: user_authentication_method.email_domain, }; user_authentication_methods.push(user_authentication_method.clone()); @@ -222,6 +242,13 @@ impl UserAuthenticationMethodInterface for MockDb { last_modified_at: common_utils::date_time::now(), ..auth_method_inner.to_owned() }, + storage::UserAuthenticationMethodUpdate::EmailDomain { email_domain } => { + storage::UserAuthenticationMethod { + email_domain: email_domain.to_owned(), + last_modified_at: common_utils::date_time::now(), + ..auth_method_inner.to_owned() + } + } }; auth_method_inner.to_owned() }) @@ -232,4 +259,20 @@ impl UserAuthenticationMethodInterface for MockDb { .into(), ) } + + #[instrument(skip_all)] + async fn list_user_authentication_methods_for_email_domain( + &self, + email_domain: &str, + ) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> { + let user_authentication_methods = self.user_authentication_methods.lock().await; + + let user_authentication_methods_list: Vec<_> = user_authentication_methods + .iter() + .filter(|auth_method_inner| auth_method_inner.email_domain == email_domain) + .cloned() + .collect(); + + Ok(user_authentication_methods_list) + } } diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 6efaac7bfed..569e7f9a99f 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -138,6 +138,15 @@ impl UserEmail { pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> { (*self.0).clone() } + + pub fn extract_domain(&self) -> UserResult<&str> { + let (_username, domain) = self + .peek() + .split_once('@') + .ok_or(UserErrors::InternalServerError)?; + + Ok(domain) + } } impl TryFrom<pii::Email> for UserEmail { diff --git a/crates/router/src/types/domain/user/user_authentication_method.rs b/crates/router/src/types/domain/user/user_authentication_method.rs index 570e144961a..29c588f15e1 100644 --- a/crates/router/src/types/domain/user/user_authentication_method.rs +++ b/crates/router/src/types/domain/user/user_authentication_method.rs @@ -14,4 +14,5 @@ pub static DEFAULT_USER_AUTH_METHOD: Lazy<UserAuthenticationMethod> = allow_signup: true, created_at: common_utils::date_time::now(), last_modified_at: common_utils::date_time::now(), + email_domain: String::from("hyperswitch"), }); diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index abd59684243..b8ffcf836d7 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -5,7 +5,7 @@ use common_enums::UserAuthType; use common_utils::{ encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier, }; -use diesel_models::{organization, organization::OrganizationBridge}; +use diesel_models::organization::{self, OrganizationBridge}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; @@ -312,3 +312,23 @@ pub fn create_merchant_account_request_for_org( pm_collect_link_config: None, }) } + +pub async fn validate_email_domain_auth_type_using_db( + state: &SessionState, + email: &domain::UserEmail, + required_auth_type: UserAuthType, +) -> UserResult<()> { + let domain = email.extract_domain()?; + let user_auth_methods = state + .store + .list_user_authentication_methods_for_email_domain(domain) + .await + .change_context(UserErrors::InternalServerError)?; + + (user_auth_methods.is_empty() + || user_auth_methods + .iter() + .any(|auth_method| auth_method.auth_type == required_auth_type)) + .then_some(()) + .ok_or(UserErrors::InvalidUserAuthMethodOperation.into()) +} diff --git a/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/down.sql b/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/down.sql new file mode 100644 index 00000000000..9f3560069c7 --- /dev/null +++ b/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +DROP INDEX email_domain_index; +ALTER TABLE user_authentication_methods DROP COLUMN email_domain; diff --git a/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/up.sql b/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/up.sql new file mode 100644 index 00000000000..831f10162ca --- /dev/null +++ b/migrations/2024-12-11-092624_add-email-domain-in-auth-methods/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +ALTER TABLE user_authentication_methods ADD COLUMN email_domain VARCHAR(64); +UPDATE user_authentication_methods SET email_domain = auth_id WHERE email_domain IS NULL; +ALTER TABLE user_authentication_methods ALTER COLUMN email_domain SET NOT NULL; + +CREATE INDEX email_domain_index ON user_authentication_methods (email_domain);
2024-12-26T07:59:40Z
## 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 --> There will be a mapping of email domain and auth methods. This PR will restrict users to enter into the dashboard based on the email domain. ### 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). --> Closes #6939. ## 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 user auth method with email domain ```bash curl --location 'http://localhost:8080/user/auth' \ --header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMjAxYTJlZWQtNGE0ZC00MjZlLTg1N2ItMjNhM2ZjZTk5NTMzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NjIzMjI0Iiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3Nzk2MDI3LCJvcmdfaWQiOiJvcmdfVzJ2NmtPZ2lMSWx3YnFoaVh4VUIifQ.HnkHHWboPt82-VlvE5GVCjTJ1sA82-dMbUxeYNl-mxk' \ --header 'Content-Type: application/json' \ --header 'api-key: ••••••' \ --data '{ "owner_id": "test", "owner_type": "organization", "auth_method": { "auth_type": "password", "private_config": { "base_url": "url", "client_id": "client_id", "client_secret": "client_secret" }, "public_config": { "name": "okta" } }, "allow_signup": true, "email_domain": "gmail.com" }' ``` Response will be 200 OK. 2. Update user auth method 1. Auth Method ```bash curl --location --request PUT 'http://localhost:8080/user/auth' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --header 'Cookie: Cookie_1=value' \ --data '{ "auth_method": { "id": "799596e6-e6ba-405c-b5cf-70fd510409dc", "auth_method": { "auth_type": "open_id_connect", "private_config": { "base_url": "base url", "client_id": "client id", "client_secret": "client secret" }, "public_config": { "name": "okta" } } } } ' ``` Response will be 200 OK. 2. Email Domain ```bash curl --location --request PUT 'http://localhost:8080/user/auth' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --header 'Cookie: Cookie_1=value' \ --data '{ "email_domain": { "owner_id": "test", "email_domain": "juspay.com" } }' ``` Response will be 200 OK. All the following APIs will restrict the users based on the email domain and the corresponding auth method 1. Signin - Password 2. Signup - Password 3. Connect Account - MagicLink 4. Forgot Password - Password 5. Send Verification Email - MagicLink 6. SSO Signin - OpenIdConnect 7. Terminate Auth Select - Selected auth method If the auth method list for email domain is empty of consists of the above auth method, the request will be continued, or else the api will be stopped. ## 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
b6249f226116a7cc96e602a8910e8b186eecda5b
juspay/hyperswitch
juspay__hyperswitch-6937
Bug: populate `profile_id` in for the HeaderAuth of v1 populate `profile_id` in for the HeaderAuth of v1
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index dd4938d8d6f..6283382258a 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -419,7 +419,7 @@ outgoing_enabled = true connectors_with_webhook_source_verification_call = "paypal" # List of connectors which has additional source verification api-call [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 9ad4f90b71f..3537834fd07 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -435,7 +435,7 @@ outgoing_enabled = true connectors_with_webhook_source_verification_call = "paypal" # List of connectors which has additional source verification api-call [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index d2132cd1e40..fcfadb339d9 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -437,7 +437,7 @@ outgoing_enabled = true connectors_with_webhook_source_verification_call = "paypal" # List of connectors which has additional source verification api-call [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/development.toml b/config/development.toml index d157894ac76..4c9b8516b5a 100644 --- a/config/development.toml +++ b/config/development.toml @@ -768,7 +768,7 @@ enabled = true file_storage_backend = "file_system" [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [opensearch] host = "https://localhost:9200" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 3bbb1106350..75699d0a967 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -609,7 +609,7 @@ source = "logs" file_storage_backend = "file_system" [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [opensearch] host = "https://opensearch:9200" diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index d35e321a7be..99800b55512 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -666,6 +666,13 @@ where metrics::PARTIAL_AUTH_FAILURE.add(1, &[]); }; + let profile_id = HeaderMapStruct::new(request_headers) + .get_id_type_from_header_if_present::<id_type::ProfileId>(headers::X_PROFILE_ID) + .change_context(errors::ValidationError::IncorrectValueProvided { + field_name: "X-Profile-Id", + }) + .change_context(errors::ApiErrorResponse::Unauthorized)?; + let payload = ExtractedPayload::from_headers(request_headers) .and_then(|value| { let (algo, secret) = state.get_detached_auth()?; @@ -687,8 +694,13 @@ where merchant_id: Some(merchant_id), key_id: Some(key_id), } => { - let auth = - construct_authentication_data(state, &merchant_id, request_headers).await?; + let auth = construct_authentication_data( + state, + &merchant_id, + request_headers, + profile_id, + ) + .await?; Ok(( auth.clone(), AuthenticationType::ApiKey { @@ -702,8 +714,13 @@ where merchant_id: Some(merchant_id), key_id: None, } => { - let auth = - construct_authentication_data(state, &merchant_id, request_headers).await?; + let auth = construct_authentication_data( + state, + &merchant_id, + request_headers, + profile_id, + ) + .await?; Ok(( auth.clone(), AuthenticationType::PublishableKey { @@ -779,6 +796,7 @@ async fn construct_authentication_data<A>( state: &A, merchant_id: &id_type::MerchantId, request_headers: &HeaderMap, + profile_id: Option<id_type::ProfileId>, ) -> RouterResult<AuthenticationData> where A: SessionStateInfo + Sync, @@ -830,7 +848,7 @@ where merchant_account: merchant, platform_merchant_account, key_store, - profile_id: None, + profile_id, }; Ok(auth) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 64d0526d147..ec58ab08b87 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -396,7 +396,7 @@ client_secret = "" partner_id = "" [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [multitenancy] enabled = false
2024-12-24T12:56:35Z
## 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 --> populate `profile_id` in for the HeaderAuth of v1 And also this pr involves the changes to unmask the profile id that is sent in the headers. ### 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
b6249f226116a7cc96e602a8910e8b186eecda5b
juspay/hyperswitch
juspay__hyperswitch-6929
Bug: disable partial auth feature for relay disable partial auth feature for relay
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index a74ababdd26..f10ffac3e2e 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -411,7 +411,7 @@ outgoing_enabled = true connectors_with_webhook_source_verification_call = "paypal" # List of connectors which has additional source verification api-call [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 0c874a452bc..7ba3a0435f8 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -427,7 +427,7 @@ outgoing_enabled = true connectors_with_webhook_source_verification_call = "paypal" # List of connectors which has additional source verification api-call [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 40e1ad01fa1..18d0bd34d0e 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -429,7 +429,7 @@ outgoing_enabled = true connectors_with_webhook_source_verification_call = "paypal" # List of connectors which has additional source verification api-call [unmasked_headers] -keys = "accept-language,user-agent" +keys = "accept-language,user-agent,x-profile-id" [saved_payment_methods] sdk_eligible_payment_methods = "card" diff --git a/crates/router/src/routes/relay.rs b/crates/router/src/routes/relay.rs index cfc66253d50..452e0023fa2 100644 --- a/crates/router/src/routes/relay.rs +++ b/crates/router/src/routes/relay.rs @@ -33,7 +33,7 @@ pub async fn relay( req, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await @@ -69,7 +69,7 @@ pub async fn relay_retrieve( req, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::ApiKeyAuth, api_locking::LockAction::NotApplicable, )) .await
2024-12-24T08:23: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 --> disable partial auth feature for relay ### 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
912091976859628ac9fbfe86475814bf8cca3edf
juspay/hyperswitch
juspay__hyperswitch-6969
Bug: [FEATURE] expose tokenize endpoints ### Feature Description HS backend to expose endpoints to help with tokenization of customer's cards. HyperSwitch makes use of an external service which helps tokenize the card and makes it usable within HS ecosystem. Once tokenized, these cards can be used in a PG agnostic manner as they're tokenized with the card networks. ### Possible Implementation Expose two endpoints - /payment_methods/tokenize-card - /payment_methods/tokenize-card-batch The flow looks like - - Create / update customer - Tokenize card with the network (through external service) - Create a payment method entry in HS storing the required references from external service - Return response For batch tokenization, above steps will be executed for every card to be tokenized. Any errors encountered during this operation will be aggregated and returned back in the response. ### 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 2e0d57d977e..45ff3e1f567 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -6974,6 +6974,90 @@ "Maestro" ] }, + "CardNetworkTokenizeRequest": { + "allOf": [ + { + "$ref": "#/components/schemas/TokenizeDataRequest" + }, + { + "type": "object", + "required": [ + "merchant_id", + "customer" + ], + "properties": { + "merchant_id": { + "type": "string", + "description": "Merchant ID associated with the tokenization request", + "example": "merchant_1671528864" + }, + "customer": { + "$ref": "#/components/schemas/CustomerDetails" + }, + "billing": { + "allOf": [ + { + "$ref": "#/components/schemas/Address" + } + ], + "nullable": true + }, + "metadata": { + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.", + "nullable": true + }, + "payment_method_issuer": { + "type": "string", + "description": "The name of the bank/ provider issuing the payment method to the end user", + "nullable": true + } + } + } + ] + }, + "CardNetworkTokenizeResponse": { + "type": "object", + "required": [ + "customer", + "card_tokenized" + ], + "properties": { + "payment_method_response": { + "allOf": [ + { + "$ref": "#/components/schemas/PaymentMethodResponse" + } + ], + "nullable": true + }, + "customer": { + "$ref": "#/components/schemas/CustomerDetails" + }, + "card_tokenized": { + "type": "boolean", + "description": "Card network tokenization status" + }, + "error_code": { + "type": "string", + "description": "Error code", + "nullable": true + }, + "error_message": { + "type": "string", + "description": "Error message", + "nullable": true + }, + "tokenization_data": { + "allOf": [ + { + "$ref": "#/components/schemas/TokenizeDataRequest" + } + ], + "nullable": true + } + } + }, "CardNetworkTypes": { "type": "object", "required": [ @@ -21707,6 +21791,113 @@ "multi_use" ] }, + "TokenizeCardRequest": { + "type": "object", + "required": [ + "raw_card_number", + "card_expiry_month", + "card_expiry_year" + ], + "properties": { + "raw_card_number": { + "type": "string", + "description": "Card Number", + "example": "4111111145551142" + }, + "card_expiry_month": { + "type": "string", + "description": "Card Expiry Month", + "example": "10" + }, + "card_expiry_year": { + "type": "string", + "description": "Card Expiry Year", + "example": "25" + }, + "card_cvc": { + "type": "string", + "description": "The CVC number for the card", + "example": "242", + "nullable": true + }, + "card_holder_name": { + "type": "string", + "description": "Card Holder Name", + "example": "John Doe", + "nullable": true + }, + "nick_name": { + "type": "string", + "description": "Card Holder's Nick Name", + "example": "John Doe", + "nullable": true + }, + "card_issuing_country": { + "type": "string", + "description": "Card Issuing Country", + "nullable": true + }, + "card_network": { + "allOf": [ + { + "$ref": "#/components/schemas/CardNetwork" + } + ], + "nullable": true + }, + "card_issuer": { + "type": "string", + "description": "Issuer Bank for Card", + "nullable": true + }, + "card_type": { + "allOf": [ + { + "$ref": "#/components/schemas/CardType" + } + ], + "nullable": true + } + }, + "additionalProperties": false + }, + "TokenizeDataRequest": { + "oneOf": [ + { + "type": "object", + "required": [ + "card" + ], + "properties": { + "card": { + "$ref": "#/components/schemas/TokenizeCardRequest" + } + } + }, + { + "type": "object", + "required": [ + "existing_payment_method" + ], + "properties": { + "existing_payment_method": { + "$ref": "#/components/schemas/TokenizePaymentMethodRequest" + } + } + } + ] + }, + "TokenizePaymentMethodRequest": { + "type": "object", + "properties": { + "card_cvc": { + "type": "string", + "description": "The CVC number for the card", + "example": "242", + "nullable": true + } + } + }, "TouchNGoRedirection": { "type": "object" }, diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index ccc055a7934..4b0a0be0f26 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -556,7 +556,6 @@ pub struct CardDetail { pub card_type: Option<String>, } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive( Debug, serde::Deserialize, @@ -906,7 +905,7 @@ pub struct ConnectorTokenDetails { } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, serde::Serialize, ToSchema, Clone)] +#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema, Clone)] pub struct PaymentMethodResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] @@ -2544,6 +2543,139 @@ impl From<(PaymentMethodRecord, id_type::MerchantId)> for customers::CustomerReq } } +#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct CardNetworkTokenizeRequest { + /// Merchant ID associated with the tokenization request + #[schema(example = "merchant_1671528864", value_type = String)] + pub merchant_id: id_type::MerchantId, + + /// Details of the card or payment method to be tokenized + #[serde(flatten)] + pub data: TokenizeDataRequest, + + /// Customer details + #[schema(value_type = CustomerDetails)] + pub customer: payments::CustomerDetails, + + /// The billing details of the payment method + #[schema(value_type = Option<Address>)] + pub billing: Option<payments::Address>, + + /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. + #[schema(value_type = Option<Object>, example = json!({ "city": "NY", "unit": "245" }))] + pub metadata: Option<pii::SecretSerdeValue>, + + /// The name of the bank/ provider issuing the payment method to the end user + pub payment_method_issuer: Option<String>, +} + +impl common_utils::events::ApiEventMetric for CardNetworkTokenizeRequest {} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum TokenizeDataRequest { + Card(TokenizeCardRequest), + ExistingPaymentMethod(TokenizePaymentMethodRequest), +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct TokenizeCardRequest { + /// Card Number + #[schema(value_type = String, example = "4111111145551142")] + pub raw_card_number: CardNumber, + + /// Card Expiry Month + #[schema(value_type = String, example = "10")] + pub card_expiry_month: masking::Secret<String>, + + /// Card Expiry Year + #[schema(value_type = String, example = "25")] + pub card_expiry_year: masking::Secret<String>, + + /// The CVC number for the card + #[schema(value_type = Option<String>, example = "242")] + pub card_cvc: Option<masking::Secret<String>>, + + /// Card Holder Name + #[schema(value_type = Option<String>, example = "John Doe")] + pub card_holder_name: Option<masking::Secret<String>>, + + /// Card Holder's Nick Name + #[schema(value_type = Option<String>, example = "John Doe")] + pub nick_name: Option<masking::Secret<String>>, + + /// Card Issuing Country + pub card_issuing_country: Option<String>, + + /// Card's Network + #[schema(value_type = Option<CardNetwork>)] + pub card_network: Option<api_enums::CardNetwork>, + + /// Issuer Bank for Card + pub card_issuer: Option<String>, + + /// Card Type + pub card_type: Option<CardType>, +} + +#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct TokenizePaymentMethodRequest { + /// Payment method's ID + #[serde(skip_deserializing)] + pub payment_method_id: String, + + /// The CVC number for the card + #[schema(value_type = Option<String>, example = "242")] + pub card_cvc: Option<masking::Secret<String>>, +} + +#[derive(Debug, Default, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct CardNetworkTokenizeResponse { + /// Response for payment method entry in DB + pub payment_method_response: Option<PaymentMethodResponse>, + + /// Customer details + #[schema(value_type = CustomerDetails)] + pub customer: Option<payments::CustomerDetails>, + + /// Card network tokenization status + pub card_tokenized: bool, + + /// Error code + #[serde(skip_serializing_if = "Option::is_none")] + pub error_code: Option<String>, + + /// Error message + #[serde(skip_serializing_if = "Option::is_none")] + pub error_message: Option<String>, + + /// Details that were sent for tokenization + #[serde(skip_serializing_if = "Option::is_none")] + pub tokenization_data: Option<TokenizeDataRequest>, +} + +impl common_utils::events::ApiEventMetric for CardNetworkTokenizeResponse {} + +impl From<&Card> for MigrateCardDetail { + fn from(card: &Card) -> Self { + Self { + card_number: masking::Secret::new(card.card_number.get_card_no()), + card_exp_month: card.card_exp_month.clone(), + card_exp_year: card.card_exp_year.clone(), + card_holder_name: card.name_on_card.clone(), + nick_name: card + .nick_name + .as_ref() + .map(|name| masking::Secret::new(name.clone())), + card_issuing_country: None, + card_network: None, + card_issuer: None, + card_type: None, + } + } +} + #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionRequest { diff --git a/crates/hyperswitch_domain_models/src/bulk_tokenization.rs b/crates/hyperswitch_domain_models/src/bulk_tokenization.rs new file mode 100644 index 00000000000..0eff34a1bf5 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/bulk_tokenization.rs @@ -0,0 +1,308 @@ +use api_models::{payment_methods as payment_methods_api, payments as payments_api}; +use cards::CardNumber; +use common_enums as enums; +use common_utils::{ + errors, + ext_traits::OptionExt, + id_type, pii, + transformers::{ForeignFrom, ForeignTryFrom}, +}; +use error_stack::report; + +use crate::{ + address::{Address, AddressDetails, PhoneDetails}, + router_request_types::CustomerDetails, +}; + +#[derive(Debug)] +pub struct CardNetworkTokenizeRequest { + pub data: TokenizeDataRequest, + pub customer: CustomerDetails, + pub billing: Option<Address>, + pub metadata: Option<pii::SecretSerdeValue>, + pub payment_method_issuer: Option<String>, +} + +#[derive(Debug)] +pub enum TokenizeDataRequest { + Card(TokenizeCardRequest), + ExistingPaymentMethod(TokenizePaymentMethodRequest), +} + +#[derive(Clone, Debug)] +pub struct TokenizeCardRequest { + pub raw_card_number: CardNumber, + pub card_expiry_month: masking::Secret<String>, + pub card_expiry_year: masking::Secret<String>, + pub card_cvc: Option<masking::Secret<String>>, + pub card_holder_name: Option<masking::Secret<String>>, + pub nick_name: Option<masking::Secret<String>>, + pub card_issuing_country: Option<String>, + pub card_network: Option<enums::CardNetwork>, + pub card_issuer: Option<String>, + pub card_type: Option<payment_methods_api::CardType>, +} + +#[derive(Clone, Debug)] +pub struct TokenizePaymentMethodRequest { + pub payment_method_id: String, + pub card_cvc: Option<masking::Secret<String>>, +} + +#[derive(Default, Debug, serde::Deserialize, serde::Serialize)] +pub struct CardNetworkTokenizeRecord { + // Card details + pub raw_card_number: Option<CardNumber>, + pub card_expiry_month: Option<masking::Secret<String>>, + pub card_expiry_year: Option<masking::Secret<String>>, + pub card_cvc: Option<masking::Secret<String>>, + pub card_holder_name: Option<masking::Secret<String>>, + pub nick_name: Option<masking::Secret<String>>, + pub card_issuing_country: Option<String>, + pub card_network: Option<enums::CardNetwork>, + pub card_issuer: Option<String>, + pub card_type: Option<payment_methods_api::CardType>, + + // Payment method details + pub payment_method_id: Option<String>, + pub payment_method_type: Option<payment_methods_api::CardType>, + pub payment_method_issuer: Option<String>, + + // Customer details + pub customer_id: id_type::CustomerId, + #[serde(rename = "name")] + pub customer_name: Option<masking::Secret<String>>, + #[serde(rename = "email")] + pub customer_email: Option<pii::Email>, + #[serde(rename = "phone")] + pub customer_phone: Option<masking::Secret<String>>, + #[serde(rename = "phone_country_code")] + pub customer_phone_country_code: Option<String>, + + // Billing details + pub billing_address_city: Option<String>, + pub billing_address_country: Option<enums::CountryAlpha2>, + pub billing_address_line1: Option<masking::Secret<String>>, + pub billing_address_line2: Option<masking::Secret<String>>, + pub billing_address_line3: Option<masking::Secret<String>>, + pub billing_address_zip: Option<masking::Secret<String>>, + pub billing_address_state: Option<masking::Secret<String>>, + pub billing_address_first_name: Option<masking::Secret<String>>, + pub billing_address_last_name: Option<masking::Secret<String>>, + pub billing_phone_number: Option<masking::Secret<String>>, + pub billing_phone_country_code: Option<String>, + pub billing_email: Option<pii::Email>, + + // Other details + pub line_number: Option<u64>, + pub merchant_id: Option<id_type::MerchantId>, +} + +impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::CustomerDetails { + fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self { + Self { + id: record.customer_id.clone(), + name: record.customer_name.clone(), + email: record.customer_email.clone(), + phone: record.customer_phone.clone(), + phone_country_code: record.customer_phone_country_code.clone(), + } + } +} + +impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::Address { + fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self { + Self { + address: Some(payments_api::AddressDetails { + first_name: record.billing_address_first_name.clone(), + last_name: record.billing_address_last_name.clone(), + line1: record.billing_address_line1.clone(), + line2: record.billing_address_line2.clone(), + line3: record.billing_address_line3.clone(), + city: record.billing_address_city.clone(), + zip: record.billing_address_zip.clone(), + state: record.billing_address_state.clone(), + country: record.billing_address_country, + }), + phone: Some(payments_api::PhoneDetails { + number: record.billing_phone_number.clone(), + country_code: record.billing_phone_country_code.clone(), + }), + email: record.billing_email.clone(), + } + } +} + +impl ForeignTryFrom<CardNetworkTokenizeRecord> for payment_methods_api::CardNetworkTokenizeRequest { + type Error = error_stack::Report<errors::ValidationError>; + fn foreign_try_from(record: CardNetworkTokenizeRecord) -> Result<Self, Self::Error> { + let billing = Some(payments_api::Address::foreign_from(&record)); + let customer = payments_api::CustomerDetails::foreign_from(&record); + let merchant_id = record.merchant_id.get_required_value("merchant_id")?; + + match ( + record.raw_card_number, + record.card_expiry_month, + record.card_expiry_year, + record.payment_method_id, + ) { + (Some(raw_card_number), Some(card_expiry_month), Some(card_expiry_year), None) => { + Ok(Self { + merchant_id, + data: payment_methods_api::TokenizeDataRequest::Card( + payment_methods_api::TokenizeCardRequest { + raw_card_number, + card_expiry_month, + card_expiry_year, + card_cvc: record.card_cvc, + card_holder_name: record.card_holder_name, + nick_name: record.nick_name, + card_issuing_country: record.card_issuing_country, + card_network: record.card_network, + card_issuer: record.card_issuer, + card_type: record.card_type.clone(), + }, + ), + billing, + customer, + metadata: None, + payment_method_issuer: record.payment_method_issuer, + }) + } + (None, None, None, Some(payment_method_id)) => Ok(Self { + merchant_id, + data: payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod( + payment_methods_api::TokenizePaymentMethodRequest { + payment_method_id, + card_cvc: record.card_cvc, + }, + ), + billing, + customer, + metadata: None, + payment_method_issuer: record.payment_method_issuer, + }), + _ => Err(report!(errors::ValidationError::InvalidValue { + message: "Invalid record in bulk tokenization - expected one of card details or payment method details".to_string() + })), + } + } +} + +impl ForeignFrom<&TokenizeCardRequest> for payment_methods_api::MigrateCardDetail { + fn foreign_from(card: &TokenizeCardRequest) -> Self { + Self { + card_number: masking::Secret::new(card.raw_card_number.get_card_no()), + card_exp_month: card.card_expiry_month.clone(), + card_exp_year: card.card_expiry_year.clone(), + card_holder_name: card.card_holder_name.clone(), + nick_name: card.nick_name.clone(), + card_issuing_country: card.card_issuing_country.clone(), + card_network: card.card_network.clone(), + card_issuer: card.card_issuer.clone(), + card_type: card + .card_type + .as_ref() + .map(|card_type| card_type.to_string()), + } + } +} + +impl ForeignTryFrom<CustomerDetails> for payments_api::CustomerDetails { + type Error = error_stack::Report<errors::ValidationError>; + fn foreign_try_from(customer: CustomerDetails) -> Result<Self, Self::Error> { + Ok(Self { + id: customer.customer_id.get_required_value("customer_id")?, + name: customer.name, + email: customer.email, + phone: customer.phone, + phone_country_code: customer.phone_country_code, + }) + } +} + +impl ForeignFrom<payment_methods_api::CardNetworkTokenizeRequest> for CardNetworkTokenizeRequest { + fn foreign_from(req: payment_methods_api::CardNetworkTokenizeRequest) -> Self { + Self { + data: TokenizeDataRequest::foreign_from(req.data), + customer: CustomerDetails::foreign_from(req.customer), + billing: req.billing.map(ForeignFrom::foreign_from), + metadata: req.metadata, + payment_method_issuer: req.payment_method_issuer, + } + } +} + +impl ForeignFrom<payment_methods_api::TokenizeDataRequest> for TokenizeDataRequest { + fn foreign_from(req: payment_methods_api::TokenizeDataRequest) -> Self { + match req { + payment_methods_api::TokenizeDataRequest::Card(card) => { + Self::Card(TokenizeCardRequest { + raw_card_number: card.raw_card_number, + card_expiry_month: card.card_expiry_month, + card_expiry_year: card.card_expiry_year, + card_cvc: card.card_cvc, + card_holder_name: card.card_holder_name, + nick_name: card.nick_name, + card_issuing_country: card.card_issuing_country, + card_network: card.card_network, + card_issuer: card.card_issuer, + card_type: card.card_type, + }) + } + payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(pm) => { + Self::ExistingPaymentMethod(TokenizePaymentMethodRequest { + payment_method_id: pm.payment_method_id, + card_cvc: pm.card_cvc, + }) + } + } + } +} + +impl ForeignFrom<payments_api::CustomerDetails> for CustomerDetails { + fn foreign_from(req: payments_api::CustomerDetails) -> Self { + Self { + customer_id: Some(req.id), + name: req.name, + email: req.email, + phone: req.phone, + phone_country_code: req.phone_country_code, + } + } +} + +impl ForeignFrom<payments_api::Address> for Address { + fn foreign_from(req: payments_api::Address) -> Self { + Self { + address: req.address.map(ForeignFrom::foreign_from), + phone: req.phone.map(ForeignFrom::foreign_from), + email: req.email, + } + } +} + +impl ForeignFrom<payments_api::AddressDetails> for AddressDetails { + fn foreign_from(req: payments_api::AddressDetails) -> Self { + Self { + city: req.city, + country: req.country, + line1: req.line1, + line2: req.line2, + line3: req.line3, + zip: req.zip, + state: req.state, + first_name: req.first_name, + last_name: req.last_name, + } + } +} + +impl ForeignFrom<payments_api::PhoneDetails> for PhoneDetails { + fn foreign_from(req: payments_api::PhoneDetails) -> Self { + Self { + number: req.number, + country_code: req.country_code, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index c97753a6dc0..004a9fd2128 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -1,6 +1,7 @@ pub mod address; pub mod api; pub mod behaviour; +pub mod bulk_tokenization; pub mod business_profile; pub mod callback_mapper; pub mod card_testing_guard_data; diff --git a/crates/hyperswitch_domain_models/src/network_tokenization.rs b/crates/hyperswitch_domain_models/src/network_tokenization.rs index bf87c750509..a29792e969e 100644 --- a/crates/hyperswitch_domain_models/src/network_tokenization.rs +++ b/crates/hyperswitch_domain_models/src/network_tokenization.rs @@ -22,7 +22,7 @@ pub struct CardData { pub card_number: CardNumber, pub exp_month: Secret<String>, pub exp_year: Secret<String>, - pub card_security_code: Secret<String>, + pub card_security_code: Option<Secret<String>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 2f8375b47c0..c715ef6610b 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -102,6 +102,20 @@ pub struct CardDetailsForNetworkTransactionId { pub card_holder_name: Option<Secret<String>>, } +#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] +pub struct CardDetail { + pub card_number: cards::CardNumber, + pub card_exp_month: Secret<String>, + pub card_exp_year: Secret<String>, + pub card_issuer: Option<String>, + pub card_network: Option<api_enums::CardNetwork>, + pub card_type: Option<String>, + pub card_issuing_country: Option<String>, + pub bank_code: Option<String>, + pub nick_name: Option<Secret<String>>, + pub card_holder_name: Option<Secret<String>>, +} + impl CardDetailsForNetworkTransactionId { pub fn get_nti_and_card_details_for_mit_flow( recurring_details: mandates::RecurringDetails, @@ -129,6 +143,23 @@ impl CardDetailsForNetworkTransactionId { } } +impl From<&Card> for CardDetail { + fn from(item: &Card) -> Self { + Self { + card_number: item.card_number.to_owned(), + card_exp_month: item.card_exp_month.to_owned(), + card_exp_year: item.card_exp_year.to_owned(), + card_issuer: item.card_issuer.to_owned(), + card_network: item.card_network.to_owned(), + card_type: item.card_type.to_owned(), + card_issuing_country: item.card_issuing_country.to_owned(), + bank_code: item.bank_code.to_owned(), + nick_name: item.nick_name.to_owned(), + card_holder_name: item.card_holder_name.to_owned(), + } + } +} + impl From<mandates::NetworkTransactionIdAndCardDetails> for CardDetailsForNetworkTransactionId { fn from(card_details_for_nti: mandates::NetworkTransactionIdAndCardDetails) -> Self { Self { diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 8d18d1fe59f..bcdb1c9e208 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -540,6 +540,12 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::SurchargePercentage, api_models::payment_methods::PaymentMethodCollectLinkRequest, api_models::payment_methods::PaymentMethodCollectLinkResponse, + api_models::payment_methods::CardType, + api_models::payment_methods::CardNetworkTokenizeRequest, + api_models::payment_methods::CardNetworkTokenizeResponse, + api_models::payment_methods::TokenizeDataRequest, + api_models::payment_methods::TokenizeCardRequest, + api_models::payment_methods::TokenizePaymentMethodRequest, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, api_models::relay::RelayRequest, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 0c84f67cb41..bc6c245db9e 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -512,6 +512,9 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::SortBy, api_models::payments::PaymentMethodListResponseForPayments, api_models::payments::ResponsePaymentMethodTypesForPayments, + api_models::payment_methods::CardNetworkTokenizeRequest, + api_models::payment_methods::CardNetworkTokenizeResponse, + api_models::payment_methods::CardType, api_models::payment_methods::RequiredFieldInfo, api_models::payment_methods::MaskedBankDetails, api_models::payment_methods::SurchargeDetailsResponse, @@ -523,6 +526,9 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodSessionRequest, api_models::payment_methods::PaymentMethodSessionResponse, api_models::payment_methods::PaymentMethodsSessionUpdateRequest, + api_models::payment_methods::TokenizeCardRequest, + api_models::payment_methods::TokenizeDataRequest, + api_models::payment_methods::TokenizePaymentMethodRequest, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, api_models::payments::AmountFilter, diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs index 2a309848a7f..9304afc69d3 100644 --- a/crates/openapi/src/routes/payment_method.rs +++ b/crates/openapi/src/routes/payment_method.rs @@ -444,6 +444,45 @@ pub fn payment_method_session_list_payment_methods() {} )] pub fn payment_method_session_update_saved_payment_method() {} +/// Card network tokenization - Create using raw card data +/// +/// Create a card network token for a customer and store it as a payment method. +/// This API expects raw card details for creating a network token with the card networks. +#[utoipa::path( + post, + path = "/payment_methods/tokenize-card", + request_body = CardNetworkTokenizeRequest, + responses( + (status = 200, description = "Payment Method Created", body = CardNetworkTokenizeResponse), + (status = 404, description = "Customer not found"), + ), + tag = "Payment Methods", + operation_id = "Create card network token", + security(("admin_api_key" = [])) +)] +pub async fn tokenize_card_api() {} + +/// Card network tokenization - Create using existing payment method +/// +/// Create a card network token for a customer for an existing payment method. +/// This API expects an existing payment method ID for a card. +#[utoipa::path( + post, + path = "/payment_methods/{id}/tokenize-card", + request_body = CardNetworkTokenizeRequest, + params ( + ("id" = String, Path, description = "The unique identifier for the Payment Method"), + ), + responses( + (status = 200, description = "Payment Method Updated", body = CardNetworkTokenizeResponse), + (status = 404, description = "Customer not found"), + ), + tag = "Payment Methods", + operation_id = "Create card network token", + security(("admin_api_key" = [])) +)] +pub async fn tokenize_card_using_pm_api() {} + /// Payment Method Session - Confirm a payment method session /// /// **Confirms a payment method session object with the payment method data** diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 215f262ea8b..f56fef1af5f 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -448,6 +448,26 @@ pub enum NetworkTokenizationError { ApiError, } +#[derive(Debug, thiserror::Error)] +pub enum BulkNetworkTokenizationError { + #[error("Failed to validate card details")] + CardValidationFailed, + #[error("Failed to validate payment method details")] + PaymentMethodValidationFailed, + #[error("Failed to assign a customer to the card")] + CustomerAssignmentFailed, + #[error("Failed to perform BIN lookup for the card")] + BinLookupFailed, + #[error("Failed to tokenize the card details with the network")] + NetworkTokenizationFailed, + #[error("Failed to store the card details in locker")] + VaultSaveFailed, + #[error("Failed to create a payment method entry")] + PaymentMethodCreationFailed, + #[error("Failed to update the payment method")] + PaymentMethodUpdationFailed, +} + #[cfg(all(feature = "revenue_recovery", feature = "v2"))] #[derive(Debug, thiserror::Error)] pub enum RevenueRecoveryError { diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 9f0fd705228..6232eeafe2b 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -6,6 +6,11 @@ pub mod cards; pub mod migration; pub mod network_tokenization; pub mod surcharge_decision_configs; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +pub mod tokenize; pub mod transformers; pub mod utils; mod validator; diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 1f37cc157e4..a1f53f85482 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -68,6 +68,19 @@ use super::surcharge_decision_configs::{ perform_surcharge_decision_management_for_payment_method_list, perform_surcharge_decision_management_for_saved_cards, }; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +use super::tokenize::NetworkTokenizationProcess; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +use crate::core::payment_methods::{ + add_payment_method_status_update_task, tokenize, + utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache}, +}; #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2"), @@ -98,7 +111,7 @@ use crate::{ api::{self, routing as routing_types, PaymentMethodCreateExt}, domain::{self, Profile}, storage::{self, enums, PaymentMethodListContext, PaymentTokenData}, - transformers::ForeignTryFrom, + transformers::{ForeignFrom, ForeignTryFrom}, }, utils, utils::OptionExt, @@ -108,17 +121,6 @@ use crate::{ consts as router_consts, core::payment_methods as pm_core, headers, types::payment_methods as pm_types, utils::ConnectorResponseExt, }; -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "payment_methods_v2") -))] -use crate::{ - core::payment_methods::{ - add_payment_method_status_update_task, - utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache}, - }, - types::transformers::ForeignFrom, -}; #[cfg(all( any(feature = "v1", feature = "v2"), @@ -6021,3 +6023,181 @@ pub async fn list_countries_currencies_for_connector_payment_method_util( .collect(), } } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +pub async fn tokenize_card_flow( + state: &routes::SessionState, + req: domain::CardNetworkTokenizeRequest, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, +) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { + match req.data { + domain::TokenizeDataRequest::Card(ref card_req) => { + let executor = tokenize::CardNetworkTokenizeExecutor::new( + state, + key_store, + merchant_account, + card_req, + &req.customer, + ); + let builder = + tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithCard>::default(); + execute_card_tokenization(executor, builder, card_req).await + } + domain::TokenizeDataRequest::ExistingPaymentMethod(ref payment_method) => { + let executor = tokenize::CardNetworkTokenizeExecutor::new( + state, + key_store, + merchant_account, + payment_method, + &req.customer, + ); + let builder = + tokenize::NetworkTokenizationBuilder::<tokenize::TokenizeWithPmId>::default(); + execute_payment_method_tokenization(executor, builder, payment_method).await + } + } +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +pub async fn execute_card_tokenization( + executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest>, + builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithCard>, + req: &domain::TokenizeCardRequest, +) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { + // Validate request and get optional customer + let optional_customer = executor + .validate_request_and_fetch_optional_customer() + .await?; + let builder = builder.set_validate_result(); + + // Perform BIN lookup and validate card network + let optional_card_info = executor + .fetch_bin_details_and_validate_card_network( + req.raw_card_number.clone(), + req.card_issuer.as_ref(), + req.card_network.as_ref(), + req.card_type.as_ref(), + req.card_issuing_country.as_ref(), + ) + .await?; + let builder = builder.set_card_details(req, optional_card_info); + + // Create customer if not present + let customer = match optional_customer { + Some(customer) => customer, + None => executor.create_customer().await?, + }; + let builder = builder.set_customer(&customer); + + // Tokenize card + let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc(); + let domain_card = optional_card + .get_required_value("card") + .change_context(errors::ApiErrorResponse::InternalServerError)?; + let network_token_details = executor + .tokenize_card(&customer.id, &domain_card, optional_cvc) + .await?; + let builder = builder.set_token_details(&network_token_details); + + // Store card and token in locker + let store_card_and_token_resp = executor + .store_card_and_token_in_locker(&network_token_details, &domain_card, &customer.id) + .await?; + let builder = builder.set_stored_card_response(&store_card_and_token_resp); + let builder = builder.set_stored_token_response(&store_card_and_token_resp); + + // Create payment method + let payment_method = executor + .create_payment_method( + &store_card_and_token_resp, + &network_token_details, + &domain_card, + &customer.id, + ) + .await?; + let builder = builder.set_payment_method_response(&payment_method); + + Ok(builder.build()) +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] +pub async fn execute_payment_method_tokenization( + executor: tokenize::CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest>, + builder: tokenize::NetworkTokenizationBuilder<'_, tokenize::TokenizeWithPmId>, + req: &domain::TokenizePaymentMethodRequest, +) -> errors::RouterResult<api::CardNetworkTokenizeResponse> { + // Fetch payment method + let payment_method = executor + .fetch_payment_method(&req.payment_method_id) + .await?; + let builder = builder.set_payment_method(&payment_method); + + // Validate payment method and customer + let (locker_id, customer) = executor + .validate_request_and_locker_reference_and_customer(&payment_method) + .await?; + let builder = builder.set_validate_result(&customer); + + // Fetch card from locker + let card_details = get_card_from_locker( + executor.state, + &customer.id, + executor.merchant_account.get_id(), + &locker_id, + ) + .await?; + + // Perform BIN lookup and validate card network + let optional_card_info = executor + .fetch_bin_details_and_validate_card_network( + card_details.card_number.clone(), + None, + None, + None, + None, + ) + .await?; + let builder = builder.set_card_details(&card_details, optional_card_info, req.card_cvc.clone()); + + // Tokenize card + let (optional_card, optional_cvc) = builder.get_optional_card_and_cvc(); + let domain_card = optional_card.get_required_value("card")?; + let network_token_details = executor + .tokenize_card(&customer.id, &domain_card, optional_cvc) + .await?; + let builder = builder.set_token_details(&network_token_details); + + // Store token in locker + let store_token_resp = executor + .store_network_token_in_locker( + &network_token_details, + &customer.id, + card_details.name_on_card.clone(), + card_details.nick_name.clone().map(Secret::new), + ) + .await?; + let builder = builder.set_stored_token_response(&store_token_resp); + + // Update payment method + let updated_payment_method = executor + .update_payment_method( + &store_token_resp, + payment_method, + &network_token_details, + &domain_card, + ) + .await?; + let builder = builder.set_payment_method(&updated_payment_method); + + Ok(builder.build()) +} diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rs index 6799a1cf5ba..41a94402baf 100644 --- a/crates/router/src/core/payment_methods/network_tokenization.rs +++ b/crates/router/src/core/payment_methods/network_tokenization.rs @@ -267,7 +267,8 @@ pub async fn generate_network_token( ))] pub async fn make_card_network_tokenization_request( state: &routes::SessionState, - card: &domain::Card, + card: &domain::CardDetail, + optional_cvc: Option<Secret<String>>, customer_id: &id_type::CustomerId, ) -> CustomResult< (domain::CardNetworkTokenResponsePayload, Option<String>), @@ -277,7 +278,7 @@ pub async fn make_card_network_tokenization_request( card_number: card.card_number.clone(), exp_month: card.card_exp_month.clone(), exp_year: card.card_exp_year.clone(), - card_security_code: card.card_cvc.clone(), + card_security_code: optional_cvc, }; let payload = card_data diff --git a/crates/router/src/core/payment_methods/tokenize.rs b/crates/router/src/core/payment_methods/tokenize.rs new file mode 100644 index 00000000000..853d3c0a2bd --- /dev/null +++ b/crates/router/src/core/payment_methods/tokenize.rs @@ -0,0 +1,428 @@ +use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm}; +use api_models::{enums as api_enums, payment_methods as payment_methods_api}; +use cards::CardNumber; +use common_utils::{ + crypto::Encryptable, + id_type, + transformers::{ForeignFrom, ForeignTryFrom}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::{ + network_tokenization as nt_domain_types, router_request_types as domain_request_types, +}; +use masking::{ExposeInterface, Secret}; +use router_env::logger; + +use super::migration; +use crate::{ + core::payment_methods::{ + cards::{add_card_to_hs_locker, create_encrypted_data, tokenize_card_flow}, + network_tokenization, transformers as pm_transformers, + }, + errors::{self, RouterResult}, + services, + types::{api, domain}, + SessionState, +}; + +pub mod card_executor; +pub mod payment_method_executor; + +pub use card_executor::*; +pub use payment_method_executor::*; +use rdkafka::message::ToBytes; + +#[derive(Debug, MultipartForm)] +pub struct CardNetworkTokenizeForm { + #[multipart(limit = "1MB")] + pub file: Bytes, + pub merchant_id: Text<id_type::MerchantId>, +} + +pub fn parse_csv( + merchant_id: &id_type::MerchantId, + data: &[u8], +) -> csv::Result<Vec<payment_methods_api::CardNetworkTokenizeRequest>> { + let mut csv_reader = csv::ReaderBuilder::new() + .has_headers(true) + .from_reader(data); + let mut records = Vec::new(); + let mut id_counter = 0; + for (i, result) in csv_reader + .deserialize::<domain::CardNetworkTokenizeRecord>() + .enumerate() + { + match result { + Ok(mut record) => { + logger::info!("Parsed Record (line {}): {:?}", i + 1, record); + id_counter += 1; + record.line_number = Some(id_counter); + record.merchant_id = Some(merchant_id.clone()); + match payment_methods_api::CardNetworkTokenizeRequest::foreign_try_from(record) { + Ok(record) => { + records.push(record); + } + Err(err) => { + logger::error!("Error parsing line {}: {}", i + 1, err.to_string()); + } + } + } + Err(e) => logger::error!("Error parsing line {}: {}", i + 1, e), + } + } + Ok(records) +} + +pub fn get_tokenize_card_form_records( + form: CardNetworkTokenizeForm, +) -> Result< + ( + id_type::MerchantId, + Vec<payment_methods_api::CardNetworkTokenizeRequest>, + ), + errors::ApiErrorResponse, +> { + match parse_csv(&form.merchant_id, form.file.data.to_bytes()) { + Ok(records) => { + logger::info!("Parsed a total of {} records", records.len()); + Ok((form.merchant_id.0, records)) + } + Err(e) => { + logger::error!("Failed to parse CSV: {:?}", e); + Err(errors::ApiErrorResponse::PreconditionFailed { + message: e.to_string(), + }) + } + } +} + +pub async fn tokenize_cards( + state: &SessionState, + records: Vec<payment_methods_api::CardNetworkTokenizeRequest>, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, +) -> errors::RouterResponse<Vec<payment_methods_api::CardNetworkTokenizeResponse>> { + use futures::stream::StreamExt; + + // Process all records in parallel + let responses = futures::stream::iter(records.into_iter()) + .map(|record| async move { + let tokenize_request = record.data.clone(); + let customer = record.customer.clone(); + Box::pin(tokenize_card_flow( + state, + domain::CardNetworkTokenizeRequest::foreign_from(record), + merchant_account, + key_store, + )) + .await + .unwrap_or_else(|e| { + let err = e.current_context(); + payment_methods_api::CardNetworkTokenizeResponse { + tokenization_data: Some(tokenize_request), + error_code: Some(err.error_code()), + error_message: Some(err.error_message()), + card_tokenized: false, + payment_method_response: None, + customer: Some(customer), + } + }) + }) + .buffer_unordered(10) + .collect() + .await; + + // Return the final response + Ok(services::ApplicationResponse::Json(responses)) +} + +// Data types +type NetworkTokenizationResponse = ( + nt_domain_types::CardNetworkTokenResponsePayload, + Option<String>, +); + +pub struct StoreLockerResponse { + pub store_card_resp: pm_transformers::StoreCardRespPayload, + pub store_token_resp: pm_transformers::StoreCardRespPayload, +} + +// Builder +pub struct NetworkTokenizationBuilder<'a, S: State> { + /// Current state + state: std::marker::PhantomData<S>, + + /// Customer details + pub customer: Option<&'a api::CustomerDetails>, + + /// Card details + pub card: Option<domain::CardDetail>, + + /// CVC + pub card_cvc: Option<Secret<String>>, + + /// Network token details + pub network_token: Option<&'a nt_domain_types::CardNetworkTokenResponsePayload>, + + /// Stored card details + pub stored_card: Option<&'a pm_transformers::StoreCardRespPayload>, + + /// Stored token details + pub stored_token: Option<&'a pm_transformers::StoreCardRespPayload>, + + /// Payment method response + pub payment_method_response: Option<api::PaymentMethodResponse>, + + /// Card network tokenization status + pub card_tokenized: bool, + + /// Error code + pub error_code: Option<&'a String>, + + /// Error message + pub error_message: Option<&'a String>, +} + +// Async executor +pub struct CardNetworkTokenizeExecutor<'a, D> { + pub state: &'a SessionState, + pub merchant_account: &'a domain::MerchantAccount, + key_store: &'a domain::MerchantKeyStore, + data: &'a D, + customer: &'a domain_request_types::CustomerDetails, +} + +// State machine +pub trait State {} +pub trait TransitionTo<S: State> {} + +// Trait for network tokenization +#[async_trait::async_trait] +pub trait NetworkTokenizationProcess<'a, D> { + fn new( + state: &'a SessionState, + key_store: &'a domain::MerchantKeyStore, + merchant_account: &'a domain::MerchantAccount, + data: &'a D, + customer: &'a domain_request_types::CustomerDetails, + ) -> Self; + async fn encrypt_card( + &self, + card_details: &domain::CardDetail, + saved_to_locker: bool, + ) -> RouterResult<Encryptable<Secret<serde_json::Value>>>; + async fn encrypt_network_token( + &self, + network_token_details: &NetworkTokenizationResponse, + card_details: &domain::CardDetail, + saved_to_locker: bool, + ) -> RouterResult<Encryptable<Secret<serde_json::Value>>>; + async fn fetch_bin_details_and_validate_card_network( + &self, + card_number: CardNumber, + card_issuer: Option<&String>, + card_network: Option<&api_enums::CardNetwork>, + card_type: Option<&api_models::payment_methods::CardType>, + card_issuing_country: Option<&String>, + ) -> RouterResult<Option<diesel_models::CardInfo>>; + fn validate_card_network( + &self, + optional_card_network: Option<&api_enums::CardNetwork>, + ) -> RouterResult<()>; + async fn tokenize_card( + &self, + customer_id: &id_type::CustomerId, + card: &domain::CardDetail, + optional_cvc: Option<Secret<String>>, + ) -> RouterResult<NetworkTokenizationResponse>; + async fn store_network_token_in_locker( + &self, + network_token: &NetworkTokenizationResponse, + customer_id: &id_type::CustomerId, + card_holder_name: Option<Secret<String>>, + nick_name: Option<Secret<String>>, + ) -> RouterResult<pm_transformers::StoreCardRespPayload>; +} + +// Generic implementation +#[async_trait::async_trait] +impl<'a, D> NetworkTokenizationProcess<'a, D> for CardNetworkTokenizeExecutor<'a, D> +where + D: Send + Sync + 'static, +{ + fn new( + state: &'a SessionState, + key_store: &'a domain::MerchantKeyStore, + merchant_account: &'a domain::MerchantAccount, + data: &'a D, + customer: &'a domain_request_types::CustomerDetails, + ) -> Self { + Self { + data, + customer, + state, + merchant_account, + key_store, + } + } + async fn encrypt_card( + &self, + card_details: &domain::CardDetail, + saved_to_locker: bool, + ) -> RouterResult<Encryptable<Secret<serde_json::Value>>> { + let pm_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod { + last4_digits: Some(card_details.card_number.get_last4()), + expiry_month: Some(card_details.card_exp_month.clone()), + expiry_year: Some(card_details.card_exp_year.clone()), + card_isin: Some(card_details.card_number.get_card_isin()), + nick_name: card_details.nick_name.clone(), + card_holder_name: card_details.card_holder_name.clone(), + issuer_country: card_details.card_issuing_country.clone(), + card_issuer: card_details.card_issuer.clone(), + card_network: card_details.card_network.clone(), + card_type: card_details.card_type.clone(), + saved_to_locker, + }); + create_encrypted_data(&self.state.into(), self.key_store, pm_data) + .await + .inspect_err(|err| logger::info!("Error encrypting payment method data: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError) + } + async fn encrypt_network_token( + &self, + network_token_details: &NetworkTokenizationResponse, + card_details: &domain::CardDetail, + saved_to_locker: bool, + ) -> RouterResult<Encryptable<Secret<serde_json::Value>>> { + let network_token = &network_token_details.0; + let token_data = api::PaymentMethodsData::Card(api::CardDetailsPaymentMethod { + last4_digits: Some(network_token.token_last_four.clone()), + expiry_month: Some(network_token.token_expiry_month.clone()), + expiry_year: Some(network_token.token_expiry_year.clone()), + card_isin: Some(network_token.token_isin.clone()), + nick_name: card_details.nick_name.clone(), + card_holder_name: card_details.card_holder_name.clone(), + issuer_country: card_details.card_issuing_country.clone(), + card_issuer: card_details.card_issuer.clone(), + card_network: card_details.card_network.clone(), + card_type: card_details.card_type.clone(), + saved_to_locker, + }); + create_encrypted_data(&self.state.into(), self.key_store, token_data) + .await + .inspect_err(|err| logger::info!("Error encrypting network token data: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError) + } + async fn fetch_bin_details_and_validate_card_network( + &self, + card_number: CardNumber, + card_issuer: Option<&String>, + card_network: Option<&api_enums::CardNetwork>, + card_type: Option<&api_models::payment_methods::CardType>, + card_issuing_country: Option<&String>, + ) -> RouterResult<Option<diesel_models::CardInfo>> { + let db = &*self.state.store; + if card_issuer.is_some() + && card_network.is_some() + && card_type.is_some() + && card_issuing_country.is_some() + { + self.validate_card_network(card_network)?; + return Ok(None); + } + + db.get_card_info(&card_number.get_card_isin()) + .await + .attach_printable("Failed to perform BIN lookup") + .change_context(errors::ApiErrorResponse::InternalServerError)? + .map(|card_info| { + self.validate_card_network(card_info.card_network.as_ref())?; + Ok(card_info) + }) + .transpose() + } + async fn tokenize_card( + &self, + customer_id: &id_type::CustomerId, + card: &domain::CardDetail, + optional_cvc: Option<Secret<String>>, + ) -> RouterResult<NetworkTokenizationResponse> { + network_tokenization::make_card_network_tokenization_request( + self.state, + card, + optional_cvc, + customer_id, + ) + .await + .map_err(|err| { + logger::error!("Failed to tokenize card with the network: {:?}", err); + report!(errors::ApiErrorResponse::InternalServerError) + }) + } + fn validate_card_network( + &self, + optional_card_network: Option<&api_enums::CardNetwork>, + ) -> RouterResult<()> { + optional_card_network.map_or( + Err(report!(errors::ApiErrorResponse::NotSupported { + message: "Unknown card network".to_string() + })), + |card_network| { + if self + .state + .conf + .network_tokenization_supported_card_networks + .card_networks + .contains(card_network) + { + Ok(()) + } else { + Err(report!(errors::ApiErrorResponse::NotSupported { + message: format!( + "Network tokenization for {} is not supported", + card_network + ) + })) + } + }, + ) + } + async fn store_network_token_in_locker( + &self, + network_token: &NetworkTokenizationResponse, + customer_id: &id_type::CustomerId, + card_holder_name: Option<Secret<String>>, + nick_name: Option<Secret<String>>, + ) -> RouterResult<pm_transformers::StoreCardRespPayload> { + let network_token = &network_token.0; + let merchant_id = self.merchant_account.get_id(); + let locker_req = + pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq { + merchant_id: merchant_id.clone(), + merchant_customer_id: customer_id.clone(), + card: payment_methods_api::Card { + card_number: network_token.token.clone(), + card_exp_month: network_token.token_expiry_month.clone(), + card_exp_year: network_token.token_expiry_year.clone(), + card_brand: Some(network_token.card_brand.to_string()), + card_isin: Some(network_token.token_isin.clone()), + name_on_card: card_holder_name, + nick_name: nick_name.map(|nick_name| nick_name.expose()), + }, + requestor_card_reference: None, + ttl: self.state.conf.locker.ttl_for_storage_in_secs, + }); + + let stored_resp = add_card_to_hs_locker( + self.state, + &locker_req, + customer_id, + api_enums::LockerChoice::HyperswitchCardVault, + ) + .await + .inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + Ok(stored_resp) + } +} diff --git a/crates/router/src/core/payment_methods/tokenize/card_executor.rs b/crates/router/src/core/payment_methods/tokenize/card_executor.rs new file mode 100644 index 00000000000..9b7f89c5199 --- /dev/null +++ b/crates/router/src/core/payment_methods/tokenize/card_executor.rs @@ -0,0 +1,589 @@ +use std::str::FromStr; + +use api_models::{enums as api_enums, payment_methods as payment_methods_api}; +use common_utils::{ + consts, + ext_traits::OptionExt, + generate_customer_id_of_default_length, id_type, + pii::Email, + type_name, + types::keymanager::{Identifier, KeyManagerState, ToEncryptable}, +}; +use error_stack::{report, ResultExt}; +use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; +use masking::{ExposeInterface, PeekInterface, SwitchStrategy}; +use router_env::logger; + +use super::{ + migration, CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess, + NetworkTokenizationResponse, State, StoreLockerResponse, TransitionTo, +}; +use crate::{ + core::payment_methods::{ + cards::{add_card_to_hs_locker, create_payment_method}, + transformers as pm_transformers, + }, + errors::{self, RouterResult}, + types::{api, domain}, + utils, +}; + +// Available states for card tokenization +pub struct TokenizeWithCard; +pub struct CardRequestValidated; +pub struct CardDetailsAssigned; +pub struct CustomerAssigned; +pub struct CardTokenized; +pub struct CardStored; +pub struct CardTokenStored; +pub struct PaymentMethodCreated; + +impl State for TokenizeWithCard {} +impl State for CustomerAssigned {} +impl State for CardRequestValidated {} +impl State for CardDetailsAssigned {} +impl State for CardTokenized {} +impl State for CardStored {} +impl State for CardTokenStored {} +impl State for PaymentMethodCreated {} + +// State transitions for card tokenization +impl TransitionTo<CardRequestValidated> for TokenizeWithCard {} +impl TransitionTo<CardDetailsAssigned> for CardRequestValidated {} +impl TransitionTo<CustomerAssigned> for CardDetailsAssigned {} +impl TransitionTo<CardTokenized> for CustomerAssigned {} +impl TransitionTo<CardTokenStored> for CardTokenized {} +impl TransitionTo<PaymentMethodCreated> for CardTokenStored {} + +impl Default for NetworkTokenizationBuilder<'_, TokenizeWithCard> { + fn default() -> Self { + Self::new() + } +} + +impl<'a> NetworkTokenizationBuilder<'a, TokenizeWithCard> { + pub fn new() -> Self { + Self { + state: std::marker::PhantomData, + customer: None, + card: None, + card_cvc: None, + network_token: None, + stored_card: None, + stored_token: None, + payment_method_response: None, + card_tokenized: false, + error_code: None, + error_message: None, + } + } + pub fn set_validate_result(self) -> NetworkTokenizationBuilder<'a, CardRequestValidated> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_card: self.stored_card, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, CardRequestValidated> { + pub fn set_card_details( + self, + card_req: &'a domain::TokenizeCardRequest, + optional_card_info: Option<diesel_models::CardInfo>, + ) -> NetworkTokenizationBuilder<'a, CardDetailsAssigned> { + let card = domain::CardDetail { + card_number: card_req.raw_card_number.clone(), + card_exp_month: card_req.card_expiry_month.clone(), + card_exp_year: card_req.card_expiry_year.clone(), + bank_code: optional_card_info + .as_ref() + .and_then(|card_info| card_info.bank_code.clone()), + nick_name: card_req.nick_name.clone(), + card_holder_name: card_req.card_holder_name.clone(), + card_issuer: optional_card_info + .as_ref() + .map_or(card_req.card_issuer.clone(), |card_info| { + card_info.card_issuer.clone() + }), + card_network: optional_card_info + .as_ref() + .map_or(card_req.card_network.clone(), |card_info| { + card_info.card_network.clone() + }), + card_type: optional_card_info.as_ref().map_or( + card_req + .card_type + .as_ref() + .map(|card_type| card_type.to_string()), + |card_info| card_info.card_type.clone(), + ), + card_issuing_country: optional_card_info + .as_ref() + .map_or(card_req.card_issuing_country.clone(), |card_info| { + card_info.card_issuing_country.clone() + }), + }; + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + card: Some(card), + card_cvc: card_req.card_cvc.clone(), + customer: self.customer, + network_token: self.network_token, + stored_card: self.stored_card, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, CardDetailsAssigned> { + pub fn set_customer( + self, + customer: &'a api::CustomerDetails, + ) -> NetworkTokenizationBuilder<'a, CustomerAssigned> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + customer: Some(customer), + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_card: self.stored_card, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, CustomerAssigned> { + pub fn get_optional_card_and_cvc( + &self, + ) -> (Option<domain::CardDetail>, Option<masking::Secret<String>>) { + (self.card.clone(), self.card_cvc.clone()) + } + pub fn set_token_details( + self, + network_token: &'a NetworkTokenizationResponse, + ) -> NetworkTokenizationBuilder<'a, CardTokenized> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + network_token: Some(&network_token.0), + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + stored_card: self.stored_card, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, CardTokenized> { + pub fn set_stored_card_response( + self, + store_card_response: &'a StoreLockerResponse, + ) -> NetworkTokenizationBuilder<'a, CardStored> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + stored_card: Some(&store_card_response.store_card_resp), + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, CardStored> { + pub fn set_stored_token_response( + self, + store_token_response: &'a StoreLockerResponse, + ) -> NetworkTokenizationBuilder<'a, CardTokenStored> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + card_tokenized: true, + stored_token: Some(&store_token_response.store_token_resp), + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_card: self.stored_card, + payment_method_response: self.payment_method_response, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, CardTokenStored> { + pub fn set_payment_method_response( + self, + payment_method: &'a domain::PaymentMethod, + ) -> NetworkTokenizationBuilder<'a, PaymentMethodCreated> { + let card_detail_from_locker = self.card.as_ref().map(|card| api::CardDetailFromLocker { + scheme: None, + issuer_country: card.card_issuing_country.clone(), + last4_digits: Some(card.card_number.clone().get_last4()), + card_number: None, + expiry_month: Some(card.card_exp_month.clone().clone()), + expiry_year: Some(card.card_exp_year.clone().clone()), + card_token: None, + card_holder_name: card.card_holder_name.clone(), + card_fingerprint: None, + nick_name: card.nick_name.clone(), + card_network: card.card_network.clone(), + card_isin: Some(card.card_number.clone().get_card_isin()), + card_issuer: card.card_issuer.clone(), + card_type: card.card_type.clone(), + saved_to_locker: true, + }); + let payment_method_response = api::PaymentMethodResponse { + merchant_id: payment_method.merchant_id.clone(), + customer_id: Some(payment_method.customer_id.clone()), + payment_method_id: payment_method.payment_method_id.clone(), + payment_method: payment_method.payment_method, + payment_method_type: payment_method.payment_method_type, + card: card_detail_from_locker, + recurring_enabled: true, + installment_payment_enabled: false, + metadata: payment_method.metadata.clone(), + created: Some(payment_method.created_at), + last_used_at: Some(payment_method.last_used_at), + client_secret: payment_method.client_secret.clone(), + bank_transfer: None, + payment_experience: None, + }; + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + payment_method_response: Some(payment_method_response), + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_card: self.stored_card, + stored_token: self.stored_token, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl NetworkTokenizationBuilder<'_, PaymentMethodCreated> { + pub fn build(self) -> api::CardNetworkTokenizeResponse { + api::CardNetworkTokenizeResponse { + payment_method_response: self.payment_method_response, + customer: self.customer.cloned(), + card_tokenized: self.card_tokenized, + error_code: self.error_code.cloned(), + error_message: self.error_message.cloned(), + // Below field is mutated by caller functions for batched API operations + tokenization_data: None, + } + } +} + +// Specific executor for card tokenization +impl CardNetworkTokenizeExecutor<'_, domain::TokenizeCardRequest> { + pub async fn validate_request_and_fetch_optional_customer( + &self, + ) -> RouterResult<Option<api::CustomerDetails>> { + // Validate card's expiry + migration::validate_card_expiry(&self.data.card_expiry_month, &self.data.card_expiry_year)?; + + // Validate customer ID + let customer_id = self + .customer + .customer_id + .as_ref() + .get_required_value("customer_id") + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "customer.customer_id", + })?; + + // Fetch customer details if present + let db = &*self.state.store; + let key_manager_state: &KeyManagerState = &self.state.into(); + db.find_customer_optional_by_customer_id_merchant_id( + key_manager_state, + customer_id, + self.merchant_account.get_id(), + self.key_store, + self.merchant_account.storage_scheme, + ) + .await + .inspect_err(|err| logger::info!("Error fetching customer: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError) + .map_or( + // Validate if customer creation is feasible + if self.customer.name.is_some() + || self.customer.email.is_some() + || self.customer.phone.is_some() + { + Ok(None) + } else { + Err(report!(errors::ApiErrorResponse::MissingRequiredFields { + field_names: vec!["customer.name", "customer.email", "customer.phone"], + })) + }, + // If found, send back CustomerDetails from DB + |optional_customer| { + Ok(optional_customer.map(|customer| api::CustomerDetails { + id: customer.customer_id.clone(), + name: customer.name.clone().map(|name| name.into_inner()), + email: customer.email.clone().map(Email::from), + phone: customer.phone.clone().map(|phone| phone.into_inner()), + phone_country_code: customer.phone_country_code.clone(), + })) + }, + ) + } + + pub async fn create_customer(&self) -> RouterResult<api::CustomerDetails> { + let db = &*self.state.store; + let customer_id = self + .customer + .customer_id + .as_ref() + .get_required_value("customer_id") + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "customer_id", + })?; + let key_manager_state: &KeyManagerState = &self.state.into(); + + let encrypted_data = crypto_operation( + key_manager_state, + type_name!(domain::Customer), + CryptoOperation::BatchEncrypt(domain::FromRequestEncryptableCustomer::to_encryptable( + domain::FromRequestEncryptableCustomer { + name: self.customer.name.clone(), + email: self + .customer + .email + .clone() + .map(|email| email.expose().switch_strategy()), + phone: self.customer.phone.clone(), + }, + )), + Identifier::Merchant(self.merchant_account.get_id().clone()), + self.key_store.key.get_inner().peek(), + ) + .await + .inspect_err(|err| logger::info!("Error encrypting customer: {:?}", err)) + .and_then(|val| val.try_into_batchoperation()) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encrypt customer")?; + + let encryptable_customer = + domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to form EncryptableCustomer")?; + + let new_customer_id = generate_customer_id_of_default_length(); + let domain_customer = domain::Customer { + customer_id: new_customer_id.clone(), + merchant_id: self.merchant_account.get_id().clone(), + name: encryptable_customer.name, + email: encryptable_customer.email.map(|email| { + utils::Encryptable::new( + email.clone().into_inner().switch_strategy(), + email.into_encrypted(), + ) + }), + phone: encryptable_customer.phone, + description: None, + phone_country_code: self.customer.phone_country_code.to_owned(), + metadata: None, + connector_customer: None, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + address_id: None, + default_payment_method_id: None, + updated_by: None, + version: hyperswitch_domain_models::consts::API_VERSION, + }; + + db.insert_customer( + domain_customer, + key_manager_state, + self.key_store, + self.merchant_account.storage_scheme, + ) + .await + .inspect_err(|err| logger::info!("Error creating a customer: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable_lazy(|| { + format!( + "Failed to insert customer [id - {:?}] for merchant [id - {:?}]", + customer_id, + self.merchant_account.get_id() + ) + })?; + + Ok(api::CustomerDetails { + id: new_customer_id, + name: self.customer.name.clone(), + email: self.customer.email.clone(), + phone: self.customer.phone.clone(), + phone_country_code: self.customer.phone_country_code.clone(), + }) + } + + pub async fn store_card_and_token_in_locker( + &self, + network_token: &NetworkTokenizationResponse, + card: &domain::CardDetail, + customer_id: &id_type::CustomerId, + ) -> RouterResult<StoreLockerResponse> { + let stored_card_resp = self.store_card_in_locker(card, customer_id).await?; + let stored_token_resp = self + .store_network_token_in_locker( + network_token, + customer_id, + card.card_holder_name.clone(), + card.nick_name.clone(), + ) + .await?; + let store_locker_response = StoreLockerResponse { + store_card_resp: stored_card_resp, + store_token_resp: stored_token_resp, + }; + Ok(store_locker_response) + } + + pub async fn store_card_in_locker( + &self, + card: &domain::CardDetail, + customer_id: &id_type::CustomerId, + ) -> RouterResult<pm_transformers::StoreCardRespPayload> { + let merchant_id = self.merchant_account.get_id(); + let locker_req = + pm_transformers::StoreLockerReq::LockerCard(pm_transformers::StoreCardReq { + merchant_id: merchant_id.clone(), + merchant_customer_id: customer_id.clone(), + card: payment_methods_api::Card { + card_number: card.card_number.clone(), + card_exp_month: card.card_exp_month.clone(), + card_exp_year: card.card_exp_year.clone(), + card_isin: Some(card.card_number.get_card_isin().clone()), + name_on_card: card.card_holder_name.clone(), + nick_name: card + .nick_name + .as_ref() + .map(|nick_name| nick_name.clone().expose()), + card_brand: None, + }, + requestor_card_reference: None, + ttl: self.state.conf.locker.ttl_for_storage_in_secs, + }); + + let stored_resp = add_card_to_hs_locker( + self.state, + &locker_req, + customer_id, + api_enums::LockerChoice::HyperswitchCardVault, + ) + .await + .inspect_err(|err| logger::info!("Error adding card in locker: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + Ok(stored_resp) + } + + pub async fn create_payment_method( + &self, + stored_locker_resp: &StoreLockerResponse, + network_token_details: &NetworkTokenizationResponse, + card_details: &domain::CardDetail, + customer_id: &id_type::CustomerId, + ) -> RouterResult<domain::PaymentMethod> { + let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); + + // Form encrypted PM data (original card) + let enc_pm_data = self.encrypt_card(card_details, true).await?; + + // Form encrypted network token data + let enc_token_data = self + .encrypt_network_token(network_token_details, card_details, true) + .await?; + + // Form PM create entry + let payment_method_create = api::PaymentMethodCreate { + payment_method: Some(api_enums::PaymentMethod::Card), + payment_method_type: card_details + .card_type + .as_ref() + .and_then(|card_type| api_enums::PaymentMethodType::from_str(card_type).ok()), + payment_method_issuer: card_details.card_issuer.clone(), + payment_method_issuer_code: None, + card: Some(api::CardDetail { + card_number: card_details.card_number.clone(), + card_exp_month: card_details.card_exp_month.clone(), + card_exp_year: card_details.card_exp_year.clone(), + card_holder_name: card_details.card_holder_name.clone(), + nick_name: card_details.nick_name.clone(), + card_issuing_country: card_details.card_issuing_country.clone(), + card_network: card_details.card_network.clone(), + card_issuer: card_details.card_issuer.clone(), + card_type: card_details.card_type.clone(), + }), + metadata: None, + customer_id: Some(customer_id.clone()), + card_network: card_details + .card_network + .as_ref() + .map(|network| network.to_string()), + bank_transfer: None, + wallet: None, + client_secret: None, + payment_method_data: None, + billing: None, + connector_mandate_details: None, + network_transaction_id: None, + }; + create_payment_method( + self.state, + &payment_method_create, + customer_id, + &payment_method_id, + Some(stored_locker_resp.store_card_resp.card_reference.clone()), + self.merchant_account.get_id(), + None, + None, + Some(enc_pm_data), + self.key_store, + None, + None, + None, + self.merchant_account.storage_scheme, + None, + None, + network_token_details.1.clone(), + Some(stored_locker_resp.store_token_resp.card_reference.clone()), + Some(enc_token_data), + ) + .await + } +} diff --git a/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs new file mode 100644 index 00000000000..967dc77f7fd --- /dev/null +++ b/crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs @@ -0,0 +1,411 @@ +use api_models::enums as api_enums; +use common_utils::{ + ext_traits::OptionExt, fp_utils::when, pii::Email, types::keymanager::KeyManagerState, +}; +use error_stack::{report, ResultExt}; +use masking::Secret; +use router_env::logger; + +use super::{ + CardNetworkTokenizeExecutor, NetworkTokenizationBuilder, NetworkTokenizationProcess, + NetworkTokenizationResponse, State, TransitionTo, +}; +use crate::{ + core::payment_methods::transformers as pm_transformers, + errors::{self, RouterResult}, + types::{api, domain}, +}; + +// Available states for payment method tokenization +pub struct TokenizeWithPmId; +pub struct PmValidated; +pub struct PmFetched; +pub struct PmAssigned; +pub struct PmTokenized; +pub struct PmTokenStored; +pub struct PmTokenUpdated; + +impl State for TokenizeWithPmId {} +impl State for PmValidated {} +impl State for PmFetched {} +impl State for PmAssigned {} +impl State for PmTokenized {} +impl State for PmTokenStored {} +impl State for PmTokenUpdated {} + +// State transitions for payment method tokenization +impl TransitionTo<PmFetched> for TokenizeWithPmId {} +impl TransitionTo<PmValidated> for PmFetched {} +impl TransitionTo<PmAssigned> for PmValidated {} +impl TransitionTo<PmTokenized> for PmAssigned {} +impl TransitionTo<PmTokenStored> for PmTokenized {} +impl TransitionTo<PmTokenUpdated> for PmTokenStored {} + +impl Default for NetworkTokenizationBuilder<'_, TokenizeWithPmId> { + fn default() -> Self { + Self::new() + } +} + +impl<'a> NetworkTokenizationBuilder<'a, TokenizeWithPmId> { + pub fn new() -> Self { + Self { + state: std::marker::PhantomData, + customer: None, + card: None, + card_cvc: None, + network_token: None, + stored_card: None, + stored_token: None, + payment_method_response: None, + card_tokenized: false, + error_code: None, + error_message: None, + } + } + pub fn set_payment_method( + self, + payment_method: &domain::PaymentMethod, + ) -> NetworkTokenizationBuilder<'a, PmFetched> { + let payment_method_response = api::PaymentMethodResponse { + merchant_id: payment_method.merchant_id.clone(), + customer_id: Some(payment_method.customer_id.clone()), + payment_method_id: payment_method.payment_method_id.clone(), + payment_method: payment_method.payment_method, + payment_method_type: payment_method.payment_method_type, + recurring_enabled: true, + installment_payment_enabled: false, + metadata: payment_method.metadata.clone(), + created: Some(payment_method.created_at), + last_used_at: Some(payment_method.last_used_at), + client_secret: payment_method.client_secret.clone(), + card: None, + bank_transfer: None, + payment_experience: None, + }; + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + payment_method_response: Some(payment_method_response), + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_card: self.stored_card, + stored_token: self.stored_token, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, PmFetched> { + pub fn set_validate_result( + self, + customer: &'a api::CustomerDetails, + ) -> NetworkTokenizationBuilder<'a, PmValidated> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + customer: Some(customer), + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_card: self.stored_card, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, PmValidated> { + pub fn set_card_details( + self, + card_from_locker: &'a api_models::payment_methods::Card, + optional_card_info: Option<diesel_models::CardInfo>, + card_cvc: Option<Secret<String>>, + ) -> NetworkTokenizationBuilder<'a, PmAssigned> { + let card = domain::CardDetail { + card_number: card_from_locker.card_number.clone(), + card_exp_month: card_from_locker.card_exp_month.clone(), + card_exp_year: card_from_locker.card_exp_year.clone(), + bank_code: optional_card_info + .as_ref() + .and_then(|card_info| card_info.bank_code.clone()), + nick_name: card_from_locker + .nick_name + .as_ref() + .map(|nick_name| Secret::new(nick_name.clone())), + card_holder_name: card_from_locker.name_on_card.clone(), + card_issuer: optional_card_info + .as_ref() + .and_then(|card_info| card_info.card_issuer.clone()), + card_network: optional_card_info + .as_ref() + .and_then(|card_info| card_info.card_network.clone()), + card_type: optional_card_info + .as_ref() + .and_then(|card_info| card_info.card_type.clone()), + card_issuing_country: optional_card_info + .as_ref() + .and_then(|card_info| card_info.card_issuing_country.clone()), + }; + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + card: Some(card), + card_cvc, + customer: self.customer, + network_token: self.network_token, + stored_card: self.stored_card, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, PmAssigned> { + pub fn get_optional_card_and_cvc( + &self, + ) -> (Option<domain::CardDetail>, Option<Secret<String>>) { + (self.card.clone(), self.card_cvc.clone()) + } + pub fn set_token_details( + self, + network_token: &'a NetworkTokenizationResponse, + ) -> NetworkTokenizationBuilder<'a, PmTokenized> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + network_token: Some(&network_token.0), + card_tokenized: true, + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + stored_card: self.stored_card, + stored_token: self.stored_token, + payment_method_response: self.payment_method_response, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, PmTokenized> { + pub fn set_stored_token_response( + self, + store_token_response: &'a pm_transformers::StoreCardRespPayload, + ) -> NetworkTokenizationBuilder<'a, PmTokenStored> { + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + stored_token: Some(store_token_response), + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + network_token: self.network_token, + stored_card: self.stored_card, + payment_method_response: self.payment_method_response, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl<'a> NetworkTokenizationBuilder<'a, PmTokenStored> { + pub fn set_payment_method( + self, + payment_method: &'a domain::PaymentMethod, + ) -> NetworkTokenizationBuilder<'a, PmTokenUpdated> { + let payment_method_response = api::PaymentMethodResponse { + merchant_id: payment_method.merchant_id.clone(), + customer_id: Some(payment_method.customer_id.clone()), + payment_method_id: payment_method.payment_method_id.clone(), + payment_method: payment_method.payment_method, + payment_method_type: payment_method.payment_method_type, + recurring_enabled: true, + installment_payment_enabled: false, + metadata: payment_method.metadata.clone(), + created: Some(payment_method.created_at), + last_used_at: Some(payment_method.last_used_at), + client_secret: payment_method.client_secret.clone(), + card: None, + bank_transfer: None, + payment_experience: None, + }; + NetworkTokenizationBuilder { + state: std::marker::PhantomData, + payment_method_response: Some(payment_method_response), + customer: self.customer, + card: self.card, + card_cvc: self.card_cvc, + stored_token: self.stored_token, + network_token: self.network_token, + stored_card: self.stored_card, + card_tokenized: self.card_tokenized, + error_code: self.error_code, + error_message: self.error_message, + } + } +} + +impl NetworkTokenizationBuilder<'_, PmTokenUpdated> { + pub fn build(self) -> api::CardNetworkTokenizeResponse { + api::CardNetworkTokenizeResponse { + payment_method_response: self.payment_method_response, + customer: self.customer.cloned(), + card_tokenized: self.card_tokenized, + error_code: self.error_code.cloned(), + error_message: self.error_message.cloned(), + // Below field is mutated by caller functions for batched API operations + tokenization_data: None, + } + } +} + +// Specific executor for payment method tokenization +impl CardNetworkTokenizeExecutor<'_, domain::TokenizePaymentMethodRequest> { + pub async fn fetch_payment_method( + &self, + payment_method_id: &str, + ) -> RouterResult<domain::PaymentMethod> { + self.state + .store + .find_payment_method( + &self.state.into(), + self.key_store, + payment_method_id, + self.merchant_account.storage_scheme, + ) + .await + .map_err(|err| match err.current_context() { + storage_impl::errors::StorageError::DatabaseError(err) + if matches!( + err.current_context(), + diesel_models::errors::DatabaseError::NotFound + ) => + { + report!(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid payment_method_id".into(), + }) + } + storage_impl::errors::StorageError::ValueNotFound(_) => { + report!(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid payment_method_id".to_string(), + }) + } + err => { + logger::info!("Error fetching payment_method: {:?}", err); + report!(errors::ApiErrorResponse::InternalServerError) + } + }) + } + pub async fn validate_request_and_locker_reference_and_customer( + &self, + payment_method: &domain::PaymentMethod, + ) -> RouterResult<(String, api::CustomerDetails)> { + // Ensure customer ID matches + let customer_id_in_req = self + .customer + .customer_id + .clone() + .get_required_value("customer_id") + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "customer", + })?; + when(payment_method.customer_id != customer_id_in_req, || { + Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: "Payment method does not belong to the customer".to_string() + })) + })?; + + // Ensure payment method is card + match payment_method.payment_method { + Some(api_enums::PaymentMethod::Card) => Ok(()), + Some(_) => Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: "Payment method is not card".to_string() + })), + None => Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: "Payment method is empty".to_string() + })), + }?; + + // Ensure card is not tokenized already + when( + payment_method + .network_token_requestor_reference_id + .is_some(), + || { + Err(report!(errors::ApiErrorResponse::InvalidRequestData { + message: "Card is already tokenized".to_string() + })) + }, + )?; + + // Ensure locker reference is present + let locker_id = payment_method.locker_id.clone().ok_or(report!( + errors::ApiErrorResponse::InvalidRequestData { + message: "locker_id not found for given payment_method_id".to_string() + } + ))?; + + // Fetch customer + let db = &*self.state.store; + let key_manager_state: &KeyManagerState = &self.state.into(); + let customer = db + .find_customer_by_customer_id_merchant_id( + key_manager_state, + &payment_method.customer_id, + self.merchant_account.get_id(), + self.key_store, + self.merchant_account.storage_scheme, + ) + .await + .inspect_err(|err| logger::info!("Error fetching customer: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError)?; + + let customer_details = api::CustomerDetails { + id: customer.customer_id.clone(), + name: customer.name.clone().map(|name| name.into_inner()), + email: customer.email.clone().map(Email::from), + phone: customer.phone.clone().map(|phone| phone.into_inner()), + phone_country_code: customer.phone_country_code.clone(), + }; + + Ok((locker_id, customer_details)) + } + pub async fn update_payment_method( + &self, + store_token_response: &pm_transformers::StoreCardRespPayload, + payment_method: domain::PaymentMethod, + network_token_details: &NetworkTokenizationResponse, + card_details: &domain::CardDetail, + ) -> RouterResult<domain::PaymentMethod> { + // Form encrypted network token data + let enc_token_data = self + .encrypt_network_token(network_token_details, card_details, true) + .await?; + + // Update payment method + let payment_method_update = diesel_models::PaymentMethodUpdate::NetworkTokenDataUpdate { + network_token_requestor_reference_id: network_token_details.1.clone(), + network_token_locker_id: Some(store_token_response.card_reference.clone()), + network_token_payment_method_data: Some(enc_token_data.into()), + }; + self.state + .store + .update_payment_method( + &self.state.into(), + self.key_store, + payment_method, + payment_method_update, + self.merchant_account.storage_scheme, + ) + .await + .inspect_err(|err| logger::info!("Error updating payment method: {:?}", err)) + .change_context(errors::ApiErrorResponse::InternalServerError) + } +} diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 3baf72901e4..0bb232f85a0 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -1030,9 +1030,11 @@ pub async fn save_network_token_in_locker( .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) .is_some() { + let optional_card_cvc = Some(card_data.card_cvc.clone()); match network_tokenization::make_card_network_tokenization_request( state, - card_data, + &domain::CardDetail::from(card_data), + optional_card_cvc, &customer_id, ) .await diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index df4b9977b9c..cc143163674 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1254,6 +1254,14 @@ impl PaymentMethods { web::resource("/migrate-batch") .route(web::post().to(payment_methods::migrate_payment_methods)), ) + .service( + web::resource("/tokenize-card") + .route(web::post().to(payment_methods::tokenize_card_api)), + ) + .service( + web::resource("/tokenize-card-batch") + .route(web::post().to(payment_methods::tokenize_card_batch_api)), + ) .service( web::resource("/collect") .route(web::post().to(payment_methods::initiate_pm_collect_link_flow)), @@ -1267,6 +1275,10 @@ impl PaymentMethods { .route(web::get().to(payment_methods::payment_method_retrieve_api)) .route(web::delete().to(payment_methods::payment_method_delete_api)), ) + .service( + web::resource("/{payment_method_id}/tokenize-card") + .route(web::post().to(payment_methods::tokenize_card_using_pm_api)), + ) .service( web::resource("/{payment_method_id}/update") .route(web::post().to(payment_methods::payment_method_update_api)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index fd490c6fe4e..4c814f6a67b 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -39,6 +39,7 @@ pub enum ApiIdentifier { ApplePayCertificatesMigration, Relay, Documentation, + CardNetworkTokenization, Hypersense, PaymentMethodSession, } @@ -313,6 +314,10 @@ impl From<Flow> for ApiIdentifier { Flow::FeatureMatrix => Self::Documentation, + Flow::TokenizeCard + | Flow::TokenizeCardUsingPaymentMethodId + | Flow::TokenizeCardBatch => Self::CardNetworkTokenization, + Flow::HypersenseTokenRequest | Flow::HypersenseVerifyToken | Flow::HypersenseSignoutToken => Self::Hypersense, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 8d17a416645..a32a0268714 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -1,13 +1,15 @@ #[cfg(all( any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"), - not(feature = "customer_v2") + all(not(feature = "customer_v2"), not(feature = "payment_methods_v2")) ))] use actix_multipart::form::MultipartForm; use actix_web::{web, HttpRequest, HttpResponse}; -use common_utils::{errors::CustomResult, id_type}; +use common_utils::{errors::CustomResult, id_type, transformers::ForeignFrom}; use diesel_models::enums::IntentStatus; use error_stack::ResultExt; -use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; +use hyperswitch_domain_models::{ + bulk_tokenization::CardNetworkTokenizeRequest, merchant_key_store::MerchantKeyStore, +}; use router_env::{instrument, logger, tracing, Flow}; use super::app::{AppState, SessionState}; @@ -17,7 +19,7 @@ use crate::{ errors::{self, utils::StorageErrorExt}, payment_methods::{self as payment_methods_routes, cards}, }, - services::{api, authentication as auth, authorization::permissions::Permission}, + services::{self, api, authentication as auth, authorization::permissions::Permission}, types::{ api::payment_methods::{self, PaymentMethodId}, domain, @@ -29,7 +31,10 @@ use crate::{ not(feature = "customer_v2") ))] use crate::{ - core::{customers, payment_methods::migration}, + core::{ + customers, + payment_methods::{migration, tokenize}, + }, types::api::customers::CustomerRequest, }; @@ -927,6 +932,129 @@ impl ParentPaymentMethodToken { } } +#[cfg(all( + any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"), + not(feature = "payment_methods_v2") +))] +#[instrument(skip_all, fields(flow = ?Flow::TokenizeCard))] +pub async fn tokenize_card_api( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>, +) -> HttpResponse { + let flow = Flow::TokenizeCard; + + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _, req, _| async move { + let merchant_id = req.merchant_id.clone(); + let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; + let res = Box::pin(cards::tokenize_card_flow( + &state, + CardNetworkTokenizeRequest::foreign_from(req), + &merchant_account, + &key_store, + )) + .await?; + Ok(services::ApplicationResponse::Json(res)) + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all( + any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"), + not(feature = "payment_methods_v2") +))] +#[instrument(skip_all, fields(flow = ?Flow::TokenizeCardUsingPaymentMethodId))] +pub async fn tokenize_card_using_pm_api( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, + json_payload: web::Json<payment_methods::CardNetworkTokenizeRequest>, +) -> HttpResponse { + let flow = Flow::TokenizeCardUsingPaymentMethodId; + let pm_id = path.into_inner(); + let mut payload = json_payload.into_inner(); + if let payment_methods::TokenizeDataRequest::ExistingPaymentMethod(ref mut pm_data) = + payload.data + { + pm_data.payment_method_id = pm_id; + } else { + return api::log_and_return_error_response(error_stack::report!( + errors::ApiErrorResponse::InvalidDataValue { field_name: "card" } + )); + } + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, _, req, _| async move { + let merchant_id = req.merchant_id.clone(); + let (key_store, merchant_account) = get_merchant_account(&state, &merchant_id).await?; + let res = Box::pin(cards::tokenize_card_flow( + &state, + CardNetworkTokenizeRequest::foreign_from(req), + &merchant_account, + &key_store, + )) + .await?; + Ok(services::ApplicationResponse::Json(res)) + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all( + any(feature = "v1", feature = "v2", feature = "olap", feature = "oltp"), + not(feature = "payment_methods_v2") +))] +#[instrument(skip_all, fields(flow = ?Flow::TokenizeCardBatch))] +pub async fn tokenize_card_batch_api( + state: web::Data<AppState>, + req: HttpRequest, + MultipartForm(form): MultipartForm<tokenize::CardNetworkTokenizeForm>, +) -> HttpResponse { + let flow = Flow::TokenizeCardBatch; + let (merchant_id, records) = match tokenize::get_tokenize_card_form_records(form) { + Ok(res) => res, + Err(e) => return api::log_and_return_error_response(e.into()), + }; + + Box::pin(api::server_wrap( + flow, + state, + &req, + records, + |state, _, req, _| { + let merchant_id = merchant_id.clone(); + async move { + let (key_store, merchant_account) = + get_merchant_account(&state, &merchant_id).await?; + Box::pin(tokenize::tokenize_cards( + &state, + req, + &merchant_account, + &key_store, + )) + .await + } + }, + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(feature = "v2")] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSessionCreate))] pub async fn payment_methods_session_create( diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index 47ad15727ee..dc2d7816ffc 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -1,8 +1,9 @@ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub use api_models::payment_methods::{ - CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardType, CustomerPaymentMethod, + CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest, + CardNetworkTokenizeResponse, CardType, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, - GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, + GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodListData, @@ -17,15 +18,17 @@ pub use api_models::payment_methods::{ not(feature = "payment_methods_v2") ))] pub use api_models::payment_methods::{ - CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod, - CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest, - GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, + CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest, + CardNetworkTokenizeResponse, CustomerPaymentMethod, CustomerPaymentMethodsListResponse, + DefaultPaymentMethod, DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, + GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrate, PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData, - TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2, - TokenizedWalletValue1, TokenizedWalletValue2, + TokenizeCardRequest, TokenizeDataRequest, TokenizePayloadEncrypted, TokenizePayloadRequest, + TokenizePaymentMethodRequest, TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, + TokenizedWalletValue2, }; use error_stack::report; diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 74329844a76..2835acb4729 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -13,11 +13,12 @@ pub use api_models::{ }, payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card, - CryptoData, CustomerAcceptance, CustomerDetailsResponse, MandateAmountData, MandateData, - MandateTransactionType, MandateType, MandateValidationFields, NextActionType, - OnlineMandate, OpenBankingSessionToken, PayLaterData, PaymentIdType, - PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentMethodData, - PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, + CryptoData, CustomerAcceptance, CustomerDetails, CustomerDetailsResponse, + MandateAmountData, MandateData, MandateTransactionType, MandateType, + MandateValidationFields, NextActionType, OnlineMandate, OpenBankingSessionToken, + PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilters, + PaymentListFiltersV2, PaymentMethodData, PaymentMethodDataRequest, + PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index 270ed3ca64d..51f07fd6d2e 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -33,6 +33,7 @@ mod merchant_connector_account; mod merchant_key_store { pub use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; } +pub use hyperswitch_domain_models::bulk_tokenization::*; pub mod payment_methods { pub use hyperswitch_domain_models::payment_methods::*; } diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs index 53bc138c649..3f7849ae0fa 100644 --- a/crates/router/src/types/domain/payments.rs +++ b/crates/router/src/types/domain/payments.rs @@ -1,8 +1,8 @@ pub use hyperswitch_domain_models::payment_method_data::{ AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, - BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, - CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, - GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData, + BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardDetail, + CardRedirectData, CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData, + GiftCardDetails, GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection, MbWayRedirection, MifinityData, NetworkTokenData, OpenBankingData, PayLaterData, PaymentMethodData, RealTimePaymentData, SamsungPayWalletData, diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index b4655b6b774..aca819e3413 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -543,6 +543,12 @@ pub enum Flow { Relay, /// Relay retrieve flow RelayRetrieve, + /// Card tokenization flow + TokenizeCard, + /// Card tokenization using payment method flow + TokenizeCardUsingPaymentMethodId, + /// Cards batch tokenization flow + TokenizeCardBatch, /// Incoming Relay Webhook Receive IncomingRelayWebhookReceive, /// Generate Hypersense Token
2025-01-20T02:15:44Z
## 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 introduces below changes - Exposes two endpoints for - Single card tokenization - Tokenizing raw card details with the network - Tokenizing an existing payment method in HS with the network (card only) - Bulk tokenization - Tokenizing using raw card details or an existing payment method More details around the flow is present in https://github.com/juspay/hyperswitch/issues/6971 ### 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 This helps merchants to tokenize their customer's payment methods with the card networks. A new payment method entry is created for every card which can be used to perform txns using the network tokens. ## How did you test it? <details> <summary>1. Tokenize using raw card details</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/tokenize-card' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "card": { "raw_card_number": "4761360080000093", "card_expiry_month": "01", "card_expiry_year": "26", "card_cvc": "947" }, "merchant_id": "merchant_1737627877", "card_type": "debit", "customer": { "id": "cus_IoFeOlGhEeD54AbBdvxI" } }' Response {"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_IoFeOlGhEeD54AbBdvxI","payment_method_id":"pm_ai4pU6o32LUgRy2kl5hd","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0093","expiry_month":"01","expiry_year":"26","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":null,"card_network":null,"card_isin":"476136","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:41:54.753Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_IoFeOlGhEeD54AbBdvxI","name":"John Nether","email":"[email protected]","phone":"6168205362","phone_country_code":"+1"},"card_tokenized":true,"req":null} </details> <details> <summary>2. Tokenize using existing payment method entry</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/tokenize-card/pm_HHZV9XC6C10jjKGiK8m1' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "existing_payment_method": { "card_cvc": "947" }, "merchant_id": "merchant_1737627877", "card_type": "debit", "customer": { "id": "cus_IoFeOlGhEeD54AbBdvxI" } }' Response {"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_IoFeOlGhEeD54AbBdvxI","payment_method_id":"pm_HHZV9XC6C10jjKGiK8m1","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"03","expiry_year":"2030","card_token":null,"card_holder_name":"John US","card_fingerprint":null,"nick_name":"JD","card_network":null,"card_isin":"491761","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:43:02.151Z","last_used_at":"2025-01-23T10:43:02.151Z","client_secret":"pm_HHZV9XC6C10jjKGiK8m1_secret_SJC4AUiR4HmYzSDOKwPi"},"customer":{"id":"cus_IoFeOlGhEeD54AbBdvxI","name":null,"email":null,"phone":null,"phone_country_code":null},"card_tokenized":true,"req":null} </details> <details> <summary>3. Bulk tokenize</summary> cURL curl --location --request POST 'http://localhost:8080/payment_methods/tokenize-card-batch' \ --header 'api-key: test_admin' \ --form 'merchant_id="merchant_1737627877"' \ --form 'file=@"/Users/Downloads/tokenization sample - Sheet 1.csv"' Response [{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_Hn03n9kbTqUxKZ0nZRVC","payment_method_id":"pm_eBONxbqiaf8T7KkGSlaq","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:53.998Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_Hn03n9kbTqUxKZ0nZRVC","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_OWDUMC1QBmsTeImT9xCs","payment_method_id":"pm_nRtoCkil21RaGNJulP2L","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:53.998Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_OWDUMC1QBmsTeImT9xCs","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_mBx8CYwaUldk2HbX9qBV","payment_method_id":"pm_nhtWX126LHU1BmoN48TB","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:53.998Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_mBx8CYwaUldk2HbX9qBV","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_tpr9V8N4mPijFOZGbqjH","payment_method_id":"pm_eoyzCgzbJjbfREVKe7c0","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.001Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_tpr9V8N4mPijFOZGbqjH","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_fdbpnmVFS3hhYZZfYquM","payment_method_id":"pm_ShvWRpaZyX5kucjVImmw","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.001Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_fdbpnmVFS3hhYZZfYquM","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_HeGLoqXGsKYbpCTvvNCX","payment_method_id":"pm_w6QqSyug2w4rJAIxQY4a","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.009Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_HeGLoqXGsKYbpCTvvNCX","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_3LgTOBzFOcMHEz1glZzF","payment_method_id":"pm_1G3NGbJG0LyJKvbIZvdJ","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.009Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_3LgTOBzFOcMHEz1glZzF","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_bYIVR0NQF4T4bv5KjVNd","payment_method_id":"pm_31KM9k8uPbwUAUaq03N5","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2026","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.010Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_bYIVR0NQF4T4bv5KjVNd","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_jxMzHRc3Ndfr9Mt2pHKg","payment_method_id":"pm_dAHGSnuIHQC4rHWEGAwF","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"25","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.010Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_jxMzHRc3Ndfr9Mt2pHKg","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_KyauqQZeqKbZCEdRCrPY","payment_method_id":"pm_im8kjgFyc5ydhrHES9z5","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"22","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.010Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_KyauqQZeqKbZCEdRCrPY","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_NuZ4Ntb7hWDXxFt7ro3D","payment_method_id":"pm_gfgZ1gOZ4kIdeBU7Cyqz","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"25","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.017Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_NuZ4Ntb7hWDXxFt7ro3D","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_UDoT3SdLhK62XG7xFo65","payment_method_id":"pm_cPsrZ1S3xV12NnF5uAH8","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"25","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.017Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_UDoT3SdLhK62XG7xFo65","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null},{"payment_method_response":{"merchant_id":"merchant_1737627877","customer_id":"cus_cxhCY1RgcvRPlIX891kU","payment_method_id":"pm_iHXORES9dupsE5ffAG0C","payment_method":"card","payment_method_type":null,"card":{"scheme":null,"issuer_country":null,"last4_digits":"0000","expiry_month":"1","expiry_year":"2022","card_token":null,"card_holder_name":null,"card_fingerprint":null,"nick_name":"real joe","card_network":null,"card_isin":"420000","card_issuer":null,"card_type":null,"saved_to_locker":false},"recurring_enabled":true,"installment_payment_enabled":false,"payment_experience":null,"metadata":null,"created":"2025-01-23T10:24:54.017Z","last_used_at":null,"client_secret":null},"customer":{"id":"cus_cxhCY1RgcvRPlIX891kU","name":"Max Mustermann","email":"[email protected]","phone":null,"phone_country_code":null},"card_tokenized":true,"req":null}] </details> <details> <summary>4. Network tokenization in payments flow</summary> 1. Enable `is_network_tokenization_enabled` in profile cURL curl --location --request POST 'http://localhost:8080/account/merchant_1739089569/business_profile/pro_y2hZRUddjwLlTtKLMPEM' \ --header 'Content-Type: application/json' \ --header 'api-key: test_admin' \ --data '{ "is_network_tokenization_enabled": true }' 2. Create a card txn using `no_three_ds` and `off_session` cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_E6uP3pz26jvUfMLK2UkVOax00881TBQscs85jNVqCBrFvcO5h2EsLtZ5HqXe93HF' \ --data-raw '{"amount":100,"currency":"USD","confirm":true,"capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","customer_id":"cus_3Nn60DzqkFOwJ9T2y4rG","email":"[email protected]","name":"John Doe","phone":"999999999","profile_id":"pro_y2hZRUddjwLlTtKLMPEM","phone_country_code":"+65","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://hyperswitch.io","setup_future_usage":"off_session","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector":["cybersource"],"payment_method":"card","payment_method_data":{"card":{"card_number":"4761360080000093","card_exp_month":"01","card_exp_year":"2026","card_cvc":"947","nick_name":"JD"},"billing":{"email":"[email protected]","address":{"first_name":"John","last_name":"US"}}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"US","first_name":"John","last_name":"US"}},"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true}}' Response {"merchant_id":"merchant_1739089569","profile_id":"pro_y2hZRUddjwLlTtKLMPEM","profile_name":"IN_default","return_url":"https://google.com/success","enable_payment_response_hash":true,"payment_response_hash_key":"onDz0wKFp8QXWiBCWX5vIvBLpcwnA6ajqvfcNmFwM66O9p59iK1uPYWVIS7pArqd","redirect_to_merchant_with_http_post":false,"webhook_details":{"webhook_version":"1.0.1","webhook_username":"random","webhook_password":"pass","webhook_url":"https://webhook.site/0728473e-e0aa-4bb6-9eea-85435cf54380","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":{"domain_name":"gdpp-dev.zurich.com","theme":"#1A1A1A","logo":"https://hyperswitch.io/favicon.ico","seller_name":null,"sdk_layout":null,"display_sdk_only":null,"enabled_saved_payment_method":true,"hide_card_nickname_field":null,"show_card_form_by_default":null,"transaction_details":null,"background_image":null,"details_layout":null,"payment_button_text":"Proceed to Payment!","business_specific_configs":null,"allowed_domains":["localhost:5500"],"branding_visibility":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,"is_network_tokenization_enabled":true,"is_auto_retries_enabled":false,"max_auto_retries_enabled":null,"is_click_to_pay_enabled":false,"authentication_product_ids":null} Verify if relevant network token locker IDs are stored in payment methods table <img width="1675" alt="Screenshot 2025-02-09 at 2 33 01 PM" src="https://github.com/user-attachments/assets/68114287-9e88-420a-8a1f-dc8474ab3bf0" /> </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
b71571d16ca4553e1c7eca17f00df24945479638
juspay/hyperswitch
juspay__hyperswitch-6919
Bug: add retrieve api support for relay /relay is a api that will be used to just forward the request sent by merchant without performing any application logic on it. This is particular to support the refunds for the payments that was directly performed with the connector (example stripe) with out hyperswitch involved during the payment flow. This PR introduces changes to add a retrieve API for relay refunds. The retrieve API will: 1. Return the relay status from our database when a retrieve call is made. 2. If force_sync = true is passed and the relay status is not in a terminal state in our system, the API will call the connector to fetch the latest status. Flow 1. Merchant performs payment directly with processor and stores the payment reference id associated with it. 2. Merchant tiggers the refund through hyperswitch using the processor reference id for the payment. 3. Merchant makes retrieve call for the relay status
diff --git a/crates/api_models/src/relay.rs b/crates/api_models/src/relay.rs index e4bc607fc0d..f54e1471632 100644 --- a/crates/api_models/src/relay.rs +++ b/crates/api_models/src/relay.rs @@ -84,9 +84,20 @@ pub struct RelayRetrieveRequest { #[serde(default)] pub force_sync: bool, /// The unique identifier for the Relay - pub id: String, + pub id: common_utils::id_type::RelayId, +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +pub struct RelayRetrieveBody { + /// The unique identifier for the Relay + #[serde(default)] + pub force_sync: bool, } impl common_utils::events::ApiEventMetric for RelayRequest {} impl common_utils::events::ApiEventMetric for RelayResponse {} + +impl common_utils::events::ApiEventMetric for RelayRetrieveRequest {} + +impl common_utils::events::ApiEventMetric for RelayRetrieveBody {} diff --git a/crates/diesel_models/src/query/relay.rs b/crates/diesel_models/src/query/relay.rs index 28ede3cd61a..034446fe6b5 100644 --- a/crates/diesel_models/src/query/relay.rs +++ b/crates/diesel_models/src/query/relay.rs @@ -35,4 +35,15 @@ impl Relay { result => result, } } + + pub async fn find_by_id( + conn: &PgPooledConn, + id: &common_utils::id_type::RelayId, + ) -> StorageResult<Self> { + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + dsl::id.eq(id.to_owned()), + ) + .await + } } diff --git a/crates/diesel_models/src/relay.rs b/crates/diesel_models/src/relay.rs index 24a6ab8b034..153e06ab17f 100644 --- a/crates/diesel_models/src/relay.rs +++ b/crates/diesel_models/src/relay.rs @@ -67,7 +67,7 @@ pub struct RelayNew { } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] -#[table_name = "relay"] +#[diesel(table_name = relay)] pub struct RelayUpdateInternal { pub connector_reference_id: Option<String>, pub status: Option<storage_enums::RelayStatus>, diff --git a/crates/router/src/core/relay.rs b/crates/router/src/core/relay.rs index 812709269d8..d25296635ad 100644 --- a/crates/router/src/core/relay.rs +++ b/crates/router/src/core/relay.rs @@ -1,5 +1,6 @@ use api_models::relay as relay_models; -use common_utils::{self, ext_traits::OptionExt, id_type}; +use common_enums::RelayStatus; +use common_utils::{self, id_type}; use error_stack::ResultExt; use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt}; @@ -11,6 +12,7 @@ use crate::{ api::{self}, domain, }, + utils::OptionExt, }; pub mod utils; @@ -27,11 +29,7 @@ pub async fn relay( let merchant_id = merchant_account.get_id(); let connector_id = &req.connector_id; - let profile_id_from_auth_layer = profile_id_optional - .get_required_value("ProfileId") - .change_context(errors::ApiErrorResponse::MissingRequiredField { - field_name: "profile id", - })?; + let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; let profile = db .find_business_profile_by_merchant_id_profile_id( @@ -175,3 +173,158 @@ pub fn validate_relay_refund_data( } Ok(()) } + +pub async fn relay_retrieve( + state: SessionState, + merchant_account: domain::MerchantAccount, + profile_id_optional: Option<id_type::ProfileId>, + key_store: domain::MerchantKeyStore, + req: relay_models::RelayRetrieveRequest, +) -> RouterResponse<relay_models::RelayResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + let merchant_id = merchant_account.get_id(); + let relay_id = &req.id; + + let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?; + + db.find_business_profile_by_merchant_id_profile_id( + key_manager_state, + &key_store, + merchant_id, + &profile_id_from_auth_layer, + ) + .await + .change_context(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id_from_auth_layer.get_string_repr().to_owned(), + })?; + + let relay_record_result = db + .find_relay_by_id(key_manager_state, &key_store, relay_id) + .await; + + let relay_record = match relay_record_result { + Err(error) => { + if error.current_context().is_db_not_found() { + Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "relay not found".to_string(), + })? + } else { + Err(error) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("error while fetch relay record")? + } + } + Ok(relay) => relay, + }; + + #[cfg(feature = "v1")] + let connector_account = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, + merchant_id, + &relay_record.connector_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: relay_record.connector_id.get_string_repr().to_string(), + })?; + + #[cfg(feature = "v2")] + let connector_account = db + .find_merchant_connector_account_by_id( + key_manager_state, + &relay_record.connector_id, + &key_store, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: relay_record.connector_id.get_string_repr().to_string(), + })?; + + let relay_response = match relay_record.relay_type { + common_enums::RelayType::Refund => { + if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) { + let relay_response = sync_relay_refund_with_gateway( + &state, + &merchant_account, + &relay_record, + connector_account, + ) + .await?; + + db.update_relay(key_manager_state, &key_store, relay_record, relay_response) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update the relay record")? + } else { + relay_record + } + } + }; + + let response = relay_models::RelayResponse::from(relay_response); + + Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( + response, + )) +} + +fn should_call_connector_for_relay_refund_status( + relay: &hyperswitch_domain_models::relay::Relay, + force_sync: bool, +) -> bool { + // This allows refund sync at connector level if force_sync is enabled, or + // check if the refund is in terminal state + !matches!(relay.status, RelayStatus::Failure | RelayStatus::Success) && force_sync +} + +pub async fn sync_relay_refund_with_gateway( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + relay_record: &hyperswitch_domain_models::relay::Relay, + connector_account: domain::MerchantConnectorAccount, +) -> RouterResult<hyperswitch_domain_models::relay::RelayUpdate> { + let connector_id = &relay_record.connector_id; + let merchant_id = merchant_account.get_id(); + + let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name( + &state.conf.connectors, + &connector_account.connector_name, + api::GetToken::Connector, + Some(connector_id.clone()), + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to get the connector")?; + + let router_data = utils::construct_relay_refund_router_data( + state, + &connector_account.connector_name, + merchant_id, + &connector_account, + relay_record, + ) + .await?; + + let connector_integration: services::BoxedRefundConnectorIntegrationInterface< + api::RSync, + hyperswitch_domain_models::router_request_types::RefundsData, + hyperswitch_domain_models::router_response_types::RefundsResponseData, + > = connector_data.connector.get_connector_integration(); + + let router_data_res = services::execute_connector_processing_step( + state, + connector_integration, + &router_data, + payments::CallConnectorAction::Trigger, + None, + ) + .await + .to_refund_failed_response()?; + + let relay_response = + hyperswitch_domain_models::relay::RelayUpdate::from(router_data_res.response); + + Ok(relay_response) +} diff --git a/crates/router/src/db/relay.rs b/crates/router/src/db/relay.rs index e869165aa33..46259679c55 100644 --- a/crates/router/src/db/relay.rs +++ b/crates/router/src/db/relay.rs @@ -28,6 +28,13 @@ pub trait RelayInterface { current_state: hyperswitch_domain_models::relay::Relay, relay_update: hyperswitch_domain_models::relay::RelayUpdate, ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; + + async fn find_relay_by_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + relay_id: &common_utils::id_type::RelayId, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>; } #[async_trait::async_trait] @@ -79,6 +86,25 @@ impl RelayInterface for Store { .await .change_context(errors::StorageError::DecryptionError) } + + async fn find_relay_by_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + relay_id: &common_utils::id_type::RelayId, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + diesel_models::relay::Relay::find_by_id(&conn, relay_id) + .await + .map_err(|error| report!(errors::StorageError::from(error)))? + .convert( + key_manager_state, + merchant_key_store.key.get_inner(), + merchant_key_store.merchant_id.clone().into(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + } } #[async_trait::async_trait] @@ -101,6 +127,15 @@ impl RelayInterface for MockDb { ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { Err(errors::StorageError::MockDbError)? } + + async fn find_relay_by_id( + &self, + _key_manager_state: &KeyManagerState, + _merchant_key_store: &domain::MerchantKeyStore, + _relay_id: &common_utils::id_type::RelayId, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } } #[async_trait::async_trait] @@ -132,4 +167,15 @@ impl RelayInterface for KafkaStore { ) .await } + + async fn find_relay_by_id( + &self, + key_manager_state: &KeyManagerState, + merchant_key_store: &domain::MerchantKeyStore, + relay_id: &common_utils::id_type::RelayId, + ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> { + self.diesel_store + .find_relay_by_id(key_manager_state, merchant_key_store, relay_id) + .await + } } diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2decddb806c..21ea9446138 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -598,6 +598,7 @@ impl Relay { web::scope("/relay") .app_data(web::Data::new(state)) .service(web::resource("").route(web::post().to(relay::relay))) + .service(web::resource("/{relay_id}").route(web::get().to(relay::relay_retrieve))) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 4b43c42f3bc..dd0fbcdc08e 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -165,7 +165,7 @@ impl From<Flow> for ApiIdentifier { | Flow::RefundsFilters | Flow::RefundsAggregate | Flow::RefundsManualUpdate => Self::Refunds, - Flow::Relay => Self::Relay, + Flow::Relay | Flow::RelayRetrieve => Self::Relay, Flow::FrmFulfillment | Flow::IncomingWebhookReceive diff --git a/crates/router/src/routes/relay.rs b/crates/router/src/routes/relay.rs index 13c92eb19a6..cfc66253d50 100644 --- a/crates/router/src/routes/relay.rs +++ b/crates/router/src/routes/relay.rs @@ -38,3 +38,39 @@ pub async fn relay( )) .await } + +#[instrument(skip_all, fields(flow = ?Flow::RelayRetrieve))] +#[cfg(feature = "oltp")] +pub async fn relay_retrieve( + state: web::Data<app::AppState>, + path: web::Path<common_utils::id_type::RelayId>, + req: actix_web::HttpRequest, + query_params: web::Query<api_models::relay::RelayRetrieveBody>, +) -> impl Responder { + let flow = Flow::RelayRetrieve; + let relay_retrieve_request = api_models::relay::RelayRetrieveRequest { + force_sync: query_params.force_sync, + id: path.into_inner(), + }; + Box::pin(api::server_wrap( + flow, + state, + &req, + relay_retrieve_request, + |state, auth: auth::AuthenticationData, req, _| { + relay::relay_retrieve( + state, + auth.merchant_account, + #[cfg(feature = "v1")] + auth.profile_id, + #[cfg(feature = "v2")] + Some(auth.profile.get_id().clone()), + auth.key_store, + req, + ) + }, + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index de2577e6c34..661375aadbf 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -531,6 +531,8 @@ pub enum Flow { VolumeSplitOnRoutingType, /// Relay flow Relay, + /// Relay retrieve flow + RelayRetrieve, } /// Trait for providing generic behaviour to flow metric
2024-12-23T09:40: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 --> /relay is a api that will be used to just forward the request sent by merchant without performing any application logic on it. This is particular to support the refunds for the payments that was directly performed with the connector (example stripe) with out hyperswitch involved during the payment flow. This PR introduces changes to add a retrieve API for relay refunds. The retrieve API will: 1. Return the relay status from our database when a retrieve call is made. 2. If force_sync = true is passed and the relay status is not in a terminal state in our system, the API will call the connector to fetch the latest status. Flow 1. Merchant performs payment directly with processor and stores the payment reference id associated with it. 2. Merchant tiggers the refund through hyperswitch using the processor reference id for the payment. 3. Merchant makes retrieve call for the relay status ### 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 account -> Make a refund request with invalid connector_resource_id ``` curl --location 'http://localhost:8080/relay' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_rIikb0gPrzd0vEY8hIiP' \ --header 'api-key: dev_qqMQAuMWCclJSk4uMBeNNSpqAPlsKlBA3blQOwOoq5ogTSFVON3taShABqtqYNA4' \ --data '{ "connector_id": "mca_8W0CQfwE89J1BJBbpcnt", "connector_resource_id": "7349526182906968904951", "data": { "refund": { "amount": 50, "currency": "USD" }}, "type": "refund" }' ``` ``` { "id": "relay_4lgXCQW0EnqKddZ9CC3b", "status": "pending", "connector_resource_id": "7349526182906968904951", "error": null, "connector_reference_id": "7349526431306986204951", "connector_id": "mca_8W0CQfwE89J1BJBbpcnt", "profile_id": "pro_rIikb0gPrzd0vEY8hIiP", "type": "refund", "data": { "refund": { "amount": 50, "currency": "USD", "reason": null } } } ``` -> Relay retrieve ``` curl --location 'http://localhost:8080/relay/relay_4lgXCQW0EnqKddZ9CC3b' \ --header 'Content-Type: application/json' \ --header 'X-Idempotency-Key: <x-idempotency-key>' \ --header 'X-Profile-Id: pro_rIikb0gPrzd0vEY8hIiP' \ --header 'api-key: dev_qqMQAuMWCclJSk4uMBeNNSpqAPlsKlBA3blQOwOoq5ogTSFVON3taShABqtqYNA4' \ --data '' ``` ``` { "id": "relay_4lgXCQW0EnqKddZ9CC3b", "status": "pending", "connector_resource_id": "7349526182906968904951", "error": null, "connector_reference_id": "7349526431306986204951", "connector_id": "mca_8W0CQfwE89J1BJBbpcnt", "profile_id": "pro_rIikb0gPrzd0vEY8hIiP", "type": "refund", "data": { "refund": { "amount": 50, "currency": "USD", "reason": null } } } ``` -> Relay retrieve force_sync = `true` ``` curl --location 'http://localhost:8080/relay/relay_4lgXCQW0EnqKddZ9CC3b?force_sync=true' \ --header 'Content-Type: application/json' \ --header 'X-Idempotency-Key: <x-idempotency-key>' \ --header 'X-Profile-Id: pro_rIikb0gPrzd0vEY8hIiP' \ --header 'api-key: dev_qqMQAuMWCclJSk4uMBeNNSpqAPlsKlBA3blQOwOoq5ogTSFVON3taShABqtqYNA4' \ --data '' ``` ``` { "id": "relay_4lgXCQW0EnqKddZ9CC3b", "status": "success", "connector_resource_id": "7349526182906968904951", "error": null, "connector_reference_id": "7349526431306986204951", "connector_id": "mca_8W0CQfwE89J1BJBbpcnt", "profile_id": "pro_rIikb0gPrzd0vEY8hIiP", "type": "refund", "data": { "refund": { "amount": 50, "currency": "USD", "reason": 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
1fc941056fb8759435f41bba004a602c176eb802
juspay/hyperswitch
juspay__hyperswitch-6916
Bug: fix(payments_list): handle same payment/attempt IDs for different merchants The query planner was applying the merchant_id filter before the join operation, which caused incorrect results when different merchants had the same payment_id or attempt_id. This prematurely filtered out valid rows from the payment_attempt table that had matching payment_id or attempt_id but a different merchant_id.
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index fe64136b743..786cbe75a43 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -831,10 +831,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { let conn = connection::pg_connection_read(self).await.switch()?; let conn = async_bb8_diesel::Connection::as_async_conn(&conn); let mut query = DieselPaymentIntent::table() + .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) .inner_join( payment_attempt_schema::table.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)), ) - .filter(pi_dsl::merchant_id.eq(merchant_id.to_owned())) + .filter(pa_dsl::merchant_id.eq(merchant_id.to_owned())) // Ensure merchant_ids match, as different merchants can share payment/attempt IDs. .into_boxed(); query = match constraints {
2024-12-23T09:39:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Changed the query to apply the merchant_id filter after the join. This ensures valid rows aren’t excluded too early and fixes an issue where **payments with the same IDs but different merchants** were being handled incorrectly. ### 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 [#6916](https://github.com/juspay/hyperswitch/issues/6916) ## How did you test it? Tried to have to merchant id that have same payment/atttempt id. And tested for the logic: <img width="1078" alt="Screenshot 2024-12-23 at 7 31 50 PM" src="https://github.com/user-attachments/assets/0cc062fd-e10a-45f2-adbb-549dc9eb34c1" /> <img width="1056" alt="Screenshot 2024-12-23 at 4 32 48 PM" src="https://github.com/user-attachments/assets/db383407-087e-43b7-948f-4065e58202f2" /> Now the list api is working as expected for merchants who have same payment id Request: ``` curl 'http://localhost:8080/payments/list' \ -H 'Accept: */*' \ -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ -H 'Connection: keep-alive' \ -H 'Content-Type: application/json' \ -H 'Origin: http://localhost:9000' \ -H 'Referer: http://localhost:9000/' \ -H 'Sec-Fetch-Dest: empty' \ -H 'Sec-Fetch-Mode: cors' \ -H 'Sec-Fetch-Site: same-site' \ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' \ -H 'api-key: hyperswitch' \ -H 'authorization: Bearer JWT' \ -H 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \ -H 'sec-ch-ua-mobile: ?0' \ -H 'sec-ch-ua-platform: "macOS"' \ --data-raw '{"offset":0,"limit":50,"start_time":"2024-11-22T18:30:00Z","amount_filter":{"start_amount":null,"end_amount":null}}' ``` Response ``` { "count": 1, "total_count": 1, "data": [ { "payment_id": "x", "merchant_id": "merchant_1734940244", "status": "succeeded", "amount": 12300, "net_amount": 18000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_gFFhcIbCS0LkwFmaCdAl_secret_GmvAjH9YCyyXzoJVaBCT", "created": "2024-12-17T04:07:36.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "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": "card", "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": "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": "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": null, "connector_transaction_id": "test_W7bBdLqIBIxUMkpKsvu9_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_N7DbBIewrQYTC9qagLJY", "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, "split_payments": 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 --> - [ ] 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
a423ff53d3523508ba6c584134e32f3f1bb4f0c0
juspay/hyperswitch
juspay__hyperswitch-6941
Bug: [FEATURE] integrate NTI flow for Worldpay and Novalnet ### Feature Description Processing card payments using Network Transaction ID is required for below payment processors - - Fiuu - Novalnet - Worldpay This helps make card payments agnostic to the acquirer. ### Possible Implementation Fiuu - closed source Novalnet - https://developer.novalnet.com/encryption/directapi (include `transaction.scheme_tid`) Worldpay - https://developer.worldpay.com/products/access/payments/openapi/other/payment#other/payment/request (Unscheduled payments) ### 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 821e854c9fa..c860420da38 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -802,7 +802,7 @@ check_token_status_url= "" # base url to check token status from token servic connector_list = "cybersource" # Supported connectors for network tokenization [network_transaction_id_supported_connectors] -connector_list = "stripe,adyen,cybersource" # Supported connectors for network transaction id +connector_list = "adyen,cybersource,novalnet,stripe,worldpay" # Supported connectors for network transaction id [grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration host = "localhost" # Client Host diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 6283382258a..b6e487e5a3b 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -191,7 +191,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] -connector_list = "stripe,adyen,cybersource" +connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [payouts] diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index fcfadb339d9..7242f263672 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -191,7 +191,7 @@ card.credit = { connector_list = "cybersource" } # Update Mandate sup card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card [network_transaction_id_supported_connectors] -connector_list = "stripe,adyen,cybersource" +connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [payouts] diff --git a/config/development.toml b/config/development.toml index 08520a2a859..a32102aeebf 100644 --- a/config/development.toml +++ b/config/development.toml @@ -653,7 +653,7 @@ card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } [network_transaction_id_supported_connectors] -connector_list = "stripe,adyen,cybersource" +connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [connector_request_reference_id_config] merchant_ids_send_payment_id_as_connector_request_id = [] diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 6f95380d2db..cfdf4b0e0c2 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -540,7 +540,7 @@ card.credit = { connector_list = "cybersource" } card.debit = { connector_list = "cybersource" } [network_transaction_id_supported_connectors] -connector_list = "stripe,adyen,cybersource" +connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [connector_customer] connector_list = "gocardless,stax,stripe" diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu.rs b/crates/hyperswitch_connectors/src/connectors/fiuu.rs index 3ea8793d9f5..70bca41582c 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu.rs @@ -254,16 +254,23 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - let url = if req.request.off_session == Some(true) { - format!( + let optional_is_mit_flow = req.request.off_session; + let optional_is_nti_flow = req + .request + .mandate_id + .as_ref() + .map(|mandate_id| mandate_id.is_network_transaction_id_flow()); + let url = match (optional_is_mit_flow, optional_is_nti_flow) { + (Some(true), Some(false)) => format!( "{}/RMS/API/Recurring/input_v7.php", self.base_url(connectors) - ) - } else { - format!( - "{}RMS/API/Direct/1.4.0/index.php", - self.base_url(connectors) - ) + ), + _ => { + format!( + "{}RMS/API/Direct/1.4.0/index.php", + self.base_url(connectors) + ) + } }; Ok(url) } @@ -280,14 +287,24 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData )?; let connector_router_data = fiuu::FiuuRouterData::from((amount, req)); - let connector_req = if req.request.off_session == Some(true) { - let recurring_request = fiuu::FiuuMandateRequest::try_from(&connector_router_data)?; - build_form_from_struct(recurring_request) - .change_context(errors::ConnectorError::ParsingFailed)? - } else { - let payment_request = fiuu::FiuuPaymentRequest::try_from(&connector_router_data)?; - build_form_from_struct(payment_request) - .change_context(errors::ConnectorError::ParsingFailed)? + let optional_is_mit_flow = req.request.off_session; + let optional_is_nti_flow = req + .request + .mandate_id + .as_ref() + .map(|mandate_id| mandate_id.is_network_transaction_id_flow()); + + let connector_req = match (optional_is_mit_flow, optional_is_nti_flow) { + (Some(true), Some(false)) => { + let recurring_request = fiuu::FiuuMandateRequest::try_from(&connector_router_data)?; + build_form_from_struct(recurring_request) + .change_context(errors::ConnectorError::ParsingFailed)? + } + _ => { + let payment_request = fiuu::FiuuPaymentRequest::try_from(&connector_router_data)?; + build_form_from_struct(payment_request) + .change_context(errors::ConnectorError::ParsingFailed)? + } }; Ok(RequestContent::FormData(connector_req)) } diff --git a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs index e914454e557..51fc23eee41 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs @@ -14,8 +14,8 @@ use common_utils::{ use error_stack::{Report, ResultExt}; use hyperswitch_domain_models::{ payment_method_data::{ - BankRedirectData, Card, GooglePayWalletData, PaymentMethodData, RealTimePaymentData, - WalletData, + BankRedirectData, Card, CardDetailsForNetworkTransactionId, GooglePayWalletData, + PaymentMethodData, RealTimePaymentData, WalletData, }, router_data::{ ApplePayPredecryptData, ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData, @@ -287,6 +287,7 @@ pub struct FiuuPaymentRequest { pub enum FiuuPaymentMethodData { FiuuQRData(Box<FiuuQRData>), FiuuCardData(Box<FiuuCardData>), + FiuuCardWithNTI(Box<FiuuCardWithNTI>), FiuuFpxData(Box<FiuuFPXData>), FiuuGooglePayData(Box<FiuuGooglePayData>), FiuuApplePayData(Box<FiuuApplePayData>), @@ -322,6 +323,18 @@ pub struct FiuuCardData { customer_email: Option<Email>, } +#[derive(Serialize, Debug, Clone)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub struct FiuuCardWithNTI { + #[serde(rename = "TxnChannel")] + txn_channel: TxnChannel, + cc_pan: CardNumber, + cc_month: Secret<String>, + cc_year: Secret<String>, + #[serde(rename = "OriginalSchemeID")] + original_scheme_id: Secret<String>, +} + #[derive(Serialize, Debug, Clone)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub struct FiuuApplePayData { @@ -412,125 +425,150 @@ impl TryFrom<&FiuuRouterData<&PaymentsAuthorizeRouterData>> for FiuuPaymentReque Url::parse(&item.router_data.request.get_webhook_url()?) .change_context(errors::ConnectorError::RequestEncodingFailed)?, ); - let payment_method_data = match item.router_data.request.payment_method_data { - PaymentMethodData::Card(ref card) => { - FiuuPaymentMethodData::try_from((card, item.router_data)) - } - PaymentMethodData::RealTimePayment(ref real_time_payment_data) => { - match *real_time_payment_data.clone() { - RealTimePaymentData::DuitNow {} => { - Ok(FiuuPaymentMethodData::FiuuQRData(Box::new(FiuuQRData { - txn_channel: TxnChannel::RppDuitNowQr, + let payment_method_data = match item + .router_data + .request + .mandate_id + .clone() + .and_then(|mandate_id| mandate_id.mandate_reference_id) + { + None => match item.router_data.request.payment_method_data { + PaymentMethodData::Card(ref card) => { + FiuuPaymentMethodData::try_from((card, item.router_data)) + } + PaymentMethodData::RealTimePayment(ref real_time_payment_data) => { + match *real_time_payment_data.clone() { + RealTimePaymentData::DuitNow {} => { + Ok(FiuuPaymentMethodData::FiuuQRData(Box::new(FiuuQRData { + txn_channel: TxnChannel::RppDuitNowQr, + }))) + } + RealTimePaymentData::Fps {} + | RealTimePaymentData::PromptPay {} + | RealTimePaymentData::VietQr {} => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("fiuu"), + ) + .into()) + } + } + } + PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data + { + BankRedirectData::OnlineBankingFpx { ref issuer } => { + Ok(FiuuPaymentMethodData::FiuuFpxData(Box::new(FiuuFPXData { + txn_channel: FPXTxnChannel::try_from(*issuer)?, + non_3ds, }))) } - RealTimePaymentData::Fps {} - | RealTimePaymentData::PromptPay {} - | RealTimePaymentData::VietQr {} => { + BankRedirectData::BancontactCard { .. } + | BankRedirectData::Bizum {} + | BankRedirectData::Blik { .. } + | BankRedirectData::Eps { .. } + | BankRedirectData::Giropay { .. } + | BankRedirectData::Ideal { .. } + | BankRedirectData::Interac { .. } + | BankRedirectData::OnlineBankingCzechRepublic { .. } + | BankRedirectData::OnlineBankingFinland { .. } + | BankRedirectData::OnlineBankingPoland { .. } + | BankRedirectData::OnlineBankingSlovakia { .. } + | BankRedirectData::OpenBankingUk { .. } + | BankRedirectData::Przelewy24 { .. } + | BankRedirectData::Sofort { .. } + | BankRedirectData::Trustly { .. } + | BankRedirectData::OnlineBankingThailand { .. } + | BankRedirectData::LocalBankRedirect {} => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("fiuu"), ) .into()) } - } - } - PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data { - BankRedirectData::OnlineBankingFpx { ref issuer } => { - Ok(FiuuPaymentMethodData::FiuuFpxData(Box::new(FiuuFPXData { - txn_channel: FPXTxnChannel::try_from(*issuer)?, - non_3ds, - }))) - } - BankRedirectData::BancontactCard { .. } - | BankRedirectData::Bizum {} - | BankRedirectData::Blik { .. } - | BankRedirectData::Eps { .. } - | BankRedirectData::Giropay { .. } - | BankRedirectData::Ideal { .. } - | BankRedirectData::Interac { .. } - | BankRedirectData::OnlineBankingCzechRepublic { .. } - | BankRedirectData::OnlineBankingFinland { .. } - | BankRedirectData::OnlineBankingPoland { .. } - | BankRedirectData::OnlineBankingSlovakia { .. } - | BankRedirectData::OpenBankingUk { .. } - | BankRedirectData::Przelewy24 { .. } - | BankRedirectData::Sofort { .. } - | BankRedirectData::Trustly { .. } - | BankRedirectData::OnlineBankingThailand { .. } - | BankRedirectData::LocalBankRedirect {} => { + }, + PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { + WalletData::GooglePay(google_pay_data) => { + FiuuPaymentMethodData::try_from(google_pay_data) + } + WalletData::ApplePay(_apple_pay_data) => { + let payment_method_token = item.router_data.get_payment_method_token()?; + match payment_method_token { + PaymentMethodToken::Token(_) => { + Err(unimplemented_payment_method!("Apple Pay", "Manual", "Fiuu"))? + } + PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { + FiuuPaymentMethodData::try_from(decrypt_data) + } + PaymentMethodToken::PazeDecrypt(_) => { + Err(unimplemented_payment_method!("Paze", "Fiuu"))? + } + } + } + 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::Paze(_) + | 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("fiuu"), + ) + .into()), + }, + PaymentMethodData::CardRedirect(_) + | PaymentMethodData::PayLater(_) + | PaymentMethodData::BankDebit(_) + | PaymentMethodData::BankTransfer(_) + | PaymentMethodData::Crypto(_) + | PaymentMethodData::MandatePayment + | PaymentMethodData::MobilePayment(_) + | PaymentMethodData::Reward + | PaymentMethodData::Upi(_) + | PaymentMethodData::Voucher(_) + | PaymentMethodData::GiftCard(_) + | PaymentMethodData::CardToken(_) + | PaymentMethodData::OpenBanking(_) + | PaymentMethodData::NetworkToken(_) + | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("fiuu"), ) .into()) } }, - PaymentMethodData::Wallet(ref wallet_data) => match wallet_data { - WalletData::GooglePay(google_pay_data) => { - FiuuPaymentMethodData::try_from(google_pay_data) - } - WalletData::ApplePay(_apple_pay_data) => { - let payment_method_token = item.router_data.get_payment_method_token()?; - match payment_method_token { - PaymentMethodToken::Token(_) => { - Err(unimplemented_payment_method!("Apple Pay", "Manual", "Fiuu"))? - } - PaymentMethodToken::ApplePayDecrypt(decrypt_data) => { - FiuuPaymentMethodData::try_from(decrypt_data) - } - PaymentMethodToken::PazeDecrypt(_) => { - Err(unimplemented_payment_method!("Paze", "Fiuu"))? - } + // Card payments using network transaction ID + Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => { + match item.router_data.request.payment_method_data { + PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => { + FiuuPaymentMethodData::try_from((raw_card_details, network_transaction_id)) } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("fiuu"), + ) + .into()), } - 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::Paze(_) - | 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("fiuu"), - ) - .into()), - }, - PaymentMethodData::CardRedirect(_) - | PaymentMethodData::PayLater(_) - | PaymentMethodData::BankDebit(_) - | PaymentMethodData::BankTransfer(_) - | PaymentMethodData::Crypto(_) - | PaymentMethodData::MandatePayment - | PaymentMethodData::MobilePayment(_) - | PaymentMethodData::Reward - | PaymentMethodData::Upi(_) - | PaymentMethodData::Voucher(_) - | PaymentMethodData::GiftCard(_) - | PaymentMethodData::CardToken(_) - | PaymentMethodData::OpenBanking(_) - | PaymentMethodData::NetworkToken(_) - | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("fiuu"), - ) - .into()) } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("fiuu"), + ) + .into()), }?; Ok(Self { @@ -556,7 +594,7 @@ impl TryFrom<(&Card, &PaymentsAuthorizeRouterData)> for FiuuPaymentMethodData { if item.request.is_customer_initiated_mandate_payment() { (Some(1), Some(item.get_billing_email()?)) } else { - (None, None) + (Some(3), None) }; let non_3ds = match item.is_three_ds() { false => 1, @@ -575,6 +613,21 @@ impl TryFrom<(&Card, &PaymentsAuthorizeRouterData)> for FiuuPaymentMethodData { } } +impl TryFrom<(&CardDetailsForNetworkTransactionId, String)> for FiuuPaymentMethodData { + type Error = Report<errors::ConnectorError>; + fn try_from( + (raw_card_data, network_transaction_id): (&CardDetailsForNetworkTransactionId, String), + ) -> Result<Self, Self::Error> { + Ok(Self::FiuuCardWithNTI(Box::new(FiuuCardWithNTI { + txn_channel: TxnChannel::Creditan, + cc_pan: raw_card_data.card_number.clone(), + cc_month: raw_card_data.card_exp_month.clone(), + cc_year: raw_card_data.card_exp_year.clone(), + original_scheme_id: Secret::new(network_transaction_id), + }))) + } +} + impl TryFrom<&GooglePayWalletData> for FiuuPaymentMethodData { type Error = Report<errors::ConnectorError>; fn try_from(data: &GooglePayWalletData) -> Result<Self, Self::Error> { @@ -1092,6 +1145,8 @@ pub struct FiuuPaymentSyncResponse { error_desc: String, #[serde(rename = "miscellaneous")] miscellaneous: Option<HashMap<String, Secret<String>>>, + #[serde(rename = "SchemeTransactionID")] + scheme_transaction_id: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, Display, Clone, PartialEq)] @@ -1183,7 +1238,10 @@ impl TryFrom<PaymentsSyncResponseRouterData<FiuuPaymentResponse>> for PaymentsSy redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, - network_txn_id: None, + network_txn_id: response + .scheme_transaction_id + .as_ref() + .map(|id| id.clone().expose()), connector_response_reference_id: None, incremental_authorization_allowed: None, charge_id: None, diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index d62d3d2a755..6d3199ecf1a 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -102,6 +102,13 @@ pub struct NovalnetCard { card_holder: Secret<String>, } +#[derive(Default, Debug, Clone, Serialize, Deserialize)] +pub struct NovalnetRawCardDetails { + card_number: CardNumber, + card_expiry_month: Secret<String>, + card_expiry_year: Secret<String>, +} + #[derive(Debug, Serialize, Deserialize, Clone)] pub struct NovalnetMandate { token: Secret<String>, @@ -121,6 +128,7 @@ pub struct NovalnetApplePay { #[serde(untagged)] pub enum NovalNetPaymentData { Card(NovalnetCard), + RawCardForNTI(NovalnetRawCardDetails), GooglePay(NovalnetGooglePay), ApplePay(NovalnetApplePay), MandatePayment(NovalnetMandate), @@ -151,6 +159,7 @@ pub struct NovalnetPaymentsRequestTransaction { error_return_url: Option<String>, enforce_3d: Option<i8>, //NOTE: Needed for CREDITCARD, GOOGLEPAY create_token: Option<i8>, + scheme_tid: Option<Secret<String>>, // Card network's transaction ID } #[derive(Debug, Serialize, Clone)] @@ -261,6 +270,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: Some(novalnet_card), enforce_3d, create_token, + scheme_tid: None, }; Ok(Self { @@ -292,6 +302,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: Some(novalnet_google_pay), enforce_3d, create_token, + scheme_tid: None, }; Ok(Self { @@ -317,6 +328,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym })), enforce_3d: None, create_token, + scheme_tid: None, }; Ok(Self { @@ -358,6 +370,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: None, enforce_3d: None, create_token, + scheme_tid: None, }; Ok(Self { merchant, @@ -416,6 +429,7 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym payment_data: Some(novalnet_mandate_data), enforce_3d, create_token: None, + scheme_tid: None, }; Ok(Self { @@ -425,6 +439,44 @@ impl TryFrom<&NovalnetRouterData<&PaymentsAuthorizeRouterData>> for NovalnetPaym custom, }) } + Some(api_models::payments::MandateReferenceId::NetworkMandateId( + network_transaction_id, + )) => match item.router_data.request.payment_method_data { + PaymentMethodData::CardDetailsForNetworkTransactionId(ref raw_card_details) => { + let novalnet_card = + NovalNetPaymentData::RawCardForNTI(NovalnetRawCardDetails { + card_number: raw_card_details.card_number.clone(), + card_expiry_month: raw_card_details.card_exp_month.clone(), + card_expiry_year: raw_card_details.card_exp_year.clone(), + }); + + let transaction = NovalnetPaymentsRequestTransaction { + test_mode, + payment_type: NovalNetPaymentTypes::CREDITCARD, + amount: NovalNetAmount::StringMinor(item.amount.clone()), + currency: item.router_data.request.currency, + order_no: item.router_data.connector_request_reference_id.clone(), + hook_url: Some(hook_url), + return_url: Some(return_url.clone()), + error_return_url: Some(return_url.clone()), + payment_data: Some(novalnet_card), + enforce_3d, + create_token, + scheme_tid: Some(network_transaction_id.into()), + }; + + Ok(Self { + merchant, + transaction, + customer, + custom, + }) + } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("novalnet"), + ) + .into()), + }, _ => Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("novalnet"), ) @@ -1466,6 +1518,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { payment_data: Some(novalnet_card), enforce_3d, create_token, + scheme_tid: None, }; Ok(Self { @@ -1495,6 +1548,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { payment_data: Some(novalnet_google_pay), enforce_3d, create_token, + scheme_tid: None, }; Ok(Self { @@ -1519,6 +1573,7 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { })), enforce_3d: None, create_token, + scheme_tid: None, }; Ok(Self { @@ -1559,7 +1614,9 @@ impl TryFrom<&SetupMandateRouterData> for NovalnetPaymentsRequest { payment_data: None, enforce_3d: None, create_token, + scheme_tid: None, }; + Ok(Self { merchant, transaction, diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index 07e4c178f9b..104e854e6fe 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -1199,6 +1199,42 @@ impl IncomingWebhook for Worldpay { let psync_body = WorldpayEventResponse::try_from(body)?; Ok(Box::new(psync_body)) } + + fn get_mandate_details( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>, + errors::ConnectorError, + > { + let body: WorldpayWebhookTransactionId = request + .body + .parse_struct("WorldpayWebhookTransactionId") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + let mandate_reference = body.event_details.token.map(|mandate_token| { + hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails { + connector_mandate_id: mandate_token.href, + } + }); + Ok(mandate_reference) + } + + fn get_network_txn_id( + &self, + request: &IncomingWebhookRequestDetails<'_>, + ) -> CustomResult< + Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>, + errors::ConnectorError, + > { + let body: WorldpayWebhookTransactionId = request + .body + .parse_struct("WorldpayWebhookTransactionId") + .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; + let optional_network_txn_id = body.event_details.scheme_reference.map(|network_txn_id| { + hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId::new(network_txn_id) + }); + Ok(optional_network_txn_id) + } } impl ConnectorRedirectResponse for Worldpay { diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs index 884caa9e840..52ae2c4f16f 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs @@ -52,18 +52,22 @@ pub enum TokenCreationType { Worldpay, } +#[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct CustomerAgreement { #[serde(rename = "type")] pub agreement_type: CustomerAgreementType, - pub stored_card_usage: StoredCardUsageType, + pub stored_card_usage: Option<StoredCardUsageType>, + #[serde(skip_serializing_if = "Option::is_none")] + pub scheme_reference: Option<Secret<String>>, } #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum CustomerAgreementType { Subscription, + Unscheduled, } #[derive(Clone, Debug, PartialEq, Serialize)] @@ -78,6 +82,7 @@ pub enum StoredCardUsageType { pub enum PaymentInstrument { Card(CardPayment), CardToken(CardToken), + RawCardForNTI(RawCardDetails), Googlepay(WalletPayment), Applepay(WalletPayment), } @@ -85,15 +90,22 @@ pub enum PaymentInstrument { #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardPayment { - #[serde(rename = "type")] - pub payment_type: PaymentType, + #[serde(flatten)] + pub raw_card_details: RawCardDetails, + pub cvc: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub card_holder_name: Option<Secret<String>>, - pub card_number: cards::CardNumber, - pub expiry_date: ExpiryDate, #[serde(skip_serializing_if = "Option::is_none")] pub billing_address: Option<BillingAddress>, - pub cvc: Secret<String>, +} + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RawCardDetails { + #[serde(rename = "type")] + pub payment_type: PaymentType, + pub card_number: cards::CardNumber, + pub expiry_date: ExpiryDate, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs index 5e9fb030424..b4d6a370401 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/response.rs @@ -43,6 +43,8 @@ pub struct AuthorizedResponse { pub fraud: Option<Fraud>, /// Mandate's token pub token: Option<MandateToken>, + /// Network transaction ID + pub scheme_reference: Option<Secret<String>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -429,9 +431,13 @@ pub struct WorldpayWebhookTransactionId { #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EventDetails { - pub transaction_reference: String, #[serde(rename = "type")] pub event_type: EventType, + pub transaction_reference: String, + /// Mandate's token + pub token: Option<MandateToken>, + /// Network transaction ID + pub scheme_reference: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs index ec23b520a20..cd028e81ef1 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs @@ -76,12 +76,14 @@ fn fetch_payment_instrument( ) -> CustomResult<PaymentInstrument, errors::ConnectorError> { match payment_method { PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment { - payment_type: PaymentType::Plain, - expiry_date: ExpiryDate { - month: card.get_expiry_month_as_i8()?, - year: card.get_expiry_year_as_4_digit_i32()?, + raw_card_details: RawCardDetails { + payment_type: PaymentType::Plain, + expiry_date: ExpiryDate { + month: card.get_expiry_month_as_i8()?, + year: card.get_expiry_year_as_4_digit_i32()?, + }, + card_number: card.card_number, }, - card_number: card.card_number, cvc: card.card_cvc, card_holder_name: billing_address.and_then(|address| address.get_optional_full_name()), billing_address: if let Some(address) = @@ -107,6 +109,16 @@ fn fetch_payment_instrument( None }, })), + PaymentMethodData::CardDetailsForNetworkTransactionId(raw_card_details) => { + Ok(PaymentInstrument::RawCardForNTI(RawCardDetails { + payment_type: PaymentType::Plain, + expiry_date: ExpiryDate { + month: raw_card_details.get_expiry_month_as_i8()?, + year: raw_card_details.get_expiry_year_as_4_digit_i32()?, + }, + card_number: raw_card_details.card_number, + })) + } PaymentMethodData::MandatePayment => mandate_ids .and_then(|mandate_ids| { mandate_ids @@ -185,13 +197,10 @@ fn fetch_payment_instrument( | PaymentMethodData::GiftCard(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::CardToken(_) - | PaymentMethodData::NetworkToken(_) - | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { - Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("worldpay"), - ) - .into()) - } + | PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("worldpay"), + ) + .into()), } } @@ -439,6 +448,7 @@ fn get_token_and_agreement( payment_method_data: &PaymentMethodData, setup_future_usage: Option<enums::FutureUsage>, off_session: Option<bool>, + mandate_ids: Option<MandateIds>, ) -> (Option<TokenCreation>, Option<CustomerAgreement>) { match (payment_method_data, setup_future_usage, off_session) { // CIT @@ -448,7 +458,8 @@ fn get_token_and_agreement( }), Some(CustomerAgreement { agreement_type: CustomerAgreementType::Subscription, - stored_card_usage: StoredCardUsageType::First, + stored_card_usage: Some(StoredCardUsageType::First), + scheme_reference: None, }), ), // MIT @@ -456,7 +467,26 @@ fn get_token_and_agreement( None, Some(CustomerAgreement { agreement_type: CustomerAgreementType::Subscription, - stored_card_usage: StoredCardUsageType::Subsequent, + stored_card_usage: Some(StoredCardUsageType::Subsequent), + scheme_reference: None, + }), + ), + // NTI with raw card data + (PaymentMethodData::CardDetailsForNetworkTransactionId(_), _, _) => ( + None, + mandate_ids.and_then(|mandate_ids| { + mandate_ids + .mandate_reference_id + .and_then(|mandate_id| match mandate_id { + MandateReferenceId::NetworkMandateId(network_transaction_id) => { + Some(CustomerAgreement { + agreement_type: CustomerAgreementType::Unscheduled, + scheme_reference: Some(network_transaction_id.into()), + stored_card_usage: None, + }) + } + _ => None, + }) }), ), _ => (None, None), @@ -487,6 +517,7 @@ impl<T: WorldpayPaymentsRequestData> TryFrom<(&WorldpayRouterData<&T>, &Secret<S item.router_data.get_payment_method_data(), item.router_data.get_setup_future_usage(), item.router_data.get_off_session(), + item.router_data.get_mandate_id(), ); Ok(Self { @@ -646,7 +677,7 @@ impl<F, T> ), ) -> Result<Self, Self::Error> { let (router_data, optional_correlation_id) = item; - let (description, redirection_data, mandate_reference, error) = router_data + let (description, redirection_data, mandate_reference, network_txn_id, error) = router_data .response .other_fields .as_ref() @@ -660,6 +691,7 @@ impl<F, T> mandate_metadata: None, connector_mandate_request_reference_id: None, }), + res.scheme_reference.clone(), None, ), WorldpayPaymentResponseFields::DDCResponse(res) => ( @@ -681,6 +713,7 @@ impl<F, T> }), None, None, + None, ), WorldpayPaymentResponseFields::ThreeDsChallenged(res) => ( None, @@ -694,16 +727,18 @@ impl<F, T> }), None, None, + None, ), WorldpayPaymentResponseFields::RefusedResponse(res) => ( None, None, None, + None, Some((res.refusal_code.clone(), res.refusal_description.clone())), ), - WorldpayPaymentResponseFields::FraudHighRisk(_) => (None, None, None, None), + WorldpayPaymentResponseFields::FraudHighRisk(_) => (None, None, None, None, None), }) - .unwrap_or((None, None, None, None)); + .unwrap_or((None, None, None, None, None)); let worldpay_status = router_data.response.outcome.clone(); let optional_error_message = match worldpay_status { PaymentOutcome::ThreeDsAuthenticationFailed => { @@ -725,7 +760,7 @@ impl<F, T> redirection_data: Box::new(redirection_data), mandate_reference: Box::new(mandate_reference), connector_metadata: None, - network_txn_id: None, + network_txn_id: network_txn_id.map(|id| id.expose()), connector_response_reference_id: optional_correlation_id.clone(), incremental_authorization_allowed: None, charge_id: None, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 190a4eb2566..671aed36378 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -17,7 +17,7 @@ use common_utils::{ use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ address::{Address, AddressDetails, PhoneDetails}, - payment_method_data::{self, Card, PaymentMethodData}, + payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData}, router_data::{ ApplePayPredecryptData, ErrorResponse, PaymentMethodToken, RecurringMandatePaymentData, }, @@ -1040,6 +1040,97 @@ impl CardData for Card { } } +impl CardData for CardDetailsForNetworkTransactionId { + fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> { + let binding = self.card_exp_year.clone(); + let year = binding.peek(); + Ok(Secret::new( + year.get(year.len() - 2..) + .ok_or(errors::ConnectorError::RequestEncodingFailed)? + .to_string(), + )) + } + fn get_card_issuer(&self) -> Result<CardIssuer, Error> { + get_card_issuer(self.card_number.peek()) + } + fn get_card_expiry_month_year_2_digit_with_delimiter( + &self, + delimiter: String, + ) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?; + Ok(Secret::new(format!( + "{}{}{}", + self.card_exp_month.peek(), + delimiter, + year.peek() + ))) + } + fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + year.peek(), + delimiter, + self.card_exp_month.peek() + )) + } + fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> { + let year = self.get_expiry_year_4_digit(); + Secret::new(format!( + "{}{}{}", + self.card_exp_month.peek(), + delimiter, + year.peek() + )) + } + fn get_expiry_year_4_digit(&self) -> Secret<String> { + let mut year = self.card_exp_year.peek().clone(); + if year.len() == 2 { + year = format!("20{}", year); + } + Secret::new(year) + } + fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?.expose(); + let month = self.card_exp_month.clone().expose(); + Ok(Secret::new(format!("{year}{month}"))) + } + fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> { + let year = self.get_card_expiry_year_2_digit()?.expose(); + let month = self.card_exp_month.clone().expose(); + Ok(Secret::new(format!("{month}{year}"))) + } + fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> { + self.card_exp_month + .peek() + .clone() + .parse::<i8>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } + fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> { + self.card_exp_year + .peek() + .clone() + .parse::<i32>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } + fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> { + self.get_expiry_year_4_digit() + .peek() + .clone() + .parse::<i32>() + .change_context(errors::ConnectorError::ResponseDeserializationFailed) + .map(Secret::new) + } + fn get_cardholder_name(&self) -> Result<Secret<String>, Error> { + self.card_holder_name + .clone() + .ok_or_else(missing_field_err("card.card_holder_name")) + } +} + #[track_caller] fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> { for (k, v) in CARD_REGEX.iter() { diff --git a/crates/router/locales/en.yml b/crates/router/locales/en.yml index c85be7ccf46..67eec844fb1 100644 --- a/crates/router/locales/en.yml +++ b/crates/router/locales/en.yml @@ -7,7 +7,7 @@ payout_link: status: title: "Payout Status" info: - ref_id: "Ref Id" + ref_id: "Reference Id" error_code: "Error Code" error_message: "Error Message" message: diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 1d2be85ba17..d957109bcef 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -67,6 +67,7 @@ impl Default for Mandates { enums::Connector::Authorizedotnet, enums::Connector::Globalpay, enums::Connector::Worldpay, + enums::Connector::Fiuu, enums::Connector::Multisafepay, enums::Connector::Nexinets, enums::Connector::Noon, @@ -88,6 +89,7 @@ impl Default for Mandates { enums::Connector::Authorizedotnet, enums::Connector::Globalpay, enums::Connector::Worldpay, + enums::Connector::Fiuu, enums::Connector::Multisafepay, enums::Connector::Nexinets, enums::Connector::Noon, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index b26b5b2e438..e90eb16ab61 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -370,7 +370,7 @@ card.credit ={connector_list ="cybersource"} card.debit = {connector_list ="cybersource"} [network_transaction_id_supported_connectors] -connector_list = "stripe,adyen,cybersource" +connector_list = "adyen,cybersource,novalnet,stripe,worldpay" [analytics] source = "sqlx"
2024-12-26T11:38:07Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Described in #6941 This PR adds NTI flow integrations for below connectors - Fiuu - store NTI ID in `payment_methods` from connector's PSync response - Novalnet - use NTI ID for card payments - Worldpay - store and use NTI ID for card payments ### 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)? --> <details> <summary>1. CIT for cards through Adyen</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_rh7Gdbe4bpB4Vxz9A7SQge8NwmI48LHgckedcW181ltQ5xJte0ADtOBsW7tmQaI0' \ --data-raw '{"amount":100,"currency":"USD","confirm":true,"capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","customer_id":"cus_VzApV1FxWKoB90X5uEcm","email":"[email protected]","name":"John Doe","phone":"999999999","profile_id":"pro_lNLLS8WnmDP5uYTJQpIE","phone_country_code":"+65","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://hyperswitch.io","setup_future_usage":"off_session","customer_acceptance":{"acceptance_type":"online","accepted_at":"1963-05-03T04:07:52.723Z","online":{"ip_address":"127.0.0.1","user_agent":"amet irure esse"}},"connector":["adyen"],"payment_method":"card","payment_method_data":{"card":{"card_number":"5454545454545454","card_exp_month":"03","card_exp_year":"2030","card_cvc":"737","nick_name":"JD"},"billing":{"email":"[email protected]","address":{"first_name":"John","last_name":"US"}}},"billing":{"address":{"line1":"1467","line2":"Harrison Street","line3":"Harrison Street","city":"San Fransico","state":"California","zip":"94122","country":"US","first_name":"John","last_name":"US"}},"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true}}' Response {"payment_id":"pay_lVqK4xVFlhPsDKVArnIo","merchant_id":"merchant_1735800357","status":"requires_customer_action","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":100,"amount_received":null,"connector":"adyen","client_secret":"pay_lVqK4xVFlhPsDKVArnIo_secret_jge63cwkJDCY1FZMzOeR","created":"2025-01-02T08:27:51.185Z","currency":"USD","customer_id":"cus_VzApV1FxWKoB90X5uEcm","customer":{"id":"cus_VzApV1FxWKoB90X5uEcm","name":"John Doe","email":"[email protected]","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":"CREDIT","card_network":"Mastercard","card_issuer":"BANKHANDLOWYWWARSZAWIE.S.A.","card_issuing_country":"POLAND","card_isin":"545454","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John US","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":null,"country":null,"line1":null,"line2":null,"line3":null,"zip":null,"state":null,"first_name":"John","last_name":"US"},"phone":null,"email":"[email protected]"}},"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":"John","last_name":"US"},"phone":null,"email":null},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://hyperswitch.io/","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_lVqK4xVFlhPsDKVArnIo/merchant_1735800357/pay_lVqK4xVFlhPsDKVArnIo_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":"cus_VzApV1FxWKoB90X5uEcm","created_at":1735806471,"expires":1735810071,"secret":"epk_d3cf3844e1144988bb2bf79bb9f0d8bf"},"manual_retry_allowed":null,"connector_transaction_id":"Z3S5HHVH5S5H3275","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"Z3S5HHVH5S5H3275","payment_link":null,"profile_id":"pro_lNLLS8WnmDP5uYTJQpIE","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_Vcy2aZeTpgwfuzHd79R3","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-01-02T08:42:51.185Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_MO7c0p19Rgc2p6nDSWCd","payment_method_status":"inactive","updated":"2025-01-02T08:27:52.557Z","split_payments":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} - Complete the transaction - Retrieve payment to get the `payment_method_id` cURL curl --location --request GET 'http://localhost:8080/payments/pay_lVqK4xVFlhPsDKVArnIo?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_rh7Gdbe4bpB4Vxz9A7SQge8NwmI48LHgckedcW181ltQ5xJte0ADtOBsW7tmQaI0' Response {"payment_id":"pay_lVqK4xVFlhPsDKVArnIo","merchant_id":"merchant_1735800357","status":"succeeded","amount":100,"net_amount":100,"shipping_cost":null,"amount_capturable":0,"amount_received":100,"connector":"adyen","client_secret":"pay_lVqK4xVFlhPsDKVArnIo_secret_jge63cwkJDCY1FZMzOeR","created":"2025-01-02T08:27:51.185Z","currency":"USD","customer_id":"cus_VzApV1FxWKoB90X5uEcm","customer":{"id":"cus_VzApV1FxWKoB90X5uEcm","name":"John Doe","email":"[email protected]","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":"CREDIT","card_network":"Mastercard","card_issuer":"BANKHANDLOWYWWARSZAWIE.S.A.","card_issuing_country":"POLAND","card_isin":"545454","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John US","payment_checks":null,"authentication_data":null},"billing":{"address":{"city":null,"country":null,"line1":null,"line2":null,"line3":null,"zip":null,"state":null,"first_name":"John","last_name":"US"},"phone":null,"email":"[email protected]"}},"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":"John","last_name":"US"},"phone":null,"email":null},"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://hyperswitch.io/","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":null,"manual_retry_allowed":false,"connector_transaction_id":"Z3S5HHVH5S5H3275","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_lVqK4xVFlhPsDKVArnIo_1","payment_link":null,"profile_id":"pro_lNLLS8WnmDP5uYTJQpIE","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_Vcy2aZeTpgwfuzHd79R3","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-01-02T08:42:51.185Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_MO7c0p19Rgc2p6nDSWCd","payment_method_status":"active","updated":"2025-01-02T08:29:21.898Z","split_payments":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details> <details> <summary>2. [Novalnet] MIT for cards using NTI</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_rh7Gdbe4bpB4Vxz9A7SQge8NwmI48LHgckedcW181ltQ5xJte0ADtOBsW7tmQaI0' \ --data-raw '{"amount":6500,"currency":"USD","confirm":true,"capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","customer_id":"cus_VzApV1FxWKoB90X5uEcm","email":"[email protected]","name":"John Doe","phone":"999999999","profile_id":"pro_lNLLS8WnmDP5uYTJQpIE","phone_country_code":"+65","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://hyperswitch.io","off_session":true,"recurring_details":{"type":"payment_method_id","data":"pm_dKKRxNRCIsi84dCE3DCc"},"connector":["novalnet"],"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true}}' Response {"payment_id":"pay_3W4Chua2lDw4bYxDaRqt","merchant_id":"merchant_1735800357","status":"succeeded","amount":6500,"net_amount":6500,"shipping_cost":null,"amount_capturable":0,"amount_received":6500,"connector":"novalnet","client_secret":"pay_3W4Chua2lDw4bYxDaRqt_secret_nA6hiXdx8QLwjt71ffOd","created":"2025-01-02T08:32:03.307Z","currency":"USD","customer_id":"cus_VzApV1FxWKoB90X5uEcm","customer":{"id":"cus_VzApV1FxWKoB90X5uEcm","name":"John Doe","email":"[email protected]","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":true,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"5454","card_type":"CREDIT","card_network":"Mastercard","card_issuer":"BANKHANDLOWYWWARSZAWIE.S.A.","card_issuing_country":"POLAND","card_isin":"545454","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John US","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://hyperswitch.io/","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":"cus_VzApV1FxWKoB90X5uEcm","created_at":1735806723,"expires":1735810323,"secret":"epk_4479174c59444f52816900c1d0a0a602"},"manual_retry_allowed":false,"connector_transaction_id":"15133000040614710","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"15133000040614710","payment_link":null,"profile_id":"pro_lNLLS8WnmDP5uYTJQpIE","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_q8uMuxuvlutjsnNPaqEs","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-01-02T08:47:03.307Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_dKKRxNRCIsi84dCE3DCc","payment_method_status":"active","updated":"2025-01-02T08:32:07.974Z","split_payments":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details> <details> <summary>3. [Worldpay] MIT for cards using NTI</summary> cURL curl --location --request POST 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_rh7Gdbe4bpB4Vxz9A7SQge8NwmI48LHgckedcW181ltQ5xJte0ADtOBsW7tmQaI0' \ --data-raw '{"amount":6500,"currency":"USD","confirm":true,"capture_method":"automatic","capture_on":"2022-09-10T10:11:12Z","customer_id":"cus_VzApV1FxWKoB90X5uEcm","email":"[email protected]","name":"John Doe","phone":"999999999","profile_id":"pro_lNLLS8WnmDP5uYTJQpIE","phone_country_code":"+65","description":"Its my first payment request","authentication_type":"no_three_ds","return_url":"https://hyperswitch.io","off_session":true,"recurring_details":{"type":"payment_method_id","data":"pm_dKKRxNRCIsi84dCE3DCc"},"connector":["worldpay"],"statement_descriptor_name":"joseph","statement_descriptor_suffix":"JS","metadata":{"udf1":"value1","new_customer":"true","login_date":"2019-09-10T10:11:12Z"},"browser_info":{"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","language":"en-US","color_depth":32,"screen_height":1117,"screen_width":1728,"time_zone":-330,"java_enabled":true,"java_script_enabled":true}}' Response {"payment_id":"pay_rzcivnTTSrT8D2doTu8S","merchant_id":"merchant_1735800357","status":"succeeded","amount":6500,"net_amount":6500,"shipping_cost":null,"amount_capturable":0,"amount_received":6500,"connector":"worldpay","client_secret":"pay_rzcivnTTSrT8D2doTu8S_secret_nFPSG4JuDSZRr6iYV7sk","created":"2025-01-02T08:30:36.855Z","currency":"USD","customer_id":"cus_VzApV1FxWKoB90X5uEcm","customer":{"id":"cus_VzApV1FxWKoB90X5uEcm","name":"John Doe","email":"[email protected]","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":true,"capture_on":null,"capture_method":"automatic","payment_method":"card","payment_method_data":{"card":{"last4":"5454","card_type":"CREDIT","card_network":"Mastercard","card_issuer":"BANKHANDLOWYWWARSZAWIE.S.A.","card_issuing_country":"POLAND","card_isin":"545454","card_extended_bin":null,"card_exp_month":"03","card_exp_year":"2030","card_holder_name":"John US","payment_checks":null,"authentication_data":null},"billing":null},"payment_token":null,"shipping":null,"billing":null,"order_details":null,"email":"[email protected]","name":"John Doe","phone":"999999999","return_url":"https://hyperswitch.io/","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":"cus_VzApV1FxWKoB90X5uEcm","created_at":1735806636,"expires":1735810236,"secret":"epk_f8f4d087bc4148f98b3b0ba8e81e22b3"},"manual_retry_allowed":false,"connector_transaction_id":"eyJrIjoiazNhYjYzMiIsImxpbmtWZXJzaW9uIjoiNS4wLjAifQ==.sN:g8wd64bwkbrp0md+bPxcanBnk2zLdsIqSa1pR99GGg8fCNQpPLoWNslSzWNPFBM5Tpa8tW7EFI5onKINsgChMHeJVoeH2lrBWCRyjZYT6h+lbqfJa+1BSoKFSY8HLiz6vUTzxKAX24Ht8ZQ4HMhu9ADJnDtIHgxF9tK1ofAqmfgF9Uk2Www3mSVoKRxeIXIe9pic4l22Rveu3MW0qp:7+4GYJYOg3e9WdLnxDKf8zDOVuNV9Smp3TrKAPuNF+l9HY8h4r+1y1WBHupQz59qPpv59wMMnZCI15w9voaKGUgn8jvCNhmdUlN6uDEfAu3+Gpx8cadeYO0VLI6Wl9IpfjEUa63t7mpDaTErQBefTyL+3aw0lAN5HuRY6n0Lw81eWY3h7IW9jcvHhnfJ6QTQ==","frm_message":null,"metadata":{"udf1":"value1","login_date":"2019-09-10T10:11:12Z","new_customer":"true"},"connector_metadata":null,"feature_metadata":null,"reference_id":"4af31547-85c9-4413-93e6-67917d09db32","payment_link":null,"profile_id":"pro_lNLLS8WnmDP5uYTJQpIE","surcharge_details":null,"attempt_count":1,"merchant_decision":null,"merchant_connector_id":"mca_9i9j8AIAxASZwPltj1ED","incremental_authorization_allowed":null,"authorization_count":null,"incremental_authorizations":null,"external_authentication_details":null,"external_3ds_authentication_attempted":false,"expires_on":"2025-01-02T08:45:36.855Z","fingerprint":null,"browser_info":{"language":"en-US","time_zone":-330,"ip_address":"129.0.0.1","user_agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36","color_depth":32,"java_enabled":true,"screen_width":1728,"accept_header":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8","screen_height":1117,"java_script_enabled":true},"payment_method_id":"pm_dKKRxNRCIsi84dCE3DCc","payment_method_status":"active","updated":"2025-01-02T08:30:38.635Z","split_payments":null,"frm_metadata":null,"merchant_order_reference_id":null,"order_tax_amount":null,"connector_mandate_id":null} </details> <details> <summary>4. Ran cypress test cases for Worldpay</summary> <img width="524" alt="Screenshot 2025-01-16 at 12 09 21 AM" src="https://github.com/user-attachments/assets/37ec3e5a-c839-4895-9320-ae023699cda0" /> </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
d01172a613b8e74564eef792b8a6915c647854fc
juspay/hyperswitch
juspay__hyperswitch-6914
Bug: [feat] show error code and message in cypress reports show error code and message in cypress reports. this is helpful to debug failures in ci
2024-12-21T07:48:52Z
## 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 introduces error code and error message validations. This nullifies the need to re-run the ci check manually in local every the check just to see the reason for the failure. With that, `error_code` and `error_message` will now be printed in the ui in every run and hence, this makes the generated reports more reliable. ### 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). --> i want reports to serve a purpose and reliable. ## 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 a ci check fail, especially from the connectors' end, ci takes a screenshot of the ui, as usual, but that will now contain the error code and message. since adyen yet again got into some issues with save card flow, it is possible to test my changes directly without the need to make any modifications to the test: <img width="539" alt="image" src="https://github.com/user-attachments/assets/c2037bb2-b393-410d-b5b4-feb093a94a7a" /> ## 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
d4b3dbc155906e8bc0fa1b14e73f45227395a32f
juspay/hyperswitch
juspay__hyperswitch-6902
Bug: [REFACTOR] send `tenant-id` and `request-id` in grpc headers
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 39e5483700a..3b437b703be 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -146,3 +146,6 @@ pub const CONNECTOR_TRANSACTION_ID_HASH_BYTES: usize = 25; /// Apple Pay validation url pub const APPLEPAY_VALIDATION_URL: &str = "https://apple-pay-gateway-cert.apple.com/paymentservices/startSession"; + +/// Request ID +pub const X_REQUEST_ID: &str = "x-request-id"; diff --git a/crates/external_services/src/grpc_client.rs b/crates/external_services/src/grpc_client.rs index 8981a1094d6..404685025ed 100644 --- a/crates/external_services/src/grpc_client.rs +++ b/crates/external_services/src/grpc_client.rs @@ -6,6 +6,8 @@ pub mod dynamic_routing; pub mod health_check_client; use std::{fmt::Debug, sync::Arc}; +#[cfg(feature = "dynamic_routing")] +use common_utils::consts; #[cfg(feature = "dynamic_routing")] use dynamic_routing::{DynamicRoutingClientConfig, RoutingStrategy}; #[cfg(feature = "dynamic_routing")] @@ -16,6 +18,8 @@ use http_body_util::combinators::UnsyncBoxBody; use hyper::body::Bytes; #[cfg(feature = "dynamic_routing")] use hyper_util::client::legacy::connect::HttpConnector; +#[cfg(feature = "dynamic_routing")] +use router_env::logger; use serde; #[cfg(feature = "dynamic_routing")] use tonic::Status; @@ -76,3 +80,51 @@ impl GrpcClientSettings { }) } } + +/// Contains grpc headers +#[derive(Debug)] +pub struct GrpcHeaders { + /// Tenant id + pub tenant_id: String, + /// Request id + pub request_id: Option<String>, +} + +#[cfg(feature = "dynamic_routing")] +/// Trait to add necessary headers to the tonic Request +pub(crate) trait AddHeaders { + /// Add necessary header fields to the tonic Request + fn add_headers_to_grpc_request(&mut self, headers: GrpcHeaders); +} + +#[cfg(feature = "dynamic_routing")] +impl<T> AddHeaders for tonic::Request<T> { + #[track_caller] + fn add_headers_to_grpc_request(&mut self, headers: GrpcHeaders) { + headers.tenant_id + .parse() + .map(|tenant_id| { + self + .metadata_mut() + .append(consts::TENANT_HEADER, tenant_id) + }) + .inspect_err( + |err| logger::warn!(header_parse_error=?err,"invalid {} received",consts::TENANT_HEADER), + ) + .ok(); + + headers.request_id.map(|request_id| { + request_id + .parse() + .map(|request_id| { + self + .metadata_mut() + .append(consts::X_REQUEST_ID, request_id) + }) + .inspect_err( + |err| logger::warn!(header_parse_error=?err,"invalid {} received",consts::X_REQUEST_ID), + ) + .ok(); + }); + } +} diff --git a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs index 6587b7941f4..bc5ce499727 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs @@ -21,6 +21,7 @@ pub mod elimination_rate { } use super::{Client, DynamicRoutingError, DynamicRoutingResult}; +use crate::grpc_client::{AddHeaders, GrpcHeaders}; /// The trait Elimination Based Routing would have the functions required to support performance, calculation and invalidation bucket #[async_trait::async_trait] @@ -32,6 +33,7 @@ pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync { params: String, labels: Vec<RoutableConnectorChoice>, configs: Option<EliminationConfig>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<EliminationResponse>; /// To update the bucket size and ttl for list of connectors with its respective bucket name async fn update_elimination_bucket_config( @@ -40,11 +42,13 @@ pub trait EliminationBasedRouting: dyn_clone::DynClone + Send + Sync { params: String, report: Vec<RoutableConnectorChoiceWithBucketName>, config: Option<EliminationConfig>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<UpdateEliminationBucketResponse>; /// To invalidate the previous id's bucket async fn invalidate_elimination_bucket( &self, id: String, + headers: GrpcHeaders, ) -> DynamicRoutingResult<InvalidateBucketResponse>; } @@ -56,6 +60,7 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { params: String, label_input: Vec<RoutableConnectorChoice>, configs: Option<EliminationConfig>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<EliminationResponse> { let labels = label_input .into_iter() @@ -64,13 +69,15 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?; - let request = tonic::Request::new(EliminationRequest { + let mut request = tonic::Request::new(EliminationRequest { id, params, labels, config, }); + request.add_headers_to_grpc_request(headers); + let response = self .clone() .get_elimination_status(request) @@ -89,6 +96,7 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { params: String, report: Vec<RoutableConnectorChoiceWithBucketName>, configs: Option<EliminationConfig>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<UpdateEliminationBucketResponse> { let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?; @@ -102,13 +110,15 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { }) .collect::<Vec<_>>(); - let request = tonic::Request::new(UpdateEliminationBucketRequest { + let mut request = tonic::Request::new(UpdateEliminationBucketRequest { id, params, labels_with_bucket_name, config, }); + request.add_headers_to_grpc_request(headers); + let response = self .clone() .update_elimination_bucket(request) @@ -122,8 +132,11 @@ impl EliminationBasedRouting for EliminationAnalyserClient<Client> { async fn invalidate_elimination_bucket( &self, id: String, + headers: GrpcHeaders, ) -> DynamicRoutingResult<InvalidateBucketResponse> { - let request = tonic::Request::new(InvalidateBucketRequest { id }); + let mut request = tonic::Request::new(InvalidateBucketRequest { id }); + + request.add_headers_to_grpc_request(headers); let response = self .clone() diff --git a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs index f6d3efb8876..3cf06ab63be 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing/success_rate_client.rs @@ -21,6 +21,7 @@ pub mod success_rate { tonic::include_proto!("success_rate"); } use super::{Client, DynamicRoutingError, DynamicRoutingResult}; +use crate::grpc_client::{AddHeaders, GrpcHeaders}; /// The trait Success Based Dynamic Routing would have the functions required to support the calculation and updation window #[async_trait::async_trait] pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { @@ -31,6 +32,7 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { success_rate_based_config: SuccessBasedRoutingConfig, params: String, label_input: Vec<RoutableConnectorChoice>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<CalSuccessRateResponse>; /// To update the success rate with the given label async fn update_success_rate( @@ -39,11 +41,13 @@ pub trait SuccessBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { success_rate_based_config: SuccessBasedRoutingConfig, params: String, response: Vec<RoutableConnectorChoiceWithStatus>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse>; /// To invalidates the success rate routing keys async fn invalidate_success_rate_routing_keys( &self, id: String, + headers: GrpcHeaders, ) -> DynamicRoutingResult<InvalidateWindowsResponse>; } @@ -55,6 +59,7 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { success_rate_based_config: SuccessBasedRoutingConfig, params: String, label_input: Vec<RoutableConnectorChoice>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<CalSuccessRateResponse> { let labels = label_input .into_iter() @@ -66,13 +71,15 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { .map(ForeignTryFrom::foreign_try_from) .transpose()?; - let request = tonic::Request::new(CalSuccessRateRequest { + let mut request = tonic::Request::new(CalSuccessRateRequest { id, params, labels, config, }); + request.add_headers_to_grpc_request(headers); + let response = self .clone() .fetch_success_rate(request) @@ -91,6 +98,7 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { success_rate_based_config: SuccessBasedRoutingConfig, params: String, label_input: Vec<RoutableConnectorChoiceWithStatus>, + headers: GrpcHeaders, ) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> { let config = success_rate_based_config .config @@ -105,13 +113,15 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { }) .collect(); - let request = tonic::Request::new(UpdateSuccessRateWindowRequest { + let mut request = tonic::Request::new(UpdateSuccessRateWindowRequest { id, params, labels_with_status, config, }); + request.add_headers_to_grpc_request(headers); + let response = self .clone() .update_success_rate_window(request) @@ -126,8 +136,11 @@ impl SuccessBasedDynamicRouting for SuccessRateCalculatorClient<Client> { async fn invalidate_success_rate_routing_keys( &self, id: String, + headers: GrpcHeaders, ) -> DynamicRoutingResult<InvalidateWindowsResponse> { - let request = tonic::Request::new(InvalidateWindowsRequest { id }); + let mut request = tonic::Request::new(InvalidateWindowsRequest { id }); + + request.add_headers_to_grpc_request(headers); let response = self .clone() diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 746b6b7fb40..6d3c0973283 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -1343,6 +1343,7 @@ pub async fn perform_success_based_routing( success_based_routing_configs, success_based_routing_config_params, routable_connectors, + state.get_grpc_headers(), ) .await .change_context(errors::RoutingError::SuccessRateCalculationError) diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 36bcb233d02..5fc54fe96e5 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -1408,7 +1408,10 @@ pub async fn success_based_routing_update_configs( .as_ref() .async_map(|sr_client| async { sr_client - .invalidate_success_rate_routing_keys(prefix_of_dynamic_routing_keys) + .invalidate_success_rate_routing_keys( + prefix_of_dynamic_routing_keys, + state.get_grpc_headers(), + ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to invalidate the routing keys".to_string(), diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index b3c951f0964..3ead2966ed7 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -719,6 +719,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( success_based_routing_configs.clone(), success_based_routing_config_params.clone(), routable_connectors.clone(), + state.get_grpc_headers(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -854,6 +855,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( }, payment_status_attribute == common_enums::AttemptStatus::Charged, )], + state.get_grpc_headers(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 766679491c5..7daed86079f 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -12,7 +12,10 @@ use common_utils::id_type; use external_services::email::{ no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService, }; -use external_services::{file_storage::FileStorageInterface, grpc_client::GrpcClients}; +use external_services::{ + file_storage::FileStorageInterface, + grpc_client::{GrpcClients, GrpcHeaders}, +}; use hyperswitch_interfaces::{ encryption_interface::EncryptionManagementInterface, secrets_interface::secret_state::{RawSecret, SecuredSecret}, @@ -123,6 +126,12 @@ impl SessionState { event_context: events::EventContext::new(self.event_handler.clone()), } } + pub fn get_grpc_headers(&self) -> GrpcHeaders { + GrpcHeaders { + tenant_id: self.tenant.tenant_id.get_string_repr().to_string(), + request_id: self.request_id.map(|req_id| (*req_id).to_string()), + } + } } pub trait SessionStateInfo {
2024-12-19T16:09:44Z
## 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 support for sending the `x-tenant-id` and `x-request-id` in the grpc headers ### 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. Create merchant_account, api_key and mca (any connector) 2. Toggle dynamic routing ``` curl --location --request POST 'http://localhost:8080/account/merchant_1734609410/business_profile/pro_gPTjn9jLm0CxI8ZD1omL/dynamic_routing/success_based/toggle?enable=metrics' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K70Wr6zqJLbPECg8eEXrnZ43TW41JNUuXYHzRB50geiG0lViLExjxNUld6sgdNd0' \ --data '' ``` 3. Create a payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_K70Wr6zqJLbPECg8eEXrnZ43TW41JNUuXYHzRB50geiG0lViLExjxNUld6sgdNd0' \ --data '{ "amount": 6540, "authentication_type": "no_three_ds", "confirm": true, "currency": "USD", "customer_acceptance": { "acceptance_type": "online" }, "customer_id": "cus_uYakn3OQTUtAgetLDOE1", "payment_method": "card", "payment_method_data": { "card": { "card_cvc": "123", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_number": "4242424242424242" } } }' ``` Check the grafana dashboard with `app = dynamo` label in loki. Logs should have `x-tenant-id` and `x-request-id` in the headers. ## 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
dcd51a7fb8df673cc74130ee732542b55783602f
juspay/hyperswitch
juspay__hyperswitch-6901
Bug: refactor(dynamic_routing): perform db operations only when payments are in terminal state
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 193998c3fd1..c3faa5c6f93 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -1304,6 +1304,20 @@ pub enum IntentStatus { } impl IntentStatus { + /// Indicates whether the payment intent is in terminal state or not + pub fn is_in_terminal_state(self) -> bool { + match self { + Self::Succeeded | Self::Failed | Self::Cancelled | Self::PartiallyCaptured => true, + Self::Processing + | Self::RequiresCustomerAction + | Self::RequiresMerchantAction + | Self::RequiresPaymentMethod + | Self::RequiresConfirmation + | Self::RequiresCapture + | Self::PartiallyCapturedAndCapturable => false, + } + } + /// Indicates whether the syncing with the connector should be allowed or not pub fn should_force_sync_with_connector(self) -> bool { match self { diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 988429a0eec..8254eeb892e 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1969,7 +1969,9 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( #[cfg(all(feature = "v1", feature = "dynamic_routing"))] { - if business_profile.dynamic_routing_algorithm.is_some() { + if payment_intent.status.is_in_terminal_state() + && business_profile.dynamic_routing_algorithm.is_some() + { let state = state.clone(); let business_profile = business_profile.clone(); let payment_attempt = payment_attempt.clone();
2024-12-19T14:48:25Z
## 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 --> Previously due to the DB insertion code being in `post_update_tracker` was being called several times as our payment's status keeps on changing, due to this our DB broke as we had a unique constraint on `attempt_id` in the `dynamic_routing_stats` table. To fix this we have added a check that only the payments that are in terminal state will be pushed, which ensures that the insert in db will be called only once for one attempt_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` --> ## 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. Toggle Success Based routing for the merchant. ``` curl --location --request POST 'http://localhost:8080/account/xxxxxx/business_profile/xxxxxxx/dynamic_routing/success_based/toggle?enable=metrics' \ --header 'api-key: xxxxxxx' ``` 2. Create a payment that goes in processing state or any non terminal state. (VOLTE) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xxxxxxxx' \ --data-raw '{ "amount": 8000, "currency": "EUR", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 8000, "customer_id": "StripeCustomer", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://www.google.com/", "payment_method": "bank_redirect", "payment_method_type": "open_banking_uk", "payment_method_data": { "bank_redirect": { "open_banking_uk": { } } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "DE", "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": "DE", "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": "xxxxx" } ' ``` 3. Hit the 3ds link and cancel the payment 5. Check `dynamic_routing_stats` table for the entry of attempt, it should be there. <img width="569" alt="Screenshot 2025-01-15 at 3 33 58 PM" src="https://github.com/user-attachments/assets/f942db2a-93f2-48f7-9918-eef69996a55c" /> ## 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
04787313941ec39b179490d0196258f09e2e51dd
juspay/hyperswitch
juspay__hyperswitch-6893
Bug: [bug] reports are being generated in cypress upon failures that is because recently, i moved cypress.config.js from being a commonjs module to esmodule and this resulted in inconsistencies which went unaddressed or unnotified.
2024-12-19T10:16:04Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> closes https://github.com/juspay/hyperswitch/issues/6893 this pr also bumps cypress dependencies ### 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 report generation ## 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)? --> the changes in this pr has been cherry picked from #6735. reports for failed tests were generated there. an example of reports being generated: https://github.com/juspay/hyperswitch/actions/runs/12409713710?pr=6735 ## 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
c525c9f4c9d23802989bc594a4acd26c7d7cd27d
juspay/hyperswitch
juspay__hyperswitch-6889
Bug: [FEATURE] Implement Payment Method Samsung Pay for Connector BankOfAmerica ### Feature Description Implement Payment Method Samsung Pay for Connector BankOfAmerica. ### Possible Implementation Samsung Pay should be implemented for BankOfAmerica ### 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/bankofamerica/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs index 4b40e36a7a6..7690b6ed3d0 100644 --- a/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs @@ -1,8 +1,11 @@ use base64::Engine; use common_enums::{enums, FutureUsage}; -use common_utils::{consts, pii}; +use common_utils::{consts, ext_traits::OptionExt, pii}; use hyperswitch_domain_models::{ - payment_method_data::{ApplePayWalletData, GooglePayWalletData, PaymentMethodData, WalletData}, + payment_method_data::{ + ApplePayWalletData, GooglePayWalletData, PaymentMethodData, SamsungPayWalletData, + WalletData, + }, router_data::{ AdditionalPaymentMethodConnectorResponse, ApplePayPredecryptData, ConnectorAuthType, ConnectorResponseData, ErrorResponse, PaymentMethodToken, RouterData, @@ -221,6 +224,7 @@ pub enum PaymentInformation { ApplePay(Box<ApplePayPaymentInformation>), ApplePayToken(Box<ApplePayTokenPaymentInformation>), MandatePayment(Box<MandatePaymentInformation>), + SamsungPay(Box<SamsungPayPaymentInformation>), } #[derive(Debug, Serialize)] @@ -254,8 +258,12 @@ pub struct TokenizedCard { #[serde(rename_all = "camelCase")] pub struct FluidData { value: Secret<String>, + #[serde(skip_serializing_if = "Option::is_none")] + descriptor: Option<String>, } +pub const FLUID_DATA_DESCRIPTOR_FOR_SAMSUNG_PAY: &str = "FID=COMMON.SAMSUNG.INAPP.PAYMENT"; + #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct OrderInformationWithBill { @@ -556,6 +564,7 @@ fn get_boa_card_type(card_network: common_enums::CardNetwork) -> Option<&'static pub enum PaymentSolution { ApplePay, GooglePay, + SamsungPay, } impl From<PaymentSolution> for String { @@ -563,6 +572,7 @@ impl From<PaymentSolution> for String { let payment_solution = match solution { PaymentSolution::ApplePay => "001", PaymentSolution::GooglePay => "012", + PaymentSolution::SamsungPay => "008", }; payment_solution.to_string() } @@ -572,6 +582,8 @@ impl From<PaymentSolution> for String { pub enum TransactionType { #[serde(rename = "1")] ApplePay, + #[serde(rename = "1")] + SamsungPay, } impl @@ -950,6 +962,27 @@ impl } } +#[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(rename_all = "camelCase")] +pub struct SamsungPayFluidDataValue { + public_key_hash: Secret<String>, + version: String, + data: Secret<String>, +} + impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> for BankOfAmericaPaymentsRequest { @@ -1042,6 +1075,9 @@ impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> WalletData::GooglePay(google_pay_data) => { Self::try_from((item, google_pay_data)) } + WalletData::SamsungPay(samsung_pay_data) => { + Self::try_from((item, samsung_pay_data)) + } WalletData::AliPayQr(_) | WalletData::AliPayRedirect(_) @@ -1061,7 +1097,6 @@ impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> | WalletData::PaypalRedirect(_) | WalletData::PaypalSdk(_) | WalletData::Paze(_) - | WalletData::SamsungPay(_) | WalletData::TwintRedirect {} | WalletData::VippsRedirect {} | WalletData::TouchNGoRedirect(_) @@ -1116,6 +1151,96 @@ impl TryFrom<&BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>> } } +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 = + josekit::jwt::decode_header(samsung_pay_token_data.data.clone().peek()) + .change_context(errors::ConnectorError::RequestEncodingFailed) + .attach_printable("Failed to decode samsung pay header")?; + + let samsung_pay_kid_optional = samsung_pay_header.claim("kid").and_then(|kid| kid.as_str()); + + 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) +} + +use error_stack::ResultExt; + +impl + TryFrom<( + &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>, + Box<SamsungPayWalletData>, + )> for BankOfAmericaPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + (item, samsung_pay_data): ( + &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>, + Box<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 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::new(consts::BASE64_ENGINE.encode(samsung_pay_fluid_data_str)), + 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.to_string()), + ))?; + let client_reference_information = ClientReferenceInformation::from(item); + let merchant_defined_information = item + .router_data + .request + .metadata + .clone() + .map(convert_metadata_to_merchant_defined_info); + + Ok(Self { + processing_information, + payment_information, + order_information, + client_reference_information, + consumer_authentication_information: None, + merchant_defined_information, + }) + } +} + impl TryFrom<( &BankOfAmericaRouterData<&PaymentsAuthorizeRouterData>, @@ -2471,6 +2596,7 @@ impl From<&ApplePayWalletData> for PaymentInformation { Self::ApplePayToken(Box::new(ApplePayTokenPaymentInformation { fluid_data: FluidData { value: Secret::from(apple_pay_data.payment_data.clone()), + descriptor: None, }, tokenized_card: ApplePayTokenizedCard { transaction_type: TransactionType::ApplePay, @@ -2486,6 +2612,7 @@ impl From<&GooglePayWalletData> for PaymentInformation { value: Secret::from( consts::BASE64_ENGINE.encode(google_pay_data.tokenization_data.token.clone()), ), + descriptor: None, }, })) }
2024-12-19T08:24:33Z
## 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 --> Implemented Payment Method Samsung Pay for connector Bankofamerica ### 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. Connector configuration with merhcant account ``` curl --location 'http://localhost:8080/account/merchant_1734596148/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "bankofamerica", "connector_account_details": { "auth_type": "SignatureKey", "api_secret": API_SECRET_HERE, "key1": KEY_1 here, "api_key": API_KEY here }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ { "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 } ] } ], "connector_wallets_details": WALLET_DETAILS_HERE, "metadata": { "city": "NY", "unit": "245" }, "connector_webhook_details": { "merchant_secret": "merchant_secret" } }' ``` Response: ``` { "connector_type": "payment_processor", "connector_name": "bankofamerica", "connector_label": "bankofamerica_US_default", "merchant_connector_id": "mca_tcLF8eNc3wyJyNa02NAY", "profile_id": "pro_PS3TEgINEPhzeeAjNjKV", "connector_account_details": { "auth_type": "SignatureKey", "api_key": "d0********************************4c", "key1": "ju*************ox", "api_secret": "rK****************************************k=" }, "payment_methods_enabled": [ { "payment_method": "wallet", "payment_method_types": [ { "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 } ] } ], "connector_webhook_details": { "merchant_secret": "merchant_secret", "additional_secret": null }, "connector_wallets_details": WALLET_DETAILS_HERE, "metadata": { "city": "NY", "unit": "245" }, "test_mode": true, "disabled": false, "frm_configs": null, "business_country": null, "business_label": null, "business_sub_label": null, "applepay_verified_domains": null, "pm_auth_config": null, "status": "active", "additional_merchant_data": null, } ``` 2. Create Payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_eJeiVMcAVr5URnyfwyv3LHLrSkfpwR44liTgmY3szossAbomjLpgsSmvN2H1ELMm' \ --data '{ "amount": 6540, "currency": "USD", "capture_method": "automatic", "authentication_type": "no_three_ds", "confirm": false, "customer_id": "cu_1726743607", "metadata": { "city": "NY", "unit": "245" } }' ``` Response: ``` { "payment_id": "pay_pUtMw6BcmjjRLpP6lS9J", "merchant_id": "merchant_1734693841", "status": "requires_payment_method", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_pUtMw6BcmjjRLpP6lS9J_secret_GD5uPWJmbU3YQiIcgoiN", "created": "2024-12-20T11:34:14.762Z", "currency": "USD", "customer_id": "cu_1726743607", "customer": { "id": "cu_1726743607", "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_1726743607", "created_at": 1734694454, "expires": 1734698054, "secret": "epk_5d8ae327451c498182e4bb121edf3e81" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "city": "NY", "unit": "245" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_mGLf47yYw0B9WO6PxMrD", "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-12-20T11:49:14.762Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-20T11:34:14.811Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` 3. Session-token ``` curl --location 'http://localhost:8080/payments/session_tokens' \ --header 'Content-Type: application/json' \ --header 'api-key: pk_dev_42fcfebecc5247588101551310c2a586' \ --data '{ "payment_id": "pay_pUtMw6BcmjjRLpP6lS9J", "wallets": [], "client_secret": "pay_pUtMw6BcmjjRLpP6lS9J_secret_GD5uPWJmbU3YQiIcgoiN" }' ``` Response: ``` { "payment_id": "pay_WuoNKWqCMOQjFtcFP10z", "client_secret": "pay_WuoNKWqCMOQjFtcFP10z_secret_j1WL1mhlMmiO1Dr4Trr1", "session_token": [ { "wallet_name": "samsung_pay", "version": "2", "service_id": SERVICE_ID HERE, "order_number": "pay-WuoNKWqCMOQjFtcFP10z", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "65.40" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] } ] } ``` 4. Confirm payment ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_AZns1EDM3pjsdDnWLh8fYVrLoDrmRqVLXADWgYhrTnecV5LT6I8hfLcQGsZsMadN' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 6540, "customer_id": "custhype123", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "[email protected]", "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": "encrypted samsung pay data" } } } } } }' ``` Response: ``` { "payment_id": "pay_FnYdRGNWyk5ivPntRVK7", "merchant_id": "merchant_1742560204", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "bankofamerica", "client_secret": "pay_FnYdRGNWyk5ivPntRVK7_secret_pFhbPDe5XdIIEoKe0KYg", "created": "2025-03-21T12:30:26.829Z", "currency": "USD", "customer_id": "custhype123", "customer": { "id": "custhype123", "name": "Joseph Doe", "email": "[email protected]", "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": { "samsung_pay": { "last4": "1661", "card_network": "Visa", "type": 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": "California", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": null }, "order_details": null, "email": "[email protected]", "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": "bankofamerica_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "custhype123", "created_at": 1742560226, "expires": 1742563826, "secret": "epk_d436e8803b7d40938ea22e261a545d7a" }, "manual_retry_allowed": false, "connector_transaction_id": "7425602271606029804806", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_FnYdRGNWyk5ivPntRVK7_1", "payment_link": null, "profile_id": "pro_gnArRjiKOTQDn7X5QQee", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_IZ7c613FVN3IZpnVootz", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-03-21T12:45:26.829Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-03-21T12:30:28.689Z", "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": null, "issuer_error_code": null, "issuer_error_message": 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
10371af561ecc7536bb1db191af90a3cac2ab515
juspay/hyperswitch
juspay__hyperswitch-6925
Bug: [FEATURE] Add support for retries with clear pan and network token payment method data Add support for payment retries with clear pan and network token payment method data and also reduced calls to locker when data is already fetch once.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 2e0d57d977e..cd8b8458364 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -10615,7 +10615,8 @@ "message", "status", "decision", - "step_up_possible" + "step_up_possible", + "clear_pan_possible" ], "properties": { "connector": { @@ -10670,6 +10671,10 @@ } ], "nullable": true + }, + "clear_pan_possible": { + "type": "boolean", + "description": "indicates if retry with pan is possible" } } }, @@ -10754,7 +10759,8 @@ "message", "status", "decision", - "step_up_possible" + "step_up_possible", + "clear_pan_possible" ], "properties": { "connector": { @@ -10811,6 +10817,10 @@ } ], "nullable": true + }, + "clear_pan_possible": { + "type": "boolean", + "description": "indicates if retry with pan is possible" } } }, @@ -10915,6 +10925,11 @@ } ], "nullable": true + }, + "clear_pan_possible": { + "type": "boolean", + "description": "indicates if retry with pan is possible", + "nullable": true } } }, @@ -18738,6 +18753,11 @@ } ], "nullable": true + }, + "is_clear_pan_retries_enabled": { + "type": "boolean", + "description": "Indicates if clear pan retries is enabled or not.", + "nullable": true } }, "additionalProperties": false @@ -18771,7 +18791,8 @@ "is_tax_connector_enabled", "is_network_tokenization_enabled", "should_collect_cvv_during_payment", - "is_click_to_pay_enabled" + "is_click_to_pay_enabled", + "is_clear_pan_retries_enabled" ], "properties": { "merchant_id": { @@ -18970,6 +18991,10 @@ } ], "nullable": true + }, + "is_clear_pan_retries_enabled": { + "type": "boolean", + "description": "Indicates if clear pan retries is enabled or not." } } }, diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index d9ae29d4b30..5d31ea70994 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1960,6 +1960,9 @@ pub struct ProfileCreate { /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, + + ///Indicates if clear pan retries is enabled or not. + pub is_clear_pan_retries_enabled: Option<bool>, } #[nutype::nutype( @@ -2081,6 +2084,9 @@ pub struct ProfileCreate { /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, + + ///Indicates if clear pan retries is enabled or not. + pub is_clear_pan_retries_enabled: Option<bool>, } #[cfg(feature = "v1")] @@ -2225,6 +2231,9 @@ pub struct ProfileResponse { /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, + + ///Indicates if clear pan retries is enabled or not. + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v2")] @@ -2352,6 +2361,9 @@ pub struct ProfileResponse { /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, + + ///Indicates if clear pan retries is enabled or not. + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v1")] @@ -2486,6 +2498,9 @@ pub struct ProfileUpdate { /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, + + ///Indicates if clear pan retries is enabled or not. + pub is_clear_pan_retries_enabled: Option<bool>, } #[cfg(feature = "v2")] @@ -2601,6 +2616,9 @@ pub struct ProfileUpdate { /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, + + ///Indicates if clear pan retries is enabled or not. + pub is_clear_pan_retries_enabled: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/api_models/src/gsm.rs b/crates/api_models/src/gsm.rs index b95794ef707..7ffc9c69413 100644 --- a/crates/api_models/src/gsm.rs +++ b/crates/api_models/src/gsm.rs @@ -29,6 +29,8 @@ pub struct GsmCreateRequest { pub unified_message: Option<String>, /// category in which error belongs to pub error_category: Option<ErrorCategory>, + /// indicates if retry with pan is possible + pub clear_pan_possible: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -93,6 +95,8 @@ pub struct GsmUpdateRequest { pub unified_message: Option<String>, /// category in which error belongs to pub error_category: Option<ErrorCategory>, + /// indicates if retry with pan is possible + pub clear_pan_possible: Option<bool>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -148,4 +152,6 @@ pub struct GsmResponse { pub unified_message: Option<String>, /// category in which error belongs to pub error_category: Option<ErrorCategory>, + /// indicates if retry with pan is possible + pub clear_pan_possible: bool, } diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index c5507d78002..744193bf51e 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -63,6 +63,7 @@ pub struct Profile { Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v1")] @@ -111,6 +112,7 @@ pub struct ProfileNew { Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v1")] @@ -157,6 +159,7 @@ pub struct ProfileUpdateInternal { Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, + pub is_clear_pan_retries_enabled: Option<bool>, } #[cfg(feature = "v1")] @@ -201,6 +204,7 @@ impl ProfileUpdateInternal { authentication_product_ids, card_testing_guard_config, card_testing_secret_key, + is_clear_pan_retries_enabled, } = self; Profile { profile_id: source.profile_id, @@ -269,6 +273,8 @@ impl ProfileUpdateInternal { card_testing_guard_config: card_testing_guard_config .or(source.card_testing_guard_config), card_testing_secret_key, + is_clear_pan_retries_enabled: is_clear_pan_retries_enabled + .unwrap_or(source.is_clear_pan_retries_enabled), } } } @@ -321,6 +327,7 @@ pub struct Profile { Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, + pub is_clear_pan_retries_enabled: bool, pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>, pub order_fulfillment_time: Option<i64>, pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>, @@ -394,6 +401,7 @@ pub struct ProfileNew { pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, + pub is_clear_pan_retries_enabled: Option<bool>, } #[cfg(feature = "v2")] @@ -442,6 +450,7 @@ pub struct ProfileUpdateInternal { pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: Option<Encryption>, + pub is_clear_pan_retries_enabled: Option<bool>, } #[cfg(feature = "v2")] @@ -488,6 +497,7 @@ impl ProfileUpdateInternal { three_ds_decision_manager_config, card_testing_guard_config, card_testing_secret_key, + is_clear_pan_retries_enabled, } = self; Profile { id: source.id, @@ -562,6 +572,8 @@ impl ProfileUpdateInternal { card_testing_guard_config: card_testing_guard_config .or(source.card_testing_guard_config), card_testing_secret_key: card_testing_secret_key.or(source.card_testing_secret_key), + is_clear_pan_retries_enabled: is_clear_pan_retries_enabled + .unwrap_or(source.is_clear_pan_retries_enabled), } } } diff --git a/crates/diesel_models/src/gsm.rs b/crates/diesel_models/src/gsm.rs index aba8d75a6eb..46583a5b22c 100644 --- a/crates/diesel_models/src/gsm.rs +++ b/crates/diesel_models/src/gsm.rs @@ -41,6 +41,7 @@ pub struct GatewayStatusMap { pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, + pub clear_pan_possible: bool, } #[derive(Clone, Debug, Eq, PartialEq, Insertable)] @@ -58,6 +59,7 @@ pub struct GatewayStatusMappingNew { pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, + pub clear_pan_possible: bool, } #[derive( @@ -78,6 +80,7 @@ pub struct GatewayStatusMapperUpdateInternal { pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, pub last_modified: PrimitiveDateTime, + pub clear_pan_possible: Option<bool>, } #[derive(Debug)] @@ -89,6 +92,7 @@ pub struct GatewayStatusMappingUpdate { pub unified_code: Option<String>, pub unified_message: Option<String>, pub error_category: Option<ErrorCategory>, + pub clear_pan_possible: Option<bool>, } impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { @@ -101,6 +105,7 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { unified_code, unified_message, error_category, + clear_pan_possible, } = value; Self { status, @@ -116,6 +121,7 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { sub_flow: None, code: None, message: None, + clear_pan_possible, } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 1de8483a3f3..9135baeb77a 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -219,6 +219,7 @@ diesel::table! { authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, + is_clear_pan_retries_enabled -> Bool, } } @@ -565,6 +566,7 @@ diesel::table! { unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, + clear_pan_possible -> Bool, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 6018d0a6999..af1b2c65f40 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -215,6 +215,7 @@ diesel::table! { authentication_product_ids -> Nullable<Jsonb>, card_testing_guard_config -> Nullable<Jsonb>, card_testing_secret_key -> Nullable<Bytea>, + is_clear_pan_retries_enabled -> Bool, #[max_length = 64] routing_algorithm_id -> Nullable<Varchar>, order_fulfillment_time -> Nullable<Int8>, @@ -576,6 +577,7 @@ diesel::table! { unified_message -> Nullable<Varchar>, #[max_length = 64] error_category -> Nullable<Varchar>, + clear_pan_possible -> Bool, } } diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 07fd0a9fd90..d4bb6ed1fce 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -64,6 +64,7 @@ pub struct Profile { Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v1")] @@ -110,6 +111,7 @@ pub struct ProfileSetter { Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v1")] @@ -162,6 +164,7 @@ impl From<ProfileSetter> for Profile { authentication_product_ids: value.authentication_product_ids, card_testing_guard_config: value.card_testing_guard_config, card_testing_secret_key: value.card_testing_secret_key, + is_clear_pan_retries_enabled: value.is_clear_pan_retries_enabled, } } } @@ -216,6 +219,7 @@ pub struct ProfileGeneralUpdate { Option<common_types::payments::AuthenticationConnectorAccountMap>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, + pub is_clear_pan_retries_enabled: Option<bool>, } #[cfg(feature = "v1")] @@ -285,6 +289,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids, card_testing_guard_config, card_testing_secret_key, + is_clear_pan_retries_enabled, } = *update; Self { @@ -327,6 +332,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), + is_clear_pan_retries_enabled, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -371,6 +377,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm, @@ -413,6 +420,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -455,6 +463,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -497,6 +506,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -539,6 +549,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -581,6 +592,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { authentication_product_ids: None, card_testing_guard_config: None, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), + is_clear_pan_retries_enabled: None, }, } } @@ -642,6 +654,7 @@ impl super::behaviour::Conversion for Profile { authentication_product_ids: self.authentication_product_ids, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(|name| name.into()), + is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, }) } @@ -728,6 +741,7 @@ impl super::behaviour::Conversion for Profile { .and_then(|val| val.try_into_optionaloperation()) }) .await?, + is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, }) } .await @@ -784,6 +798,7 @@ impl super::behaviour::Conversion for Profile { authentication_product_ids: self.authentication_product_ids, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(Encryption::from), + is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, }) } } @@ -834,6 +849,7 @@ pub struct Profile { pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v2")] @@ -880,6 +896,7 @@ pub struct ProfileSetter { pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>, pub card_testing_guard_config: Option<CardTestingGuardConfig>, pub card_testing_secret_key: OptionalEncryptableName, + pub is_clear_pan_retries_enabled: bool, } #[cfg(feature = "v2")] @@ -932,6 +949,7 @@ impl From<ProfileSetter> for Profile { three_ds_decision_manager_config: value.three_ds_decision_manager_config, card_testing_guard_config: value.card_testing_guard_config, card_testing_secret_key: value.card_testing_secret_key, + is_clear_pan_retries_enabled: value.is_clear_pan_retries_enabled, } } } @@ -1100,6 +1118,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config, card_testing_guard_config, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), + is_clear_pan_retries_enabled: None, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -1146,6 +1165,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -1190,6 +1210,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -1234,6 +1255,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::DefaultRoutingFallbackUpdate { default_fallback_routing, @@ -1278,6 +1300,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -1322,6 +1345,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::CollectCvvDuringPaymentUpdate { should_collect_cvv_during_payment, @@ -1366,6 +1390,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config, @@ -1410,6 +1435,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: Some(three_ds_decision_manager_config), card_testing_guard_config: None, card_testing_secret_key: None, + is_clear_pan_retries_enabled: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -1454,6 +1480,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { three_ds_decision_manager_config: None, card_testing_guard_config: None, card_testing_secret_key: card_testing_secret_key.map(Encryption::from), + is_clear_pan_retries_enabled: None, }, } } @@ -1519,6 +1546,7 @@ impl super::behaviour::Conversion for Profile { three_ds_decision_manager_config: self.three_ds_decision_manager_config, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(|name| name.into()), + is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, }) } @@ -1605,6 +1633,7 @@ impl super::behaviour::Conversion for Profile { .and_then(|val| val.try_into_optionaloperation()) }) .await?, + is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, }) } .await @@ -1665,6 +1694,7 @@ impl super::behaviour::Conversion for Profile { three_ds_decision_manager_config: self.three_ds_decision_manager_config, card_testing_guard_config: self.card_testing_guard_config, card_testing_secret_key: self.card_testing_secret_key.map(Encryption::from), + is_clear_pan_retries_enabled: Some(self.is_clear_pan_retries_enabled), }) } } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 2f8375b47c0..78b2144f3ed 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -71,6 +71,10 @@ impl PaymentMethodData { Self::CardToken(_) | Self::MandatePayment => None, } } + + pub fn is_network_token_payment_method_data(&self) -> bool { + matches!(self, Self::NetworkToken(_)) + } } #[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)] diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 606a8af51c3..d7816915ba5 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -35,13 +35,13 @@ use diesel_models::{ }; use self::payment_attempt::PaymentAttempt; -#[cfg(feature = "v1")] -use crate::RemoteStorageObject; #[cfg(feature = "v2")] use crate::{ address::Address, business_profile, errors, merchant_account, payment_address, payment_method_data, ApiModelToDieselModelConvertor, }; +#[cfg(feature = "v1")] +use crate::{payment_method_data, RemoteStorageObject}; #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)] @@ -633,3 +633,80 @@ where &self.payment_intent.id } } + +#[derive(Clone, serde::Serialize, Debug)] +pub enum VaultOperation { + ExistingVaultData(VaultData), +} + +impl VaultOperation { + pub fn get_updated_vault_data( + existing_vault_data: Option<&Self>, + payment_method_data: &payment_method_data::PaymentMethodData, + ) -> Option<Self> { + match (existing_vault_data, payment_method_data) { + (None, payment_method_data::PaymentMethodData::Card(card)) => { + Some(Self::ExistingVaultData(VaultData::Card(card.clone()))) + } + (None, payment_method_data::PaymentMethodData::NetworkToken(nt_data)) => Some( + Self::ExistingVaultData(VaultData::NetworkToken(nt_data.clone())), + ), + (Some(Self::ExistingVaultData(vault_data)), payment_method_data) => { + match (vault_data, payment_method_data) { + ( + VaultData::Card(card), + payment_method_data::PaymentMethodData::NetworkToken(nt_data), + ) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken( + Box::new(CardAndNetworkTokenData { + card_data: card.clone(), + network_token_data: nt_data.clone(), + }), + ))), + ( + VaultData::NetworkToken(nt_data), + payment_method_data::PaymentMethodData::Card(card), + ) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken( + Box::new(CardAndNetworkTokenData { + card_data: card.clone(), + network_token_data: nt_data.clone(), + }), + ))), + _ => Some(Self::ExistingVaultData(vault_data.clone())), + } + } + //payment_method_data is not card or network token + _ => None, + } + } +} + +#[derive(Clone, serde::Serialize, Debug)] +pub enum VaultData { + Card(payment_method_data::Card), + NetworkToken(payment_method_data::NetworkTokenData), + CardAndNetworkToken(Box<CardAndNetworkTokenData>), +} + +#[derive(Default, Clone, serde::Serialize, Debug)] +pub struct CardAndNetworkTokenData { + pub card_data: payment_method_data::Card, + pub network_token_data: payment_method_data::NetworkTokenData, +} + +impl VaultData { + pub fn get_card_vault_data(&self) -> Option<payment_method_data::Card> { + match self { + Self::Card(card_data) => Some(card_data.clone()), + Self::NetworkToken(_network_token_data) => None, + Self::CardAndNetworkToken(vault_data) => Some(vault_data.card_data.clone()), + } + } + + pub fn get_network_token_data(&self) -> Option<payment_method_data::NetworkTokenData> { + match self { + Self::Card(_card_data) => None, + Self::NetworkToken(network_token_data) => Some(network_token_data.clone()), + Self::CardAndNetworkToken(vault_data) => Some(vault_data.network_token_data.clone()), + } + } +} diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 38b1ddb0f8b..157b8570522 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3786,6 +3786,7 @@ impl ProfileCreateBridge for api::ProfileCreate { .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, + is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), })) } @@ -3941,6 +3942,7 @@ impl ProfileCreateBridge for api::ProfileCreate { .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, + is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(), })) } } @@ -4227,6 +4229,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { .card_testing_guard_config .map(ForeignInto::foreign_into), card_testing_secret_key, + is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled, }, ))) } diff --git a/crates/router/src/core/gsm.rs b/crates/router/src/core/gsm.rs index c7daee111a9..6c544791a18 100644 --- a/crates/router/src/core/gsm.rs +++ b/crates/router/src/core/gsm.rs @@ -68,6 +68,7 @@ pub async fn update_gsm_rule( unified_code, unified_message, error_category, + clear_pan_possible, } = gsm_request; GsmInterface::update_gsm_rule( db, @@ -84,6 +85,7 @@ pub async fn update_gsm_rule( unified_code, unified_message, error_category, + clear_pan_possible, }, ) .await diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 9f0fd705228..452364b654c 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -24,7 +24,7 @@ use api_models::payment_methods; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] -use common_utils::ext_traits::Encode; +use common_utils::ext_traits::{Encode, OptionExt}; use common_utils::{consts::DEFAULT_LOCALE, id_type}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use common_utils::{ @@ -47,7 +47,9 @@ use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData}; use hyperswitch_domain_models::mandates::CommonMandateReference; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use hyperswitch_domain_models::payment_method_data; -use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; +use hyperswitch_domain_models::payments::{ + payment_attempt::PaymentAttempt, PaymentIntent, VaultData, +}; use masking::{PeekInterface, Secret}; use router_env::{instrument, tracing}; use time::Duration; @@ -541,6 +543,8 @@ pub async fn retrieve_payment_method_with_token( mandate_id: Option<api_models::payments::MandateIds>, payment_method_info: Option<domain::PaymentMethod>, business_profile: &domain::Profile, + should_retry_with_pan: bool, + vault_data: Option<&VaultData>, ) -> RouterResult<storage::PaymentMethodDataWithId> { let token = match token_data { storage::PaymentTokenData::TemporaryGeneric(generic_token) => { @@ -584,7 +588,7 @@ pub async fn retrieve_payment_method_with_token( } storage::PaymentTokenData::Permanent(card_token) => { - payment_helpers::retrieve_card_with_permanent_token( + payment_helpers::retrieve_payment_method_data_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), card_token @@ -596,9 +600,14 @@ pub async fn retrieve_payment_method_with_token( merchant_key_store, storage_scheme, mandate_id, - payment_method_info, + payment_method_info + .get_required_value("PaymentMethod") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("PaymentMethod not found")?, business_profile, payment_attempt.connector.clone(), + should_retry_with_pan, + vault_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? @@ -619,7 +628,7 @@ pub async fn retrieve_payment_method_with_token( } storage::PaymentTokenData::PermanentCard(card_token) => { - payment_helpers::retrieve_card_with_permanent_token( + payment_helpers::retrieve_payment_method_data_with_permanent_token( state, card_token.locker_id.as_ref().unwrap_or(&card_token.token), card_token @@ -631,9 +640,14 @@ pub async fn retrieve_payment_method_with_token( merchant_key_store, storage_scheme, mandate_id, - payment_method_info, + payment_method_info + .get_required_value("PaymentMethod") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("PaymentMethod not found")?, business_profile, payment_attempt.connector.clone(), + should_retry_with_pan, + vault_data, ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 7ea847ce653..f29bcb98ee7 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -51,7 +51,7 @@ use hyperswitch_domain_models::router_response_types::RedirectForm; pub use hyperswitch_domain_models::{ mandates::{CustomerAcceptance, MandateData}, payment_address::PaymentAddress, - payments::HeaderPayload, + payments::{self as domain_payments, HeaderPayload}, router_data::{PaymentMethodToken, RouterData}, router_request_types::CustomerDetails, }; @@ -214,6 +214,7 @@ where None, profile, false, + false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType ) .await?; @@ -519,6 +520,7 @@ where None, &business_profile, false, + false, ) .await?; @@ -638,6 +640,7 @@ where None, &business_profile, false, + false, ) .await?; @@ -659,7 +662,7 @@ where req_state.clone(), &mut payment_data, connectors, - connector_data.clone(), + &connector_data, router_data, &merchant_account, &key_store, @@ -2738,6 +2741,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, + should_retry_with_pan: bool, ) -> RouterResult<( RouterData<F, RouterDReq, router_types::PaymentsResponseData>, helpers::MerchantConnectorAccountType, @@ -2790,6 +2794,7 @@ where key_store, customer, business_profile, + should_retry_with_pan, ) .await?; *payment_data = pd; @@ -2990,6 +2995,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>( frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, is_retry_payment: bool, + should_retry_with_pan: bool, ) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>> where F: Send + Clone + Sync, @@ -4705,6 +4711,7 @@ pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<(D, TokenizationAction)> where F: Send + Clone, @@ -4776,6 +4783,7 @@ where merchant_key_store, customer, business_profile, + should_retry_with_pan, ) .await?; payment_data.set_payment_method_data(payment_method_data); @@ -4795,6 +4803,7 @@ where merchant_key_store, customer, business_profile, + should_retry_with_pan, ) .await?; @@ -4883,6 +4892,7 @@ where merchant_key_store, customer, business_profile, + false, ) .await?; payment_data.set_payment_method_data(payment_method_data); @@ -4950,6 +4960,7 @@ where pub service_details: Option<api_models::payments::CtpServiceDetails>, pub card_testing_guard_data: Option<hyperswitch_domain_models::card_testing_guard_data::CardTestingGuardData>, + pub vault_operation: Option<domain_payments::VaultOperation>, } #[derive(Clone, serde::Serialize, Debug)] @@ -7190,7 +7201,6 @@ pub async fn payment_external_authentication<F: Clone + Sync>( &payment_intent, &key_store, storage_scheme, - &business_profile, ) .await? .ok_or(errors::ApiErrorResponse::InternalServerError) @@ -7603,6 +7613,9 @@ pub trait OperationSessionGetters<F> { fn get_force_sync(&self) -> Option<bool>; fn get_capture_method(&self) -> Option<enums::CaptureMethod>; + #[cfg(feature = "v1")] + fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>; + #[cfg(feature = "v2")] fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>; } @@ -7647,6 +7660,9 @@ pub trait OperationSessionSetters<F> { straight_through_algorithm: serde_json::Value, ); fn set_connector_in_payment_attempt(&mut self, connector: Option<String>); + + #[cfg(feature = "v1")] + fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation); } #[cfg(feature = "v1")] @@ -7779,6 +7795,11 @@ impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> { self.payment_attempt.capture_method } + #[cfg(feature = "v1")] + fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation> { + self.vault_operation.as_ref() + } + // #[cfg(feature = "v2")] // fn get_capture_method(&self) -> Option<enums::CaptureMethod> { // Some(self.payment_intent.capture_method) @@ -7895,6 +7916,10 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> { fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) { self.payment_attempt.connector = connector; } + + fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation) { + self.vault_operation = Some(vault_operation); + } } #[cfg(feature = "v2")] diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 21d84d3cba1..05b4d592c23 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -32,8 +32,8 @@ use hyperswitch_domain_models::{ mandates::MandateData, payment_method_data::{GetPaymentMethodType, PazeWalletData}, payments::{ - payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints, - PaymentIntent, + self as domain_payments, payment_attempt::PaymentAttempt, + payment_intent::PaymentIntentFetchConstraints, PaymentIntent, }, router_data::KlarnaSdkResponse, }; @@ -1988,12 +1988,96 @@ pub async fn retrieve_card_with_permanent_token( todo!() } +pub enum VaultFetchAction { + FetchCardDetailsFromLocker, + FetchCardDetailsForNetworkTransactionIdFlowFromLocker, + FetchNetworkTokenDataFromTokenizationService(String), + FetchNetworkTokenDetailsFromLocker(api_models::payments::NetworkTokenWithNTIRef), + NoFetchAction, +} + +pub fn decide_payment_method_retrieval_action( + is_network_tokenization_enabled: bool, + mandate_id: Option<api_models::payments::MandateIds>, + connector: Option<api_enums::Connector>, + network_tokenization_supported_connectors: &HashSet<api_enums::Connector>, + should_retry_with_pan: bool, + network_token_requestor_ref_id: Option<String>, +) -> VaultFetchAction { + let standard_flow = || { + determine_standard_vault_action( + is_network_tokenization_enabled, + mandate_id, + connector, + network_tokenization_supported_connectors, + network_token_requestor_ref_id, + ) + }; + + should_retry_with_pan + .then_some(VaultFetchAction::FetchCardDetailsFromLocker) + .unwrap_or_else(standard_flow) +} + +pub fn determine_standard_vault_action( + is_network_tokenization_enabled: bool, + mandate_id: Option<api_models::payments::MandateIds>, + connector: Option<api_enums::Connector>, + network_tokenization_supported_connectors: &HashSet<api_enums::Connector>, + network_token_requestor_ref_id: Option<String>, +) -> VaultFetchAction { + let is_network_transaction_id_flow = mandate_id + .as_ref() + .map(|mandate_ids| mandate_ids.is_network_transaction_id_flow()) + .unwrap_or(false); + + if !is_network_tokenization_enabled { + if is_network_transaction_id_flow { + VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker + } else { + VaultFetchAction::FetchCardDetailsFromLocker + } + } else { + match mandate_id { + Some(mandate_ids) => match mandate_ids.mandate_reference_id { + Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(nt_data)) => { + VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) + } + Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { + VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker + } + Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => { + VaultFetchAction::NoFetchAction + } + }, + None => { + //saved card flow + let is_network_token_supported_connector = connector + .map(|conn| network_tokenization_supported_connectors.contains(&conn)) + .unwrap_or(false); + + match ( + is_network_token_supported_connector, + network_token_requestor_ref_id, + ) { + (true, Some(ref_id)) => { + VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(ref_id) + } + (false, Some(_)) | (true, None) | (false, None) => { + VaultFetchAction::FetchCardDetailsFromLocker + } + } + } + } + } +} + #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[allow(clippy::too_many_arguments)] -pub async fn retrieve_card_with_permanent_token( +pub async fn retrieve_payment_method_data_with_permanent_token( state: &SessionState, locker_id: &str, _payment_method_id: &str, @@ -2002,9 +2086,11 @@ pub async fn retrieve_card_with_permanent_token( _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, mandate_id: Option<api_models::payments::MandateIds>, - payment_method_info: Option<domain::PaymentMethod>, + payment_method_info: domain::PaymentMethod, business_profile: &domain::Profile, connector: Option<String>, + should_retry_with_pan: bool, + vault_data: Option<&domain_payments::VaultData>, ) -> RouterResult<domain::PaymentMethodData> { let customer_id = payment_intent .customer_id @@ -2014,238 +2100,176 @@ pub async fn retrieve_card_with_permanent_token( message: "no customer id provided for the payment".to_string(), })?; - if !business_profile.is_network_tokenization_enabled { - let is_network_transaction_id_flow = mandate_id - .map(|mandate_ids| mandate_ids.is_network_transaction_id_flow()) - .unwrap_or(false); + let network_tokenization_supported_connectors = &state + .conf + .network_tokenization_supported_connectors + .connector_list; - if is_network_transaction_id_flow { - let card_details_from_locker = cards::get_card_from_locker( - state, - customer_id, - &payment_intent.merchant_id, - locker_id, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to fetch card details from locker")?; - - let card_network = card_details_from_locker - .card_brand - .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) - .transpose() - .map_err(|e| { - logger::error!("Failed to parse card network {e:?}"); + let connector_variant = connector + .as_ref() + .map(|conn| { + api_enums::Connector::from_str(conn.as_str()) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", }) - .ok() - .flatten(); + .attach_printable_lazy(|| format!("unable to parse connector name {connector:?}")) + }) + .transpose()?; - let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { - card_number: card_details_from_locker.card_number, - card_exp_month: card_details_from_locker.card_exp_month, - card_exp_year: card_details_from_locker.card_exp_year, - card_issuer: None, - card_network, - card_type: None, - card_issuing_country: None, - bank_code: None, - nick_name: card_details_from_locker.nick_name.map(masking::Secret::new), - card_holder_name: card_details_from_locker.name_on_card.clone(), - }; + let vault_fetch_action = decide_payment_method_retrieval_action( + business_profile.is_network_tokenization_enabled, + mandate_id, + connector_variant, + network_tokenization_supported_connectors, + should_retry_with_pan, + payment_method_info + .network_token_requestor_reference_id + .clone(), + ); + match vault_fetch_action { + VaultFetchAction::FetchCardDetailsFromLocker => { + let card = vault_data + .and_then(|vault_data| vault_data.get_card_vault_data()) + .map(Ok) + .async_unwrap_or_else(|| async { + fetch_card_details_from_locker( + state, + customer_id, + &payment_intent.merchant_id, + locker_id, + card_token_data, + ) + .await + }) + .await?; - Ok( - domain::PaymentMethodData::CardDetailsForNetworkTransactionId( - card_details_for_network_transaction_id, - ), - ) - } else { - fetch_card_details_from_locker( + Ok(domain::PaymentMethodData::Card(card)) + } + VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker => { + fetch_card_details_for_network_transaction_flow_from_locker( state, customer_id, &payment_intent.merchant_id, locker_id, - card_token_data, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("failed to fetch card information from the permanent locker") } - } else { - match (payment_method_info, mandate_id) { - (None, _) => Err(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Payment method data is not present"), - (Some(ref pm_data), None) => { - // Regular (non-mandate) Payment flow - let network_tokenization_supported_connectors = &state - .conf - .network_tokenization_supported_connectors - .connector_list; - let connector_variant = connector - .as_ref() - .map(|conn| { - api_enums::Connector::from_str(conn.as_str()) - .change_context(errors::ApiErrorResponse::InvalidDataValue { - field_name: "connector", - }) - .attach_printable_lazy(|| { - format!("unable to parse connector name {connector:?}") - }) - }) - .transpose()?; - if let (Some(_conn), Some(token_ref)) = ( - connector_variant - .filter(|conn| network_tokenization_supported_connectors.contains(conn)), - pm_data.network_token_requestor_reference_id.clone(), - ) { - logger::info!("Fetching network token data from tokenization service"); - match network_tokenization::get_token_from_tokenization_service( - state, token_ref, pm_data, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "failed to fetch network token data from tokenization service", - ) { - Ok(network_token_data) => { - Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) - } - Err(err) => { - logger::info!("Failed to fetch network token data from tokenization service {err:?}"); - logger::info!("Falling back to fetch card details from locker"); - fetch_card_details_from_locker( - state, - customer_id, - &payment_intent.merchant_id, - locker_id, - card_token_data, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "failed to fetch card information from the permanent locker", - ) - } - } - } else { - logger::info!("Either the connector is not in the NT supported list or token requestor reference ID is absent"); - logger::info!("Falling back to fetch card details from locker"); - fetch_card_details_from_locker( - state, - customer_id, - &payment_intent.merchant_id, - locker_id, - card_token_data, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to fetch card information from the permanent locker") + VaultFetchAction::FetchNetworkTokenDataFromTokenizationService( + network_token_requestor_ref_id, + ) => { + logger::info!("Fetching network token data from tokenization service"); + match network_tokenization::get_token_from_tokenization_service( + state, + network_token_requestor_ref_id, + &payment_method_info, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch network token data from tokenization service") + { + Ok(network_token_data) => { + Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) } - } - (Some(ref pm_data), Some(mandate_ids)) => { - // Mandate Payment flow - match mandate_ids.mandate_reference_id { - Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI( - nt_data, - )) => { - { - if let Some(network_token_locker_id) = - pm_data.network_token_locker_id.as_ref() - { - let mut token_data = cards::get_card_from_locker( + Err(err) => { + logger::info!( + "Failed to fetch network token data from tokenization service {err:?}" + ); + logger::info!("Falling back to fetch card details from locker"); + Ok(domain::PaymentMethodData::Card( + vault_data + .and_then(|vault_data| vault_data.get_card_vault_data()) + .map(Ok) + .async_unwrap_or_else(|| async { + fetch_card_details_from_locker( state, customer_id, &payment_intent.merchant_id, - network_token_locker_id, + locker_id, + card_token_data, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "failed to fetch network token information from the permanent locker", - )?; - let expiry = nt_data.token_exp_month.zip(nt_data.token_exp_year); - if let Some((exp_month, exp_year)) = expiry { - token_data.card_exp_month = exp_month; - token_data.card_exp_year = exp_year; - } - let network_token_data = domain::NetworkTokenData { - token_number: token_data.card_number, - token_cryptogram: None, - token_exp_month: token_data.card_exp_month, - token_exp_year: token_data.card_exp_year, - nick_name: token_data.nick_name.map(masking::Secret::new), - card_issuer: None, - card_network: None, - card_type: None, - card_issuing_country: None, - bank_code: None, - eci: None, - }; - Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) - } else { - // Mandate but network token locker id is not present - Err(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Network token locker id is not present") - } - } - } - - Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { - let card_details_from_locker = cards::get_card_from_locker( + }) + .await?, + )) + } + } + } + VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) => { + if let Some(network_token_locker_id) = + payment_method_info.network_token_locker_id.as_ref() + { + let network_token_data = vault_data + .and_then(|vault_data| vault_data.get_network_token_data()) + .map(Ok) + .async_unwrap_or_else(|| async { + fetch_network_token_details_from_locker( state, customer_id, &payment_intent.merchant_id, - locker_id, + network_token_locker_id, + nt_data, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("failed to fetch card details from locker")?; - - let card_network = card_details_from_locker - .card_brand - .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) - .transpose() - .map_err(|e| { - logger::error!("Failed to parse card network {e:?}"); - }) - .ok() - .flatten(); - - let card_details_for_network_transaction_id = hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { - card_number: card_details_from_locker.card_number, - card_exp_month: card_details_from_locker.card_exp_month, - card_exp_year: card_details_from_locker.card_exp_year, - card_issuer: None, - card_network, - card_type: None, - card_issuing_country: None, - bank_code: None, - nick_name: card_details_from_locker.nick_name.map(masking::Secret::new), - card_holder_name: card_details_from_locker.name_on_card, - }; - - Ok( - domain::PaymentMethodData::CardDetailsForNetworkTransactionId( - card_details_for_network_transaction_id, - ), - ) - } - - Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) - | None => Err(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Payment method data is not present"), - } + }) + .await?; + Ok(domain::PaymentMethodData::NetworkToken(network_token_data)) + } else { + Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Network token locker id is not present") } } + VaultFetchAction::NoFetchAction => Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Payment method data is not present"), } } +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] +#[allow(clippy::too_many_arguments)] +pub async fn retrieve_card_with_permanent_token_for_external_authentication( + state: &SessionState, + locker_id: &str, + payment_intent: &PaymentIntent, + card_token_data: Option<&domain::CardToken>, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: enums::MerchantStorageScheme, +) -> RouterResult<domain::PaymentMethodData> { + let customer_id = payment_intent + .customer_id + .as_ref() + .get_required_value("customer_id") + .change_context(errors::ApiErrorResponse::UnprocessableEntity { + message: "no customer id provided for the payment".to_string(), + })?; + Ok(domain::PaymentMethodData::Card( + fetch_card_details_from_locker( + state, + customer_id, + &payment_intent.merchant_id, + locker_id, + card_token_data, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch card information from the permanent locker")?, + )) +} + +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] pub async fn fetch_card_details_from_locker( state: &SessionState, customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, locker_id: &str, card_token_data: Option<&domain::CardToken>, -) -> RouterResult<domain::PaymentMethodData> { +) -> RouterResult<domain::Card> { let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -2290,7 +2314,106 @@ pub async fn fetch_card_details_from_locker( card_issuing_country: None, bank_code: None, }; - Ok(domain::PaymentMethodData::Card(api_card.into())) + Ok(api_card.into()) +} + +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] +pub async fn fetch_network_token_details_from_locker( + state: &SessionState, + customer_id: &id_type::CustomerId, + merchant_id: &id_type::MerchantId, + network_token_locker_id: &str, + network_transaction_data: api_models::payments::NetworkTokenWithNTIRef, +) -> RouterResult<domain::NetworkTokenData> { + let mut token_data = + cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "failed to fetch network token information from the permanent locker", + )?; + let expiry = network_transaction_data + .token_exp_month + .zip(network_transaction_data.token_exp_year); + if let Some((exp_month, exp_year)) = expiry { + token_data.card_exp_month = exp_month; + token_data.card_exp_year = exp_year; + } + + let card_network = token_data + .card_brand + .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) + .transpose() + .map_err(|e| { + logger::error!("Failed to parse card network {e:?}"); + }) + .ok() + .flatten(); + + let network_token_data = domain::NetworkTokenData { + token_number: token_data.card_number, + token_cryptogram: None, + token_exp_month: token_data.card_exp_month, + token_exp_year: token_data.card_exp_year, + nick_name: token_data.nick_name.map(masking::Secret::new), + card_issuer: None, + card_network, + card_type: None, + card_issuing_country: None, + bank_code: None, + eci: None, + }; + Ok(network_token_data) +} + +#[cfg(all( + any(feature = "v2", feature = "v1"), + not(feature = "payment_methods_v2") +))] +pub async fn fetch_card_details_for_network_transaction_flow_from_locker( + state: &SessionState, + customer_id: &id_type::CustomerId, + merchant_id: &id_type::MerchantId, + locker_id: &str, +) -> RouterResult<domain::PaymentMethodData> { + let card_details_from_locker = + cards::get_card_from_locker(state, customer_id, merchant_id, locker_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("failed to fetch card details from locker")?; + + let card_network = card_details_from_locker + .card_brand + .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) + .transpose() + .map_err(|e| { + logger::error!("Failed to parse card network {e:?}"); + }) + .ok() + .flatten(); + + let card_details_for_network_transaction_id = + hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId { + card_number: card_details_from_locker.card_number, + card_exp_month: card_details_from_locker.card_exp_month, + card_exp_year: card_details_from_locker.card_exp_year, + card_issuer: None, + card_network, + card_type: None, + card_issuing_country: None, + bank_code: None, + nick_name: card_details_from_locker.nick_name.map(masking::Secret::new), + card_holder_name: card_details_from_locker.name_on_card.clone(), + }; + + Ok( + domain::PaymentMethodData::CardDetailsForNetworkTransactionId( + card_details_for_network_transaction_id, + ), + ) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -2424,6 +2547,7 @@ pub async fn make_pm_data<'a, F: Clone, R, D>( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] +#[allow(clippy::too_many_arguments)] pub async fn make_pm_data<'a, F: Clone, R, D>( operation: BoxedOperation<'a, F, R, D>, state: &'a SessionState, @@ -2432,11 +2556,15 @@ pub async fn make_pm_data<'a, F: Clone, R, D>( customer: &Option<domain::Customer>, storage_scheme: common_enums::enums::MerchantStorageScheme, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )> { + use super::OperationSessionSetters; + use crate::core::payments::OperationSessionGetters; + let request = payment_data.payment_method_data.clone(); let mut card_token_data = payment_data @@ -2484,6 +2612,12 @@ pub async fn make_pm_data<'a, F: Clone, R, D>( // TODO: Handle case where payment method and token both are present in request properly. let (payment_method, pm_id) = match (&request, payment_data.token_data.as_ref()) { (_, Some(hyperswitch_token)) => { + let existing_vault_data = payment_data.get_vault_operation(); + + let vault_data = existing_vault_data.map(|data| match data { + domain_payments::VaultOperation::ExistingVaultData(vault_data) => vault_data, + }); + let pm_data = Box::pin(payment_methods::retrieve_payment_method_with_token( state, merchant_key_store, @@ -2496,11 +2630,25 @@ pub async fn make_pm_data<'a, F: Clone, R, D>( mandate_id, payment_data.payment_method_info.clone(), business_profile, + should_retry_with_pan, + vault_data, )) .await; let payment_method_details = pm_data.attach_printable("in 'make_pm_data'")?; + if let Some(ref payment_method_data) = payment_method_details.payment_method_data { + let updated_vault_operation = + domain_payments::VaultOperation::get_updated_vault_data( + existing_vault_data, + payment_method_data, + ); + + if let Some(vault_operation) = updated_vault_operation { + payment_data.set_vault_operation(vault_operation); + } + }; + Ok::<_, error_stack::Report<errors::ApiErrorResponse>>( if let Some(payment_method_data) = payment_method_details.payment_method_data { payment_data.payment_attempt.payment_method = @@ -6471,7 +6619,6 @@ pub async fn get_payment_method_details_from_payment_token( payment_intent: &PaymentIntent, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, - business_profile: &domain::Profile, ) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> { let hyperswitch_token = if let Some(token) = payment_attempt.payment_token.clone() { let redis_conn = state @@ -6546,43 +6693,31 @@ pub async fn get_payment_method_details_from_payment_token( .await } - storage::PaymentTokenData::Permanent(card_token) => retrieve_card_with_permanent_token( - state, - &card_token.token, - card_token - .payment_method_id - .as_ref() - .unwrap_or(&card_token.token), - payment_intent, - None, - key_store, - storage_scheme, - None, - None, - business_profile, - payment_attempt.connector.clone(), - ) - .await - .map(|card| Some((card, enums::PaymentMethod::Card))), + storage::PaymentTokenData::Permanent(card_token) => { + retrieve_card_with_permanent_token_for_external_authentication( + state, + &card_token.token, + payment_intent, + None, + key_store, + storage_scheme, + ) + .await + .map(|card| Some((card, enums::PaymentMethod::Card))) + } - storage::PaymentTokenData::PermanentCard(card_token) => retrieve_card_with_permanent_token( - state, - &card_token.token, - card_token - .payment_method_id - .as_ref() - .unwrap_or(&card_token.token), - payment_intent, - None, - key_store, - storage_scheme, - None, - None, - business_profile, - payment_attempt.connector.clone(), - ) - .await - .map(|card| Some((card, enums::PaymentMethod::Card))), + storage::PaymentTokenData::PermanentCard(card_token) => { + retrieve_card_with_permanent_token_for_external_authentication( + state, + &card_token.token, + payment_intent, + None, + key_store, + storage_scheme, + ) + .await + .map(|card| Some((card, enums::PaymentMethod::Card))) + } storage::PaymentTokenData::AuthBankDebit(auth_token) => { retrieve_payment_method_from_auth_service( diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index a1ebaa04152..fde773de8a1 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -261,6 +261,7 @@ pub trait Domain<F: Clone, R, D>: Send + Sync { merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, @@ -557,6 +558,7 @@ where _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, Option<domain::PaymentMethodData>, @@ -651,6 +653,7 @@ where _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::PaymentMethodData>, @@ -756,6 +759,7 @@ where _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::PaymentMethodData>, @@ -840,6 +844,7 @@ where _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index 393d08a68d4..3ab64a1361d 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -201,6 +201,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index d713e7aa567..f5ce637a5ba 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -212,6 +212,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 2a58adb822c..a6c9594eb84 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -261,6 +261,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rs index 93b7ffa6c19..f69dd8de62c 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -247,6 +247,7 @@ impl<F: Clone + Send> Domain<F, PaymentsCaptureRequest, PaymentCaptureData<F>> f _key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index fab2a9144c7..2dc118a60fe 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -355,6 +355,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let customer_details = Some(CustomerDetails { @@ -412,6 +413,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<( CompleteAuthorizeOperation<'a, F>, Option<domain::PaymentMethodData>, @@ -425,6 +427,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for customer, storage_scheme, business_profile, + should_retry_with_pan, )) .await?; Ok((op, payment_method_data, pm_id)) diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 852e51f4a8e..556954155e8 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -827,6 +827,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> session_id: None, service_details: request.ctp_service_details.clone(), card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -909,6 +910,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<( PaymentConfirmOperation<'a, F>, Option<domain::PaymentMethodData>, @@ -922,6 +924,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for customer, storage_scheme, business_profile, + should_retry_with_pan, )) .await?; utils::when(payment_method_data.is_none(), || { diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 40b1918323c..a5b0e6eb65e 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -321,6 +321,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConf key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 06036c4bc59..7211b88a10a 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -626,6 +626,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -777,6 +778,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<( PaymentCreateOperation<'a, F>, Option<domain::PaymentMethodData>, @@ -790,6 +792,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for customer, storage_scheme, business_profile, + should_retry_with_pan, )) .await } diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index 1cd0010bdf6..755c4e153ce 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -258,6 +258,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsCreateIntentRequest, payments::Pa _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsCreateIntentOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index fdf5350bed8..f15990d67b9 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -251,6 +251,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusDat _key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( BoxedConfirmOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 0041209eb0f..05f939ee31b 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -190,6 +190,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsGetIntentRequest, payments::Payme _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsGetIntentOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index 0a3efc92ccd..45a659c85b5 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -170,6 +170,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), @@ -214,6 +215,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsPostSessionTokensRequest, Pa _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentPostSessionTokensOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index 91317dbde68..1d919fc45bd 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -199,6 +199,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index a86ca0be4ef..5833ec3e87a 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -217,6 +217,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -339,6 +340,7 @@ where _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentSessionOperation<'b, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index 9bca88c6d04..b2ab23223d7 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -197,6 +197,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsSessionRequest, payments::Payment _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsCreateIntentOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index ebae54e1220..8023f9ed959 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -204,6 +204,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -311,6 +312,7 @@ where merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<( PaymentSessionOperation<'a, F>, Option<domain::PaymentMethodData>, @@ -331,6 +333,7 @@ where customer, storage_scheme, business_profile, + should_retry_with_pan, )) .await } else { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index e05eed41419..bcfe90367d7 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -95,6 +95,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentStatusOperation<'a, F, api::PaymentsRequest>, Option<domain::PaymentMethodData>, @@ -535,6 +536,7 @@ async fn get_tracker_for_sync< session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 89a94552bc2..e7cc8a41b85 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -496,6 +496,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -646,6 +647,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<( PaymentUpdateOperation<'a, F>, Option<domain::PaymentMethodData>, @@ -659,6 +661,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for customer, storage_scheme, business_profile, + should_retry_with_pan, )) .await } diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index af6b7d57838..7662c07eee0 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -419,6 +419,7 @@ impl<F: Clone + Send> Domain<F, PaymentsUpdateIntentRequest, payments::PaymentIn _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentsUpdateIntentOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 8ef656599a7..cdd823483e2 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -178,6 +178,7 @@ impl<F: Send + Clone + Sync> session_id: None, service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { @@ -348,6 +349,7 @@ impl<F: Clone + Send + Sync> _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentIncrementalAuthorizationOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs index 0d31c4d5de1..aac91e20c10 100644 --- a/crates/router/src/core/payments/operations/tax_calculation.rs +++ b/crates/router/src/core/payments/operations/tax_calculation.rs @@ -184,6 +184,7 @@ impl<F: Send + Clone + Sync> session_id: request.session_id.clone(), service_details: None, card_testing_guard_data: None, + vault_operation: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), @@ -338,6 +339,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsDynamicTaxCalculationRequest _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, + _should_retry_with_pan: bool, ) -> RouterResult<( PaymentSessionUpdateOperation<'a, F>, Option<domain::PaymentMethodData>, diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs index d113cfd55de..5fdf14dbf5a 100644 --- a/crates/router/src/core/payments/retry.rs +++ b/crates/router/src/core/payments/retry.rs @@ -35,7 +35,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, D>( req_state: ReqState, payment_data: &mut D, mut connectors: IntoIter<api::ConnectorData>, - original_connector_data: api::ConnectorData, + original_connector_data: &api::ConnectorData, mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, @@ -110,6 +110,7 @@ where true, frm_suggestion, business_profile, + false, //should_retry_with_pan is not applicable for step-up ) .await?; } @@ -140,12 +141,29 @@ where break; } - let connector = super::get_connector_data(&mut connectors)?; + let is_network_token = payment_data + .get_payment_method_data() + .map(|pmd| pmd.is_network_token_payment_method_data()) + .unwrap_or(false); + + let should_retry_with_pan = is_network_token + && initial_gsm + .as_ref() + .map(|gsm| gsm.clear_pan_possible) + .unwrap_or(false) + && business_profile.is_clear_pan_retries_enabled; + + let connector = if should_retry_with_pan { + // If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector. + original_connector_data.clone() + } else { + super::get_connector_data(&mut connectors)? + }; router_data = do_retry( &state.clone(), req_state.clone(), - connector, + &connector, operation, customer, merchant_account, @@ -158,6 +176,7 @@ where false, frm_suggestion, business_profile, + should_retry_with_pan, ) .await?; @@ -297,7 +316,7 @@ fn get_flow_name<F>() -> RouterResult<String> { pub async fn do_retry<F, ApiRequest, FData, D>( state: &routes::SessionState, req_state: ReqState, - connector: api::ConnectorData, + connector: &api::ConnectorData, operation: &operations::BoxedOperation<'_, F, ApiRequest, D>, customer: &Option<domain::Customer>, merchant_account: &domain::MerchantAccount, @@ -309,6 +328,7 @@ pub async fn do_retry<F, ApiRequest, FData, D>( is_step_up: bool, frm_suggestion: Option<storage_enums::FrmSuggestion>, business_profile: &domain::Profile, + should_retry_with_pan: bool, ) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>> where F: Clone + Send + Sync, @@ -341,7 +361,7 @@ where req_state, merchant_account, key_store, - connector, + connector.clone(), operation, payment_data, customer, @@ -352,6 +372,7 @@ where frm_suggestion, business_profile, true, + should_retry_with_pan, ) .await?; diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 2852766cdd3..67e8990e113 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -187,6 +187,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { card_testing_guard_config: item .card_testing_guard_config .map(ForeignInto::foreign_into), + is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, }) } } @@ -261,6 +262,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { card_testing_guard_config: item .card_testing_guard_config .map(ForeignInto::foreign_into), + is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled, }) } } @@ -435,5 +437,6 @@ pub async fn create_profile_from_merchant_account( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("error while generating card testing secret key")?, + is_clear_pan_retries_enabled: request.is_clear_pan_retries_enabled.unwrap_or_default(), })) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 8938461eec4..1035aed2f99 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1838,6 +1838,7 @@ impl ForeignFrom<gsm_api_types::GsmCreateRequest> for storage::GatewayStatusMapp unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, + clear_pan_possible: value.clear_pan_possible, } } } @@ -1857,6 +1858,7 @@ impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { unified_code: value.unified_code, unified_message: value.unified_message, error_category: value.error_category, + clear_pan_possible: value.clear_pan_possible, } } } diff --git a/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/down.sql b/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/down.sql new file mode 100644 index 00000000000..80199b9a334 --- /dev/null +++ b/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE gateway_status_map DROP COLUMN IF EXISTS clear_pan_possible; \ No newline at end of file diff --git a/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/up.sql b/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/up.sql new file mode 100644 index 00000000000..4423df380c4 --- /dev/null +++ b/migrations/2024-12-10-091820_add-clear-pan-possible-to-gsm/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE gateway_status_map ADD COLUMN IF NOT EXISTS clear_pan_possible BOOLEAN NOT NULL DEFAULT FALSE; \ No newline at end of file diff --git a/migrations/2025-02-27-171444_add-clear-pan-retries-enabled-to-profile/down.sql b/migrations/2025-02-27-171444_add-clear-pan-retries-enabled-to-profile/down.sql new file mode 100644 index 00000000000..ac61e6b3dca --- /dev/null +++ b/migrations/2025-02-27-171444_add-clear-pan-retries-enabled-to-profile/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE business_profile DROP COLUMN IF EXISTS is_clear_pan_retries_enabled; \ No newline at end of file diff --git a/migrations/2025-02-27-171444_add-clear-pan-retries-enabled-to-profile/up.sql b/migrations/2025-02-27-171444_add-clear-pan-retries-enabled-to-profile/up.sql new file mode 100644 index 00000000000..9a877729291 --- /dev/null +++ b/migrations/2025-02-27-171444_add-clear-pan-retries-enabled-to-profile/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS is_clear_pan_retries_enabled BOOLEAN NOT NULL DEFAULT FALSE; \ No newline at end of file
2024-12-19T21:16:38Z
## 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 to retry a transaction with clear PAN or Network Token - added support for clear pan retry with same connector when previous attempt failed with payment method data - network token. - refactored `make_pm_data` which does fetch payment method data from locker and construction of payment method data domain types. - refactored `make_pm_data` for reducing locker calls during retries. by adding vault_data which holds payment method data from previous attempt. ### 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? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> test cases - 1 - enable network tokenization, auto retries for profile 2 - make a setup future usage= on_session payment. 3 - make saved card payment (with payment token) (payment will happen with network token + cryptogram) with adyen, if it fails, a retry will happen with card data fetched from locker with same connector. verification - 2 payment attempts will be created for that payment intent id. 1st attempt payment method data would be network token and 2nd would be card Curl for test case added to the [issue](https://github.com/juspay/hyperswitch/issues/6925) ## 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
b71571d16ca4553e1c7eca17f00df24945479638
juspay/hyperswitch
juspay__hyperswitch-6886
Bug: [BUG] fix cypress test cases for adyenplatform ### Bug Description Cypress test cases for adyenplatform (Payout specific test cases) are failing. ### Expected Behavior They should be successfully executed. ### Actual Behavior They're failing while doing a status check in the expected response and actual response. Expected - `success` Actual - `initiated` Fix - update expected response to be `initiated` ### 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!
2024-12-19T07:03:39Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description This PR fixes the cypress payout test cases for 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 Helps in enabling the Adyenplatform connector for payout cypress test cases as a part of Github CI checks. ## How did you test it? Locally. <img width="845" alt="Screenshot 2024-12-19 at 12 33 27 PM" src="https://github.com/user-attachments/assets/e9cd904d-c9a7-4b1e-93e9-5c78ae705a4e" /> ## 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
4bc88a71903bbb06cc757569b4c20d2d63f9d245
juspay/hyperswitch
juspay__hyperswitch-6898
Bug: add api model changes for /relay endpoint /relay is a api that will be used to just forward the request sent by merchant without performing any application logic on it. In this pr the changes is particular to support the refunds for the payments that was directly performed with the connector (example stripe) with out hyperswitch involved during the payment flow.
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index a28332e7fea..2d1e87ebf01 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -31,6 +31,7 @@ pub mod poll; #[cfg(feature = "recon")] pub mod recon; pub mod refunds; +pub mod relay; pub mod routing; pub mod surcharge_decision_configs; pub mod user; diff --git a/crates/api_models/src/relay.rs b/crates/api_models/src/relay.rs new file mode 100644 index 00000000000..7e094f28360 --- /dev/null +++ b/crates/api_models/src/relay.rs @@ -0,0 +1,103 @@ +pub use common_utils::types::MinorUnit; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use crate::enums; + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +pub struct RelayRequest { + /// The identifier that is associated to a resource at the connector to which the relay request is being made + #[schema(example = "7256228702616471803954")] + pub connector_resource_id: String, + /// Identifier of the connector ( merchant connector account ) to which relay request is being made + #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] + pub connector_id: common_utils::id_type::MerchantConnectorAccountId, + /// The type of relay request + #[serde(rename = "type")] + pub relay_type: RelayType, + /// The data that is associated with the relay request + pub data: Option<RelayData>, +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RelayType { + /// The relay request is for a refund + Refund, +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +#[serde(rename_all = "snake_case", untagged)] +pub enum RelayData { + /// The data that is associated with a refund relay request + Refund(RelayRefundRequest), +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +pub struct RelayRefundRequest { + /// The amount that is being refunded + #[schema(value_type = i64 , example = 6540)] + pub amount: MinorUnit, + /// The currency in which the amount is being refunded + #[schema(value_type = Currency)] + pub currency: enums::Currency, + /// The reason for the refund + #[schema(max_length = 255, example = "Customer returned the product")] + pub reason: Option<String>, +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +pub struct RelayResponse { + /// The unique identifier for the Relay + #[schema(example = "relay_mbabizu24mvu3mela5njyhpit4", value_type = String)] + pub id: common_utils::id_type::RelayId, + /// The status of the relay request + pub status: RelayStatus, + /// The reference identifier provided by the connector for the relay request + #[schema(example = "pi_3MKEivSFNglxLpam0ZaL98q9")] + pub connector_reference_id: Option<String>, + /// The error details if the relay request failed + pub error: Option<RelayError>, + /// The identifier that is associated to a resource at the connector to which the relay request is being made + #[schema(example = "7256228702616471803954")] + pub connector_resource_id: String, + /// Identifier of the connector ( merchant connector account ) to which relay request is being made + #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] + pub connector_id: common_utils::id_type::MerchantConnectorAccountId, + /// The business profile that is associated with this relay request + #[schema(example = "pro_abcdefghijklmnopqrstuvwxyz", value_type = String)] + pub profile_id: common_utils::id_type::ProfileId, + /// The type of relay request + #[serde(rename = "type")] + pub relay_type: RelayType, + /// The data that is associated with the relay request + pub data: Option<RelayData>, +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum RelayStatus { + /// The relay request is successful + Success, + /// The relay request is being processed + Processing, + /// The relay request has failed + Failure, +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +pub struct RelayError { + /// The error code + pub code: String, + /// The error message + pub message: String, +} + +#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] +pub struct RelayRetrieveRequest { + /// The unique identifier for the Relay + #[serde(default)] + pub force_sync: bool, + /// The unique identifier for the Relay + pub id: String, +} diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 594078bb405..c7393155226 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -11,6 +11,7 @@ mod organization; mod payment; mod profile; mod refunds; +mod relay; mod routing; mod tenant; @@ -43,6 +44,7 @@ pub use self::{ payment::{PaymentId, PaymentReferenceId}, profile::ProfileId, refunds::RefundReferenceId, + relay::RelayId, routing::RoutingId, tenant::TenantId, }; diff --git a/crates/common_utils/src/id_type/relay.rs b/crates/common_utils/src/id_type/relay.rs new file mode 100644 index 00000000000..5db48c492f9 --- /dev/null +++ b/crates/common_utils/src/id_type/relay.rs @@ -0,0 +1,7 @@ +crate::id_type!( + RelayId, + "A type for relay_id that can be used for relay ids" +); +crate::impl_id_type_methods!(RelayId, "relay_id"); + +crate::impl_debug_id_type!(RelayId); diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 65c76f8929f..94bc84814bc 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -84,6 +84,10 @@ Never share your secret api keys. Keep them guarded and secure. routes::payments::payments_complete_authorize, routes::payments::payments_post_session_tokens, + // Routes for relay + routes::relay, + routes::relay_retrieve, + // Routes for refunds routes::refunds::refunds_create, routes::refunds::refunds_retrieve, @@ -515,6 +519,13 @@ 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::relay::RelayRequest, + api_models::relay::RelayType, + api_models::relay::RelayData, + api_models::relay::RelayRefundRequest, + api_models::relay::RelayResponse, + api_models::relay::RelayStatus, + api_models::relay::RelayError, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse, diff --git a/crates/openapi/src/routes.rs b/crates/openapi/src/routes.rs index 453f7f557d3..2c1c5824412 100644 --- a/crates/openapi/src/routes.rs +++ b/crates/openapi/src/routes.rs @@ -16,10 +16,11 @@ pub mod payouts; pub mod poll; pub mod profile; pub mod refunds; +pub mod relay; pub mod routing; pub mod webhook_events; pub use self::{ customers::*, mandates::*, merchant_account::*, merchant_connector_account::*, organization::*, - payment_method::*, payments::*, poll::*, refunds::*, routing::*, webhook_events::*, + payment_method::*, payments::*, poll::*, refunds::*, relay::*, routing::*, webhook_events::*, }; diff --git a/crates/openapi/src/routes/relay.rs b/crates/openapi/src/routes/relay.rs new file mode 100644 index 00000000000..9100bf47f75 --- /dev/null +++ b/crates/openapi/src/routes/relay.rs @@ -0,0 +1,57 @@ +/// Relay - Create +/// +/// Creates a relay request. +#[utoipa::path( + post, + path = "/relay", + request_body( + content = RelayRequest, + examples(( + "Create a relay request" = ( + value = json!({ + "connector_resource_id": "7256228702616471803954", + "connector_id": "mca_5apGeP94tMts6rg3U3kR", + "type": "refund", + "data": { + "amount": 6540, + "currency": "USD" + } + }) + ) + )) + ), + responses( + (status = 200, description = "Relay request", body = RelayResponse), + (status = 400, description = "Invalid data") + ), + params( + ("X-Profile-Id" = String, Header, description = "Profile ID for authentication"), + ("X-Idempotency-Key" = String, Header, description = "Idempotency Key for relay request") + ), + tag = "Relay", + operation_id = "Relay Request", + security(("api_key" = [])) +)] + +pub async fn relay() {} + +/// Relay - Retrieve +/// +/// Retrieves a relay details. +#[utoipa::path( + get, + path = "/relay/{relay_id}", + params (("id" = String, Path, description = "The unique identifier for the Relay")), + responses( + (status = 200, description = "Relay Retrieved", body = RelayResponse), + (status = 404, description = "Relay details was not found") + ), + params( + ("X-Profile-Id" = String, Header, description = "Profile ID for authentication") + ), + tag = "Relay", + operation_id = "Retrieve a Relay details", + security(("api_key" = []), ("ephemeral_key" = [])) +)] + +pub async fn relay_retrieve() {}
2024-12-18T06:00: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 --> /relay is a api that will be used to just forward the request sent my merchant without performing any application logic on it. In this pr the changes is particular to support the refunds for the payments that was directly performed with the connector (example stripe) with out hyperswitch involved during the payment flow. ### 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). --> ## 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="1675" alt="image" src="https://github.com/user-attachments/assets/246da847-274c-4d1e-b441-07326e4a6d00" /> <img width="1721" alt="image" src="https://github.com/user-attachments/assets/0cb733ee-562d-4994-b57c-289296fff720" /> ## 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
dcd51a7fb8df673cc74130ee732542b55783602f
juspay/hyperswitch
juspay__hyperswitch-6892
Bug: feat(email): Local SMTP server Add mailhog by default in docker-compose for local smtp server.
diff --git a/config/docker_compose.toml b/config/docker_compose.toml index cfdf4b0e0c2..4296a5931dc 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -55,9 +55,9 @@ master_enc_key = "73ad7bbbbc640c845a150f67d058b279849370cd2c1f3c67c4dd6c869213e1 password_validity_in_days = 90 two_factor_auth_expiry_in_secs = 300 totp_issuer_name = "Hyperswitch" -base_url = "http://localhost:8080" +base_url = "http://localhost:9000" force_two_factor_auth = false -force_cookies = true +force_cookies = false [locker] host = "" @@ -572,6 +572,7 @@ authentication_analytics_topic = "hyperswitch-authentication-events" [analytics] source = "sqlx" +forex_enabled = false # Enable or disable forex conversion for analytics [analytics.clickhouse] username = "default" @@ -695,7 +696,7 @@ connector_list = "cybersource" sender_email = "[email protected]" # 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 = "NO_EMAIL_CLIENT" # The currently active email client +active_email_client = "SMTP" # The currently active email client recon_recipient_email = "[email protected]" # Recipient email for recon request email prod_intent_recipient_email = "[email protected]" # Recipient email for prod intent email @@ -707,6 +708,13 @@ sts_role_session_name = "" # An identifier for the assumed role session, used to [theme.storage] file_storage_backend = "file_system" # Theme storage backend to be used +# Configuration for smtp, applicable when the active email client is SMTP +[email.smtp] +host = "mailhog" # SMTP host +port = 1025 # SMTP port +timeout = 10 # Timeout for SMTP connection in seconds +connection = "plaintext" #currently plaintext and starttls are supported + [theme.email_config] entity_name = "Hyperswitch" # Name of the entity to be showed in emails entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails diff --git a/docker-compose.yml b/docker-compose.yml index 7450a650119..4bc08b09f63 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -51,6 +51,14 @@ services: environment: # format -> postgresql://DB_USER:DB_PASSWORD@HOST:PORT/DATABASE_NAME - DATABASE_URL=postgresql://db_user:db_pass@pg:5432/hyperswitch_db + + mailhog: + image: mailhog/mailhog + networks: + - router_net + ports: + - "1025:1025" + - "8025:8025" ### Application services hyperswitch-server:
2024-12-18T04:38:10Z
## 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 --> Add support to run local email server in docker-compose. User can see the email we send even in local setup ### 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 --> - [ ] 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
e35f7079e3fc9ada76d0602739053bdd5d595008
juspay/hyperswitch
juspay__hyperswitch-6883
Bug: feat(core): setup platform merchant account - Setup platform merchant account. Platform merchant account is a special type of merchant account which can do operations on behalf of other merchant account present in the same organisation. - Add APIs to create a platform merchant account / convert a merchant account into platform account. - Feature should be disabled in sandbox and production.
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 7fdc0c6d5e8..65ce1fdbc0a 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -428,3 +428,6 @@ card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] connector_list = "cybersource" + +[platform] +enabled = true diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 9c91c12f3b4..8900b0ac385 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -444,3 +444,6 @@ card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] connector_list = "cybersource" + +[platform] +enabled = false diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 152f4f04cd8..ae4afb2ec3f 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -446,3 +446,6 @@ card_networks = "Visa, AmericanExpress, Mastercard" [network_tokenization_supported_connectors] connector_list = "cybersource" + +[platform] +enabled = false diff --git a/config/development.toml b/config/development.toml index 133823d6cb3..7e3c3c8ba07 100644 --- a/config/development.toml +++ b/config/development.toml @@ -830,3 +830,6 @@ entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be foreground_color = "#000000" # Foreground color of email text primary_color = "#006DF9" # Primary color of email body background_color = "#FFFFFF" # Background color of email body + +[platform] +enabled = true diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 1ad2ef91336..09b27d6bd7f 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -710,3 +710,6 @@ entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be foreground_color = "#000000" # Foreground color of email text primary_color = "#006DF9" # Primary color of email body background_color = "#FFFFFF" # Background color of email body + +[platform] +enabled = true diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 12d51311e87..b5c2bc28572 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -51,6 +51,7 @@ pub struct MerchantAccount { pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, + pub is_platform_account: bool, } #[cfg(feature = "v1")] @@ -83,6 +84,7 @@ pub struct MerchantAccountSetter { pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, + pub is_platform_account: bool, } #[cfg(feature = "v1")] @@ -117,6 +119,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, + is_platform_account: item.is_platform_account, } } } @@ -148,6 +151,7 @@ pub struct MerchantAccount { pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, pub id: common_utils::id_type::MerchantId, + pub is_platform_account: bool, } #[cfg(feature = "v2")] @@ -165,6 +169,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { organization_id: item.organization_id, recon_status: item.recon_status, version: item.version, + is_platform_account: item.is_platform_account, } } } @@ -182,6 +187,7 @@ pub struct MerchantAccountSetter { pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: storage_enums::ReconStatus, pub version: common_enums::ApiVersion, + pub is_platform_account: bool, } impl MerchantAccount { @@ -228,6 +234,7 @@ pub struct MerchantAccountNew { pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, + pub is_platform_account: bool, } #[cfg(feature = "v2")] @@ -244,6 +251,7 @@ pub struct MerchantAccountNew { pub recon_status: storage_enums::ReconStatus, pub id: common_utils::id_type::MerchantId, pub version: common_enums::ApiVersion, + pub is_platform_account: bool, } #[cfg(feature = "v2")] @@ -258,6 +266,7 @@ pub struct MerchantAccountUpdateInternal { pub modified_at: time::PrimitiveDateTime, pub organization_id: Option<common_utils::id_type::OrganizationId>, pub recon_status: Option<storage_enums::ReconStatus>, + pub is_platform_account: Option<bool>, } #[cfg(feature = "v2")] @@ -272,6 +281,7 @@ impl MerchantAccountUpdateInternal { modified_at, organization_id, recon_status, + is_platform_account, } = self; MerchantAccount { @@ -286,6 +296,7 @@ impl MerchantAccountUpdateInternal { recon_status: recon_status.unwrap_or(source.recon_status), version: source.version, id: source.id, + is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), } } } @@ -319,6 +330,7 @@ pub struct MerchantAccountUpdateInternal { pub recon_status: Option<storage_enums::ReconStatus>, pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, + pub is_platform_account: Option<bool>, } #[cfg(feature = "v1")] @@ -350,6 +362,7 @@ impl MerchantAccountUpdateInternal { recon_status, payment_link_config, pm_collect_link_config, + is_platform_account, } = self; MerchantAccount { @@ -385,6 +398,7 @@ impl MerchantAccountUpdateInternal { payment_link_config: payment_link_config.or(source.payment_link_config), pm_collect_link_config: pm_collect_link_config.or(source.pm_collect_link_config), version: source.version, + is_platform_account: is_platform_account.unwrap_or(source.is_platform_account), } } } diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 8b834ee5d82..20c14d0dd10 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -74,6 +74,7 @@ pub struct PaymentIntent { pub id: common_utils::id_type::GlobalPaymentId, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, + pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, } #[cfg(feature = "v1")] @@ -140,6 +141,7 @@ pub struct PaymentIntent { pub skip_external_tax_calculation: Option<bool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, + pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)] @@ -300,6 +302,7 @@ pub struct PaymentIntentNew { pub enable_payment_link: Option<bool>, pub apply_mit_exemption: Option<bool>, pub id: common_utils::id_type::GlobalPaymentId, + pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, } #[cfg(feature = "v1")] @@ -366,6 +369,7 @@ pub struct PaymentIntentNew { pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, + pub platform_merchant_id: Option<common_utils::id_type::MerchantId>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 366c917d2d1..95bb714cb71 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -717,6 +717,7 @@ diesel::table! { payment_link_config -> Nullable<Jsonb>, pm_collect_link_config -> Nullable<Jsonb>, version -> ApiVersion, + is_platform_account -> Bool, } } @@ -970,6 +971,8 @@ diesel::table! { skip_external_tax_calculation -> Nullable<Bool>, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, + #[max_length = 64] + platform_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index fcfe05e5731..9faf3830605 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -708,6 +708,7 @@ diesel::table! { version -> ApiVersion, #[max_length = 64] id -> Varchar, + is_platform_account -> Bool, } } @@ -933,6 +934,8 @@ diesel::table! { id -> Varchar, psd2_sca_exemption_type -> Nullable<ScaExemptionType>, split_payments -> Nullable<Jsonb>, + #[max_length = 64] + platform_merchant_id -> Nullable<Varchar>, } } diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index 850cc470316..6fa9f9450c8 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -279,7 +279,10 @@ pub enum ApiErrorResponse { message = "Cookies are not found in the request" )] CookieNotFound, - + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_43", message = "API does not support platform account operation")] + PlatformAccountAuthNotSupported, + #[error(error_type = ErrorType::InvalidRequestError, code = "IR_44", message = "Invalid platform account operation")] + InvalidPlatformOperation, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] WebhookAuthenticationFailed, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")] @@ -667,6 +670,12 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon ..Default::default() }) )), + Self::PlatformAccountAuthNotSupported => { + AER::BadRequest(ApiError::new("IR", 43, "API does not support platform operation", None)) + } + Self::InvalidPlatformOperation => { + AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None)) + } } } } diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index a6d2114f0fe..c42b0005513 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -47,6 +47,7 @@ pub struct MerchantAccount { pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, + pub is_platform_account: bool, } #[cfg(feature = "v1")] @@ -81,6 +82,7 @@ pub struct MerchantAccountSetter { pub payment_link_config: Option<serde_json::Value>, pub pm_collect_link_config: Option<serde_json::Value>, pub version: common_enums::ApiVersion, + pub is_platform_account: bool, } #[cfg(feature = "v1")] @@ -115,6 +117,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, + is_platform_account: item.is_platform_account, } } } @@ -133,6 +136,7 @@ pub struct MerchantAccountSetter { pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, + pub is_platform_account: bool, } #[cfg(feature = "v2")] @@ -149,6 +153,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { modified_at, organization_id, recon_status, + is_platform_account, } = item; Self { id, @@ -161,6 +166,7 @@ impl From<MerchantAccountSetter> for MerchantAccount { modified_at, organization_id, recon_status, + is_platform_account, } } } @@ -178,6 +184,7 @@ pub struct MerchantAccount { pub modified_at: time::PrimitiveDateTime, pub organization_id: common_utils::id_type::OrganizationId, pub recon_status: diesel_models::enums::ReconStatus, + pub is_platform_account: bool, } impl MerchantAccount { @@ -233,6 +240,7 @@ pub enum MerchantAccountUpdate { }, UnsetDefaultProfile, ModifiedAtUpdate, + ToPlatformAccount, } #[cfg(feature = "v2")] @@ -252,6 +260,7 @@ pub enum MerchantAccountUpdate { recon_status: diesel_models::enums::ReconStatus, }, ModifiedAtUpdate, + ToPlatformAccount, } #[cfg(feature = "v1")] @@ -307,6 +316,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { organization_id: None, is_recon_enabled: None, recon_status: None, + is_platform_account: None, }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { storage_scheme: Some(storage_scheme), @@ -334,6 +344,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { recon_status: None, payment_link_config: None, pm_collect_link_config: None, + is_platform_account: None, }, MerchantAccountUpdate::ReconUpdate { recon_status } => Self { recon_status: Some(recon_status), @@ -361,6 +372,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { default_profile: None, payment_link_config: None, pm_collect_link_config: None, + is_platform_account: None, }, MerchantAccountUpdate::UnsetDefaultProfile => Self { default_profile: Some(None), @@ -388,6 +400,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { recon_status: None, payment_link_config: None, pm_collect_link_config: None, + is_platform_account: None, }, MerchantAccountUpdate::ModifiedAtUpdate => Self { modified_at: now, @@ -415,6 +428,35 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { recon_status: None, payment_link_config: None, pm_collect_link_config: None, + is_platform_account: None, + }, + MerchantAccountUpdate::ToPlatformAccount => Self { + modified_at: now, + merchant_name: None, + merchant_details: None, + return_url: None, + webhook_details: None, + sub_merchants_enabled: None, + parent_merchant_id: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + publishable_key: None, + storage_scheme: None, + locker_id: None, + metadata: None, + routing_algorithm: None, + primary_business_details: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + organization_id: None, + is_recon_enabled: None, + default_profile: None, + recon_status: None, + payment_link_config: None, + pm_collect_link_config: None, + is_platform_account: Some(true), }, } } @@ -440,6 +482,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { storage_scheme: None, organization_id: None, recon_status: None, + is_platform_account: None, }, MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self { storage_scheme: Some(storage_scheme), @@ -450,6 +493,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { metadata: None, organization_id: None, recon_status: None, + is_platform_account: None, }, MerchantAccountUpdate::ReconUpdate { recon_status } => Self { recon_status: Some(recon_status), @@ -460,6 +504,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { storage_scheme: None, metadata: None, organization_id: None, + is_platform_account: None, }, MerchantAccountUpdate::ModifiedAtUpdate => Self { modified_at: now, @@ -470,6 +515,18 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { metadata: None, organization_id: None, recon_status: None, + is_platform_account: None, + }, + MerchantAccountUpdate::ToPlatformAccount => Self { + modified_at: now, + merchant_name: None, + merchant_details: None, + publishable_key: None, + storage_scheme: None, + metadata: None, + organization_id: None, + recon_status: None, + is_platform_account: Some(true), }, } } @@ -495,6 +552,7 @@ impl super::behaviour::Conversion for MerchantAccount { organization_id: self.organization_id, recon_status: self.recon_status, version: crate::consts::API_VERSION, + is_platform_account: self.is_platform_account, }; Ok(diesel_models::MerchantAccount::from(setter)) @@ -554,6 +612,7 @@ impl super::behaviour::Conversion for MerchantAccount { modified_at: item.modified_at, organization_id: item.organization_id, recon_status: item.recon_status, + is_platform_account: item.is_platform_account, }) } .await @@ -575,6 +634,7 @@ impl super::behaviour::Conversion for MerchantAccount { organization_id: self.organization_id, recon_status: self.recon_status, version: crate::consts::API_VERSION, + is_platform_account: self.is_platform_account, }) } } @@ -614,6 +674,7 @@ impl super::behaviour::Conversion for MerchantAccount { payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, version: self.version, + is_platform_account: self.is_platform_account, }; Ok(diesel_models::MerchantAccount::from(setter)) @@ -691,6 +752,7 @@ impl super::behaviour::Conversion for MerchantAccount { payment_link_config: item.payment_link_config, pm_collect_link_config: item.pm_collect_link_config, version: item.version, + is_platform_account: item.is_platform_account, }) } .await @@ -729,6 +791,7 @@ impl super::behaviour::Conversion for MerchantAccount { payment_link_config: self.payment_link_config, pm_collect_link_config: self.pm_collect_link_config, version: crate::consts::API_VERSION, + is_platform_account: self.is_platform_account, }) } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 1c88b83d087..095b4c33a46 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -109,6 +109,7 @@ pub struct PaymentIntent { pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: Option<bool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, + pub platform_merchant_id: Option<id_type::MerchantId>, } impl PaymentIntent { @@ -365,6 +366,8 @@ pub struct PaymentIntent { pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>, /// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile. pub routing_algorithm_id: Option<id_type::RoutingId>, + /// Identifier for the platform merchant. + pub platform_merchant_id: Option<id_type::MerchantId>, } #[cfg(feature = "v2")] @@ -411,6 +414,7 @@ impl PaymentIntent { profile: &business_profile::Profile, request: api_models::payments::PaymentsCreateIntentRequest, decrypted_payment_intent: DecryptedPaymentIntent, + platform_merchant_id: Option<&merchant_account::MerchantAccount>, ) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> { let connector_metadata = request .get_connector_metadata_as_value() @@ -504,6 +508,8 @@ impl PaymentIntent { .payment_link_config .map(ApiModelToDieselModelConvertor::convert_from), routing_algorithm_id: request.routing_algorithm_id, + platform_merchant_id: platform_merchant_id + .map(|merchant_account| merchant_account.get_id().to_owned()), }) } } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index cbd3a8137ca..953d39c131a 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1326,6 +1326,7 @@ impl behaviour::Conversion for PaymentIntent { customer_present, routing_algorithm_id, payment_link_config, + platform_merchant_id, } = self; Ok(DieselPaymentIntent { skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()), @@ -1396,6 +1397,7 @@ impl behaviour::Conversion for PaymentIntent { payment_link_config, routing_algorithm_id, psd2_sca_exemption_type: None, + platform_merchant_id, split_payments: None, }) } @@ -1522,6 +1524,7 @@ impl behaviour::Conversion for PaymentIntent { customer_present: storage_model.customer_present.into(), payment_link_config: storage_model.payment_link_config, routing_algorithm_id: storage_model.routing_algorithm_id, + platform_merchant_id: storage_model.platform_merchant_id, }) } .await @@ -1594,6 +1597,7 @@ impl behaviour::Conversion for PaymentIntent { tax_details: amount_details.tax_details, enable_payment_link: Some(self.enable_payment_link.as_bool()), apply_mit_exemption: Some(self.apply_mit_exemption.as_bool()), + platform_merchant_id: self.platform_merchant_id, }) } } @@ -1660,6 +1664,7 @@ impl behaviour::Conversion for PaymentIntent { tax_details: self.tax_details, skip_external_tax_calculation: self.skip_external_tax_calculation, psd2_sca_exemption_type: self.psd2_sca_exemption_type, + platform_merchant_id: self.platform_merchant_id, }) } @@ -1748,6 +1753,7 @@ impl behaviour::Conversion for PaymentIntent { organization_id: storage_model.organization_id, skip_external_tax_calculation: storage_model.skip_external_tax_calculation, psd2_sca_exemption_type: storage_model.psd2_sca_exemption_type, + platform_merchant_id: storage_model.platform_merchant_id, }) } .await @@ -1812,6 +1818,7 @@ impl behaviour::Conversion for PaymentIntent { tax_details: self.tax_details, skip_external_tax_calculation: self.skip_external_tax_calculation, psd2_sca_exemption_type: self.psd2_sca_exemption_type, + platform_merchant_id: self.platform_merchant_id, }) } } diff --git a/crates/router/build.rs b/crates/router/build.rs index b33c168833d..7c8043c48ad 100644 --- a/crates/router/build.rs +++ b/crates/router/build.rs @@ -1,8 +1,8 @@ fn main() { - // Set thread stack size to 8 MiB for debug builds + // Set thread stack size to 10 MiB for debug builds // Reference: https://doc.rust-lang.org/std/thread/#stack-size #[cfg(debug_assertions)] - println!("cargo:rustc-env=RUST_MIN_STACK=8388608"); // 8 * 1024 * 1024 = 8 MiB + println!("cargo:rustc-env=RUST_MIN_STACK=10485760"); // 10 * 1024 * 1024 = 10 MiB #[cfg(feature = "vergen")] router_env::vergen::generate_cargo_instructions(); diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 6cf078b5f81..630d4dfdca0 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -278,6 +278,10 @@ pub enum StripeErrorCode { InvalidTenant, #[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")] AmountConversionFailed { amount_type: &'static str }, + #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")] + PlatformBadRequest, + #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")] + PlatformUnauthorizedRequest, // [#216]: https://github.com/juspay/hyperswitch/issues/216 // Implement the remaining stripe error codes @@ -678,6 +682,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { errors::ApiErrorResponse::AmountConversionFailed { amount_type } => { Self::AmountConversionFailed { amount_type } } + errors::ApiErrorResponse::PlatformAccountAuthNotSupported => Self::PlatformBadRequest, + errors::ApiErrorResponse::InvalidPlatformOperation => Self::PlatformUnauthorizedRequest, } } } @@ -687,7 +693,7 @@ impl actix_web::ResponseError for StripeErrorCode { use reqwest::StatusCode; match self { - Self::Unauthorized => StatusCode::UNAUTHORIZED, + Self::Unauthorized | Self::PlatformUnauthorizedRequest => StatusCode::UNAUTHORIZED, Self::InvalidRequestUrl | Self::GenericNotFoundError { .. } => StatusCode::NOT_FOUND, Self::ParameterUnknown { .. } | Self::HyperswitchUnprocessableEntity { .. } => { StatusCode::UNPROCESSABLE_ENTITY @@ -751,6 +757,7 @@ impl actix_web::ResponseError for StripeErrorCode { | Self::CurrencyConversionFailed | Self::PaymentMethodDeleteFailed | Self::ExtendedCardInfoNotFound + | Self::PlatformBadRequest | Self::LinkConfigurationError { .. } => StatusCode::BAD_REQUEST, Self::RefundFailed | Self::PayoutFailed diff --git a/crates/router/src/compatibility/stripe/payment_intents.rs b/crates/router/src/compatibility/stripe/payment_intents.rs index 5bbb4e7cf22..6652f42ee00 100644 --- a/crates/router/src/compatibility/stripe/payment_intents.rs +++ b/crates/router/src/compatibility/stripe/payment_intents.rs @@ -92,6 +92,7 @@ pub async fn payment_intents_create( payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -162,6 +163,7 @@ pub async fn payment_intents_retrieve( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, @@ -240,6 +242,7 @@ pub async fn payment_intents_retrieve_with_gateway_creds( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, @@ -316,6 +319,7 @@ pub async fn payment_intents_update( payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, @@ -401,6 +405,7 @@ pub async fn payment_intents_confirm( payments::CallConnectorAction::Trigger, eligible_connectors, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, @@ -472,6 +477,7 @@ pub async fn payment_intents_capture( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -547,6 +553,7 @@ pub async fn payment_intents_cancel( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, diff --git a/crates/router/src/compatibility/stripe/setup_intents.rs b/crates/router/src/compatibility/stripe/setup_intents.rs index 919ced993aa..6dde49b0d62 100644 --- a/crates/router/src/compatibility/stripe/setup_intents.rs +++ b/crates/router/src/compatibility/stripe/setup_intents.rs @@ -78,6 +78,7 @@ pub async fn setup_intents_create( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -148,6 +149,7 @@ pub async fn setup_intents_retrieve( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, @@ -224,6 +226,7 @@ pub async fn setup_intents_update( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, @@ -301,6 +304,7 @@ pub async fn setup_intents_confirm( payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 3862f70536f..7b74aca7647 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -546,5 +546,6 @@ pub(crate) async fn fetch_raw_secrets( network_tokenization_service, network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors, theme: conf.theme, + platform: conf.platform, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index ccd43d25b8e..ad5d9e89aaa 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -129,6 +129,12 @@ pub struct Settings<S: SecretState> { pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>, pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, pub theme: ThemeSettings, + pub platform: Platform, +} + +#[derive(Debug, Deserialize, Clone, Default)] +pub struct Platform { + pub enabled: bool, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index ccb563b0610..05aaf99421b 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -402,6 +402,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { payment_link_config: None, pm_collect_link_config, version: hyperswitch_domain_models::consts::API_VERSION, + is_platform_account: false, }, ) } @@ -669,6 +670,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { modified_at: date_time::now(), organization_id: organization.get_organization_id(), recon_status: diesel_models::enums::ReconStatus::NotRequested, + is_platform_account: false, }), ) } @@ -4769,3 +4771,35 @@ async fn locker_recipient_create_call( Ok(store_resp.card_reference) } + +pub async fn enable_platform_account( + state: SessionState, + merchant_id: id_type::MerchantId, +) -> RouterResponse<()> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + let key_store = db + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &merchant_id, + &db.get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; + + db.update_merchant( + key_manager_state, + merchant_account, + storage::MerchantAccountUpdate::ToPlatformAccount, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error while enabling platform merchant account") + .map(|_| services::ApplicationResponse::StatusOk) +} diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs index 70c35b460e8..99a60817303 100644 --- a/crates/router/src/core/fraud_check.rs +++ b/crates/router/src/core/fraud_check.rs @@ -588,6 +588,7 @@ pub async fn post_payment_frm_core<'a, F, D>( customer: &Option<domain::Customer>, key_store: domain::MerchantKeyStore, should_continue_capture: &mut bool, + platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<Option<FrmData>> where F: Send + Clone, @@ -647,6 +648,7 @@ where payment_data, customer, should_continue_capture, + platform_merchant_account, ) .await?; logger::debug!("frm_post_tasks_data: {:?}", frm_data); diff --git a/crates/router/src/core/fraud_check/operation.rs b/crates/router/src/core/fraud_check/operation.rs index d802339b675..721afaa1e49 100644 --- a/crates/router/src/core/fraud_check/operation.rs +++ b/crates/router/src/core/fraud_check/operation.rs @@ -85,6 +85,7 @@ pub trait Domain<F, D>: Send + Sync { _payment_data: &mut D, _customer: &Option<domain::Customer>, _should_continue_capture: &mut bool, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<Option<FrmData>> where F: Send + Clone, diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs index 308a00ffa1d..69f06e59416 100644 --- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs +++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs @@ -226,6 +226,7 @@ where _payment_data: &mut D, _customer: &Option<domain::Customer>, _should_continue_capture: &mut bool, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<Option<FrmData>> { todo!() } @@ -244,6 +245,7 @@ where payment_data: &mut D, customer: &Option<domain::Customer>, _should_continue_capture: &mut bool, + platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<Option<FrmData>> { if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Fraud) && matches!( @@ -277,6 +279,7 @@ where payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + platform_merchant_account.cloned(), )) .await?; logger::debug!("payment_id : {:?} has been cancelled since it has been found fraudulent by configured frm connector",payment_data.get_payment_attempt().payment_id); @@ -334,6 +337,7 @@ where payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + platform_merchant_account.cloned(), )) .await?; logger::debug!("payment_id : {:?} has been captured since it has been found legit by configured frm connector",payment_data.get_payment_attempt().payment_id); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e68bd09ba46..535a6b72bd6 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -242,6 +242,7 @@ pub async fn payments_operation_core<F, Req, Op, FData, D>( auth_flow: services::AuthFlow, eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>, header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, @@ -286,6 +287,7 @@ where &key_store, auth_flow, &header_payload, + platform_merchant_account.as_ref(), ) .await?; core_utils::validate_profile_id_from_auth_layer( @@ -716,6 +718,7 @@ where &customer, key_store.clone(), &mut should_continue_capture, + platform_merchant_account.as_ref(), )) .await?; } @@ -823,8 +826,8 @@ pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>( req: Req, call_connector_action: CallConnectorAction, auth_flow: services::AuthFlow, - header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, @@ -869,6 +872,7 @@ where &key_store, auth_flow, &header_payload, + platform_merchant_account.as_ref(), ) .await?; @@ -1021,6 +1025,7 @@ pub async fn payments_intent_operation_core<F, Req, Op, D>( req: Req, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>)> where F: Send + Clone + Sync, @@ -1048,6 +1053,7 @@ where &profile, &key_store, &header_payload, + platform_merchant_account.as_ref(), ) .await?; @@ -1339,6 +1345,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, D>( call_connector_action: CallConnectorAction, eligible_connectors: Option<Vec<enums::Connector>>, header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, @@ -1377,6 +1384,7 @@ where auth_flow, eligible_routable_connectors, header_payload.clone(), + platform_merchant_account, ) .await?; @@ -1406,6 +1414,7 @@ pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>( auth_flow: services::AuthFlow, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, @@ -1437,6 +1446,7 @@ where call_connector_action, auth_flow, header_payload.clone(), + platform_merchant_account, ) .await?; @@ -1465,6 +1475,7 @@ pub async fn payments_intent_core<F, Res, Req, Op, D>( req: Req, payment_id: id_type::GlobalPaymentId, header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, @@ -1483,6 +1494,7 @@ where req, payment_id, header_payload.clone(), + platform_merchant_account, ) .await?; @@ -1556,6 +1568,7 @@ where &profile, &key_store, &header_payload, + None, ) .await?; @@ -1624,9 +1637,11 @@ pub trait PaymentRedirectFlow: Sync { connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse>; #[cfg(feature = "v2")] + #[allow(clippy::too_many_arguments)] async fn call_payment_flow( &self, state: &SessionState, @@ -1635,6 +1650,7 @@ pub trait PaymentRedirectFlow: Sync { merchant_key_store: domain::MerchantKeyStore, profile: domain::Profile, req: PaymentsRedirectResponseData, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse>; fn get_payment_action(&self) -> services::PaymentAction; @@ -1661,6 +1677,7 @@ pub trait PaymentRedirectFlow: Sync { merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, req: PaymentsRedirectResponseData, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, @@ -1715,6 +1732,7 @@ pub trait PaymentRedirectFlow: Sync { flow_type, connector.clone(), resource_id.clone(), + platform_merchant_account, ) .await?; @@ -1722,6 +1740,7 @@ pub trait PaymentRedirectFlow: Sync { } #[cfg(feature = "v2")] + #[allow(clippy::too_many_arguments)] async fn handle_payments_redirect_response( &self, state: SessionState, @@ -1730,6 +1749,7 @@ pub trait PaymentRedirectFlow: Sync { key_store: domain::MerchantKeyStore, profile: domain::Profile, request: PaymentsRedirectResponseData, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<api::RedirectionResponse> { metrics::REDIRECTION_TRIGGERED.add( 1, @@ -1744,6 +1764,7 @@ pub trait PaymentRedirectFlow: Sync { key_store, profile, request, + platform_merchant_account, ) .await?; @@ -1770,6 +1791,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); @@ -1805,6 +1827,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { connector_action, None, HeaderPayload::default(), + platform_merchant_account, )) .await?; let payments_response = match response { @@ -1910,6 +1933,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { connector_action: CallConnectorAction, _connector: String, _payment_id: id_type::PaymentId, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let key_manager_state = &state.into(); @@ -1942,6 +1966,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { connector_action, None, HeaderPayload::default(), + platform_merchant_account, ), ) .await?; @@ -2031,6 +2056,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { merchant_key_store: domain::MerchantKeyStore, profile: domain::Profile, req: PaymentsRedirectResponseData, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let payment_id = req.payment_id.clone(); @@ -2057,6 +2083,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync { &profile, &merchant_key_store, &HeaderPayload::default(), + platform_merchant_account.as_ref(), ) .await?; @@ -2168,6 +2195,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { connector_action: CallConnectorAction, connector: String, payment_id: id_type::PaymentId, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<Self::PaymentFlowResponse> { let merchant_id = merchant_account.get_id().clone(); let key_manager_state = &state.into(); @@ -2267,6 +2295,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { connector_action, None, HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), + platform_merchant_account, )) .await? } else { @@ -2299,6 +2328,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { connector_action, None, HeaderPayload::default(), + platform_merchant_account, ), ) .await? diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index c243686a76c..eda869c3a6c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -3614,6 +3614,7 @@ mod tests { tax_details: None, skip_external_tax_calculation: None, psd2_sca_exemption_type: None, + platform_merchant_id: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok()); @@ -3684,6 +3685,7 @@ mod tests { tax_details: None, skip_external_tax_calculation: None, psd2_sca_exemption_type: None, + platform_merchant_id: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err()) @@ -3752,6 +3754,7 @@ mod tests { tax_details: None, skip_external_tax_calculation: None, psd2_sca_exemption_type: None, + platform_merchant_id: None, }; let req_cs = Some("1".to_string()); assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err()) diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 38911bb2d6d..4adb9403418 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -190,6 +190,7 @@ pub trait GetTracker<F: Clone, D, R>: Send { mechant_key_store: &domain::MerchantKeyStore, auth_flow: services::AuthFlow, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<GetTrackerResponse<'a, F, R, D>>; #[cfg(feature = "v2")] @@ -203,6 +204,7 @@ pub trait GetTracker<F: Clone, D, R>: Send { profile: &domain::Profile, mechant_key_store: &domain::MerchantKeyStore, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<GetTrackerResponse<D>>; } diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index a5993eb2f01..c830b7618d0 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -45,6 +45,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>, > { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 427c10aab62..c6679e481f1 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -46,6 +46,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>, > { diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index f8d304bcb79..ebe49f59f64 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -45,6 +45,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, diff --git a/crates/router/src/core/payments/operations/payment_capture_v2.rs b/crates/router/src/core/payments/operations/payment_capture_v2.rs index 0ee62ea73c1..81ffa8e992f 100644 --- a/crates/router/src/core/payments/operations/payment_capture_v2.rs +++ b/crates/router/src/core/payments/operations/payment_capture_v2.rs @@ -142,6 +142,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentCaptureData<F>, PaymentsCaptureReques _profile: &domain::Profile, key_store: &domain::MerchantKeyStore, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<PaymentCaptureData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 914ddf251ef..72c04c6a549 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -48,6 +48,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>> { let db = &*state.store; diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 96406932445..c309685a6a2 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -77,6 +77,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> key_store: &domain::MerchantKeyStore, auth_flow: services::AuthFlow, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>> { let key_manager_state = &state.into(); diff --git a/crates/router/src/core/payments/operations/payment_confirm_intent.rs b/crates/router/src/core/payments/operations/payment_confirm_intent.rs index 374a33026da..71d99d03e41 100644 --- a/crates/router/src/core/payments/operations/payment_confirm_intent.rs +++ b/crates/router/src/core/payments/operations/payment_confirm_intent.rs @@ -158,6 +158,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfir profile: &domain::Profile, key_store: &domain::MerchantKeyStore, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 36b338f2d52..b7b3420987d 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -78,6 +78,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> merchant_key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>> { let db = &*state.store; @@ -304,6 +305,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> attempt_id, profile_id.clone(), session_expiry, + platform_merchant_account, ) .await?; @@ -1308,6 +1310,7 @@ impl PaymentCreate { active_attempt_id: String, profile_id: common_utils::id_type::ProfileId, session_expiry: PrimitiveDateTime, + platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<storage::PaymentIntent> { let created_at @ modified_at @ last_synced = common_utils::date_time::now(); @@ -1494,6 +1497,8 @@ impl PaymentCreate { tax_details, skip_external_tax_calculation, psd2_sca_exemption_type: request.psd2_sca_exemption_type, + platform_merchant_id: platform_merchant_account + .map(|platform_merchant_account| platform_merchant_account.get_id().to_owned()), }) } diff --git a/crates/router/src/core/payments/operations/payment_create_intent.rs b/crates/router/src/core/payments/operations/payment_create_intent.rs index f9cdd192f18..1cd0010bdf6 100644 --- a/crates/router/src/core/payments/operations/payment_create_intent.rs +++ b/crates/router/src/core/payments/operations/payment_create_intent.rs @@ -99,6 +99,7 @@ impl<F: Send + Clone + Sync> profile: &domain::Profile, key_store: &domain::MerchantKeyStore, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); @@ -137,6 +138,7 @@ impl<F: Send + Clone + Sync> profile, request.clone(), encrypted_data, + platform_merchant_account, ) .await?; diff --git a/crates/router/src/core/payments/operations/payment_get.rs b/crates/router/src/core/payments/operations/payment_get.rs index 403ee544314..6419376f090 100644 --- a/crates/router/src/core/payments/operations/payment_get.rs +++ b/crates/router/src/core/payments/operations/payment_get.rs @@ -119,6 +119,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetriev _profile: &domain::Profile, key_store: &domain::MerchantKeyStore, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<PaymentStatusData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); diff --git a/crates/router/src/core/payments/operations/payment_get_intent.rs b/crates/router/src/core/payments/operations/payment_get_intent.rs index 16b44436c18..3cc26e7b67f 100644 --- a/crates/router/src/core/payments/operations/payment_get_intent.rs +++ b/crates/router/src/core/payments/operations/payment_get_intent.rs @@ -89,6 +89,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme _profile: &domain::Profile, key_store: &domain::MerchantKeyStore, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs index 7337f080884..0e189583d0a 100644 --- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -45,6 +45,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index a6a10be8e9a..e5321b1f984 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -43,6 +43,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>> { let db = &*state.store; diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index f93327b275c..0e94fbe09c6 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -44,6 +44,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest, PaymentData<F>>, > { diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rs index 2454b9fcbf3..ec59ba3473e 100644 --- a/crates/router/src/core/payments/operations/payment_session_intent.rs +++ b/crates/router/src/core/payments/operations/payment_session_intent.rs @@ -101,6 +101,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, Payme _profile: &domain::Profile, key_store: &domain::MerchantKeyStore, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index a895855cefc..1da9a1a2264 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -43,6 +43,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsStartRequest, PaymentData<F>>, > { diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 9aa905345c8..dd28043ba2b 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -213,6 +213,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieve key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>, > { diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index c75794dd17f..0e60407aa7c 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -56,6 +56,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> key_store: &domain::MerchantKeyStore, auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>> { let (mut payment_intent, mut payment_attempt, currency): (_, _, storage_enums::Currency); diff --git a/crates/router/src/core/payments/operations/payment_update_intent.rs b/crates/router/src/core/payments/operations/payment_update_intent.rs index f8ce03d558e..4782d237e21 100644 --- a/crates/router/src/core/payments/operations/payment_update_intent.rs +++ b/crates/router/src/core/payments/operations/payment_update_intent.rs @@ -135,6 +135,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpda _profile: &domain::Profile, key_store: &domain::MerchantKeyStore, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs index 035c4e8e2ec..2c816ad39d1 100644 --- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs +++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs @@ -48,6 +48,7 @@ impl<F: Send + Clone + Sync> key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs index 859422920e1..5b9c90f3add 100644 --- a/crates/router/src/core/payments/operations/tax_calculation.rs +++ b/crates/router/src/core/payments/operations/tax_calculation.rs @@ -50,6 +50,7 @@ impl<F: Send + Clone + Sync> key_store: &domain::MerchantKeyStore, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, + _platform_merchant_account: Option<&domain::MerchantAccount>, ) -> RouterResult< operations::GetTrackerResponse< 'a, diff --git a/crates/router/src/core/payments/session_operation.rs b/crates/router/src/core/payments/session_operation.rs index d7b6ad0d345..40a2717fea7 100644 --- a/crates/router/src/core/payments/session_operation.rs +++ b/crates/router/src/core/payments/session_operation.rs @@ -42,6 +42,7 @@ pub async fn payments_session_core<F, Res, Req, Op, FData, D>( payment_id: id_type::GlobalPaymentId, call_connector_action: CallConnectorAction, header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResponse<Res> where F: Send + Clone + Sync, @@ -71,6 +72,7 @@ where payment_id, call_connector_action, header_payload.clone(), + platform_merchant_account, ) .await?; @@ -100,6 +102,7 @@ pub async fn payments_session_operation_core<F, Req, Op, FData, D>( payment_id: id_type::GlobalPaymentId, _call_connector_action: CallConnectorAction, header_payload: HeaderPayload, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)> where F: Send + Clone + Sync, @@ -132,6 +135,7 @@ where &profile, &key_store, &header_payload, + platform_merchant_account.as_ref(), ) .await?; diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 73d9cfdcaee..ff9849958b5 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -617,6 +617,7 @@ async fn payments_incoming_webhook_flow( consume_or_trigger_flow.clone(), None, HeaderPayload::default(), + None, //Platform merchant account )) .await; // When mandate details are present in successful webhooks, and consuming webhooks are skipped during payment sync if the payment status is already updated to charged, this function is used to update the connector mandate details. @@ -1159,6 +1160,7 @@ async fn external_authentication_incoming_webhook_flow( payments::CallConnectorAction::Trigger, None, HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator), + None, // Platform merchant account )) .await?; match payments_response { @@ -1356,6 +1358,7 @@ async fn frm_incoming_webhook_flow( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + None, // Platform merchant account )) .await? } @@ -1385,6 +1388,7 @@ async fn frm_incoming_webhook_flow( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + None, // Platform merchant account )) .await? } @@ -1543,6 +1547,7 @@ async fn bank_transfer_webhook_flow( payments::CallConnectorAction::Trigger, None, HeaderPayload::with_source(common_enums::PaymentSource::Webhook), + None, //Platform merchant account )) .await } else { diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 625a4d9c95b..9ed724c36ef 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -90,6 +90,7 @@ pub mod headers { pub const X_REDIRECT_URI: &str = "x-redirect-uri"; pub const X_TENANT_ID: &str = "x-tenant-id"; pub const X_CLIENT_SECRET: &str = "X-Client-Secret"; + pub const X_CONNECTED_MERCHANT_ID: &str = "x-connected-merchant-id"; pub const X_RESOURCE_TYPE: &str = "X-Resource-Type"; } diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index a57fd56e6c8..9557aabbe81 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -910,3 +910,26 @@ pub async fn merchant_account_transfer_keys( )) .await } + +/// Merchant Account - Platform Account +/// +/// Enable platform account +#[instrument(skip_all)] +pub async fn merchant_account_enable_platform_account( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<common_utils::id_type::MerchantId>, +) -> HttpResponse { + let flow = Flow::EnablePlatformAccount; + let merchant_id = path.into_inner(); + Box::pin(api::server_wrap( + flow, + state, + &req, + merchant_id, + |state, _, req, _| enable_platform_account(state, req), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 2decddb806c..5865c1014fb 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1337,8 +1337,7 @@ impl MerchantAccount { #[cfg(all(feature = "olap", feature = "v1"))] impl MerchantAccount { pub fn server(state: AppState) -> Scope { - web::scope("/accounts") - .app_data(web::Data::new(state)) + let mut routes = web::scope("/accounts") .service(web::resource("").route(web::post().to(admin::merchant_account_create))) .service(web::resource("/list").route(web::get().to(admin::merchant_account_list))) .service( @@ -1358,7 +1357,14 @@ impl MerchantAccount { .route(web::get().to(admin::retrieve_merchant_account)) .route(web::post().to(admin::update_merchant_account)) .route(web::delete().to(admin::delete_merchant_account)), + ); + if state.conf.platform.enabled { + routes = routes.service( + web::resource("/{id}/platform") + .route(web::post().to(admin::merchant_account_enable_platform_account)), ) + } + routes.app_data(web::Data::new(state)) } } diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 4b43c42f3bc..198692ac2d6 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -48,7 +48,8 @@ impl From<Flow> for ApiIdentifier { | Flow::MerchantsAccountUpdate | Flow::MerchantsAccountDelete | Flow::MerchantTransferKey - | Flow::MerchantAccountList => Self::MerchantAccount, + | Flow::MerchantAccountList + | Flow::EnablePlatformAccount => Self::MerchantAccount, Flow::OrganizationCreate | Flow::OrganizationRetrieve | Flow::OrganizationUpdate => { Self::Organization diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index a9005644beb..46f6a5e492a 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -85,6 +85,7 @@ pub async fn payments_create( header_payload.clone(), req, api::AuthFlow::Merchant, + auth.platform_merchant_account, ) }, match env::which() { @@ -143,6 +144,7 @@ pub async fn payments_create_intent( req, global_payment_id.clone(), header_payload.clone(), + auth.platform_merchant_account, ) }, match env::which() { @@ -206,6 +208,7 @@ pub async fn payments_get_intent( req, global_payment_id.clone(), header_payload.clone(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -261,6 +264,7 @@ pub async fn payments_update_intent( req.payload, global_payment_id.clone(), header_payload.clone(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -316,6 +320,7 @@ pub async fn payments_start( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + None, ) }, &auth::MerchantIdAuth(merchant_id), @@ -390,6 +395,7 @@ pub async fn payments_retrieve( payments::CallConnectorAction::Trigger, None, header_payload.clone(), + auth.platform_merchant_account, ) }, auth::auth_type( @@ -460,6 +466,7 @@ pub async fn payments_retrieve_with_gateway_creds( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + auth.platform_merchant_account, ) }, &*auth_type, @@ -512,6 +519,7 @@ pub async fn payments_update( HeaderPayload::default(), req, auth_flow, + auth.platform_merchant_account, ) }, &*auth_type, @@ -570,6 +578,7 @@ pub async fn payments_post_session_tokens( payments::CallConnectorAction::Trigger, None, header_payload.clone(), + None, ) }, &auth::PublishableKeyAuth, @@ -632,6 +641,7 @@ pub async fn payments_confirm( header_payload.clone(), req, auth_flow, + auth.platform_merchant_account, ) }, &*auth_type, @@ -684,6 +694,7 @@ pub async fn payments_capture( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -743,6 +754,7 @@ pub async fn payments_dynamic_tax_calculation( payments::CallConnectorAction::Trigger, None, header_payload.clone(), + None, ) }, &auth::PublishableKeyAuth, @@ -806,6 +818,7 @@ pub async fn payments_connector_session( payment_id, payments::CallConnectorAction::Trigger, header_payload.clone(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::PublishableKeyAuth), @@ -864,6 +877,7 @@ pub async fn payments_connector_session( payments::CallConnectorAction::Trigger, None, header_payload.clone(), + None, ) }, &auth::HeaderAuth(auth::PublishableKeyAuth), @@ -913,7 +927,7 @@ pub async fn payments_redirect_response( auth.merchant_account, auth.key_store, req, - + auth.platform_merchant_account, ) }, &auth::MerchantIdAuth(merchant_id), @@ -963,7 +977,7 @@ pub async fn payments_redirect_response_with_creds_identifier( auth.merchant_account, auth.key_store, req, - + auth.platform_merchant_account, ) }, &auth::MerchantIdAuth(merchant_id), @@ -1014,7 +1028,7 @@ pub async fn payments_complete_authorize_redirect( auth.merchant_account, auth.key_store, req, - + auth.platform_merchant_account, ) }, &auth::MerchantIdAuth(merchant_id), @@ -1080,6 +1094,7 @@ pub async fn payments_complete_authorize( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + None, ) }, &*auth_type, @@ -1129,6 +1144,7 @@ pub async fn payments_cancel( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -1409,6 +1425,7 @@ pub async fn payments_approve( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + auth.platform_merchant_account, ) }, match env::which() { @@ -1473,6 +1490,7 @@ pub async fn payments_reject( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + auth.platform_merchant_account, ) }, match env::which() { @@ -1502,6 +1520,7 @@ async fn authorize_verify_select<Op>( header_payload: HeaderPayload, req: api_models::payments::PaymentsRequest, auth_flow: api::AuthFlow, + platform_merchant_account: Option<domain::MerchantAccount>, ) -> errors::RouterResponse<api_models::payments::PaymentsResponse> where Op: Sync @@ -1551,6 +1570,7 @@ where auth_flow, payments::CallConnectorAction::Trigger, header_payload, + platform_merchant_account, ) .await } else { @@ -1578,6 +1598,7 @@ where payments::CallConnectorAction::Trigger, eligible_connectors, header_payload, + platform_merchant_account, ) .await } @@ -1601,6 +1622,7 @@ where payments::CallConnectorAction::Trigger, eligible_connectors, header_payload, + platform_merchant_account, ) .await } @@ -1649,6 +1671,7 @@ pub async fn payments_incremental_authorization( payments::CallConnectorAction::Trigger, None, HeaderPayload::default(), + auth.platform_merchant_account, ) }, &auth::HeaderAuth(auth::ApiKeyAuth), @@ -1734,6 +1757,7 @@ pub async fn post_3ds_payments_authorize( auth.merchant_account, auth.key_store, req, + auth.platform_merchant_account, ) }, &auth::MerchantIdAuth(merchant_id), @@ -2437,6 +2461,7 @@ pub async fn payments_finish_redirection( auth.key_store, auth.profile, req, + auth.platform_merchant_account ) }, &auth::PublishableKeyAndProfileIdAuth { diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index e5412c20fe2..d35e321a7be 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -63,6 +63,7 @@ mod detached; #[derive(Clone, Debug)] pub struct AuthenticationData { pub merchant_account: domain::MerchantAccount, + pub platform_merchant_account: Option<domain::MerchantAccount>, pub key_store: domain::MerchantKeyStore, pub profile_id: Option<id_type::ProfileId>, } @@ -73,6 +74,7 @@ pub struct AuthenticationData { pub merchant_account: domain::MerchantAccount, pub key_store: domain::MerchantKeyStore, pub profile: domain::Profile, + pub platform_merchant_account: Option<domain::MerchantAccount>, } #[derive(Clone, Debug)] @@ -466,6 +468,28 @@ where .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account + let (merchant, platform_merchant_account) = if state.conf().platform.enabled { + get_platform_merchant_account(state, request_headers, merchant).await? + } else { + (merchant, None) + }; + + let key_store = if platform_merchant_account.is_some() { + state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant.get_id(), + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")? + } else { + key_store + }; + let profile = state .store() .find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id) @@ -474,6 +498,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account, key_store, profile, }; @@ -563,8 +588,31 @@ where .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account + let (merchant, platform_merchant_account) = if state.conf().platform.enabled { + get_platform_merchant_account(state, request_headers, merchant).await? + } else { + (merchant, None) + }; + + let key_store = if platform_merchant_account.is_some() { + state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant.get_id(), + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")? + } else { + key_store + }; + let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account, key_store, profile_id, }; @@ -639,7 +687,8 @@ where merchant_id: Some(merchant_id), key_id: Some(key_id), } => { - let auth = construct_authentication_data(state, &merchant_id).await?; + let auth = + construct_authentication_data(state, &merchant_id, request_headers).await?; Ok(( auth.clone(), AuthenticationType::ApiKey { @@ -653,7 +702,8 @@ where merchant_id: Some(merchant_id), key_id: None, } => { - let auth = construct_authentication_data(state, &merchant_id).await?; + let auth = + construct_authentication_data(state, &merchant_id, request_headers).await?; Ok(( auth.clone(), AuthenticationType::PublishableKey { @@ -716,6 +766,7 @@ where let auth_data_v2 = AuthenticationData { merchant_account: auth_data.merchant_account, + platform_merchant_account: auth_data.platform_merchant_account, key_store: auth_data.key_store, profile, }; @@ -727,9 +778,10 @@ where async fn construct_authentication_data<A>( state: &A, merchant_id: &id_type::MerchantId, + request_headers: &HeaderMap, ) -> RouterResult<AuthenticationData> where - A: SessionStateInfo, + A: SessionStateInfo + Sync, { let key_store = state .store() @@ -752,8 +804,31 @@ where .await .to_not_found_response(errors::ApiErrorResponse::Unauthorized)?; + // Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account + let (merchant, platform_merchant_account) = if state.conf().platform.enabled { + get_platform_merchant_account(state, request_headers, merchant).await? + } else { + (merchant, None) + }; + + let key_store = if platform_merchant_account.is_some() { + state + .store() + .get_merchant_key_store_by_merchant_id( + &(&state.session_state()).into(), + merchant.get_id(), + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")? + } else { + key_store + }; + let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account, key_store, profile_id: None, }; @@ -1003,6 +1078,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: None, }; @@ -1025,6 +1101,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1063,6 +1143,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( @@ -1084,6 +1165,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1182,6 +1267,34 @@ impl<'a> HeaderMapStruct<'a> { ) }) } + + pub fn get_id_type_from_header_if_present<T>(&self, key: &str) -> RouterResult<Option<T>> + where + T: TryFrom< + std::borrow::Cow<'static, str>, + Error = error_stack::Report<errors::ValidationError>, + >, + { + self.headers + .get(key) + .map(|value| value.to_str()) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "`{key}` in headers", + }) + .attach_printable(format!( + "Failed to convert header value to string for header key: {}", + key + ))? + .map(|value| { + T::try_from(std::borrow::Cow::Owned(value.to_owned())).change_context( + errors::ApiErrorResponse::InvalidRequestData { + message: format!("`{}` header is invalid", key), + }, + ) + }) + .transpose() + } } /// Get the merchant-id from `x-merchant-id` header @@ -1225,6 +1338,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: None, }; @@ -1246,6 +1360,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1286,6 +1404,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( auth, @@ -1306,6 +1425,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + AdminApiAuth .authenticate_and_fetch(request_headers, state) .await?; @@ -1418,9 +1541,13 @@ where { async fn authenticate_and_fetch( &self, - _request_headers: &HeaderMap, + request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -1440,6 +1567,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: None, }; @@ -1463,6 +1591,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + let key_manager_state = &(&state.session_state()).into(); let profile_id = get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)? @@ -1497,6 +1629,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( auth.clone(), @@ -1525,6 +1658,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + let key_manager_state = &(&state.session_state()).into(); let key_store = state .store() @@ -1556,6 +1693,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( auth.clone(), @@ -1615,6 +1753,7 @@ where merchant_account, key_store, profile, + platform_merchant_account: None, }, AuthenticationType::PublishableKey { merchant_id }, )) @@ -1642,6 +1781,10 @@ where request_headers: &HeaderMap, state: &A, ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + if state.conf().platform.enabled { + throw_error_if_platform_merchant_authentication_required(request_headers)?; + } + let publishable_key = get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; let key_manager_state = &(&state.session_state()).into(); @@ -1655,6 +1798,7 @@ where ( AuthenticationData { merchant_account, + platform_merchant_account: None, key_store, profile_id: None, }, @@ -1703,6 +1847,7 @@ where merchant_account, key_store, profile, + platform_merchant_account: None, }, AuthenticationType::PublishableKey { merchant_id }, )) @@ -1991,6 +2136,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; @@ -2073,6 +2219,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( @@ -2239,6 +2386,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; @@ -2314,6 +2462,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( auth.clone(), @@ -2448,6 +2597,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; @@ -2519,6 +2669,7 @@ where // if both of them are same then proceed with the profile id present in the request let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: Some(self.profile_id.clone()), }; @@ -2592,6 +2743,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( auth.clone(), @@ -2680,6 +2832,7 @@ where let merchant_id = merchant.get_id().clone(); let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; @@ -2756,6 +2909,7 @@ where merchant_account: merchant, key_store, profile, + platform_merchant_account: None, }; Ok(( auth, @@ -2816,6 +2970,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; @@ -2934,6 +3089,7 @@ where let auth = AuthenticationData { merchant_account: merchant, + platform_merchant_account: None, key_store, profile_id: Some(payload.profile_id), }; @@ -3298,6 +3454,96 @@ where } } +async fn get_connected_merchant_account<A>( + state: &A, + connected_merchant_id: id_type::MerchantId, + platform_org_id: id_type::OrganizationId, +) -> RouterResult<domain::MerchantAccount> +where + A: SessionStateInfo + Sync, +{ + let key_manager_state = &(&state.session_state()).into(); + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + &connected_merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let connected_merchant_account = state + .store() + .find_merchant_account_by_merchant_id(key_manager_state, &connected_merchant_id, &key_store) + .await + .to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation) + .attach_printable("Failed to fetch merchant account for the merchant id")?; + + if platform_org_id != connected_merchant_account.organization_id { + return Err(errors::ApiErrorResponse::InvalidPlatformOperation) + .attach_printable("Access for merchant id Unauthorized"); + } + + Ok(connected_merchant_account) +} + +async fn get_platform_merchant_account<A>( + state: &A, + request_headers: &HeaderMap, + merchant_account: domain::MerchantAccount, +) -> RouterResult<(domain::MerchantAccount, Option<domain::MerchantAccount>)> +where + A: SessionStateInfo + Sync, +{ + let connected_merchant_id = + get_and_validate_connected_merchant_id(request_headers, &merchant_account)?; + + match connected_merchant_id { + Some(merchant_id) => { + let connected_merchant_account = get_connected_merchant_account( + state, + merchant_id, + merchant_account.organization_id.clone(), + ) + .await?; + Ok((connected_merchant_account, Some(merchant_account))) + } + None => Ok((merchant_account, None)), + } +} + +fn get_and_validate_connected_merchant_id( + request_headers: &HeaderMap, + merchant_account: &domain::MerchantAccount, +) -> RouterResult<Option<id_type::MerchantId>> { + HeaderMapStruct::new(request_headers) + .get_id_type_from_header_if_present::<id_type::MerchantId>( + headers::X_CONNECTED_MERCHANT_ID, + )? + .map(|merchant_id| { + merchant_account + .is_platform_account + .then_some(merchant_id) + .ok_or(errors::ApiErrorResponse::InvalidPlatformOperation) + }) + .transpose() + .attach_printable("Non platform_merchant_account using X_CONNECTED_MERCHANT_ID header") +} + +fn throw_error_if_platform_merchant_authentication_required( + request_headers: &HeaderMap, +) -> RouterResult<()> { + HeaderMapStruct::new(request_headers) + .get_id_type_from_header_if_present::<id_type::MerchantId>( + headers::X_CONNECTED_MERCHANT_ID, + )? + .map_or(Ok(()), |_| { + Err(errors::ApiErrorResponse::PlatformAccountAuthNotSupported.into()) + }) +} + #[cfg(feature = "recon")] #[async_trait] impl<A> AuthenticateAndFetch<UserFromTokenWithRoleInfo, A> for JWTAuth diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs index 09cd7cfa103..bf84dd568a2 100644 --- a/crates/router/src/utils/user/sample_data.rs +++ b/crates/router/src/utils/user/sample_data.rs @@ -275,6 +275,7 @@ pub async fn generate_sample_data( tax_details: None, skip_external_tax_calculation: None, psd2_sca_exemption_type: None, + platform_merchant_id: None, }; let (connector_transaction_id, connector_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs index 1bfcc8ebe7b..c7df4aeff0c 100644 --- a/crates/router/src/workflows/outgoing_webhook_retry.rs +++ b/crates/router/src/workflows/outgoing_webhook_retry.rs @@ -400,6 +400,7 @@ async fn get_outgoing_webhook_content_and_event_type( CallConnectorAction::Avoid, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + None, //Platform merchant account )) .await? { diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 04fa1648492..fb83922935e 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -91,6 +91,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { services::AuthFlow::Client, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + None, //Platform merchant account )) .await?; diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index 37fb57e05f3..beaacb79fc0 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -472,6 +472,7 @@ async fn payments_create_core() { payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + None, )) .await .unwrap(); @@ -734,6 +735,7 @@ async fn payments_create_core_adyen_no_redirect() { payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + None, )) .await .unwrap(); diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index 415ea07cb9f..1d573d007ba 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -234,6 +234,7 @@ async fn payments_create_core() { payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + None, )) .await .unwrap(); @@ -504,6 +505,7 @@ async fn payments_create_core_adyen_no_redirect() { payments::CallConnectorAction::Trigger, None, hyperswitch_domain_models::payments::HeaderPayload::default(), + None, )) .await .unwrap(); diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index de2577e6c34..ccbf9598a56 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -88,6 +88,8 @@ pub enum Flow { ConfigKeyCreate, /// ConfigKey fetch flow. ConfigKeyFetch, + /// Enable platform account flow. + EnablePlatformAccount, /// ConfigKey Update flow. ConfigKeyUpdate, /// ConfigKey Delete flow. diff --git a/migrations/2024-12-03-072318_platform_merchant_account/down.sql b/migrations/2024-12-03-072318_platform_merchant_account/down.sql new file mode 100644 index 00000000000..342380e0933 --- /dev/null +++ b/migrations/2024-12-03-072318_platform_merchant_account/down.sql @@ -0,0 +1,4 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE merchant_account DROP COLUMN IF EXISTS is_platform_account; + +ALTER TABLE payment_intent DROP COLUMN IF EXISTS platform_merchant_id; diff --git a/migrations/2024-12-03-072318_platform_merchant_account/up.sql b/migrations/2024-12-03-072318_platform_merchant_account/up.sql new file mode 100644 index 00000000000..cd07e163d7c --- /dev/null +++ b/migrations/2024-12-03-072318_platform_merchant_account/up.sql @@ -0,0 +1,4 @@ +-- Your SQL goes here +ALTER TABLE merchant_account ADD COLUMN IF NOT EXISTS is_platform_account BOOL NOT NULL DEFAULT FALSE; + +ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS platform_merchant_id VARCHAR(64);
2024-12-18T18:20:15Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [X] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description #### About the feature - This the first PR for the Platform Account feature. - Feature is under development and behind the feature flag. - Feature is supposed to be disabled for sandbox and production environments. #### Enabling the platform account. - New API has been created to enable platform account. - API requires Admin API auth. - Once enabled, there is no way of disabling platform account as of now. #### How it works - A new special header is to be sent by the platform called `x-connected-merchant-id`. - Platform will use its own API key irrespective of the merchant id present in the above header. - Value of this header is supposed to be the merchant id of the merchant account on behalf of which the platform is performing the operation. - **If the platform has `is_platform` true and the merchant account on behalf of which operation is performed belongs to the same organisation as platform** then the operation is allowed. #### Payment Intent - Operation will be performed for merchant id present in the `x-connected-merchant-id` header. - `platform_merchant_id` column for the payment intent will be populated with platforms merchant id. #### Other operations - Will add context of `platform_merchant_id` in other operations as well. <!-- Describe your changes in detail --> ### 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 #6883 <!-- 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 a merchant account(m1). 2. Use below api to convert it into platform account. ```sh curl --location --request POST '<BASE URL>/accounts/{merchant_id}/platform' \ --header 'api-key:<ADMIN API KEY>' ``` 3. Create another merchant account in the same organisation(m2). 4. Do a payment using platform's(m1) API key for connected merchant account(m2) by passing header `x-connected-merchant-id` with value as connected merchant account's merchant id. 5. Check if payment is created for connected merchant account. 6. Check if `platform_merchant_id` is populated with platform's merchant id. <!-- 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
1fc941056fb8759435f41bba004a602c176eb802
juspay/hyperswitch
juspay__hyperswitch-6861
Bug: refactor(users): move roles schema to global storeage interface - We need to have roles schema in global schema. It should be global along with user, user_roles and user_key_store - We need to remove themes from global schema, since themes are not global and can depend on tenant, organization, merchant or profile.
diff --git a/crates/router/src/core/user/theme.rs b/crates/router/src/core/user/theme.rs index 27b342d9053..2a896b7158f 100644 --- a/crates/router/src/core/user/theme.rs +++ b/crates/router/src/core/user/theme.rs @@ -21,7 +21,7 @@ pub async fn get_theme_using_lineage( lineage: ThemeLineage, ) -> UserResponse<theme_api::GetThemeResponse> { let theme = state - .global_store + .store .find_theme_by_lineage(lineage) .await .to_not_found_response(UserErrors::ThemeNotFound)?; @@ -55,7 +55,7 @@ pub async fn get_theme_using_theme_id( theme_id: String, ) -> UserResponse<theme_api::GetThemeResponse> { let theme = state - .global_store + .store .find_theme_by_theme_id(theme_id.clone()) .await .to_not_found_response(UserErrors::ThemeNotFound)?; @@ -90,7 +90,7 @@ pub async fn upload_file_to_theme_storage( request: theme_api::UploadFileRequest, ) -> UserResponse<()> { let db_theme = state - .global_store + .store .find_theme_by_lineage(request.lineage) .await .to_not_found_response(UserErrors::ThemeNotFound)?; @@ -131,7 +131,7 @@ pub async fn create_theme( ); let db_theme = state - .global_store + .store .insert_theme(new_theme) .await .to_duplicate_response(UserErrors::ThemeAlreadyExists)?; @@ -176,7 +176,7 @@ pub async fn update_theme( request: theme_api::UpdateThemeRequest, ) -> UserResponse<theme_api::GetThemeResponse> { let db_theme = state - .global_store + .store .find_theme_by_lineage(request.lineage) .await .to_not_found_response(UserErrors::ThemeNotFound)?; @@ -225,7 +225,7 @@ pub async fn delete_theme( lineage: ThemeLineage, ) -> UserResponse<()> { state - .global_store + .store .delete_theme_by_lineage_and_theme_id(theme_id.clone(), lineage) .await .to_not_found_response(UserErrors::ThemeNotFound)?; diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 714bf9fed3c..e897e1b336a 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -86,7 +86,7 @@ pub async fn create_role( } let role = state - .store + .global_store .insert_role(RoleNew { role_id: generate_id_with_default_len("role"), role_name: role_name.get_role_name(), @@ -220,7 +220,7 @@ pub async fn update_role( } let updated_role = state - .store + .global_store .update_role_by_role_id( role_id, RoleUpdate::UpdateDetails { @@ -271,7 +271,7 @@ pub async fn list_roles_with_info( let custom_roles = match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? { EntityType::Tenant | EntityType::Organization => state - .store + .global_store .list_roles_for_org_by_parameters( &user_from_token.org_id, None, @@ -282,7 +282,7 @@ pub async fn list_roles_with_info( .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get roles")?, EntityType::Merchant => state - .store + .global_store .list_roles_for_org_by_parameters( &user_from_token.org_id, Some(&user_from_token.merchant_id), @@ -344,7 +344,7 @@ pub async fn list_roles_at_entity_level( let custom_roles = match req.entity_type { EntityType::Tenant | EntityType::Organization => state - .store + .global_store .list_roles_for_org_by_parameters( &user_from_token.org_id, None, @@ -356,7 +356,7 @@ pub async fn list_roles_at_entity_level( .attach_printable("Failed to get roles")?, EntityType::Merchant => state - .store + .global_store .list_roles_for_org_by_parameters( &user_from_token.org_id, Some(&user_from_token.merchant_id), diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index cc9a1e2f436..fbb75b6af60 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -128,10 +128,10 @@ pub trait StorageInterface: + authorization::AuthorizationInterface + user::sample_data::BatchSampleDataInterface + health_check::HealthCheckDbInterface - + role::RoleInterface + user_authentication_method::UserAuthenticationMethodInterface + authentication::AuthenticationInterface + generic_link::GenericLinkInterface + + user::theme::ThemeInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; @@ -147,7 +147,7 @@ pub trait GlobalStorageInterface: + user::UserInterface + user_role::UserRoleInterface + user_key_store::UserKeyStoreInterface - + user::theme::ThemeInterface + + role::RoleInterface + 'static { } diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 2b7e8bd7340..da296373d80 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -73,7 +73,8 @@ where A: SessionStateInfo + Sync, { state - .store() + .session_state() + .global_store .find_by_role_id_and_org_id(role_id, org_id) .await .map(roles::RoleInfo::from) diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index dcffa3107c9..c9c64b76143 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -126,7 +126,7 @@ impl RoleInfo { Ok(role.clone()) } else { state - .store + .global_store .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id) .await .map(Self::from) @@ -142,7 +142,7 @@ impl RoleInfo { Ok(role.clone()) } else { state - .store + .global_store .find_by_role_id_and_org_id(role_id, org_id) .await .map(Self::from) diff --git a/crates/router/src/utils/user/theme.rs b/crates/router/src/utils/user/theme.rs index 1c8b76989ae..9cc1c43462c 100644 --- a/crates/router/src/utils/user/theme.rs +++ b/crates/router/src/utils/user/theme.rs @@ -190,7 +190,7 @@ pub async fn get_most_specific_theme_using_lineage( lineage: ThemeLineage, ) -> UserResult<Option<Theme>> { match state - .global_store + .store .find_most_specific_theme_in_lineage(lineage) .await { @@ -210,7 +210,7 @@ pub async fn get_theme_using_optional_theme_id( theme_id: Option<String>, ) -> UserResult<Option<Theme>> { match theme_id - .async_map(|theme_id| state.global_store.find_theme_by_theme_id(theme_id)) + .async_map(|theme_id| state.store.find_theme_by_theme_id(theme_id)) .await .transpose() { diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index b8f93bff943..ac8ee11fc6a 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -57,7 +57,7 @@ pub async fn validate_role_name( // TODO: Create and use find_by_role_name to make this efficient let is_present_in_custom_roles = state - .store + .global_store .list_all_roles(merchant_id, org_id) .await .change_context(UserErrors::InternalServerError)?
2024-12-17T12:04:20Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Refactor: - move roles to global schema - remove themes from global schema ### 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 [#6861](https://github.com/juspay/hyperswitch/issues/6861) ## How did you test it? Refactoring changes, currently in config global schema points to public, so no change in behaviour. Changes will be reflected after we turn on feature flag for multi-tenancy and update the configs. Global interface will point to global (shared resources) schema. When interacting with roles and themes storeage fucntions/queries we are getting expected response as we were getting before. ``` curl --location 'http://localhost:8080/user/role' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --header 'Cookie: Cookier' \ --data '{ "role_name": "custom_role_1", "groups": ["users_view"], "role_scope": "merchant" }' ``` Response ``` { "role_id": "role_Ve3BT4c2knBPYnI0EIbq", "groups": [ "users_view" ], "role_name": "custom_role_1", "role_scope": "merchant" } ``` ## 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
e8bfd0e2270300fff3f051143f34ebb782da5366
juspay/hyperswitch
juspay__hyperswitch-6854
Bug: refactor(dynamic_routing): add col payment_method_type in dynamic_routing_stats
diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rs index 168699d7f56..c055359d8b0 100644 --- a/crates/diesel_models/src/dynamic_routing_stats.rs +++ b/crates/diesel_models/src/dynamic_routing_stats.rs @@ -19,6 +19,7 @@ pub struct DynamicRoutingStatsNew { pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, + pub payment_method_type: Option<common_enums::PaymentMethodType>, } #[derive(Clone, Debug, Eq, PartialEq, Queryable, Selectable, Insertable)] @@ -38,4 +39,5 @@ pub struct DynamicRoutingStats { pub payment_status: common_enums::AttemptStatus, pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, pub created_at: time::PrimitiveDateTime, + pub payment_method_type: Option<common_enums::PaymentMethodType>, } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 178f5600542..61a8a7e19b9 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -417,6 +417,8 @@ diesel::table! { payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, + #[max_length = 64] + payment_method_type -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index da2298d934b..6569c035365 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -429,6 +429,8 @@ diesel::table! { payment_status -> AttemptStatus, conclusive_classification -> SuccessBasedRoutingConclusiveState, created_at -> Timestamp, + #[max_length = 64] + payment_method_type -> Nullable<Varchar>, } } diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index b3c951f0964..2abb5e64cd4 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -761,6 +761,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( amount: payment_attempt.get_total_amount(), success_based_routing_connector: first_success_based_connector.to_string(), payment_connector: payment_connector.to_string(), + payment_method_type: payment_attempt.payment_method_type, currency: payment_attempt.currency, payment_method: payment_attempt.payment_method, capture_method: payment_attempt.capture_method, diff --git a/migrations/2024-12-16-111228_add_new_col_payment_method_type_in_dynamic_routing_stats/down.sql b/migrations/2024-12-16-111228_add_new_col_payment_method_type_in_dynamic_routing_stats/down.sql new file mode 100644 index 00000000000..bc2f40c91d2 --- /dev/null +++ b/migrations/2024-12-16-111228_add_new_col_payment_method_type_in_dynamic_routing_stats/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE dynamic_routing_stats +DROP COLUMN IF EXISTS payment_method_type; diff --git a/migrations/2024-12-16-111228_add_new_col_payment_method_type_in_dynamic_routing_stats/up.sql b/migrations/2024-12-16-111228_add_new_col_payment_method_type_in_dynamic_routing_stats/up.sql new file mode 100644 index 00000000000..2b5af8090f0 --- /dev/null +++ b/migrations/2024-12-16-111228_add_new_col_payment_method_type_in_dynamic_routing_stats/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE dynamic_routing_stats +ADD COLUMN IF NOT EXISTS payment_method_type VARCHAR(64);
2024-12-16T12:13:56Z
## 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 change will add `payment_method_type` in dynamic_routing_stats. ### Additional Changes - [ ] 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? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> Testing can be done in following way: 1. Enable Success based routing for a profile with feature as metrics. 2. Make a payment. 3. Search the `dynamic_routing_stats` table for the new col. `payment_method_type` for that payment. <img width="441" alt="Screenshot 2024-12-16 at 5 38 33 PM" src="https://github.com/user-attachments/assets/24e47a6c-e06b-43a4-b3d4-dea5bab432ba" /> ## 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
ae00a103de5bd283695969270a421c7609a699e8
juspay/hyperswitch
juspay__hyperswitch-6872
Bug: [FEATURE] [Network Tokenization]: Tokenize before payment ### Feature Description Tokenize the card before payment based on profile level config. ### Possible Implementation Tokenize the card before payment based on profile level 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/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index a7b57b7433c..60eca62b618 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -2002,6 +2002,9 @@ pub struct ProfileCreate { /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, + + /// Indicates if pre network tokenization is enabled or not + pub is_pre_network_tokenization_enabled: Option<bool>, } #[nutype::nutype( @@ -2302,6 +2305,10 @@ pub struct ProfileResponse { //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, + + /// Indicates if pre network tokenization is enabled or not + #[schema(default = false, example = false)] + pub is_pre_network_tokenization_enabled: bool, } #[cfg(feature = "v2")] @@ -2602,6 +2609,10 @@ pub struct ProfileUpdate { /// Indicates if the redirection has to open in the iframe pub is_iframe_redirection_enabled: Option<bool>, + + /// Indicates if pre network tokenization is enabled or not + #[schema(default = false, example = false)] + pub is_pre_network_tokenization_enabled: Option<bool>, } #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 9309bb42871..a7c606fb94b 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -71,6 +71,7 @@ pub struct Profile { pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub id: Option<common_utils::id_type::ProfileId>, pub is_iframe_redirection_enabled: Option<bool>, + pub is_pre_network_tokenization_enabled: Option<bool>, } #[cfg(feature = "v1")] @@ -125,6 +126,7 @@ pub struct ProfileNew { pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub id: Option<common_utils::id_type::ProfileId>, pub is_iframe_redirection_enabled: Option<bool>, + pub is_pre_network_tokenization_enabled: Option<bool>, } #[cfg(feature = "v1")] @@ -177,6 +179,7 @@ pub struct ProfileUpdateInternal { pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, + pub is_pre_network_tokenization_enabled: Option<bool>, } #[cfg(feature = "v1")] @@ -226,6 +229,7 @@ impl ProfileUpdateInternal { is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled, } = self; Profile { profile_id: source.profile_id, @@ -303,6 +307,8 @@ impl ProfileUpdateInternal { .or(source.merchant_business_country), is_iframe_redirection_enabled: is_iframe_redirection_enabled .or(source.is_iframe_redirection_enabled), + is_pre_network_tokenization_enabled: is_pre_network_tokenization_enabled + .or(source.is_pre_network_tokenization_enabled), } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index f890963c18a..5994670e1d5 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -226,6 +226,7 @@ diesel::table! { #[max_length = 64] id -> Nullable<Varchar>, is_iframe_redirection_enabled -> Nullable<Bool>, + is_pre_network_tokenization_enabled -> Nullable<Bool>, } } diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs index 9f70f462386..2c8b2e99792 100644 --- a/crates/hyperswitch_domain_models/src/business_profile.rs +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -74,6 +74,7 @@ pub struct Profile { pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<common_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, + pub is_pre_network_tokenization_enabled: bool, } #[cfg(feature = "v1")] @@ -126,6 +127,7 @@ pub struct ProfileSetter { pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, + pub is_pre_network_tokenization_enabled: bool, } #[cfg(feature = "v1")] @@ -183,6 +185,7 @@ impl From<ProfileSetter> for Profile { is_debit_routing_enabled: value.is_debit_routing_enabled, merchant_business_country: value.merchant_business_country, is_iframe_redirection_enabled: value.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: value.is_pre_network_tokenization_enabled, } } } @@ -242,6 +245,7 @@ pub struct ProfileGeneralUpdate { pub is_debit_routing_enabled: bool, pub merchant_business_country: Option<api_enums::CountryAlpha2>, pub is_iframe_redirection_enabled: Option<bool>, + pub is_pre_network_tokenization_enabled: Option<bool>, } #[cfg(feature = "v1")] @@ -316,6 +320,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled, } = *update; Self { @@ -363,6 +368,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled, merchant_business_country, is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled, } } ProfileUpdate::RoutingAlgorithmUpdate { @@ -412,6 +418,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, + is_pre_network_tokenization_enabled: None, }, ProfileUpdate::DynamicRoutingAlgorithmUpdate { dynamic_routing_algorithm, @@ -459,6 +466,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, + is_pre_network_tokenization_enabled: None, }, ProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, @@ -506,6 +514,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, + is_pre_network_tokenization_enabled: None, }, ProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, @@ -553,6 +562,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, + is_pre_network_tokenization_enabled: None, }, ProfileUpdate::NetworkTokenizationUpdate { is_network_tokenization_enabled, @@ -600,6 +610,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, + is_pre_network_tokenization_enabled: None, }, ProfileUpdate::CardTestingSecretKeyUpdate { card_testing_secret_key, @@ -647,6 +658,7 @@ impl From<ProfileUpdate> for ProfileUpdateInternal { is_debit_routing_enabled: false, merchant_business_country: None, is_iframe_redirection_enabled: None, + is_pre_network_tokenization_enabled: None, }, } } @@ -714,6 +726,7 @@ impl super::behaviour::Conversion for Profile { is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled), }) } @@ -805,6 +818,9 @@ impl super::behaviour::Conversion for Profile { is_debit_routing_enabled: item.is_debit_routing_enabled, merchant_business_country: item.merchant_business_country, is_iframe_redirection_enabled: item.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: item + .is_pre_network_tokenization_enabled + .unwrap_or(false), }) } .await @@ -867,6 +883,7 @@ impl super::behaviour::Conversion for Profile { is_debit_routing_enabled: self.is_debit_routing_enabled, merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled), }) } } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 9f62dbbe987..b3e0e9540b3 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -2002,3 +2002,37 @@ impl SingleUseTokenKey { &self.0 } } + +#[cfg(feature = "v1")] +impl From<Card> for payment_methods::CardDetail { + fn from(card_data: Card) -> Self { + Self { + card_number: card_data.card_number.clone(), + card_exp_month: card_data.card_exp_month.clone(), + card_exp_year: card_data.card_exp_year.clone(), + card_holder_name: None, + nick_name: None, + card_issuing_country: None, + card_network: card_data.card_network.clone(), + card_issuer: None, + card_type: None, + } + } +} + +#[cfg(feature = "v1")] +impl From<NetworkTokenData> for payment_methods::CardDetail { + fn from(network_token_data: NetworkTokenData) -> Self { + Self { + card_number: network_token_data.token_number.clone(), + card_exp_month: network_token_data.token_exp_month.clone(), + card_exp_year: network_token_data.token_exp_year.clone(), + card_holder_name: None, + nick_name: None, + card_issuing_country: None, + card_network: network_token_data.card_network.clone(), + card_issuer: None, + card_type: None, + } + } +} diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 103ccd593f5..047fe7fb2cf 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -999,9 +999,29 @@ where } } +#[derive(Default, Clone, serde::Serialize, Debug)] +pub struct CardAndNetworkTokenDataForVault { + pub card_data: payment_method_data::Card, + pub network_token: NetworkTokenDataForVault, +} + +#[derive(Default, Clone, serde::Serialize, Debug)] +pub struct NetworkTokenDataForVault { + pub network_token_data: payment_method_data::NetworkTokenData, + pub network_token_req_ref_id: String, +} + +#[derive(Default, Clone, serde::Serialize, Debug)] +pub struct CardDataForVault { + pub card_data: payment_method_data::Card, + pub network_token_req_ref_id: Option<String>, +} + #[derive(Clone, serde::Serialize, Debug)] pub enum VaultOperation { ExistingVaultData(VaultData), + SaveCardData(CardDataForVault), + SaveCardAndNetworkTokenData(Box<CardAndNetworkTokenDataForVault>), } impl VaultOperation { diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index f12dc48924c..db8a44df16e 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3924,6 +3924,9 @@ impl ProfileCreateBridge for api::ProfileCreate { is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: self + .is_pre_network_tokenization_enabled + .unwrap_or_default(), })) } @@ -4373,6 +4376,7 @@ impl ProfileUpdateBridge for api::ProfileUpdate { is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: self.merchant_business_country, is_iframe_redirection_enabled: self.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: self.is_pre_network_tokenization_enabled, }, ))) } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f5350e81d5f..e1567054aab 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -55,7 +55,7 @@ pub use hyperswitch_domain_models::{ router_request_types::CustomerDetails, }; use hyperswitch_domain_models::{ - payments::{payment_intent::CustomerData, ClickToPayMetaData}, + payments::{self, payment_intent::CustomerData, ClickToPayMetaData}, router_data::AccessToken, }; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -478,6 +478,7 @@ where } _ => (), }; + payment_data = match connector_details { ConnectorCallType::PreDetermined(ref connector) => { #[cfg(all(feature = "dynamic_routing", feature = "v1"))] @@ -498,6 +499,7 @@ where } else { None }; + let (router_data, mca) = call_connector_service( state, req_state.clone(), @@ -3042,6 +3044,53 @@ where ) .await?; + let customer_acceptance = payment_data + .get_payment_attempt() + .customer_acceptance + .clone(); + + if is_pre_network_tokenization_enabled( + state, + business_profile, + customer_acceptance, + connector.connector_name, + ) { + let payment_method_data = payment_data.get_payment_method_data(); + let customer_id = payment_data.get_payment_intent().customer_id.clone(); + if let (Some(domain::PaymentMethodData::Card(card_data)), Some(customer_id)) = + (payment_method_data, customer_id) + { + let vault_operation = + get_vault_operation_for_pre_network_tokenization(state, customer_id, card_data) + .await; + match vault_operation { + payments::VaultOperation::SaveCardAndNetworkTokenData( + card_and_network_token_data, + ) => { + payment_data.set_vault_operation( + payments::VaultOperation::SaveCardAndNetworkTokenData(Box::new( + *card_and_network_token_data.clone(), + )), + ); + + payment_data.set_payment_method_data(Some( + domain::PaymentMethodData::NetworkToken( + card_and_network_token_data + .network_token + .network_token_data + .clone(), + ), + )); + } + payments::VaultOperation::SaveCardData(card_data_for_vault) => payment_data + .set_vault_operation(payments::VaultOperation::SaveCardData( + card_data_for_vault.clone(), + )), + payments::VaultOperation::ExistingVaultData(_) => (), + } + } + } + #[cfg(feature = "v1")] if payment_data .get_payment_attempt() @@ -4189,7 +4238,7 @@ pub async fn get_session_token_for_click_to_pay( merchant_id: &id_type::MerchantId, merchant_context: &domain::MerchantContext, authentication_product_ids: common_types::payments::AuthenticationConnectorAccountMap, - payment_intent: &hyperswitch_domain_models::payments::PaymentIntent, + payment_intent: &payments::PaymentIntent, profile_id: &id_type::ProfileId, ) -> RouterResult<api_models::payments::SessionToken> { let click_to_pay_mca_id = authentication_product_ids @@ -6126,6 +6175,64 @@ where Ok(()) } +#[cfg(feature = "v1")] +pub fn is_pre_network_tokenization_enabled( + state: &SessionState, + business_profile: &domain::Profile, + customer_acceptance: Option<Secret<serde_json::Value>>, + connector_name: enums::Connector, +) -> bool { + let ntid_supported_connectors = &state + .conf + .network_transaction_id_supported_connectors + .connector_list; + + let is_nt_supported_connector = ntid_supported_connectors.contains(&connector_name); + + business_profile.is_network_tokenization_enabled + && business_profile.is_pre_network_tokenization_enabled + && customer_acceptance.is_some() + && is_nt_supported_connector +} + +#[cfg(feature = "v1")] +pub async fn get_vault_operation_for_pre_network_tokenization( + state: &SessionState, + customer_id: id_type::CustomerId, + card_data: &hyperswitch_domain_models::payment_method_data::Card, +) -> payments::VaultOperation { + let pre_tokenization_response = + tokenization::pre_payment_tokenization(state, customer_id, card_data) + .await + .ok(); + match pre_tokenization_response { + Some((Some(token_response), Some(token_ref))) => { + let token_data = domain::NetworkTokenData::from(token_response); + let network_token_data_for_vault = payments::NetworkTokenDataForVault { + network_token_data: token_data.clone(), + network_token_req_ref_id: token_ref, + }; + + payments::VaultOperation::SaveCardAndNetworkTokenData(Box::new( + payments::CardAndNetworkTokenDataForVault { + card_data: card_data.clone(), + network_token: network_token_data_for_vault.clone(), + }, + )) + } + Some((None, Some(token_ref))) => { + payments::VaultOperation::SaveCardData(payments::CardDataForVault { + card_data: card_data.clone(), + network_token_req_ref_id: Some(token_ref), + }) + } + _ => payments::VaultOperation::SaveCardData(payments::CardDataForVault { + card_data: card_data.clone(), + network_token_req_ref_id: None, + }), + } +} + #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] pub async fn get_connector_choice<F, Req, D>( diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 59b25d9b86b..32158085cde 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2608,8 +2608,10 @@ pub async fn make_pm_data<'a, F: Clone, R, D>( (_, Some(hyperswitch_token)) => { let existing_vault_data = payment_data.get_vault_operation(); - let vault_data = existing_vault_data.map(|data| match data { - domain_payments::VaultOperation::ExistingVaultData(vault_data) => vault_data, + let vault_data = existing_vault_data.and_then(|data| match data { + domain_payments::VaultOperation::ExistingVaultData(vault_data) => Some(vault_data), + domain_payments::VaultOperation::SaveCardData(_) + | domain_payments::VaultOperation::SaveCardAndNetworkTokenData(_) => None, }); let pm_data = Box::pin(payment_methods::retrieve_payment_method_with_token( diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 0b182d249bd..4c8edfb04ed 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -170,6 +170,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor .and_then(|billing_details| billing_details.address.as_ref()) .and_then(|address| address.get_optional_full_name()); let mut should_avoid_saving = false; + let vault_operation = payment_data.vault_operation.clone(); + let payment_method_info = payment_data.payment_method_info.clone(); if let Some(payment_method_info) = &payment_data.payment_method_info { if payment_data.payment_intent.off_session.is_none() && resp.response.is_ok() { @@ -207,6 +209,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor business_profile, connector_mandate_reference_id.clone(), merchant_connector_id.clone(), + vault_operation.clone(), + payment_method_info.clone(), )); let is_connector_mandate = resp.request.customer_acceptance.is_some() @@ -321,6 +325,8 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor &business_profile, connector_mandate_reference_id, merchant_connector_id.clone(), + vault_operation.clone(), + payment_method_info.clone(), )) .await; @@ -1178,7 +1184,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa .connector_mandate_detail .as_ref() .map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone())); - + let vault_operation = payment_data.vault_operation.clone(); + let payment_method_info = payment_data.payment_method_info.clone(); let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone(); let tokenization::SavePaymentMethodDataResponse { payment_method_id, @@ -1196,6 +1203,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestDa business_profile, connector_mandate_reference_id, merchant_connector_id.clone(), + vault_operation, + payment_method_info, )) .await?; diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 25008523633..34d2302ab8b 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -13,12 +13,15 @@ use common_enums::{ConnectorMandateStatus, PaymentMethod}; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, Encode, ValueExt}, - id_type, pii, + id_type, + metrics::utils::record_operation_time, + pii, }; use error_stack::{report, ResultExt}; #[cfg(feature = "v1")] -use hyperswitch_domain_models::mandates::{ - CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord, +use hyperswitch_domain_models::{ + mandates::{CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord}, + payment_method_data, }; use masking::{ExposeInterface, Secret}; use router_env::{instrument, tracing}; @@ -42,7 +45,7 @@ use crate::{ types::{ self, api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, PaymentMethodCreateExt}, - domain, + domain, payment_methods as pm_types, storage::enums as storage_enums, }, utils::{generate_id, OptionExt}, @@ -92,6 +95,8 @@ pub async fn save_payment_method<FData>( business_profile: &domain::Profile, mut original_connector_mandate_reference_id: Option<ConnectorMandateReferenceId>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, + vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>, + payment_method_info: Option<domain::PaymentMethod>, ) -> RouterResult<SavePaymentMethodDataResponse> where FData: mandate::MandateBehaviour + Clone, @@ -194,9 +199,11 @@ where }; let pm_id = if customer_acceptance.is_some() { + let payment_method_data = + save_payment_method_data.request.get_payment_method_data(); let payment_method_create_request = payment_methods::get_payment_method_create_request( - Some(&save_payment_method_data.request.get_payment_method_data()), + Some(&payment_method_data), Some(save_payment_method_data.payment_method), payment_method_type, &customer_id.clone(), @@ -219,42 +226,22 @@ where .await?; ((res, dc, None), None) } else { - pm_status = Some(common_enums::PaymentMethodStatus::from( + let payment_method_status = common_enums::PaymentMethodStatus::from( save_payment_method_data.attempt_status, - )); - let (res, dc) = Box::pin(save_in_locker( + ); + pm_status = Some(payment_method_status); + save_card_and_network_token_in_locker( state, + customer_id.clone(), + payment_method_status, + payment_method_data.clone(), + vault_operation, + payment_method_info, merchant_context, - payment_method_create_request.to_owned(), - )) - .await?; - - if is_network_tokenization_enabled { - let pm_data = &save_payment_method_data.request.get_payment_method_data(); - match pm_data { - domain::PaymentMethodData::Card(card) => { - let ( - network_token_resp, - _network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice - network_token_requestor_ref_id, - ) = Box::pin(save_network_token_in_locker( - state, - merchant_context, - card, - payment_method_create_request.clone(), - )) - .await?; - - ( - (res, dc, network_token_requestor_ref_id), - network_token_resp, - ) - } - _ => ((res, dc, None), None), //network_token_resp is None in case of other payment methods - } - } else { - ((res, dc, None), None) - } + payment_method_create_request.clone(), + is_network_tokenization_enabled, + ) + .await? }; let network_token_locker_id = match network_token_resp { Some(ref token_resp) => { @@ -267,10 +254,7 @@ where None => None, }; - let optional_pm_details = match ( - resp.card.as_ref(), - save_payment_method_data.request.get_payment_method_data(), - ) { + let optional_pm_details = match (resp.card.as_ref(), payment_method_data) { (Some(card), _) => Some(PaymentMethodsData::Card( CardDetailsPaymentMethod::from(card.clone()), )), @@ -840,6 +824,80 @@ where todo!() } +#[cfg(feature = "v1")] +pub async fn pre_payment_tokenization( + state: &SessionState, + customer_id: id_type::CustomerId, + card: &payment_method_data::Card, +) -> RouterResult<(Option<pm_types::TokenResponse>, Option<String>)> { + let network_tokenization_supported_card_networks = &state + .conf + .network_tokenization_supported_card_networks + .card_networks; + + if card + .card_network + .as_ref() + .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) + .is_some() + { + let optional_card_cvc = Some(card.card_cvc.clone()); + let card_detail = payment_method_data::CardDetail::from(card); + match network_tokenization::make_card_network_tokenization_request( + state, + &card_detail, + optional_card_cvc, + &customer_id, + ) + .await + { + Ok((_token_response, network_token_requestor_ref_id)) => { + let network_tokenization_service = &state.conf.network_tokenization_service; + match ( + network_token_requestor_ref_id.clone(), + network_tokenization_service, + ) { + (Some(token_ref), Some(network_tokenization_service)) => { + let network_token = record_operation_time( + async { + network_tokenization::get_network_token( + state, + customer_id, + token_ref, + network_tokenization_service.get_inner(), + ) + .await + }, + &metrics::FETCH_NETWORK_TOKEN_TIME, + &[], + ) + .await; + match network_token { + Ok(token_response) => { + Ok((Some(token_response), network_token_requestor_ref_id.clone())) + } + _ => { + logger::error!( + "Error while fetching token from tokenization service" + ); + Ok((None, network_token_requestor_ref_id.clone())) + } + } + } + (Some(token_ref), _) => Ok((None, Some(token_ref))), + _ => Ok((None, None)), + } + } + Err(err) => { + logger::error!("Failed to tokenize card: {:?}", err); + Ok((None, None)) //None will be returned in case of error when calling network tokenization service + } + } + } else { + Ok((None, None)) //None will be returned in case of unsupported card network. + } +} + #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -951,6 +1009,7 @@ pub async fn save_in_locker( state: &SessionState, merchant_context: &domain::MerchantContext, payment_method_request: api::PaymentMethodCreate, + card_detail: Option<api::CardDetail>, ) -> RouterResult<( api_models::payment_methods::PaymentMethodResponse, Option<payment_methods::transformers::DataDuplicationCheck>, @@ -961,8 +1020,8 @@ pub async fn save_in_locker( .customer_id .clone() .get_required_value("customer_id")?; - match payment_method_request.card.clone() { - Some(card) => Box::pin( + match (payment_method_request.card.clone(), card_detail) { + (_, Some(card)) | (Some(card), _) => Box::pin( PmCards { state, merchant_context, @@ -972,7 +1031,7 @@ pub async fn save_in_locker( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Add Card Failed"), - None => { + _ => { let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm"); let payment_method_response = api::PaymentMethodResponse { merchant_id: merchant_id.clone(), @@ -1029,7 +1088,8 @@ pub async fn save_network_token_in_locker( pub async fn save_network_token_in_locker( state: &SessionState, merchant_context: &domain::MerchantContext, - card_data: &domain::Card, + card_data: &payment_method_data::Card, + network_token_data: Option<api::CardDetail>, payment_method_request: api::PaymentMethodCreate, ) -> RouterResult<( Option<api_models::payment_methods::PaymentMethodResponse>, @@ -1045,60 +1105,83 @@ pub async fn save_network_token_in_locker( .network_tokenization_supported_card_networks .card_networks; - if card_data - .card_network - .as_ref() - .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) - .is_some() - { - let optional_card_cvc = Some(card_data.card_cvc.clone()); - match network_tokenization::make_card_network_tokenization_request( - state, - &domain::CardDetail::from(card_data), - optional_card_cvc, - &customer_id, - ) - .await - { - Ok((token_response, network_token_requestor_ref_id)) => { - // Only proceed if the tokenization was successful - let network_token_data = api::CardDetail { - card_number: token_response.token.clone(), - card_exp_month: token_response.token_expiry_month.clone(), - card_exp_year: token_response.token_expiry_year.clone(), - card_holder_name: None, - nick_name: None, - card_issuing_country: None, - card_network: Some(token_response.card_brand.clone()), - card_issuer: None, - card_type: None, - }; + match network_token_data { + Some(nt_data) => { + let (res, dc) = Box::pin( + PmCards { + state, + merchant_context, + } + .add_card_to_locker( + payment_method_request, + &nt_data, + &customer_id, + None, + ), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Network Token Failed")?; - let (res, dc) = Box::pin( - PmCards { - state, - merchant_context, - } - .add_card_to_locker( - payment_method_request, - &network_token_data, - &customer_id, - None, - ), + Ok((Some(res), dc, None)) + } + None => { + if card_data + .card_network + .as_ref() + .filter(|cn| network_tokenization_supported_card_networks.contains(cn)) + .is_some() + { + let optional_card_cvc = Some(card_data.card_cvc.clone()); + match network_tokenization::make_card_network_tokenization_request( + state, + &domain::CardDetail::from(card_data), + optional_card_cvc, + &customer_id, ) .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Add Network Token Failed")?; + { + Ok((token_response, network_token_requestor_ref_id)) => { + // Only proceed if the tokenization was successful + let network_token_data = api::CardDetail { + card_number: token_response.token.clone(), + card_exp_month: token_response.token_expiry_month.clone(), + card_exp_year: token_response.token_expiry_year.clone(), + card_holder_name: None, + nick_name: None, + card_issuing_country: None, + card_network: Some(token_response.card_brand.clone()), + card_issuer: None, + card_type: None, + }; - Ok((Some(res), dc, network_token_requestor_ref_id)) - } - Err(err) => { - logger::error!("Failed to tokenize card: {:?}", err); - Ok((None, None, None)) //None will be returned in case of error when calling network tokenization service + let (res, dc) = Box::pin( + PmCards { + state, + merchant_context, + } + .add_card_to_locker( + payment_method_request, + &network_token_data, + &customer_id, + None, + ), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Network Token Failed")?; + + Ok((Some(res), dc, network_token_requestor_ref_id)) + } + Err(err) => { + logger::error!("Failed to tokenize card: {:?}", err); + Ok((None, None, None)) //None will be returned in case of error when calling network tokenization service + } + } + } else { + Ok((None, None, None)) //None will be returned in case of unsupported card network. } } - } else { - Ok((None, None, None)) //None will be returned in case of unsupported card network. } } @@ -1441,3 +1524,171 @@ pub async fn add_token_for_payment_method( }), } } + +#[cfg(feature = "v1")] +#[allow(clippy::too_many_arguments)] +pub async fn save_card_and_network_token_in_locker( + state: &SessionState, + customer_id: id_type::CustomerId, + payment_method_status: common_enums::PaymentMethodStatus, + payment_method_data: domain::PaymentMethodData, + vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>, + payment_method_info: Option<domain::PaymentMethod>, + merchant_context: &domain::MerchantContext, + payment_method_create_request: api::PaymentMethodCreate, + is_network_tokenization_enabled: bool, +) -> RouterResult<( + ( + api_models::payment_methods::PaymentMethodResponse, + Option<payment_methods::transformers::DataDuplicationCheck>, + Option<String>, + ), + Option<api_models::payment_methods::PaymentMethodResponse>, +)> { + let network_token_requestor_reference_id = payment_method_info + .and_then(|pm_info| pm_info.network_token_requestor_reference_id.clone()); + + match vault_operation { + Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardData(card)) => { + let card_data = api::CardDetail::from(card.card_data.clone()); + if let (Some(nt_ref_id), Some(tokenization_service)) = ( + card.network_token_req_ref_id.clone(), + &state.conf.network_tokenization_service, + ) { + let _ = record_operation_time( + async { + network_tokenization::delete_network_token_from_tokenization_service( + state, + nt_ref_id.clone(), + &customer_id, + tokenization_service.get_inner(), + ) + .await + }, + &metrics::DELETE_NETWORK_TOKEN_TIME, + &[], + ) + .await; + } + let (res, dc) = Box::pin(save_in_locker( + state, + merchant_context, + payment_method_create_request.to_owned(), + Some(card_data), + )) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Card In Locker Failed")?; + + Ok(((res, dc, None), None)) + } + Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardAndNetworkTokenData( + save_card_and_network_token_data, + )) => { + let card_data = + api::CardDetail::from(save_card_and_network_token_data.card_data.clone()); + + let network_token_data = api::CardDetail::from( + save_card_and_network_token_data + .network_token + .network_token_data + .clone(), + ); + + if payment_method_status == common_enums::PaymentMethodStatus::Active { + let (res, dc) = Box::pin(save_in_locker( + state, + merchant_context, + payment_method_create_request.to_owned(), + Some(card_data), + )) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Card In Locker Failed")?; + + let (network_token_resp, _dc, _) = Box::pin(save_network_token_in_locker( + state, + merchant_context, + &save_card_and_network_token_data.card_data, + Some(network_token_data), + payment_method_create_request.clone(), + )) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Network Token In Locker Failed")?; + + Ok(( + (res, dc, network_token_requestor_reference_id), + network_token_resp, + )) + } else { + if let (Some(nt_ref_id), Some(tokenization_service)) = ( + network_token_requestor_reference_id.clone(), + &state.conf.network_tokenization_service, + ) { + let _ = record_operation_time( + async { + network_tokenization::delete_network_token_from_tokenization_service( + state, + nt_ref_id.clone(), + &customer_id, + tokenization_service.get_inner(), + ) + .await + }, + &metrics::DELETE_NETWORK_TOKEN_TIME, + &[], + ) + .await; + } + let (res, dc) = Box::pin(save_in_locker( + state, + merchant_context, + payment_method_create_request.to_owned(), + Some(card_data), + )) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Add Card In Locker Failed")?; + + Ok(((res, dc, None), None)) + } + } + _ => { + let (res, dc) = Box::pin(save_in_locker( + state, + merchant_context, + payment_method_create_request.to_owned(), + None, + )) + .await?; + + if is_network_tokenization_enabled { + match &payment_method_data { + domain::PaymentMethodData::Card(card) => { + let ( + network_token_resp, + _network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice + network_token_requestor_ref_id, + ) = Box::pin(save_network_token_in_locker( + state, + merchant_context, + card, + None, + payment_method_create_request.clone(), + )) + .await?; + + Ok(( + (res, dc, network_token_requestor_ref_id), + network_token_resp, + )) + } + _ => Ok(((res, dc, None), None)), //network_token_resp is None in case of other payment methods + } + } else { + Ok(((res, dc, None), None)) + } + } + } +} diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7e715d40ce6..95aca373080 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -40,7 +40,7 @@ use crate::{ types::{ self, api::{self, ConnectorTransactionId}, - domain, + domain, payment_methods as pm_types, storage::{self, enums}, transformers::{ForeignFrom, ForeignInto, ForeignTryFrom}, MultipleCaptureRequestData, @@ -5159,3 +5159,22 @@ impl ForeignFrom<(Self, Option<&api_models::payments::AdditionalPaymentData>)> }) } } + +#[cfg(feature = "v1")] +impl From<pm_types::TokenResponse> for domain::NetworkTokenData { + fn from(token_response: pm_types::TokenResponse) -> Self { + Self { + token_number: token_response.authentication_details.token, + token_exp_month: token_response.token_details.exp_month, + token_exp_year: token_response.token_details.exp_year, + token_cryptogram: Some(token_response.authentication_details.cryptogram), + card_issuer: None, + card_network: Some(token_response.network), + card_type: None, + card_issuing_country: None, + bank_code: None, + nick_name: None, + eci: None, + } + } +} diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index bf7596adb43..50bd54756d1 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -195,6 +195,7 @@ impl ForeignTryFrom<domain::Profile> for ProfileResponse { force_3ds_challenge: item.force_3ds_challenge, is_debit_routing_enabled: Some(item.is_debit_routing_enabled), merchant_business_country: item.merchant_business_country, + is_pre_network_tokenization_enabled: item.is_pre_network_tokenization_enabled, }) } } @@ -443,5 +444,8 @@ pub async fn create_profile_from_merchant_account( is_debit_routing_enabled: request.is_debit_routing_enabled.unwrap_or_default(), merchant_business_country: request.merchant_business_country, is_iframe_redirection_enabled: request.is_iframe_redirection_enabled, + is_pre_network_tokenization_enabled: request + .is_pre_network_tokenization_enabled + .unwrap_or_default(), })) } diff --git a/migrations/2025-05-16-064616_add_is_pre_network_tokenization_enabled_in_business_profile/down.sql b/migrations/2025-05-16-064616_add_is_pre_network_tokenization_enabled_in_business_profile/down.sql new file mode 100644 index 00000000000..6d40bb55733 --- /dev/null +++ b/migrations/2025-05-16-064616_add_is_pre_network_tokenization_enabled_in_business_profile/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE business_profile DROP COLUMN IF EXISTS is_pre_network_tokenization_enabled; \ No newline at end of file diff --git a/migrations/2025-05-16-064616_add_is_pre_network_tokenization_enabled_in_business_profile/up.sql b/migrations/2025-05-16-064616_add_is_pre_network_tokenization_enabled_in_business_profile/up.sql new file mode 100644 index 00000000000..23448365f35 --- /dev/null +++ b/migrations/2025-05-16-064616_add_is_pre_network_tokenization_enabled_in_business_profile/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS is_pre_network_tokenization_enabled BOOLEAN; \ No newline at end of file diff --git a/v2_migrations/2025-05-05-073505_remove_is_pre_network_tokenization_enabled_from_business_profile/down.sql b/v2_migrations/2025-05-05-073505_remove_is_pre_network_tokenization_enabled_from_business_profile/down.sql new file mode 100644 index 00000000000..d239f77f1a5 --- /dev/null +++ b/v2_migrations/2025-05-05-073505_remove_is_pre_network_tokenization_enabled_from_business_profile/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS is_pre_network_tokenization_enabled BOOLEAN; \ No newline at end of file diff --git a/v2_migrations/2025-05-05-073505_remove_is_pre_network_tokenization_enabled_from_business_profile/up.sql b/v2_migrations/2025-05-05-073505_remove_is_pre_network_tokenization_enabled_from_business_profile/up.sql new file mode 100644 index 00000000000..68100350105 --- /dev/null +++ b/v2_migrations/2025-05-05-073505_remove_is_pre_network_tokenization_enabled_from_business_profile/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE business_profile DROP COLUMN IF EXISTS is_pre_network_tokenization_enabled; \ No newline at end of file
2024-12-18T06:19:09Z
## 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 --> Introduced a new field in business_profile (is_pre_network_tokenization_enabled). Based on that field the card will be tokenized before first payment. If the payment get succeeded the card and network token data will be stored in the locker afterwards. ### Additional Changes - [ ] 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? <!-- Did you write an integration/unit/API test to verify the code changes? Or did you test this change manually (provide relevant screenshots)? --> 1. Enable is_network_tokenization_enabled and is_pre_network_tokenization_enabled in business_profile 2. Create a card payment with a network tokenization supported connector. (Customer acceptance should be there) Connector Create(Cybersource): ``` curl --location 'http://localhost:8080/account/merchant_1747299015/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_6YZ1hGvUYrgBzKrKO25WteTts6KvLVXCodhEmuqaogJZvLhGIEVSVNftVcZytpdE' \ --data '{ "connector_type": "payment_processor", "connector_name": "cybersource", "connector_account_details": { "auth_type": "SignatureKey", "api_secret": "abc", "api_key": "abc", "key1": "abc" }, "test_mode": true, "disabled": false, "payment_methods_enabled": [ { "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": "card", "payment_method_types": [ { "payment_method_type": "credit", "payment_experience": null, "card_networks": [ "Visa", "Mastercard", "AmericanExpress" ], "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 } ] } ], "metadata": { "status_url": "url", "account_name": "transaction_processing", "pricing_type": "fixed_price", "acquirer_bin": "438309", "acquirer_merchant_id": "00002000000" }, "business_country": "US", "business_label": "default", "frm_configs": null, "connector_webhook_details": { "merchant_secret": "abc" } }' ``` Payments Create: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --data-raw '{ "amount": 10, "amount_to_capture": 10, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "customer1747403711", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "setup_future_usage": "on_session", "return_url": "http://127.0.0.1:4040", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "4761360080000093", "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "joseph Doe", "card_cvc": "947" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" }, "email": "[email protected]" }, "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": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` Response: ``` { "payment_id": "pay_hW2g73Y3LCCl8K59On4s", "merchant_id": "merchant_1747404722", "status": "succeeded", "amount": 10, "net_amount": 10, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10, "connector": "cybersource", "client_secret": "abc", "created": "2025-05-16T14:13:37.029Z", "currency": "USD", "customer_id": "customer1747404817", "customer": { "id": "customer1747404817", "name": "John Doe", "email": "[email protected]", "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": "on_session", "off_session": null, "capture_on": null, "capture_method": "automatic", "payment_method": "card", "payment_method_data": { "card": { "last4": "0093", "card_type": "DEBIT", "card_network": "Visa", "card_issuer": "BANKMUSCAT (SAOG)", "card_issuing_country": "OMAN", "card_isin": "476136", "card_extended_bin": null, "card_exp_month": "01", "card_exp_year": "2026", "card_holder_name": "joseph Doe", "payment_checks": null, "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": "California", "first_name": null, "last_name": null }, "phone": null, "email": "[email protected]" }, "order_details": null, "email": "[email protected]", "name": "John Doe", "phone": "999999999", "return_url": "http://127.0.0.1:4040/", "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": "customer1747404817", "created_at": 1747404816, "expires": 1747408416, "secret": "abc" }, "manual_retry_allowed": false, "connector_transaction_id": "abc", "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_hW2g73Y3LCCl8K59On4s_1", "payment_link": null, "profile_id": "pro_cjkyoVtfdaQY5JKvfh3v", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_WI36rV75QJhAyHC02iup", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-05-16T14:28:37.028Z", "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": null, "payment_method_status": null, "updated": "2025-05-16T14:13:44.489Z", "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", "force_3ds_challenge": false, "force_3ds_challenge_trigger": false, "issuer_error_code": null, "issuer_error_message": null, "is_iframe_redirection_enabled": null } ``` **Logs:** Raw Connector Request: ``` raw_connector_request: Object {"processingInformation": Object {"actionList": Null, "actionTokenTypes": Null, "authorizationOptions": Object {"initiator": Null, "merchantIntitiatedTransaction": Null, "ignoreAvsResult": Null, "ignoreCvResult": Null}, "commerceIndicator": String("internet"), "capture": Bool(true), "captureOptions": Null, "paymentSolution": Null}, "paymentInformation": Object {"tokenizedCard": Object {"number": String("460400**********"), "expirationMonth": String("*** alloc::string::String ***"), "expirationYear": String("*** alloc::string::String ***"), "cryptogram": String("*** alloc::string::String ***"), "transactionType": String("1")}}, "orderInformation": Object {"amountDetails": Object {"totalAmount": String("0.10"), "currency": String("USD")}, "billTo": Object {"firstName": String("*** alloc::string::String ***"), "lastName": String("*** alloc::string::String ***"), "address1": String("*** alloc::string::String ***"), "locality": String("San Fransico"), "administrativeArea": String("*** alloc::string::String ***"), "postalCode": String("*** alloc::string::String ***"), "country": String("US"), "email": String("*****@example.com")}}, "clientReferenceInformation": Object {"code": String("pay_hW2g73Y3LCCl8K59On4s_1")}, "merchantDefinedInformation": Array [Object {"key": Number(1), "value": String("login_date=\"2019-09-10T10:11:12Z\"")}, Object {"key": Number(2), "value": String("new_customer=\"true\"")}, Object {"key": Number(3), "value": String("udf1=\"value1\"")}]} ``` ## 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
1192bd5247dc099f647963a90ccc85a356b9f742
juspay/hyperswitch
juspay__hyperswitch-6850
Bug: [bug] adyen mit transactions in ntid flow fail due mis matched expiry conversion ```txt "The provided Expiry Date is not valid.: Expiry year should be a 4 digit number greater than 2000: 30" ``` above error is being thrown during ntid transaction resulting in payment to fail: <img width="441" alt="image" src="https://github.com/user-attachments/assets/cc6ec9a1-498e-4943-9d77-a8bb0f703955" /> to reproduce: create a profileId and mcaId, enable connector agnostic for the business profile make a payment create another profileId and mcaId, and again, enable connector agnostic for the business profile make a payment (payment fails if the card number is 30 and not 2030) verified on integ env
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 16cab2fda47..3e84dffcfaf 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2650,7 +2650,7 @@ impl .card_exp_month .clone(), expiry_year: card_details_for_network_transaction_id - .card_exp_year + .get_expiry_year_4_digit() .clone(), cvc: None, holder_name: card_holder_name,
2024-12-16T11:55:03Z
## 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 MIT payments failing especially during NTID flow. We previously used to get below error message during MIT Confirm call: ```log "The provided Expiry Date is not valid.: Expiry year should be a 4 digit number greater than 2000: 30" ``` closes https://github.com/juspay/hyperswitch/issues/6850 ### 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)? --> xecuted below commands: ```sh # cherry picked commits from my cypress branch which is where the existence of this issue came into light git cherry-pick -n ..cypress-delete-pm # ran necessary migrations on the latest branch just migrate # started the server cargo r ``` ran the cypress NTID tests for Adyen: <img width="1425" alt="image" src="https://github.com/user-attachments/assets/6fea7809-854f-428b-be45-c2632a71f5a8" /> full test (based on #6735) -- no regressions found with adyen: ![image](https://github.com/user-attachments/assets/320ee534-f5a7-4efb-9d0e-4a37575495f2) ## 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
986de77b4868e48d00161c9d30071d809360e9a6
juspay/hyperswitch
juspay__hyperswitch-6835
Bug: feat(redis-interface): add redis interface command to set multiple the keys in redis and increment if the key already exists add redis interface command to set multiple the keys in redis and increment if the key already exists
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 746b424abc8..19497d6fbb8 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -14,7 +14,7 @@ use common_utils::{ use error_stack::{report, ResultExt}; use fred::{ interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface}, - prelude::RedisErrorKind, + prelude::{LuaInterface, RedisErrorKind}, types::{ Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings, MultipleValues, RedisKey, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, @@ -852,12 +852,31 @@ impl super::RedisConnectionPool { .await .change_context(errors::RedisError::ConsumerGroupClaimFailed) } + + #[instrument(level = "DEBUG", skip(self))] + pub async fn incr_keys_using_script<V>( + &self, + lua_script: &'static str, + key: Vec<String>, + values: V, + ) -> CustomResult<(), errors::RedisError> + where + V: TryInto<MultipleValues> + Debug + Send + Sync, + V::Error: Into<fred::error::RedisError> + Send + Sync, + { + self.pool + .eval(lua_script, key, values) + .await + .change_context(errors::RedisError::IncrementHashFieldFailed) + } } #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] + use std::collections::HashMap; + use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings}; #[tokio::test] @@ -911,7 +930,6 @@ mod tests { assert!(is_success); } - #[tokio::test] async fn test_delete_non_existing_key_success() { let is_success = tokio::task::spawn_blocking(move || { @@ -930,6 +948,44 @@ mod tests { }) .await .expect("Spawn block failure"); + assert!(is_success); + } + + #[tokio::test] + async fn test_setting_keys_using_scripts() { + let is_success = tokio::task::spawn_blocking(move || { + futures::executor::block_on(async { + // Arrange + let pool = RedisConnectionPool::new(&RedisSettings::default()) + .await + .expect("failed to create redis connection pool"); + let lua_script = r#" + local results = {} + for i = 1, #KEYS do + results[i] = redis.call("INCRBY", KEYS[i], ARGV[i]) + end + return results + "#; + let mut keys_and_values = HashMap::new(); + for i in 0..10 { + keys_and_values.insert(format!("key{}", i), i); + } + + let key = keys_and_values.keys().cloned().collect::<Vec<_>>(); + let values = keys_and_values + .values() + .map(|val| val.to_string()) + .collect::<Vec<String>>(); + + // Act + let result = pool.incr_keys_using_script(lua_script, key, values).await; + + // Assert Setup + result.is_ok() + }) + }) + .await + .expect("Spawn block failure"); assert!(is_success); }
2024-12-12T11:51:49Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description add redis interface command to set multiple the keys in redis and increment if the key already exists ### 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? - Wrote a unit test to insert the keys <img width="1725" alt="Screenshot 2024-12-13 at 1 05 33 PM" src="https://github.com/user-attachments/assets/5165c747-6e53-4db2-9dce-6aa338c33517" /> ## 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
573fc2ce0ff306d15ec97e7c8d5b8a03528165f4
juspay/hyperswitch
juspay__hyperswitch-6840
Bug: [FEATURE] [Deutschebank] : Implement 3ds Card Flow ### Feature Description Implement 3ds Card Flow for Deutschebank ### Possible Implementation Implement 3ds Card Flow 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/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 03facc2ebab..a450a30fa76 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -3426,6 +3426,10 @@ pub enum RedirectForm { access_token: String, step_up_url: String, }, + DeutschebankThreeDSChallengeFlow { + acs_url: String, + creq: String, + }, Payme, Braintree { client_token: String, diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs index 3098d27e7ec..f4d5fe5fdf1 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -59,7 +59,7 @@ use crate::{ types::ResponseRouterData, utils::{ self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, - RefundsRequestData, + RefundsRequestData, RouterData as ConnectorRouterData, }, }; @@ -131,7 +131,7 @@ impl ConnectorCommon for Deutschebank { } fn get_currency_unit(&self) -> api::CurrencyUnit { - api::CurrencyUnit::Base + api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { @@ -311,18 +311,30 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - if req.request.connector_mandate_id().is_none() { + let event_id = req.connector_request_reference_id.clone(); + let tx_action = if req.request.is_auto_capture()? { + "authorization" + } else { + "preauthorization" + }; + + if req.is_three_ds() && req.request.is_card() { + Ok(format!( + "{}/services/v2.1/headless3DSecure/event/{event_id}/{tx_action}/initialize", + self.base_url(connectors) + )) + } else if !req.is_three_ds() && req.request.is_card() { + Err(errors::ConnectorError::NotSupported { + message: "Non-ThreeDs".to_owned(), + connector: "deutschebank", + } + .into()) + } else 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) @@ -375,7 +387,19 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - if data.request.connector_mandate_id().is_none() { + if data.is_three_ds() && data.request.is_card() { + let response: deutschebank::DeutschebankThreeDSInitializeResponse = 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, + }) + } else if data.request.connector_mandate_id().is_none() { let response: deutschebank::DeutschebankMandatePostResponse = res .response .parse_struct("DeutschebankMandatePostResponse") @@ -437,10 +461,18 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp } else { "preauthorization" }; - Ok(format!( - "{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}", - self.base_url(connectors) - )) + + if req.is_three_ds() && matches!(req.payment_method, enums::PaymentMethod::Card) { + Ok(format!( + "{}/services/v2.1//headless3DSecure/event/{event_id}/final", + self.base_url(connectors) + )) + } else { + Ok(format!( + "{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}", + self.base_url(connectors) + )) + } } fn get_request_body( @@ -453,10 +485,9 @@ impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResp 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)?; + deutschebank::DeutschebankCompleteAuthorizeRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } @@ -952,10 +983,20 @@ lazy_static! { deutschebank_supported_payment_methods.add( enums::PaymentMethod::BankDebit, enums::PaymentMethodType::Sepa, + PaymentMethodDetails{ + mandates: enums::FeatureStatus::Supported, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), + } + ); + + deutschebank_supported_payment_methods.add( + enums::PaymentMethod::Card, + enums::PaymentMethodType::Credit, PaymentMethodDetails{ mandates: enums::FeatureStatus::NotSupported, - refunds: enums::FeatureStatus::NotSupported, - supported_capture_methods, + refunds: enums::FeatureStatus::Supported, + supported_capture_methods: supported_capture_methods.clone(), } ); diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index 85c5fc8dc81..8133be2fa79 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; -use common_enums::enums; +use cards::CardNumber; +use common_enums::{enums, PaymentMethod}; use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit}; use error_stack::ResultExt; use hyperswitch_domain_models::{ @@ -22,14 +23,14 @@ use hyperswitch_domain_models::{ PaymentsCompleteAuthorizeRouterData, RefundsRouterData, }, }; -use hyperswitch_interfaces::errors; -use masking::{PeekInterface, Secret}; +use hyperswitch_interfaces::{consts, errors}; +use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ - self, AddressDetailsData, PaymentsAuthorizeRequestData, + self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData, }, }; @@ -129,6 +130,75 @@ pub struct DeutschebankMandatePostRequest { pub enum DeutschebankPaymentsRequest { MandatePost(DeutschebankMandatePostRequest), DirectDebit(DeutschebankDirectDebitRequest), + CreditCard(Box<DeutschebankThreeDSInitializeRequest>), +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequest { + means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment, + tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data, + amount_total: DeutschebankThreeDSInitializeRequestAmountTotal, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestMeansOfPayment { + credit_card: DeutschebankThreeDSInitializeRequestCreditCard, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestCreditCard { + number: CardNumber, + expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry, + code: Secret<String>, + cardholder: Secret<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestCreditCardExpiry { + year: Secret<String>, + month: Secret<String>, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestAmountTotal { + amount: MinorUnit, + currency: api_models::enums::Currency, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestTds20Data { + communication_data: DeutschebankThreeDSInitializeRequestCommunicationData, + customer_data: DeutschebankThreeDSInitializeRequestCustomerData, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestCommunicationData { + method_notification_url: String, + cres_notification_url: String, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestCustomerData { + billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData, + cardholder_email: Email, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "snake_case")] +pub struct DeutschebankThreeDSInitializeRequestCustomerBillingData { + street: Secret<String>, + postal_code: Secret<String>, + city: String, + state: Secret<String>, + country: String, } impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> @@ -148,11 +218,9 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> None => { // To facilitate one-off payments via SEPA with Deutsche Bank, we are considering not storing the connector mandate ID in our system if future usage is on-session. // We will only check for customer acceptance to make a one-off payment. we will be storing the connector mandate details only when setup future usage is off-session. - if item.router_data.request.customer_acceptance.is_some() { - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { - iban, .. - }) => { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => { + if item.router_data.request.customer_acceptance.is_some() { let billing_address = item.router_data.get_billing_address()?; Ok(Self::MandatePost(DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval::Click, @@ -161,17 +229,60 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> first_name: billing_address.get_first_name()?.clone(), last_name: billing_address.get_last_name()?.clone(), })) + } else { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "customer_acceptance", + } + .into()) } - _ => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("deutschebank"), - ) - .into()), } - } else { - Err(errors::ConnectorError::MissingRequiredField { - field_name: "customer_acceptance", + PaymentMethodData::Card(ccard) => { + if !item.router_data.clone().is_three_ds() { + Err(errors::ConnectorError::NotSupported { + message: "Non-ThreeDs".to_owned(), + connector: "deutschebank", + } + .into()) + } else { + let billing_address = item.router_data.get_billing_address()?; + Ok(Self::CreditCard(Box::new(DeutschebankThreeDSInitializeRequest { + means_of_payment: DeutschebankThreeDSInitializeRequestMeansOfPayment { + credit_card: DeutschebankThreeDSInitializeRequestCreditCard { + number: ccard.clone().card_number, + expiry_date: DeutschebankThreeDSInitializeRequestCreditCardExpiry { + year: ccard.get_expiry_year_4_digit(), + month: ccard.card_exp_month, + }, + code: ccard.card_cvc, + cardholder: item.router_data.get_billing_full_name()?, + }}, + amount_total: DeutschebankThreeDSInitializeRequestAmountTotal { + amount: item.amount, + currency: item.router_data.request.currency, + }, + tds_20_data: DeutschebankThreeDSInitializeRequestTds20Data { + communication_data: DeutschebankThreeDSInitializeRequestCommunicationData { + method_notification_url: item.router_data.request.get_complete_authorize_url()?, + cres_notification_url: item.router_data.request.get_complete_authorize_url()?, + }, + customer_data: DeutschebankThreeDSInitializeRequestCustomerData { + billing_address: DeutschebankThreeDSInitializeRequestCustomerBillingData { + street: billing_address.get_line1()?.clone(), + postal_code: billing_address.get_zip()?.clone(), + city: billing_address.get_city()?.to_string(), + state: billing_address.get_state()?.clone(), + country: item.router_data.get_billing_country()?.to_string(), + }, + cardholder_email: item.router_data.request.get_email()?, + } + } + }))) + } } - .into()) + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()), } } Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => { @@ -209,6 +320,138 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> } } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankThreeDSInitializeResponse { + outcome: DeutschebankThreeDSInitializeResponseOutcome, + challenge_required: Option<DeutschebankThreeDSInitializeResponseChallengeRequired>, + processed: Option<DeutschebankThreeDSInitializeResponseProcessed>, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankThreeDSInitializeResponseProcessed { + rc: String, + message: String, + tx_id: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum DeutschebankThreeDSInitializeResponseOutcome { + Processed, + ChallengeRequired, + MethodRequired, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankThreeDSInitializeResponseChallengeRequired { + acs_url: String, + creq: String, +} + +impl + TryFrom< + ResponseRouterData< + Authorize, + DeutschebankThreeDSInitializeResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + Authorize, + DeutschebankThreeDSInitializeResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + match item.response.outcome { + DeutschebankThreeDSInitializeResponseOutcome::Processed => { + match item.response.processed { + Some(processed) => Ok(Self { + status: if is_response_success(&processed.rc) { + match item.data.request.is_auto_capture()? { + true => common_enums::AttemptStatus::Charged, + false => common_enums::AttemptStatus::Authorized, + } + } else { + common_enums::AttemptStatus::AuthenticationFailed + }, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + processed.tx_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(processed.tx_id.clone()), + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }), + None => { + let response_string = format!("{:?}", item.response); + Err( + errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from( + response_string, + )) + .into(), + ) + } + } + } + DeutschebankThreeDSInitializeResponseOutcome::ChallengeRequired => { + match item.response.challenge_required { + Some(challenge) => Ok(Self { + status: common_enums::AttemptStatus::AuthenticationPending, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::NoResponseId, + redirection_data: Box::new(Some( + RedirectForm::DeutschebankThreeDSChallengeFlow { + acs_url: challenge.acs_url, + creq: challenge.creq, + }, + )), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }), + None => { + let response_string = format!("{:?}", item.response); + Err( + errors::ConnectorError::UnexpectedResponseError(bytes::Bytes::from( + response_string, + )) + .into(), + ) + } + } + } + DeutschebankThreeDSInitializeResponseOutcome::MethodRequired => Ok(Self { + status: common_enums::AttemptStatus::Failure, + response: Err(ErrorResponse { + code: consts::NO_ERROR_CODE.to_owned(), + message: "METHOD_REQUIRED Flow not supported for deutschebank 3ds payments".to_owned(), + reason: Some("METHOD_REQUIRED Flow is not currently supported for deutschebank 3ds payments".to_owned()), + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: None, + }), + ..item.data + }), + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DeutschebankSEPAMandateStatus { @@ -450,79 +693,117 @@ pub struct DeutschebankDirectDebitRequest { mandate: DeutschebankMandate, } +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum DeutschebankCompleteAuthorizeRequest { + DeutschebankDirectDebitRequest(DeutschebankDirectDebitRequest), + DeutschebankThreeDSCompleteAuthorizeRequest(DeutschebankThreeDSCompleteAuthorizeRequest), +} + +#[derive(Debug, Serialize, PartialEq)] +pub struct DeutschebankThreeDSCompleteAuthorizeRequest { + cres: String, +} + impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> - for DeutschebankDirectDebitRequest + for DeutschebankCompleteAuthorizeRequest { 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(), + if matches!(item.router_data.payment_method, PaymentMethod::Card) { + let redirect_response_payload = item + .router_data + .request + .get_redirect_response_payload()? + .expose(); + + let cres = redirect_response_payload + .get("cres") + .and_then(|v| v.as_str()) + .map(String::from) + .ok_or(errors::ConnectorError::MissingRequiredField { field_name: "cres" })?; + + Ok(Self::DeutschebankThreeDSCompleteAuthorizeRequest( + DeutschebankThreeDSCompleteAuthorizeRequest { cres }, + )) + } else { + match item.router_data.request.payment_method_data.clone() { + Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { + iban, .. + })) => { + 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(), ); - } - 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 = 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: Secret::from(iban.peek().replace(" ", "")), + let signed_on = queries_params + .get("signed_on") + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "signed_on", + })? + .to_owned(); + Ok(Self::DeutschebankDirectDebitRequest( + DeutschebankDirectDebitRequest { + amount_total: DeutschebankAmount { + amount: item.amount, + currency: item.router_data.request.currency, + }, + means_of_payment: DeutschebankMeansOfPayment { + bank_account: DeutschebankBankAccount { + account_holder, + iban: Secret::from(iban.peek().replace(" ", "")), + }, + }, + mandate: { + DeutschebankMandate { + reference, + signed_on, + } + }, }, - }, - mandate: { - DeutschebankMandate { - reference, - signed_on, - } - }, - }) + )) + } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()), } - _ => Err(errors::ConnectorError::NotImplemented( - utils::get_unimplemented_payment_method_error_message("deutschebank"), - ) - .into()), } } } @@ -636,6 +917,8 @@ impl #[serde(rename_all = "UPPERCASE")] pub enum DeutschebankTransactionKind { Directdebit, + #[serde(rename = "CREDITCARD_3DS20")] + Creditcard3ds20, } #[derive(Debug, Serialize, PartialEq)] @@ -649,10 +932,24 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCaptureRouterData>> for Deutscheba fn try_from( item: &DeutschebankRouterData<&PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { - Ok(Self { - changed_amount: item.amount, - kind: DeutschebankTransactionKind::Directdebit, - }) + if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) { + Ok(Self { + changed_amount: item.amount, + kind: DeutschebankTransactionKind::Directdebit, + }) + } else if item.router_data.is_three_ds() + && matches!(item.router_data.payment_method, PaymentMethod::Card) + { + Ok(Self { + changed_amount: item.amount, + kind: DeutschebankTransactionKind::Creditcard3ds20, + }) + } else { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()) + } } } @@ -772,10 +1069,21 @@ pub struct DeutschebankReversalRequest { 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, - }) + fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> { + if matches!(item.payment_method, PaymentMethod::BankDebit) { + Ok(Self { + kind: DeutschebankTransactionKind::Directdebit, + }) + } else if item.is_three_ds() && matches!(item.payment_method, PaymentMethod::Card) { + Ok(Self { + kind: DeutschebankTransactionKind::Creditcard3ds20, + }) + } else { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()) + } } } @@ -815,10 +1123,24 @@ pub struct DeutschebankRefundRequest { 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, - }) + if matches!(item.router_data.payment_method, PaymentMethod::BankDebit) { + Ok(Self { + changed_amount: item.amount, + kind: DeutschebankTransactionKind::Directdebit, + }) + } else if item.router_data.is_three_ds() + && matches!(item.router_data.payment_method, PaymentMethod::Card) + { + Ok(Self { + changed_amount: item.amount, + kind: DeutschebankTransactionKind::Creditcard3ds20, + }) + } else { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()) + } } } diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index 61453f36b84..613797e2988 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -236,6 +236,10 @@ pub enum RedirectForm { access_token: String, step_up_url: String, }, + DeutschebankThreeDSChallengeFlow { + acs_url: String, + creq: String, + }, Payme, Braintree { client_token: String, @@ -313,6 +317,9 @@ impl From<RedirectForm> for diesel_models::payment_attempt::RedirectForm { access_token, step_up_url, }, + RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { + Self::DeutschebankThreeDSChallengeFlow { acs_url, creq } + } RedirectForm::Payme => Self::Payme, RedirectForm::Braintree { client_token, @@ -392,6 +399,9 @@ impl From<diesel_models::payment_attempt::RedirectForm> for RedirectForm { access_token, step_up_url, }, + diesel_models::RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { + Self::DeutschebankThreeDSChallengeFlow { acs_url, creq } + } diesel_models::payment_attempt::RedirectForm::Payme => Self::Payme, diesel_models::payment_attempt::RedirectForm::Braintree { client_token, diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 9e42aec4a51..b4ada6fd8fe 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -941,6 +941,129 @@ impl Default for settings::RequiredFields { ), } ), + ( + enums::Connector::Deutschebank, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate : HashMap::from( + [ + ( + "payment_method_data.card.card_number".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_number".to_string(), + display_name: "card_number".to_string(), + field_type: enums::FieldType::UserCardNumber, + value: None, + } + ), + ( + "payment_method_data.card.card_exp_month".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_exp_month".to_string(), + display_name: "card_exp_month".to_string(), + field_type: enums::FieldType::UserCardExpiryMonth, + value: None, + } + ), + ( + "payment_method_data.card.card_exp_year".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_exp_year".to_string(), + display_name: "card_exp_year".to_string(), + field_type: enums::FieldType::UserCardExpiryYear, + value: None, + } + ), + ( + "payment_method_data.card.card_cvc".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_cvc".to_string(), + display_name: "card_cvc".to_string(), + field_type: enums::FieldType::UserCardCvc, + value: None, + } + ), + ( + "email".to_string(), + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + } + ), + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserAddressLine1, + value: None, + } + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserAddressCity, + value: None, + } + ), + ( + "billing.address.state".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserAddressState, + value: None, + } + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserAddressPincode, + value: None, + } + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ] + ), + common: HashMap::new(), + } + ), ( enums::Connector::Dlocal, RequiredFieldFinal { @@ -4138,6 +4261,129 @@ impl Default for settings::RequiredFields { ), } ), + ( + enums::Connector::Deutschebank, + RequiredFieldFinal { + mandate: HashMap::new(), + non_mandate : HashMap::from( + [ + ( + "payment_method_data.card.card_number".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_number".to_string(), + display_name: "card_number".to_string(), + field_type: enums::FieldType::UserCardNumber, + value: None, + } + ), + ( + "payment_method_data.card.card_exp_month".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_exp_month".to_string(), + display_name: "card_exp_month".to_string(), + field_type: enums::FieldType::UserCardExpiryMonth, + value: None, + } + ), + ( + "payment_method_data.card.card_exp_year".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_exp_year".to_string(), + display_name: "card_exp_year".to_string(), + field_type: enums::FieldType::UserCardExpiryYear, + value: None, + } + ), + ( + "payment_method_data.card.card_cvc".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.card.card_cvc".to_string(), + display_name: "card_cvc".to_string(), + field_type: enums::FieldType::UserCardCvc, + value: None, + } + ), + ( + "email".to_string(), + RequiredFieldInfo { + required_field: "email".to_string(), + display_name: "email".to_string(), + field_type: enums::FieldType::UserEmailAddress, + value: None, + } + ), + ( + "billing.address.line1".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserAddressLine1, + value: None, + } + ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserAddressCity, + value: None, + } + ), + ( + "billing.address.state".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserAddressState, + value: None, + } + ), + ( + "billing.address.zip".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserAddressPincode, + value: None, + } + ), + ( + "billing.address.country".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "billing.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.first_name".to_string(), + display_name: "first_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ), + ( + "billing.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.last_name".to_string(), + display_name: "last_name".to_string(), + field_type: enums::FieldType::UserFullName, + value: None, + } + ) + ] + ), + common: HashMap::new(), + } + ), ( enums::Connector::Dlocal, RequiredFieldFinal { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index cac856b2c48..0c2cc0bb86f 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1532,6 +1532,46 @@ pub fn build_redirection_form( </script>"))) }} } + RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => { + maud::html! { + (maud::DOCTYPE) + html { + head { + meta name="viewport" content="width=device-width, initial-scale=1"; + } + + body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" { + div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-top: 150px; margin-left: auto; margin-right: auto;" { "" } + + (PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#)) + + (PreEscaped(r#" + <script> + var anime = bodymovin.loadAnimation({ + container: document.getElementById('loader1'), + renderer: 'svg', + loop: true, + autoplay: true, + name: 'hyperswitch loader', + animationData: {"v":"4.8.0","meta":{"g":"LottieFiles AE 3.1.1","a":"","k":"","d":"","tc":""},"fr":29.9700012207031,"ip":0,"op":31.0000012626559,"w":400,"h":250,"nm":"loader_shape","ddd":0,"assets":[],"layers":[{"ddd":0,"ind":1,"ty":4,"nm":"circle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[278.25,202.671,0],"ix":2},"a":{"a":0,"k":[23.72,23.72,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[12.935,0],[0,-12.936],[-12.935,0],[0,12.935]],"o":[[-12.952,0],[0,12.935],[12.935,0],[0,-12.936]],"v":[[0,-23.471],[-23.47,0.001],[0,23.471],[23.47,0.001]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":10,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":19.99,"s":[100]},{"t":29.9800012211104,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[23.72,23.721],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0},{"ddd":0,"ind":2,"ty":4,"nm":"square 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[196.25,201.271,0],"ix":2},"a":{"a":0,"k":[22.028,22.03,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[1.914,0],[0,0],[0,-1.914],[0,0],[-1.914,0],[0,0],[0,1.914],[0,0]],"o":[[0,0],[-1.914,0],[0,0],[0,1.914],[0,0],[1.914,0],[0,0],[0,-1.914]],"v":[[18.313,-21.779],[-18.312,-21.779],[-21.779,-18.313],[-21.779,18.314],[-18.312,21.779],[18.313,21.779],[21.779,18.314],[21.779,-18.313]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":5,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":14.99,"s":[100]},{"t":24.9800010174563,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[22.028,22.029],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":47.0000019143492,"st":0,"bm":0},{"ddd":0,"ind":3,"ty":4,"nm":"Triangle 2","sr":1,"ks":{"o":{"a":0,"k":100,"ix":11},"r":{"a":0,"k":0,"ix":10},"p":{"a":0,"k":[116.25,200.703,0],"ix":2},"a":{"a":0,"k":[27.11,21.243,0],"ix":1},"s":{"a":0,"k":[100,100,100],"ix":6}},"ao":0,"shapes":[{"ty":"gr","it":[{"ind":0,"ty":"sh","ix":1,"ks":{"a":0,"k":{"i":[[0,0],[0.558,-0.879],[0,0],[-1.133,0],[0,0],[0.609,0.947],[0,0]],"o":[[-0.558,-0.879],[0,0],[-0.609,0.947],[0,0],[1.133,0],[0,0],[0,0]],"v":[[1.209,-20.114],[-1.192,-20.114],[-26.251,18.795],[-25.051,20.993],[25.051,20.993],[26.251,18.795],[1.192,-20.114]],"c":true},"ix":2},"nm":"Path 1","mn":"ADBE Vector Shape - Group","hd":false},{"ty":"fl","c":{"a":0,"k":[0,0.427451010311,0.976470648074,1],"ix":4},"o":{"a":1,"k":[{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":0,"s":[10]},{"i":{"x":[0.667],"y":[1]},"o":{"x":[0.333],"y":[0]},"t":9.99,"s":[100]},{"t":19.9800008138021,"s":[10]}],"ix":5},"r":1,"bm":0,"nm":"Fill 1","mn":"ADBE Vector Graphic - Fill","hd":false},{"ty":"tr","p":{"a":0,"k":[27.11,21.243],"ix":2},"a":{"a":0,"k":[0,0],"ix":1},"s":{"a":0,"k":[100,100],"ix":3},"r":{"a":0,"k":0,"ix":6},"o":{"a":0,"k":100,"ix":7},"sk":{"a":0,"k":0,"ix":4},"sa":{"a":0,"k":0,"ix":5},"nm":"Transform"}],"nm":"Group 1","np":2,"cix":2,"bm":0,"ix":1,"mn":"ADBE Vector Group","hd":false}],"ip":0,"op":48.0000019550801,"st":0,"bm":0}],"markers":[]} + }) + </script> + "#)) + + h3 style="text-align: center;" { "Please wait while we process your payment..." } + } + (PreEscaped(format!("<form id=\"PaReqForm\" method=\"POST\" action=\"{acs_url}\"> + <input type=\"hidden\" name=\"creq\" value=\"{creq}\"> + </form>"))) + (PreEscaped(format!("<script> + {logging_template} + window.onload = function() {{ + var paReqForm = document.querySelector('#PaReqForm'); if(paReqForm) paReqForm.submit(); + }} + </script>"))) + } + } + } RedirectForm::Payme => { maud::html! { (maud::DOCTYPE)
2024-12-16T08:25:48Z
## 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 --> Implement Card 3ds for Deutschebank ### 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://testmerch.directpos.de/rest-api/apidoc/v2.1/index.html#creditCard3DSecureInitializingThePaymentSsteps1_4 ## 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)? --> **Cypress Tests** **1. No3DSManualCapture** ![image](https://github.com/user-attachments/assets/cca4c8ed-2205-419b-8eb4-4759daf20f8a) **2. 3DSAutoCapture** ![image](https://github.com/user-attachments/assets/38318c13-fba1-40f9-a4a8-16ee655e6127) **3. 3DSManualCapture** ![image](https://github.com/user-attachments/assets/58c72d9d-9668-49dd-a8af-20c6f7407b2c) **4. No3DSAutoCapture** ![image](https://github.com/user-attachments/assets/bc0b897d-5f45-4878-9a98-1498e8c9ce82) **5. VoidPayment** ![image](https://github.com/user-attachments/assets/3cedc848-9b4c-4d95-bc66-9019085648d1) **6. SyncPayment** ![image](https://github.com/user-attachments/assets/b4508f59-95b7-49e7-b079-df8933b38c3e) **7. RefundPayment** ![image](https://github.com/user-attachments/assets/b8372b26-3945-47b6-afa7-06ca75b267f9) **8. SyncRefund** ![image](https://github.com/user-attachments/assets/625f7bab-1c1f-4e89-8c89-9c4793cf78d9) Note: Currently, no 3ds for card payments are not being supported for Deutschebank. Hence, no 3ds flows are expected to return an error message saying that the payment method type is not supported, and has been handled in the cypress tests accordingly. **Postman Tests** **1. Authorize (Manual)** - Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_o6c9H4UPb00h8hMpjOww9sHv5IWOqwTuJrNC45fOVdUdPOs0sjRQ7peoX7KgqRWp' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "capture_method": "manual", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "cybersourcecustomer", "email": "[email protected]", "name": "Cardholder", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4761739090000088", "card_exp_month": "12", "card_exp_year": "34", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "online" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari", "last_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari", "last_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "count_tickets": 1, "transaction_number": "5590045" } }' ``` - Response ``` { "payment_id": "pay_PS9a7QNMXDs1Qr3GjLSV", "merchant_id": "postman_merchant_GHAction_89b212fc-9f25-469f-ba4b-1a3288efcdd6", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": null, "connector": "deutschebank", "client_secret": "pay_PS9a7QNMXDs1Qr3GjLSV_secret_dfXLVVwCzeorfBNuOGCD", "created": "2024-12-16T11:36:46.533Z", "currency": "USD", "customer_id": "cybersourcecustomer", "customer": { "id": "cybersourcecustomer", "name": "Cardholder", "email": "[email protected]", "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": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0088", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "476173", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "34", "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": "sundari", "last_name": "sundari" }, "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": "sundari", "last_name": "sundari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "Cardholder", "phone": "999999999", "return_url": "https://duck.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_PS9a7QNMXDs1Qr3GjLSV/postman_merchant_GHAction_89b212fc-9f25-469f-ba4b-1a3288efcdd6/pay_PS9a7QNMXDs1Qr3GjLSV_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": "deutschebank_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cybersourcecustomer", "created_at": 1734349006, "expires": 1734352606, "secret": "epk_0036b25eb0ef4d599e0b2957ff64beb3" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_hwz1M9UiyP6KcFovaoe2", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tQJBbQeTqAOBfStOjwz6", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-16T11:51:46.533Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-16T11:36:49.083Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **2. Capture (Manual)** - Request ``` curl --location 'http://localhost:8080/payments/pay_PS9a7QNMXDs1Qr3GjLSV/capture' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_o6c9H4UPb00h8hMpjOww9sHv5IWOqwTuJrNC45fOVdUdPOs0sjRQ7peoX7KgqRWp' \ --data '{ "amount_to_capture": 6540, "statement_descriptor_name": "Joseph", "statement_descriptor_suffix": "JS" }' ``` - Response ``` { "payment_id": "pay_PS9a7QNMXDs1Qr3GjLSV", "merchant_id": "postman_merchant_GHAction_89b212fc-9f25-469f-ba4b-1a3288efcdd6", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "deutschebank", "client_secret": "pay_PS9a7QNMXDs1Qr3GjLSV_secret_dfXLVVwCzeorfBNuOGCD", "created": "2024-12-16T11:36:46.533Z", "currency": "USD", "customer_id": "cybersourcecustomer", "customer": { "id": "cybersourcecustomer", "name": "Cardholder", "email": "[email protected]", "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": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0088", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "476173", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "34", "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": "sundari", "last_name": "sundari" }, "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": "sundari", "last_name": "sundari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "Cardholder", "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": "credit", "connector_label": "deutschebank_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "nAYkZmc4a3I6pxU53fJzNP", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_hwz1M9UiyP6KcFovaoe2", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tQJBbQeTqAOBfStOjwz6", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-16T11:51:46.533Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_RncRqkyYbJrKGoU8Ywnr", "payment_method_status": null, "updated": "2024-12-16T11:37:16.619Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **3. Authorize + Capture** - Request ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_o6c9H4UPb00h8hMpjOww9sHv5IWOqwTuJrNC45fOVdUdPOs0sjRQ7peoX7KgqRWp' \ --data-raw '{ "amount": 6540, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "cybersourcecustomer", "email": "[email protected]", "name": "Cardholder", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "authentication_type": "three_ds", "return_url": "https://duck.com", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4761739090000088", "card_exp_month": "12", "card_exp_year": "34", "card_holder_name": "joseph Doe", "card_cvc": "123" } }, "customer_acceptance": { "acceptance_type": "online" }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari", "last_name": "sundari" } }, "shipping": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "sundari", "last_name": "sundari" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "count_tickets": 1, "transaction_number": "5590045" } }' ``` - Response ``` { "payment_id": "pay_4ueYRDmGUyI31AuqI0ea", "merchant_id": "postman_merchant_GHAction_89b212fc-9f25-469f-ba4b-1a3288efcdd6", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": null, "connector": "deutschebank", "client_secret": "pay_4ueYRDmGUyI31AuqI0ea_secret_IixVMy93O7YiEP4JJGpN", "created": "2024-12-16T11:43:10.558Z", "currency": "USD", "customer_id": "cybersourcecustomer", "customer": { "id": "cybersourcecustomer", "name": "Cardholder", "email": "[email protected]", "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": "card", "payment_method_data": { "card": { "last4": "0088", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "476173", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "34", "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": "sundari", "last_name": "sundari" }, "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": "sundari", "last_name": "sundari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "Cardholder", "phone": "999999999", "return_url": "https://duck.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_4ueYRDmGUyI31AuqI0ea/postman_merchant_GHAction_89b212fc-9f25-469f-ba4b-1a3288efcdd6/pay_4ueYRDmGUyI31AuqI0ea_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": "deutschebank_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "cybersourcecustomer", "created_at": 1734349390, "expires": 1734352990, "secret": "epk_df66b67348a9425dabef0cf41381d6f4" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_hwz1M9UiyP6KcFovaoe2", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tQJBbQeTqAOBfStOjwz6", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-16T11:58:10.558Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-16T11:43:14.008Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **4. PSync** - Request ``` curl --location 'http://localhost:8080/payments/pay_4ueYRDmGUyI31AuqI0ea?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_o6c9H4UPb00h8hMpjOww9sHv5IWOqwTuJrNC45fOVdUdPOs0sjRQ7peoX7KgqRWp' ``` - Response ``` { "payment_id": "pay_4ueYRDmGUyI31AuqI0ea", "merchant_id": "postman_merchant_GHAction_89b212fc-9f25-469f-ba4b-1a3288efcdd6", "status": "succeeded", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": 6540, "connector": "deutschebank", "client_secret": "pay_4ueYRDmGUyI31AuqI0ea_secret_IixVMy93O7YiEP4JJGpN", "created": "2024-12-16T11:43:10.558Z", "currency": "USD", "customer_id": "cybersourcecustomer", "customer": { "id": "cybersourcecustomer", "name": "Cardholder", "email": "[email protected]", "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": "card", "payment_method_data": { "card": { "last4": "0088", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "476173", "card_extended_bin": null, "card_exp_month": "12", "card_exp_year": "34", "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": "sundari", "last_name": "sundari" }, "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": "sundari", "last_name": "sundari" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "name": "Cardholder", "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": "credit", "connector_label": "deutschebank_US_default", "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": null, "manual_retry_allowed": false, "connector_transaction_id": "nVHvIf4P3jcAovFh4yPRTj", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_hwz1M9UiyP6KcFovaoe2", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tQJBbQeTqAOBfStOjwz6", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-16T11:58:10.558Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_nsOk8a7WMuZY0WZfZaNb", "payment_method_status": "active", "updated": "2024-12-16T11:45:26.008Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **5. Refund** - Request ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_o6c9H4UPb00h8hMpjOww9sHv5IWOqwTuJrNC45fOVdUdPOs0sjRQ7peoX7KgqRWp' \ --data '{ "payment_id": "pay_ySLbJ4uxZJbOwybYIOxJ", "amount": 6540, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` - Response ``` { "refund_id": "ref_UbPDiWkAlJ3YXxAVydkh", "payment_id": "pay_ySLbJ4uxZJbOwybYIOxJ", "amount": 6540, "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-12-16T11:47:19.520Z", "updated_at": "2024-12-16T11:47:21.373Z", "connector": "deutschebank", "profile_id": "pro_hwz1M9UiyP6KcFovaoe2", "merchant_connector_id": "mca_tQJBbQeTqAOBfStOjwz6", "split_refunds": null } ``` **6. RSync** - Request ``` curl --location 'http://localhost:8080/refunds/ref_UbPDiWkAlJ3YXxAVydkh' \ --header 'Accept: application/json' \ --header 'api-key: dev_o6c9H4UPb00h8hMpjOww9sHv5IWOqwTuJrNC45fOVdUdPOs0sjRQ7peoX7KgqRWp' ``` - Response ``` { "refund_id": "ref_UbPDiWkAlJ3YXxAVydkh", "payment_id": "pay_ySLbJ4uxZJbOwybYIOxJ", "amount": 6540, "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-12-16T11:47:19.520Z", "updated_at": "2024-12-16T11:47:21.373Z", "connector": "deutschebank", "profile_id": "pro_hwz1M9UiyP6KcFovaoe2", "merchant_connector_id": "mca_tQJBbQeTqAOBfStOjwz6", "split_refunds": null } ``` **7. Cancel/Void** - Request ``` curl --location 'http://localhost:8080/payments/pay_jtzc7sPBlQ6sNNgoPG7D/cancel' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_o6c9H4UPb00h8hMpjOww9sHv5IWOqwTuJrNC45fOVdUdPOs0sjRQ7peoX7KgqRWp' \ --data '{ "cancellation_reason": "requested_by_customer" }' ``` - Response ``` { "payment_id": "pay_jtzc7sPBlQ6sNNgoPG7D", "merchant_id": "postman_merchant_GHAction_89b212fc-9f25-469f-ba4b-1a3288efcdd6", "status": "cancelled", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "deutschebank", "client_secret": "pay_jtzc7sPBlQ6sNNgoPG7D_secret_nRyINaFU4g6pBbm8id0r", "created": "2024-12-16T11:51:03.676Z", "currency": "USD", "customer_id": "cybersourcecustomer", "customer": { "id": "cybersourcecustomer", "name": "John Doe", "email": "[email protected]", "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": "manual", "payment_method": "card", "payment_method_data": { "card": { "last4": "0088", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "476173", "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": "likhin", "last_name": "bopanna" }, "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": "likhin", "last_name": "bopanna" }, "phone": null, "email": null }, "order_details": null, "email": "[email protected]", "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": "requested_by_customer", "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": "pZEtlCeAsWQZqLpBNhZto5", "frm_message": null, "metadata": { "count_tickets": 1, "transaction_number": "5590045" }, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_hwz1M9UiyP6KcFovaoe2", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_tQJBbQeTqAOBfStOjwz6", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-16T12:06:03.676Z", "fingerprint": null, "browser_info": null, "payment_method_id": "pm_lbLyNoKaCcTRjxwQKYON", "payment_method_status": null, "updated": "2024-12-16T11:51:35.365Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` **8. Supported Payments** -Request ``` curl --location --request GET 'http://localhost:8080/feature_matrix' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_jfD66VYra1Ckqm2IxU5cy1N4chjamXfyyOyXUqNEmHv0pSyCjZh3DvqOBKR0HyU8' \ --header 'X-Merchant-Id: postman_merchant_GHAction_32615a11-9334-48e0-8c5f-767da86facd7' \ --data '{ }' ``` -Response ``` { "connector_count": 3, "connectors": [ { "name": "bambora", "description": "Bambora is a leading online payment provider in Canada and United States.", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "CA", "US" ], "supported_currencies": [ "USD" ] }, { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": [ "US", "CA" ], "supported_currencies": [ "USD" ] } ], "supported_webhook_flows": [] }, { "name": "deutschebank", "description": "Deutsche Bank is a German multinational investment bank and financial services company ", "category": "bank_acquirer", "supported_payment_methods": [ { "payment_method": "card", "payment_method_type": "credit", "mandates": "not_supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null }, { "payment_method": "bank_debit", "payment_method_type": "sepa", "mandates": "supported", "refunds": "supported", "supported_capture_methods": [ "automatic", "manual", "sequential_automatic" ], "supported_countries": null, "supported_currencies": null } ], "supported_webhook_flows": [] }, { "name": "zsl", "description": "Zsl is a payment gateway operating in China, specializing in facilitating local bank transfers", "category": "payment_gateway", "supported_payment_methods": [ { "payment_method": "bank_transfer", "payment_method_type": "local_bank_transfer", "mandates": "not_supported", "refunds": "not_supported", "supported_capture_methods": [ "automatic" ], "supported_countries": [ "CN" ], "supported_currencies": [ "CNY" ] } ], "supported_webhook_flows": [] } ] } ``` ## 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
3eb2eb1cf5b9855432b49994b433e6f7fa404212
juspay/hyperswitch
juspay__hyperswitch-6841
Bug: Add support to pass apple pay recurring details in the payment request Whenever a customer makes an Applepay payment a unique network token called a DPAN (Device Primary Account Number) is created and stored securely on the customer’s Apple device. This token acts as the payment information for all purchases and keeps the raw card number safe from bad actors. However, Apple Pay’s DPAN (Device Primary Account Number) may not be ideal for all subscription businesses, because it can result in involuntary churn. Visa is making enhancements to network tokens to ensure their continued compatibility with follow-on transactions. Due to these changes, there is impact to a few use cases for Apple Pay recurring transactions. [Beginning July 30th, 2025, the current device generated Apple Pay network tokens will no longer be applicable for Standing Instruction transactions](https://support.visaacceptance.com/knowledgebase/knowledgearticle/?code=KA-04318). Standing Instruction use cases constitute recurring, installments, or unscheduled credential on file token usages. In order to add support apple pay MPAN recurring object needs to be passed to apple pay in the /sessions call.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index ee5654cfb6b..17849948516 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -3288,12 +3288,169 @@ } ], "nullable": true + }, + "recurring_payment_request": { + "allOf": [ + { + "$ref": "#/components/schemas/ApplePayRecurringPaymentRequest" + } + ], + "nullable": true + } + } + }, + "ApplePayPaymentTiming": { + "type": "string", + "enum": [ + "immediate", + "recurring" + ] + }, + "ApplePayRecurringDetails": { + "type": "object", + "required": [ + "payment_description", + "regular_billing", + "management_url" + ], + "properties": { + "payment_description": { + "type": "string", + "description": "A description of the recurring payment that Apple Pay displays to the user in the payment sheet" + }, + "regular_billing": { + "$ref": "#/components/schemas/ApplePayRegularBillingDetails" + }, + "billing_agreement": { + "type": "string", + "description": "A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment", + "nullable": true + }, + "management_url": { + "type": "string", + "description": "A URL to a web page where the user can update or delete the payment method for the recurring payment", + "example": "https://hyperswitch.io" + } + } + }, + "ApplePayRecurringPaymentRequest": { + "type": "object", + "required": [ + "payment_description", + "regular_billing", + "management_url" + ], + "properties": { + "payment_description": { + "type": "string", + "description": "A description of the recurring payment that Apple Pay displays to the user in the payment sheet" + }, + "regular_billing": { + "$ref": "#/components/schemas/ApplePayRegularBillingRequest" + }, + "billing_agreement": { + "type": "string", + "description": "A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment", + "nullable": true + }, + "management_url": { + "type": "string", + "description": "A URL to a web page where the user can update or delete the payment method for the recurring payment", + "example": "https://hyperswitch.io" } } }, "ApplePayRedirectData": { "type": "object" }, + "ApplePayRegularBillingDetails": { + "type": "object", + "required": [ + "label" + ], + "properties": { + "label": { + "type": "string", + "description": "The label that Apple Pay displays to the user in the payment sheet with the recurring details" + }, + "recurring_payment_start_date": { + "type": "string", + "format": "date-time", + "description": "The date of the first payment", + "example": "2023-09-10T23:59:59Z", + "nullable": true + }, + "recurring_payment_end_date": { + "type": "string", + "format": "date-time", + "description": "The date of the final payment", + "example": "2023-09-10T23:59:59Z", + "nullable": true + }, + "recurring_payment_interval_unit": { + "allOf": [ + { + "$ref": "#/components/schemas/RecurringPaymentIntervalUnit" + } + ], + "nullable": true + }, + "recurring_payment_interval_count": { + "type": "integer", + "format": "int32", + "description": "The number of interval units that make up the total payment interval", + "nullable": true + } + } + }, + "ApplePayRegularBillingRequest": { + "type": "object", + "required": [ + "amount", + "label", + "payment_timing" + ], + "properties": { + "amount": { + "type": "string", + "description": "The amount of the recurring payment", + "example": "38.02" + }, + "label": { + "type": "string", + "description": "The label that Apple Pay displays to the user in the payment sheet with the recurring details" + }, + "payment_timing": { + "$ref": "#/components/schemas/ApplePayPaymentTiming" + }, + "recurring_payment_start_date": { + "type": "string", + "format": "date-time", + "description": "The date of the first payment", + "nullable": true + }, + "recurring_payment_end_date": { + "type": "string", + "format": "date-time", + "description": "The date of the final payment", + "nullable": true + }, + "recurring_payment_interval_unit": { + "allOf": [ + { + "$ref": "#/components/schemas/RecurringPaymentIntervalUnit" + } + ], + "nullable": true + }, + "recurring_payment_interval_count": { + "type": "integer", + "format": "int32", + "description": "The number of interval units that make up the total payment interval", + "nullable": true + } + } + }, "ApplePaySessionResponse": { "oneOf": [ { @@ -8396,6 +8553,14 @@ }, "description": "Additional tags to be used for global search", "nullable": true + }, + "apple_pay_recurring_details": { + "allOf": [ + { + "$ref": "#/components/schemas/ApplePayRecurringDetails" + } + ], + "nullable": true } } }, @@ -18323,6 +18488,16 @@ "propertyName": "type" } }, + "RecurringPaymentIntervalUnit": { + "type": "string", + "enum": [ + "year", + "month", + "day", + "hour", + "minute" + ] + }, "RedirectResponse": { "type": "object", "properties": { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 2464cdf62db..f0b59dfe375 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -6227,6 +6227,57 @@ pub struct ApplePayPaymentRequest { #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, + /// Recurring payment request for apple pay Merchant Token + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct ApplePayRecurringPaymentRequest { + /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet + pub payment_description: String, + /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count + pub regular_billing: ApplePayRegularBillingRequest, + /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment + #[serde(skip_serializing_if = "Option::is_none")] + pub billing_agreement: Option<String>, + /// A URL to a web page where the user can update or delete the payment method for the recurring payment + #[schema(value_type = String, example = "https://hyperswitch.io")] + pub management_url: common_utils::types::Url, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct ApplePayRegularBillingRequest { + /// The amount of the recurring payment + #[schema(value_type = String, example = "38.02")] + pub amount: StringMajorUnit, + /// The label that Apple Pay displays to the user in the payment sheet with the recurring details + pub label: String, + /// The time that the payment occurs as part of a successful transaction + pub payment_timing: ApplePayPaymentTiming, + /// The date of the first payment + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub recurring_payment_start_date: Option<PrimitiveDateTime>, + /// The date of the final payment + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub recurring_payment_end_date: Option<PrimitiveDateTime>, + /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, + /// The number of interval units that make up the total payment interval + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring_payment_interval_count: Option<i32>, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ApplePayPaymentTiming { + /// A value that specifies that the payment occurs when the transaction is complete + Immediate, + /// A value that specifies that the payment occurs on a regular basis + Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] @@ -6504,6 +6555,49 @@ pub struct FeatureMetadata { /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, + /// Recurring payment details required for apple pay Merchant Token + pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct ApplePayRecurringDetails { + /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet + pub payment_description: String, + /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count + pub regular_billing: ApplePayRegularBillingDetails, + /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment + pub billing_agreement: Option<String>, + /// A URL to a web page where the user can update or delete the payment method for the recurring payment + #[schema(value_type = String, example = "https://hyperswitch.io")] + pub management_url: common_utils::types::Url, +} + +#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] +pub struct ApplePayRegularBillingDetails { + /// The label that Apple Pay displays to the user in the payment sheet with the recurring details + pub label: String, + /// The date of the first payment + #[schema(example = "2023-09-10T23:59:59Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub recurring_payment_start_date: Option<PrimitiveDateTime>, + /// The date of the final payment + #[schema(example = "2023-09-10T23:59:59Z")] + #[serde(default, with = "common_utils::custom_serde::iso8601::option")] + pub recurring_payment_end_date: Option<PrimitiveDateTime>, + /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval + pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, + /// The number of interval units that make up the total payment interval + pub recurring_payment_interval_count: Option<i32>, +} + +#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum RecurringPaymentIntervalUnit { + Year, + Month, + Day, + Hour, + Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index 94f1fa8d266..31a9672b910 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -44,8 +44,55 @@ pub struct FeatureMetadata { // TODO: Convert this to hashedstrings to avoid PII sensitive data /// Additional tags to be used for global search pub search_tags: Option<Vec<HashedString<WithType>>>, + /// Recurring payment details required for apple pay Merchant Token + pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } -impl masking::SerializableSecret for FeatureMetadata {} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] +#[diesel(sql_type = Json)] +pub struct ApplePayRecurringDetails { + /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet + pub payment_description: String, + /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count + pub regular_billing: ApplePayRegularBillingDetails, + /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment + pub billing_agreement: Option<String>, + /// A URL to a web page where the user can update or delete the payment method for the recurring payment + pub management_url: common_utils::types::Url, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] +#[diesel(sql_type = Json)] +pub struct ApplePayRegularBillingDetails { + /// The label that Apple Pay displays to the user in the payment sheet with the recurring details + pub label: String, + /// The date of the first payment + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub recurring_payment_start_date: Option<time::PrimitiveDateTime>, + /// The date of the final payment + #[serde(with = "common_utils::custom_serde::iso8601::option")] + pub recurring_payment_end_date: Option<time::PrimitiveDateTime>, + /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval + pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, + /// The number of interval units that make up the total payment interval + pub recurring_payment_interval_count: Option<i32>, +} + +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, FromSqlRow, AsExpression)] +#[diesel(sql_type = Json)] +#[serde(rename_all = "snake_case")] +pub enum RecurringPaymentIntervalUnit { + Year, + Month, + Day, + Hour, + Minute, +} + +common_utils::impl_to_sql_from_sql_json!(ApplePayRecurringDetails); +common_utils::impl_to_sql_from_sql_json!(ApplePayRegularBillingDetails); +common_utils::impl_to_sql_from_sql_json!(RecurringPaymentIntervalUnit); + common_utils::impl_to_sql_from_sql_json!(FeatureMetadata); #[derive(Default, Debug, Eq, PartialEq, Deserialize, Serialize, Clone)] diff --git a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs index 2e4503c3469..7970b1b1d42 100644 --- a/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs @@ -555,6 +555,7 @@ impl merchant_identifier: Some(session_token_data.merchant_identifier), required_billing_contact_fields: None, required_shipping_contact_fields: None, + recurring_payment_request: None, }), connector: "bluesnap".to_string(), delayed_session_token: false, diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 0e8722644bd..4b78fd3c788 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -32,10 +32,16 @@ pub trait PayoutAttemptInterface {} pub trait PayoutsInterface {} use api_models::payments::{ + ApplePayRecurringDetails as ApiApplePayRecurringDetails, + ApplePayRegularBillingDetails as ApiApplePayRegularBillingDetails, FeatureMetadata as ApiFeatureMetadata, OrderDetailsWithAmount as ApiOrderDetailsWithAmount, + RecurringPaymentIntervalUnit as ApiRecurringPaymentIntervalUnit, RedirectResponse as ApiRedirectResponse, }; -use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount, RedirectResponse}; +use diesel_models::types::{ + ApplePayRecurringDetails, ApplePayRegularBillingDetails, FeatureMetadata, + OrderDetailsWithAmount, RecurringPaymentIntervalUnit, RedirectResponse, +}; #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] pub enum RemoteStorageObject<T: ForeignIDRef> { @@ -75,10 +81,13 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { let ApiFeatureMetadata { redirect_response, search_tags, + apple_pay_recurring_details, } = from; Self { redirect_response: redirect_response.map(RedirectResponse::convert_from), search_tags, + apple_pay_recurring_details: apple_pay_recurring_details + .map(ApplePayRecurringDetails::convert_from), } } @@ -86,11 +95,14 @@ impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata { let Self { redirect_response, search_tags, + apple_pay_recurring_details, } = self; ApiFeatureMetadata { redirect_response: redirect_response .map(|redirect_response| redirect_response.convert_back()), search_tags, + apple_pay_recurring_details: apple_pay_recurring_details + .map(|value| value.convert_back()), } } } @@ -119,6 +131,77 @@ impl ApiModelToDieselModelConvertor<ApiRedirectResponse> for RedirectResponse { } } +impl ApiModelToDieselModelConvertor<ApiRecurringPaymentIntervalUnit> + for RecurringPaymentIntervalUnit +{ + fn convert_from(from: ApiRecurringPaymentIntervalUnit) -> Self { + match from { + ApiRecurringPaymentIntervalUnit::Year => Self::Year, + ApiRecurringPaymentIntervalUnit::Month => Self::Month, + ApiRecurringPaymentIntervalUnit::Day => Self::Day, + ApiRecurringPaymentIntervalUnit::Hour => Self::Hour, + ApiRecurringPaymentIntervalUnit::Minute => Self::Minute, + } + } + fn convert_back(self) -> ApiRecurringPaymentIntervalUnit { + match self { + Self::Year => ApiRecurringPaymentIntervalUnit::Year, + Self::Month => ApiRecurringPaymentIntervalUnit::Month, + Self::Day => ApiRecurringPaymentIntervalUnit::Day, + Self::Hour => ApiRecurringPaymentIntervalUnit::Hour, + Self::Minute => ApiRecurringPaymentIntervalUnit::Minute, + } + } +} + +impl ApiModelToDieselModelConvertor<ApiApplePayRegularBillingDetails> + for ApplePayRegularBillingDetails +{ + fn convert_from(from: ApiApplePayRegularBillingDetails) -> Self { + Self { + label: from.label, + recurring_payment_start_date: from.recurring_payment_start_date, + recurring_payment_end_date: from.recurring_payment_end_date, + recurring_payment_interval_unit: from + .recurring_payment_interval_unit + .map(RecurringPaymentIntervalUnit::convert_from), + recurring_payment_interval_count: from.recurring_payment_interval_count, + } + } + + fn convert_back(self) -> ApiApplePayRegularBillingDetails { + ApiApplePayRegularBillingDetails { + label: self.label, + recurring_payment_start_date: self.recurring_payment_start_date, + recurring_payment_end_date: self.recurring_payment_end_date, + recurring_payment_interval_unit: self + .recurring_payment_interval_unit + .map(|value| value.convert_back()), + recurring_payment_interval_count: self.recurring_payment_interval_count, + } + } +} + +impl ApiModelToDieselModelConvertor<ApiApplePayRecurringDetails> for ApplePayRecurringDetails { + fn convert_from(from: ApiApplePayRecurringDetails) -> Self { + Self { + payment_description: from.payment_description, + regular_billing: ApplePayRegularBillingDetails::convert_from(from.regular_billing), + billing_agreement: from.billing_agreement, + management_url: from.management_url, + } + } + + fn convert_back(self) -> ApiApplePayRecurringDetails { + ApiApplePayRecurringDetails { + payment_description: self.payment_description, + regular_billing: self.regular_billing.convert_back(), + billing_agreement: self.billing_agreement, + management_url: self.management_url, + } + } +} + impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsWithAmount { fn convert_from(from: ApiOrderDetailsWithAmount) -> Self { let ApiOrderDetailsWithAmount { diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 2f68b481d88..210047f8e1f 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -830,6 +830,7 @@ pub struct PaymentsSessionData { pub email: Option<pii::Email>, // Minor Unit amount for amount frame work pub minor_amount: MinorUnit, + pub apple_pay_recurring_details: Option<api_models::payments::ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Default)] diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 7ad5645e75a..5a3fb3ac649 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -416,6 +416,12 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::ApplePayPaymentRequest, api_models::payments::ApplePayBillingContactFields, api_models::payments::ApplePayShippingContactFields, + api_models::payments::ApplePayRecurringPaymentRequest, + api_models::payments::ApplePayRegularBillingRequest, + api_models::payments::ApplePayPaymentTiming, + api_models::payments::RecurringPaymentIntervalUnit, + api_models::payments::ApplePayRecurringDetails, + api_models::payments::ApplePayRegularBillingDetails, api_models::payments::ApplePayAddressParameters, api_models::payments::AmountInfo, api_models::payments::ClickToPaySessionResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index 5a5454e2505..f197f843afb 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -380,6 +380,12 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::ApplePayBillingContactFields, api_models::payments::ApplePayShippingContactFields, api_models::payments::ApplePayAddressParameters, + api_models::payments::ApplePayRecurringPaymentRequest, + api_models::payments::ApplePayRegularBillingRequest, + api_models::payments::ApplePayPaymentTiming, + api_models::payments::RecurringPaymentIntervalUnit, + api_models::payments::ApplePayRecurringDetails, + api_models::payments::ApplePayRegularBillingDetails, api_models::payments::AmountInfo, api_models::payments::GooglePayWalletData, api_models::payments::PayPalWalletData, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 7b6b67c8408..0e88ae23665 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -579,6 +579,7 @@ impl<F> merchant_identifier: None, required_billing_contact_fields: None, required_shipping_contact_fields: None, + recurring_payment_request: None, }, ), connector: "payme".to_string(), diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index dafca256529..c20cc1aeb3a 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1231,6 +1231,7 @@ pub fn get_apple_pay_session<F, T>( merchant_identifier: None, required_billing_contact_fields: None, required_shipping_contact_fields: None, + recurring_payment_request: None, }), connector: "trustpay".to_string(), delayed_session_token: true, diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e8a591437de..7466b638922 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -1769,6 +1769,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize { json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()), }), search_tags: None, + apple_pay_recurring_details: None, }), ..Default::default() }; @@ -2230,6 +2231,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize { ), }), search_tags: None, + apple_pay_recurring_details: None, }), ..Default::default() }; diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 464781f3d7c..1e3432220ac 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -715,6 +715,7 @@ fn get_apple_pay_payment_request( merchant_identifier: Some(merchant_identifier.to_string()), required_billing_contact_fields, required_shipping_contact_fields, + recurring_payment_request: session_data.apple_pay_recurring_details, }; Ok(applepay_payment_request) } diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 92486320cde..f48dd6915c9 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -8,7 +8,10 @@ use common_enums::{Currency, RequestIncrementalAuthorization}; use common_utils::{ consts::X_HS_LATENCY, fp_utils, pii, - types::{self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnitForConnector}, + types::{ + self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnit, + StringMajorUnitForConnector, + }, }; use diesel_models::{ ephemeral_key, @@ -562,6 +565,25 @@ pub async fn construct_payment_router_data_for_sdk_session<'a>( .map(|order_detail| order_detail.expose()) .collect() }); + let required_amount_type = StringMajorUnitForConnector; + + let apple_pay_amount = required_amount_type + .convert( + payment_data.payment_intent.amount_details.order_amount, + payment_data.payment_intent.amount_details.currency, + ) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert amount to string major unit for applePay".to_string(), + })?; + + let apple_pay_recurring_details = payment_data + .payment_intent + .feature_metadata + .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) + .map(|apple_pay_recurring_details| { + ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount)) + }); + // TODO: few fields are repeated in both routerdata and request let request = types::PaymentsSessionData { amount: payment_data @@ -585,6 +607,7 @@ pub async fn construct_payment_router_data_for_sdk_session<'a>( order_details, email, minor_amount: payment_data.payment_intent.amount_details.order_amount, + apple_pay_recurring_details, }; // TODO: evaluate the fields in router data, if they are required or not @@ -3097,6 +3120,22 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD // net_amount here would include amount, surcharge_amount and shipping_cost let net_amount = amount + surcharge_amount + shipping_cost; + let required_amount_type = StringMajorUnitForConnector; + + let apple_pay_amount = required_amount_type + .convert(net_amount, payment_data.currency) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert amount to string major unit for applePay".to_string(), + })?; + + let apple_pay_recurring_details = payment_data + .payment_intent + .feature_metadata + .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) + .map(|apple_pay_recurring_details| { + ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount)) + }); + Ok(Self { amount: amount.get_amount_as_i64(), //need to change once we move to connector module minor_amount: amount, @@ -3112,6 +3151,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD order_details, surcharge_details: payment_data.surcharge_details, email: payment_data.email, + apple_pay_recurring_details, }) } } @@ -3158,6 +3198,29 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD // net_amount here would include amount, surcharge_amount and shipping_cost let net_amount = amount + surcharge_amount + shipping_cost; + let required_amount_type = StringMajorUnitForConnector; + + let apple_pay_amount = required_amount_type + .convert(net_amount, payment_data.currency) + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: "Failed to convert amount to string major unit for applePay".to_string(), + })?; + + let apple_pay_recurring_details = payment_data + .payment_intent + .feature_metadata + .map(|feature_metadata| { + feature_metadata + .parse_value::<diesel_models::types::FeatureMetadata>("FeatureMetadata") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed parsing FeatureMetadata") + }) + .transpose()? + .and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details) + .map(|apple_pay_recurring_details| { + ForeignFrom::foreign_from((apple_pay_recurring_details, apple_pay_amount)) + }); + Ok(Self { amount: net_amount.get_amount_as_i64(), //need to change once we move to connector module minor_amount: amount, @@ -3173,10 +3236,99 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD order_details, email: payment_data.email, surcharge_details: payment_data.surcharge_details, + apple_pay_recurring_details, }) } } +impl + ForeignFrom<( + diesel_models::types::ApplePayRecurringDetails, + StringMajorUnit, + )> for api_models::payments::ApplePayRecurringPaymentRequest +{ + fn foreign_from( + (apple_pay_recurring_details, net_amount): ( + diesel_models::types::ApplePayRecurringDetails, + StringMajorUnit, + ), + ) -> Self { + Self { + payment_description: apple_pay_recurring_details.payment_description, + regular_billing: api_models::payments::ApplePayRegularBillingRequest { + amount: net_amount, + label: apple_pay_recurring_details.regular_billing.label, + payment_timing: api_models::payments::ApplePayPaymentTiming::Recurring, + recurring_payment_start_date: apple_pay_recurring_details + .regular_billing + .recurring_payment_start_date, + recurring_payment_end_date: apple_pay_recurring_details + .regular_billing + .recurring_payment_end_date, + recurring_payment_interval_unit: apple_pay_recurring_details + .regular_billing + .recurring_payment_interval_unit + .map(ForeignFrom::foreign_from), + recurring_payment_interval_count: apple_pay_recurring_details + .regular_billing + .recurring_payment_interval_count, + }, + billing_agreement: apple_pay_recurring_details.billing_agreement, + management_url: apple_pay_recurring_details.management_url, + } + } +} + +impl ForeignFrom<diesel_models::types::ApplePayRecurringDetails> + for api_models::payments::ApplePayRecurringDetails +{ + fn foreign_from( + apple_pay_recurring_details: diesel_models::types::ApplePayRecurringDetails, + ) -> Self { + Self { + payment_description: apple_pay_recurring_details.payment_description, + regular_billing: ForeignFrom::foreign_from(apple_pay_recurring_details.regular_billing), + billing_agreement: apple_pay_recurring_details.billing_agreement, + management_url: apple_pay_recurring_details.management_url, + } + } +} + +impl ForeignFrom<diesel_models::types::ApplePayRegularBillingDetails> + for api_models::payments::ApplePayRegularBillingDetails +{ + fn foreign_from( + apple_pay_regular_billing: diesel_models::types::ApplePayRegularBillingDetails, + ) -> Self { + Self { + label: apple_pay_regular_billing.label, + recurring_payment_start_date: apple_pay_regular_billing.recurring_payment_start_date, + recurring_payment_end_date: apple_pay_regular_billing.recurring_payment_end_date, + recurring_payment_interval_unit: apple_pay_regular_billing + .recurring_payment_interval_unit + .map(ForeignFrom::foreign_from), + recurring_payment_interval_count: apple_pay_regular_billing + .recurring_payment_interval_count, + } + } +} + +impl ForeignFrom<diesel_models::types::RecurringPaymentIntervalUnit> + for api_models::payments::RecurringPaymentIntervalUnit +{ + fn foreign_from( + apple_pay_recurring_payment_interval_unit: diesel_models::types::RecurringPaymentIntervalUnit, + ) -> Self { + match apple_pay_recurring_payment_interval_unit { + diesel_models::types::RecurringPaymentIntervalUnit::Day => Self::Day, + diesel_models::types::RecurringPaymentIntervalUnit::Month => Self::Month, + diesel_models::types::RecurringPaymentIntervalUnit::Year => Self::Year, + diesel_models::types::RecurringPaymentIntervalUnit::Hour => Self::Hour, + diesel_models::types::RecurringPaymentIntervalUnit::Minute => Self::Minute, + } + } +} + #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequestData { type Error = error_stack::Report<errors::ApiErrorResponse>;
2024-12-06T12:20:54Z
## 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 --> Whenever a customer makes an Applepay payment a unique network token called a DPAN (Device Primary Account Number) is created and stored securely on the customer’s Apple device. This token acts as the payment information for all purchases and keeps the raw card number safe from bad actors. However, Apple Pay’s DPAN (Device Primary Account Number) may not be ideal for all subscription businesses, because it can result in involuntary churn. Visa is making enhancements to network tokens to ensure their continued compatibility with follow-on transactions. Due to these changes, there is impact to a few use cases for Apple Pay recurring transactions. [Beginning July 30th, 2025, the current device generated Apple Pay network tokens will no longer be applicable for Standing Instruction transactions](https://support.visaacceptance.com/knowledgebase/knowledgearticle/?code=KA-04318). Standing Instruction use cases constitute recurring, installments, or unscheduled credential on file token usages. In order to add support apple pay MPAN recurring object needs to be passed to apple pay in the /sessions call. This adds supports to accept the `ApplePayRecurringPaymentRequest` in the `FeatureMetadata` for the payment request. Based the request details passed the appropriate recurring details will be displayed in the apple pay modal during the customer authentication. ### 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). --> ## 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 account with applepay metadata to decrypt the apple pay token at hyperswitch -> Create a payment by passing `apple_pay_recurring_details` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_9ZJ9etprVKsDp4YNdgBxXsiq8bvL2ksaGVHJFTrBawKCd0ylxJb4hN8IAct6DTDa' \ --data-raw '{ "amount": 6100, "currency": "USD", "confirm": false, "business_country": "US", "business_label": "default", "amount_to_capture": 6100, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "return_url": "https://google.com", "email": "[email protected]", "setup_future_usage": "off_session", "name": "Joseph Doe", "phone": "999999999", "phone_country_code": "+65", "description": "Its my first payment request", "statement_descriptor_name": "Juspay", "statement_descriptor_suffix": "Router", "customer_id": "1733817585", "feature_metadata": { "apple_pay_recurring_details": { "payment_description": "this is the apple pay recurring payment", "regular_billing": { "amount": 10, "label": "pay to hyperswitch'\''s merchant", "recurring_payment_start_date": "2027-09-10T10:11:12.000Z", "recurring_payment_end_date": "2027-09-10T10:11:12.000Z", "recurring_payment_interval_unit": "year", "recurring_payment_interval_count": 1 }, "billing_agreement": "billing starts from the above mentioned start date", "management_url": "https://applepaydemo.apple.com" } }, "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_id": "pay_VMgqfeubSlEFDvzkl0uf", "merchant_id": "merchant_1733816953", "status": "requires_payment_method", "amount": 6100, "net_amount": 6100, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_VMgqfeubSlEFDvzkl0uf_secret_ewyd5zHoVQckfAXdzF9V", "created": "2024-12-10T07:59:03.063Z", "currency": "USD", "customer_id": "1733817543", "customer": { "id": "1733817543", "name": "Joseph Doe", "email": "[email protected]", "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": null, "payment_method_data": 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": "[email protected]", "name": "Joseph Doe", "phone": "999999999", "return_url": "https://google.com/", "authentication_type": null, "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": null, "connector_label": null, "business_country": "US", "business_label": "default", "business_sub_label": null, "allowed_payment_method_types": null, "ephemeral_key": { "customer_id": "1733817543", "created_at": 1733817543, "expires": 1733821143, "secret": "epk_8c23ceac435c470ea279d9ea0e1659ca" }, "manual_retry_allowed": null, "connector_transaction_id": null, "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": { "redirect_response": null, "search_tags": null, "apple_pay_recurring_details": { "payment_description": "this is the apple pay recurring payment", "regular_billing": { "amount": 10, "label": "pay to hyperswitch's merchant", "recurring_payment_start_date": "2027-09-10T10:11:12.000Z", "recurring_payment_end_date": "2027-09-10T10:11:12.000Z", "recurring_payment_interval_unit": "year", "recurring_payment_interval_count": 1 }, "billing_agreement": "billing starts from the above mentioned start date", "management_url": "https://applepaydemo.apple.com" } }, "reference_id": null, "payment_link": null, "profile_id": "pro_JcYIJy9B8xXAnFuBEdhc", "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-12-10T08:14:03.063Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-10T07:59:03.107Z", "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 'api-key: pk_dev_4bc816e9fc4549d6b50106976df7b29b' \ --data '{ "payment_id": "pay_VMgqfeubSlEFDvzkl0uf", "wallets": [], "client_secret": "pay_VMgqfeubSlEFDvzkl0uf_secret_ewyd5zHoVQckfAXdzF9V" }' ``` ``` { "payment_id": "pay_VMgqfeubSlEFDvzkl0uf", "client_secret": "pay_VMgqfeubSlEFDvzkl0uf_secret_ewyd5zHoVQckfAXdzF9V", "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": "61.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-VMgqfeubSlEFDvzkl0uf", "merchant": { "name": "Hyperswitch", "url": null, "country_code": "IN" }, "amount": { "option": "FORMAT_TOTAL_PRICE_ONLY", "currency_code": "USD", "total": "61.00" }, "protocol": "PROTOCOL3DS", "allowed_brands": [ "visa", "masterCard", "amex", "discover" ] }, { "wallet_name": "apple_pay", "session_token_data": { "epoch_timestamp": 1733817642366, "expires_at": 1733821242366, "merchant_session_identifier": "SSH9848925D8DD4473D8EA96E628A9F20C0_A0E617ED4A56A343E07C6E1255BD4098423B3A8E1243236462D07B14B4A0F7C3", "nonce": "ebdd4037", "merchant_identifier": "6ACD34193A900BA07E215155E3647CF4759340CF486BABAEE6C0840F9267AB10", "domain_name": "debuglab.basilisk-char.ts.net", "display_name": "Zurich Insurance (non-PROD)", "signature": "308006092a864886f70d010702a0803080020101310d300b0609608648016503040201308006092a864886f70d0107010000a080308203e330820388a003020102020816634c8b0e305717300a06082a8648ce3d040302307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3234303432393137343732375a170d3239303432383137343732365a305f3125302306035504030c1c6563632d736d702d62726f6b65722d7369676e5f5543342d50524f4431143012060355040b0c0b694f532053797374656d7331133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004c21577edebd6c7b2218f68dd7090a1218dc7b0bd6f2c283d846095d94af4a5411b83420ed811f3407e83331f1c54c3f7eb3220d6bad5d4eff49289893e7c0f13a38202113082020d300c0603551d130101ff04023000301f0603551d2304183016801423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b304506082b0601050507010104393037303506082b060105050730018629687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65616963613330323082011d0603551d2004820114308201103082010c06092a864886f7636405013081fe3081c306082b060105050702023081b60c81b352656c69616e6365206f6e207468697320636572746966696361746520627920616e7920706172747920617373756d657320616363657074616e6365206f6620746865207468656e206170706c696361626c65207374616e64617264207465726d7320616e6420636f6e646974696f6e73206f66207573652c20636572746966696361746520706f6c69637920616e642063657274696669636174696f6e2070726163746963652073746174656d656e74732e303606082b06010505070201162a687474703a2f2f7777772e6170706c652e636f6d2f6365727469666963617465617574686f726974792f30340603551d1f042d302b3029a027a0258623687474703a2f2f63726c2e6170706c652e636f6d2f6170706c6561696361332e63726c301d0603551d0e041604149457db6fd57481868989762f7e578507e79b5824300e0603551d0f0101ff040403020780300f06092a864886f76364061d04020500300a06082a8648ce3d0403020349003046022100c6f023cb2614bb303888a162983e1a93f1056f50fa78cdb9ba4ca241cc14e25e022100be3cd0dfd16247f6494475380e9d44c228a10890a3a1dc724b8b4cb8889818bc308202ee30820275a0030201020208496d2fbf3a98da97300a06082a8648ce3d0403023067311b301906035504030c124170706c6520526f6f74204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553301e170d3134303530363233343633305a170d3239303530363233343633305a307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b30090603550406130255533059301306072a8648ce3d020106082a8648ce3d03010703420004f017118419d76485d51a5e25810776e880a2efde7bae4de08dfc4b93e13356d5665b35ae22d097760d224e7bba08fd7617ce88cb76bb6670bec8e82984ff5445a381f73081f4304606082b06010505070101043a3038303606082b06010505073001862a687474703a2f2f6f6373702e6170706c652e636f6d2f6f63737030342d6170706c65726f6f7463616733301d0603551d0e0416041423f249c44f93e4ef27e6c4f6286c3fa2bbfd2e4b300f0603551d130101ff040530030101ff301f0603551d23041830168014bbb0dea15833889aa48a99debebdebafdacb24ab30370603551d1f0430302e302ca02aa0288626687474703a2f2f63726c2e6170706c652e636f6d2f6170706c65726f6f74636167332e63726c300e0603551d0f0101ff0404030201063010060a2a864886f7636406020e04020500300a06082a8648ce3d040302036700306402303acf7283511699b186fb35c356ca62bff417edd90f754da28ebef19c815e42b789f898f79b599f98d5410d8f9de9c2fe0230322dd54421b0a305776c5df3383b9067fd177c2c216d964fc6726982126f54f87a7d1b99cb9b0989216106990f09921d00003182018930820185020101308186307a312e302c06035504030c254170706c65204170706c69636174696f6e20496e746567726174696f6e204341202d20473331263024060355040b0c1d4170706c652043657274696669636174696f6e20417574686f7269747931133011060355040a0c0a4170706c6520496e632e310b3009060355040613025553020816634c8b0e305717300b0609608648016503040201a08193301806092a864886f70d010903310b06092a864886f70d010701301c06092a864886f70d010905310f170d3234313231303038303034325a302806092a864886f70d010934311b3019300b0609608648016503040201a10a06082a8648ce3d040302302f06092a864886f70d01090431220420ddd14d539103e445be353bf622995c58155b83740ac408582cfd95adffe59ccb300a06082a8648ce3d04030204483046022100a7071bc77f59318dc772a5e7e8a1270262a56887b019b2f449735169e2eebdf8022100c0682381a1d93da7cfa6928896cde5a58efec957855d82476531135bc359c04f000000000000", "operational_analytics_identifier": "Zurich Insurance (non-PROD):6ACD34193A900BA07E215155E3647CF4759340CF486BABAEE6C0840F9267AB10", "retries": 0, "psp_id": "6ACD34193A900BA07E215155E3647CF4759340CF486BABAEE6C0840F9267AB10" }, "payment_request_data": { "country_code": "AU", "currency_code": "USD", "total": { "label": "applepay", "type": "final", "amount": "61.00" }, "merchant_capabilities": [ "supports3DS" ], "supported_networks": [ "visa", "masterCard", "amex", "discover" ], "merchant_identifier": "merchant.sandbox.hyperswitch", "recurring_payment_request": { "payment_description": "this is the apple pay recurring payment", "regular_billing": { "amount": "10", "label": "pay to hyperswitch's merchant", "payment_timing": "recurring", "recurring_payment_start_date": "2027-09-10T10:11:12.000Z", "recurring_payment_end_date": "2027-09-10T10:11:12.000Z", "recurring_payment_interval_unit": "year", "recurring_payment_interval_count": 1 }, "billing_agreement": "billing starts from the above mentioned start date", "management_url": "https://applepaydemo.apple.com" } }, "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 the payment with the token ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_9ZJ9etprVKsDp4YNdgBxXsiq8bvL2ksaGVHJFTrBawKCd0ylxJb4hN8IAct6DTDa' \ --data-raw '{ "amount": 650, "currency": "USD", "confirm": true, "business_country": "US", "business_label": "default", "amount_to_capture": 650, "customer_id": "cu_1733817737", "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "authentication_type": "no_three_ds", "return_url": "https://google.com", "email": "[email protected]", "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": "apple_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": { "apple_pay": { "payment_data": "CnsiZGF0YSI6IjhmMFppZDhMTGd4U1dwcE84Z3VZY25pK3RacTVTcGRJTlFOYkszZGQyMTk5ZlJGTUZrazFNUjFORkFyM1pQMjVEaEtMaHZrM1B1c05GRlRDY0hqQ1g3OXlGWTZ6WEs5T2NLYVJqVllLa3lQOUdndnpxVm1CS3pYazhMV09Ba3JBdXZ4TlVjQW1aVnZIUDZ1Mm1zWEcrQ3JFdnA0TnE0dGxwTlQ3aGFjUm5zZFd6bmlFQ0dpYWw4R3ZwM1k3aWlyeGEvL0l6RkFHSkxjdk9qOURUTWh5NVBieXpzWGQ1S3JWVGU5U1ZKcEFmT3RXaERQOHN3NnlnUWV5SnJIT2hlcXNzY3VzT3FEclZBWW5HSTRYalB0bC91aXJFZTJDUmlRQ2lVY2ZTdDdVelNLODN5ZTB0d0ErdjlTZ2VTWUhZVlN6TWQwcGdkWnVLbkJWYmJRa0JNZElFTU56aUZjRnhLOCttRlpIUVV0cll3N0JsOU5STmZzdG5qS3hPa0d5TW9Pd3RqNTdjRS9yQWphLzk2UDg5a1dHSU9PYlhzdEoxaUp2Wms4RVp3YUVRSmc9Iiwic2lnbmF0dXJlIjoiTUlBR0NTcUdTSWIzRFFFSEFxQ0FNSUFDQVFFeERUQUxCZ2xnaGtnQlpRTUVBZ0V3Z0FZSktvWklodmNOQVFjQkFBQ2dnRENDQStRd2dnT0xvQU1DQVFJQ0NGbllvYnlxOU9QTk1Bb0dDQ3FHU000OUJBTUNNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QWVGdzB5TVRBME1qQXhPVE0zTURCYUZ3MHlOakEwTVRreE9UTTJOVGxhTUdJeEtEQW1CZ05WQkFNTUgyVmpZeTF6YlhBdFluSnZhMlZ5TFhOcFoyNWZWVU0wTFZOQlRrUkNUMWd4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQklJdy9hdkRuUGRlSUN4UTJadEZFdVkzNHFrQjNXeXo0TEhOUzFKbm1QalBUcjNvR2lXb3doNU1NOTNPamlxV3d2YXZvWk1EUmNUb2VrUW16cFViRXBXamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCUUNKREFMbXU3dFJqR1hwS1phS1o1Q2NZSWNSVEFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05IQURCRUFpQjBvYk1rMjBKSlF3M1RKMHhRZE1TQWpab2ZTQTQ2aGNYQk5pVm1NbCs4b3dJZ2FUYVFVNnYxQzFwUytmWUFUY1dLcld4UXA5WUlhRGVRNEtjNjBCNUsyWUV3Z2dMdU1JSUNkYUFEQWdFQ0FnaEpiUysvT3BqYWx6QUtCZ2dxaGtqT1BRUURBakJuTVJzd0dRWURWUVFEREJKQmNIQnNaU0JTYjI5MElFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QWVGdzB4TkRBMU1EWXlNelEyTXpCYUZ3MHlPVEExTURZeU16UTJNekJhTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekJaTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEEwSUFCUEFYRVlRWjEyU0YxUnBlSllFSGR1aUFvdS9lZTY1TjRJMzhTNVBoTTFiVlpsczFyaUxRbDNZTklrNTd1Z2o5ZGhmT2lNdDJ1Mlp3dnNqb0tZVC9WRVdqZ2Zjd2dmUXdSZ1lJS3dZQkJRVUhBUUVFT2pBNE1EWUdDQ3NHQVFVRkJ6QUJoaXBvZEhSd09pOHZiMk56Y0M1aGNIQnNaUzVqYjIwdmIyTnpjREEwTFdGd2NHeGxjbTl2ZEdOaFp6TXdIUVlEVlIwT0JCWUVGQ1B5U2NSUGsrVHZKK2JFOWloc1A2SzcvUzVMTUE4R0ExVWRFd0VCL3dRRk1BTUJBZjh3SHdZRFZSMGpCQmd3Rm9BVXU3RGVvVmd6aUpxa2lwbmV2cjNycjlyTEpLc3dOd1lEVlIwZkJEQXdMakFzb0NxZ0tJWW1hSFIwY0RvdkwyTnliQzVoY0hCc1pTNWpiMjB2WVhCd2JHVnliMjkwWTJGbk15NWpjbXd3RGdZRFZSMFBBUUgvQkFRREFnRUdNQkFHQ2lxR1NJYjNZMlFHQWc0RUFnVUFNQW9HQ0NxR1NNNDlCQU1DQTJjQU1HUUNNRHJQY29OUkZwbXhodnMxdzFiS1lyLzBGKzNaRDNWTm9vNis4WnlCWGtLM2lmaVk5NXRabjVqVlFRMlBuZW5DL2dJd01pM1ZSQ0d3b3dWM2JGM3pPRHVRWi8wWGZDd2hiWlpQeG5KcGdoSnZWUGg2ZlJ1Wnk1c0ppU0ZoQnBrUENaSWRBQUF4Z2dHSU1JSUJoQUlCQVRDQmhqQjZNUzR3TEFZRFZRUUREQ1ZCY0hCc1pTQkJjSEJzYVdOaGRHbHZiaUJKYm5SbFozSmhkR2x2YmlCRFFTQXRJRWN6TVNZd0pBWURWUVFMREIxQmNIQnNaU0JEWlhKMGFXWnBZMkYwYVc5dUlFRjFkR2h2Y21sMGVURVRNQkVHQTFVRUNnd0tRWEJ3YkdVZ1NXNWpMakVMTUFrR0ExVUVCaE1DVlZNQ0NGbllvYnlxOU9QTk1Bc0dDV0NHU0FGbEF3UUNBYUNCa3pBWUJna3Foa2lHOXcwQkNRTXhDd1lKS29aSWh2Y05BUWNCTUJ3R0NTcUdTSWIzRFFFSkJURVBGdzB5TkRFeU1UQXdOekU1TkRWYU1DZ0dDU3FHU0liM0RRRUpOREViTUJrd0N3WUpZSVpJQVdVREJBSUJvUW9HQ0NxR1NNNDlCQU1DTUM4R0NTcUdTSWIzRFFFSkJERWlCQ0M5bGcwVE43Vmhxa1h3eWphQTVGYjVuc0I2WDBZdE5najVvdXJHU3V3cVBUQUtCZ2dxaGtqT1BRUURBZ1JITUVVQ0lRRFp3ZENJQUFxenJlWGpnbk9paG43QXFpdTQ3TnhhUFRJR0ZBdEVMRVpkcHdJZ0ZKRDFUK25GRHd2QkxBSlpKMmVJN21qdnB6NzRlVlF3Q0ZhcWh1d2wrNElBQUFBQUFBQT0iLCJoZWFkZXIiOnsicHVibGljS2V5SGFzaCI6IjJDZ1k1N0xESVRVRDBxUjdEd3lIbHVUbTEyMkJ6MDlzYXMyQlVaK0VFOVU9IiwiZXBoZW1lcmFsUHVibGljS2V5IjoiTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFcVFmOTU1a0FnbmhJZzBHUmdBUU52dzBCRjBZVTRxbjdKVzdmZFY4K084Wk1mZlRWQTdwV2ZZYkwrd0M3RHl3MEFuT25INDJYWDluTS81ZWVpRjI5ZUE9PSIsInRyYW5zYWN0aW9uSWQiOiJjMWU5NGZmMjBhYjYyMTFkYzE5MWIxOTc0MDM2ZmE2NGMxNWJiNTQyYmFlMGJhMmQ4YWM4ODhiNDlhNzgwZGY5In0sInZlcnNpb24iOiJFQ192MSJ9", "payment_method": { "display_name": "Discover 9319", "network": "Discover", "type": "credit" }, "transaction_identifier": "c635c5b3af900d7bd81fecd7028f1262f9d030754ee65ec7afd988a678194751" } } } }' ``` ``` { "payment_id": "pay_1wv3HjvEqjxUQqEEY2RE", "merchant_id": "merchant_1733816953", "status": "succeeded", "amount": 650, "net_amount": 650, "shipping_cost": null, "amount_capturable": 0, "amount_received": 650, "connector": "cybersource", "client_secret": "pay_1wv3HjvEqjxUQqEEY2RE_secret_oPQa4cWsuyqIneiCfSFW", "created": "2024-12-10T07:49:21.254Z", "currency": "USD", "customer_id": "cu_1733816961", "customer": { "id": "cu_1733816961", "name": "Joseph Doe", "email": "[email protected]", "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": { "apple_pay": { "last4": "9319", "card_network": "Discover", "type": "credit" } }, "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": "[email protected]", "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": "apple_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": "cu_1733816961", "created_at": 1733816961, "expires": 1733820561, "secret": "epk_cc4776fce33d4024a350427ee01be604" }, "manual_retry_allowed": false, "connector_transaction_id": "7338169629566049304951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_1wv3HjvEqjxUQqEEY2RE_1", "payment_link": null, "profile_id": "pro_JcYIJy9B8xXAnFuBEdhc", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_pC2ENkiwqh6uOUT1d4lQ", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-12-10T08:04:21.254Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-12-10T07:49:23.458Z", "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
da4642761495fba88e76ae7cbb567afdac28dce0
juspay/hyperswitch
juspay__hyperswitch-6807
Bug: [FEATURE] [AIRWALLEX] Add refferer data to whitelist hyperswitch ### Feature Description Referrer data needs to be added in Airwallex's Create Payment Intent request in order to whitelist Hyperswitch for processing raw card details. ### Possible Implementation Referrer data needs to be added in Airwallex's Create Payment Intent request in order to whitelist Hyperswitch for processing raw card details. ### 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/airwallex/transformers.rs b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs index 97c9ed4d36a..e8ab479c978 100644 --- a/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs @@ -43,6 +43,14 @@ impl TryFrom<&ConnectorAuthType> for AirwallexAuthType { } } } + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct ReferrerData { + #[serde(rename = "type")] + r_type: String, + version: String, +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct AirwallexIntentRequest { // Unique ID to be sent for each transaction/operation request to the connector @@ -51,10 +59,16 @@ pub struct AirwallexIntentRequest { currency: enums::Currency, //ID created in merchant's order system that corresponds to this PaymentIntent. merchant_order_id: String, + // This data is required to whitelist Hyperswitch at Airwallex. + referrer_data: ReferrerData, } impl TryFrom<&types::PaymentsPreProcessingRouterData> for AirwallexIntentRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { + let referrer_data = ReferrerData { + r_type: "hyperswitch".to_string(), + version: "1.0.0".to_string(), + }; // amount and currency will always be Some since PaymentsPreProcessingData is constructed using PaymentsAuthorizeData let amount = item .request @@ -73,6 +87,7 @@ impl TryFrom<&types::PaymentsPreProcessingRouterData> for AirwallexIntentRequest amount: utils::to_currency_base_unit(amount, currency)?, currency, merchant_order_id: item.connector_request_reference_id.clone(), + referrer_data, }) } }
2024-12-11T11:54:10Z
## 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 referrer data in Airwallex's Create Payment Intent request in order to whitelist Hyperswitch for processing raw card 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/6807 ## 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)? --> Testing can be done by verifying payment logs for Airwallex payments <img width="1276" alt="Screenshot 2024-12-11 at 5 28 08 PM" src="https://github.com/user-attachments/assets/55f4ce53-6e38-46be-9055-d0ea50dd7b0c"> Payments Request: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_cEY8PgIkrpv1Y8pe0oVj6izFmGmxSlhrtV78ead9czZGWd5vp4h2GK8iLtenibs7' \ --data '{ "amount": 8059, "currency": "USD", "confirm": true, "capture_method": "automatic", "authentication_type": "no_three_ds", "payment_method": "card", "payment_method_type": "credit", "payment_method_data": { "card": { "card_number": "4035 5010 0000 0008", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "Joseph Doe", "card_cvc": "123" } } }' ``` ## 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
cd205378c035780586f6b94e5c9e03466165a33b
juspay/hyperswitch
juspay__hyperswitch-6788
Bug: refactor(permissions): Give access to connector view group in operation groups Currently `connector_label` is not visible in payments page of control-center. This is because, the payment retrieve API doesn't send the `connector_label`. As it is a big change in the payments flow, we are providing access to connector list API, so that control-center can fetch the data from there.
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 80d22ad22bf..a57fd56e6c8 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -431,7 +431,10 @@ pub async fn connector_retrieve( &auth::AdminApiAuthWithMerchantIdFromHeader, &auth::JWTAuthMerchantFromRoute { merchant_id, - required_permission: Permission::ProfileConnectorRead, + // This should ideally be ProfileConnectorRead, but since this API responds with + // sensitive data, keeping this as ProfileConnectorWrite + // TODO: Convert this to ProfileConnectorRead once data is masked. + required_permission: Permission::ProfileConnectorWrite, }, req.headers(), ), diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs index 8c45210e4b5..0cdb68ec8d7 100644 --- a/crates/router/src/services/authorization/permission_groups.rs +++ b/crates/router/src/services/authorization/permission_groups.rs @@ -60,8 +60,12 @@ impl PermissionGroupExt for PermissionGroup { fn accessible_groups(&self) -> Vec<Self> { match self { - Self::OperationsView => vec![Self::OperationsView], - Self::OperationsManage => vec![Self::OperationsView, Self::OperationsManage], + Self::OperationsView => vec![Self::OperationsView, Self::ConnectorsView], + Self::OperationsManage => vec![ + Self::OperationsView, + Self::OperationsManage, + Self::ConnectorsView, + ], Self::ConnectorsView => vec![Self::ConnectorsView], Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage],
2024-12-10T13:06:55Z
## 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 will make connector_view group accessible by operation groups. This PR will also change the permission of connector_retrieve API from connector_read to connector_write as it contains sensitive data. ### 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 #6788. ## 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/account/merchant_1733829021/profile/connectors' \ -H 'Content-Type: application/json' \ -H 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMzgyMWViZTktNGVkZS00Y2Y5LTlkNDQtNDgzZGFjMTM2ODEzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMzODI5MDIxIiwicm9sZV9pZCI6InJvbGVfRHZDdGFtenBGanZPdW9oSVpEMUEiLCJleHAiOjE3MzQwMDgzODEsIm9yZ19pZCI6Im9yZ19FWnZWZFJ6NVRxT1FxaWJzUERRZSIsInByb2ZpbGVfaWQiOiJwcm9fN2x3clIwWVVUbU1hbzhpWHJSVEkiLCJ0ZW5hbnRfaWQiOiJwdWJsaWMifQ.GvNXaj3YAwfPYQhoR7EeC-PpQmocZ_y8G02fdN_DuQU' \ ``` The above API should be accessible by users who are in only `operations_view` group. ``` curl 'http://localhost:8080/account/merchant_1733829021/connectors/mca_NEyNsfAyBFqewjPVz7sY' \ -H 'Content-Type: application/json' \ -H 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNjA0N2I5NGYtYjlmYi00MGY4LWI1NWUtODcwMDdhZDc2M2ZhIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMzODI5MDIxIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczNDAwODcyOCwib3JnX2lkIjoib3JnX0VadlZkUno1VHFPUXFpYnNQRFFlIiwicHJvZmlsZV9pZCI6InByb183bHdyUjBZVVRtTWFvOGlYclJUSSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.GMuhFhjCvP_3aM8IEHuKXH3la3uRgtCU3Q_zVVpEOyQ' \ ``` The above API should not be accessible by users who are not in `connector_manage` group. ## 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
08ab3ad7a2e60bc35332be606941793bc6a8a32f
juspay/hyperswitch
juspay__hyperswitch-6800
Bug: [deps] update scylla driver
diff --git a/Cargo.lock b/Cargo.lock index e8315e8049a..4284539c5e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7153,9 +7153,8 @@ dependencies = [ [[package]] name = "scylla" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8139623d3fb0c8205b15e84fa587f3aa0ba61f876c19a9157b688f7c1763a7c5" +version = "0.15.0" +source = "git+https://github.com/juspay/scylla-rust-driver.git?rev=5700aa2847b25437cdd4fcf34d707aa90dca8b89#5700aa2847b25437cdd4fcf34d707aa90dca8b89" dependencies = [ "arc-swap", "async-trait", @@ -7184,9 +7183,8 @@ dependencies = [ [[package]] name = "scylla-cql" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de7020bcd1f6fdbeaed356cd426bf294b2071bd7120d48d2e8e319295e2acdcd" +version = "0.4.0" +source = "git+https://github.com/juspay/scylla-rust-driver.git?rev=5700aa2847b25437cdd4fcf34d707aa90dca8b89#5700aa2847b25437cdd4fcf34d707aa90dca8b89" dependencies = [ "async-trait", "byteorder", @@ -7194,16 +7192,17 @@ dependencies = [ "lz4_flex", "scylla-macros", "snap", + "stable_deref_trait", "thiserror", "tokio 1.40.0", "uuid", + "yoke", ] [[package]] name = "scylla-macros" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3859b6938663fc5062e3b26f3611649c9bd26fb252e85f6fdfa581e0d2ce74b6" +version = "0.7.0" +source = "git+https://github.com/juspay/scylla-rust-driver.git?rev=5700aa2847b25437cdd4fcf34d707aa90dca8b89#5700aa2847b25437cdd4fcf34d707aa90dca8b89" dependencies = [ "darling 0.20.10", "proc-macro2", diff --git a/crates/masking/Cargo.toml b/crates/masking/Cargo.toml index 425c1ca36ec..00300798976 100644 --- a/crates/masking/Cargo.toml +++ b/crates/masking/Cargo.toml @@ -28,7 +28,7 @@ subtle = "2.5.0" time = { version = "0.3.35", optional = true, features = ["serde-human-readable"] } url = { version = "2.5.0", features = ["serde"] } zeroize = { version = "1.7", default-features = false } -scylla = { version = "0.14.0", optional = true} +scylla = { git = "https://github.com/juspay/scylla-rust-driver.git",rev = "5700aa2847b25437cdd4fcf34d707aa90dca8b89", optional = true} [dev-dependencies] serde_json = "1.0.115" diff --git a/crates/masking/src/cassandra.rs b/crates/masking/src/cassandra.rs index dc81512e79d..2544ab18a7a 100644 --- a/crates/masking/src/cassandra.rs +++ b/crates/masking/src/cassandra.rs @@ -1,7 +1,6 @@ use scylla::{ - cql_to_rust::FromCqlVal, deserialize::DeserializeValue, - frame::response::result::{ColumnType, CqlValue}, + frame::response::result::ColumnType, serialize::{ value::SerializeValue, writers::{CellWriter, WrittenCellProof}, @@ -17,34 +16,25 @@ where { fn serialize<'b>( &self, - typ: &ColumnType, + typ: &ColumnType<'_>, writer: CellWriter<'b>, ) -> Result<WrittenCellProof<'b>, SerializationError> { self.peek().serialize(typ, writer) } } -impl<'frame, T> DeserializeValue<'frame> for StrongSecret<T> +impl<'frame, 'metadata, T> DeserializeValue<'frame, 'metadata> for StrongSecret<T> where - T: DeserializeValue<'frame> + zeroize::Zeroize + Clone, + T: DeserializeValue<'frame, 'metadata> + zeroize::Zeroize + Clone, { - fn type_check(typ: &ColumnType) -> Result<(), scylla::deserialize::TypeCheckError> { + fn type_check(typ: &ColumnType<'_>) -> Result<(), scylla::deserialize::TypeCheckError> { T::type_check(typ) } fn deserialize( - typ: &'frame ColumnType, + typ: &'metadata ColumnType<'metadata>, v: Option<scylla::deserialize::FrameSlice<'frame>>, ) -> Result<Self, scylla::deserialize::DeserializationError> { Ok(Self::new(T::deserialize(typ, v)?)) } } - -impl<T> FromCqlVal<CqlValue> for StrongSecret<T> -where - T: FromCqlVal<CqlValue> + zeroize::Zeroize + Clone, -{ - fn from_cql(cql_val: CqlValue) -> Result<Self, scylla::cql_to_rust::FromCqlValError> { - Ok(Self::new(T::from_cql(cql_val)?)) - } -}
2024-12-11T06:19:00Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Dependency updates ## Description <!-- Describe your changes in detail --> Update scylla driver on masking crate ## 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). --> Update scylla driver on masking crate ## 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)? --> Compiler guided. Testing not needed in environments ## 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
400d9a42de4cb99e3e2d7dc69510f503661700e4
juspay/hyperswitch
juspay__hyperswitch-6787
Bug: refactor(constraint_graph): add cypress test cases for 'mandate_details'
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 13575961108..0ca77f3a5ee 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -4589,7 +4589,7 @@ pub async fn filter_payment_methods( .map(|future_usage| { future_usage == common_enums::FutureUsage::OnSession }) - .unwrap_or(false) + .unwrap_or(true) }) .and_then(|res| { res.then(|| {
2024-12-11T12:50:44Z
## 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 --> This will handel the cases for constraint_graph for PML where setup_future_usage is not passed in payments. ### 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 can be tested in the following way: 1. Connector create (Fiuu) ``` curl --location 'http://127.0.0.1:8080/account/merchant_1733312955/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "fiuu", "connector_account_details": { "auth_type": "SignatureKey", "api_key": ".....", "key1": "......", "api_secret": "......" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "online_banking_fpx", "payment_experience": null, "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "connector_webhook_details": { "merchant_secret": ".....", "additional_secret": null } }' ``` 2. Payment (no setup_future_usage) ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Cookie;' \ --header 'api-key: .....' \ --data-raw '{ "amount": 6540, // "setup_future_usage": "off_session", "currency": "EUR", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 6540, "customer_id": "uiuiuiui", "email": "[email protected]", "description": "Its my first payment request", "authentication_type": "no_three_ds", "return_url": "https://duck.com", "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "NL", "first_name": "joseph", "last_name": "Doe" }, "phone": { "number": "8056594427", "country_code": "+91" }, "email": "[email protected]" }, "shipping": { "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" } }, "statement_descriptor_name": "joseph", "statement_descriptor_suffix": "JS", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 3. List payment methods (`setup_future_usage` = null) ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret=......' \ --header 'Accept: application/json' \ --header 'api-key: .....' \ --data '' ``` Response ``` { "redirect_url": "https://google.com/success", "currency": "MYR", "payment_methods": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "online_banking_fpx", "payment_experience": null, "card_networks": null, "bank_names": [ { "bank_name": [ "affin_bank", "bank_islam", "rhb_bank", "bank_of_china", "bank_simpanan_nasional", "bank_muamalat", "bank_rakyat", "maybank", "public_bank", "uob_bank", "hong_leong_bank", "hsbc_bank", "ocbc_bank", "alliance_bank", "agro_bank", "cimb_bank", "kuwait_finance_house", "am_bank", "standard_chartered_bank" ], "eligible_connectors": [ "fiuu" ] } ], "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "Prajjwal", "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 } ``` 4. `setup_future_usage` = `on_session` ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xxxxxx' \ --data '{ "amount": 1000, "currency": "MYR", "amount_to_capture": 1000, "confirm": false, "payment_link" : true, "capture_method": "automatic", "payment_method": "bank_redirect", "setup_future_usage": "on_session", "payment_method_type": "online_banking_fpx", "return_url": "https://google.com", "payment_method_data": { "bank_redirect": { "online_banking_fpx": { "issuer": "bank_islam" } } } }' ``` List PM response: ``` { "redirect_url": "https://google.com/success", "currency": "MYR", "payment_methods": [ { "payment_method": "bank_redirect", "payment_method_types": [ { "payment_method_type": "online_banking_fpx", "payment_experience": null, "card_networks": null, "bank_names": [ { "bank_name": [ "ocbc_bank", "uob_bank", "kuwait_finance_house", "standard_chartered_bank", "cimb_bank", "bank_simpanan_nasional", "hsbc_bank", "bank_rakyat", "alliance_bank", "am_bank", "public_bank", "rhb_bank", "agro_bank", "hong_leong_bank", "bank_of_china", "maybank", "affin_bank", "bank_muamalat", "bank_islam" ], "eligible_connectors": [ "fiuu" ] } ], "bank_debits": null, "bank_transfers": null, "required_fields": null, "surcharge_details": null, "pm_auth_connector": null } ] } ], "mandate_payment": null, "merchant_name": "Prajjwal", "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 } ``` 5. `setup_future_usage` = off_session ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: xxxxx' \ --data '{ "amount": 1000, "currency": "MYR", "amount_to_capture": 1000, "confirm": false, "payment_link" : true, "capture_method": "automatic", "payment_method": "bank_redirect", "setup_future_usage": "off_session", "payment_method_type": "online_banking_fpx", "return_url": "https://google.com", "payment_method_data": { "bank_redirect": { "online_banking_fpx": { "issuer": "bank_islam" } } } }' ``` List PM response: ``` { "redirect_url": "https://google.com/success", "currency": "MYR", "payment_methods": [], "mandate_payment": null, "merchant_name": "Prajjwal", "show_surcharge_breakup_screen": false, "payment_type": "new_mandate", "request_external_three_ds_authentication": false, "collect_shipping_details_from_wallets": false, "collect_billing_details_from_wallets": false, "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
9466ced89407f31963bb0eb7c762749e3713591a
juspay/hyperswitch
juspay__hyperswitch-6808
Bug: feat(users): handle email URLs for users in different tenancies We will be sending emails to users in different tenancies, on clicking the email they should land on that particular tenant URL. For that we need tenant level user configs. And 'll be using it to generate emails.
diff --git a/config/config.example.toml b/config/config.example.toml index 0fe6b8caa2c..8d7c926c3e2 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -758,8 +758,15 @@ sdk_eligible_payment_methods = "card" enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} -[multitenancy.tenants] -public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } # schema -> Postgres db schema, redis_key_prefix -> redis key distinguisher, base_url -> url of the tenant +[multitenancy.tenants.public] +base_url = "http://localhost:8080" # URL of the tenant +schema = "public" # Postgres db schema +redis_key_prefix = "" # Redis key distinguisher +clickhouse_database = "default" # Clickhouse database + +[multitenancy.tenants.public.user] +control_center_url = "http://localhost:9000" # Control center URL + [user_auth_methods] encryption_key = "" # Encryption key used for encrypting data in user_authentication_methods table diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 848a2305ae4..286639e89f3 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -304,8 +304,14 @@ region = "kms_region" # The AWS region used by the KMS SDK for decrypting data. enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} -[multitenancy.tenants] -public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } +[multitenancy.tenants.public] +base_url = "http://localhost:8080" +schema = "public" +redis_key_prefix = "" +clickhouse_database = "default" + +[multitenancy.tenants.public.user] +control_center_url = "http://localhost:9000" [user_auth_methods] encryption_key = "user_auth_table_encryption_key" # Encryption key used for encrypting data in user_authentication_methods table diff --git a/config/development.toml b/config/development.toml index 077e09f0463..d3cdbd11bbc 100644 --- a/config/development.toml +++ b/config/development.toml @@ -774,8 +774,14 @@ sdk_eligible_payment_methods = "card" enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} -[multitenancy.tenants] -public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +[multitenancy.tenants.public] +base_url = "http://localhost:8080" +schema = "public" +redis_key_prefix = "" +clickhouse_database = "default" + +[multitenancy.tenants.public.user] +control_center_url = "http://localhost:9000" [user_auth_methods] encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index dbd5286b290..b861e47e594 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -633,8 +633,14 @@ sdk_eligible_payment_methods = "card" enabled = false global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default" } -[multitenancy.tenants] -public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default" } +[multitenancy.tenants.public] +base_url = "http://localhost:8080" +schema = "public" +redis_key_prefix = "" +clickhouse_database = "default" + +[multitenancy.tenants.public.user] +control_center_url = "http://localhost:9000" [user_auth_methods] encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F" diff --git a/crates/external_services/src/email.rs b/crates/external_services/src/email.rs index 2e05a26e1f1..a98b03c0b54 100644 --- a/crates/external_services/src/email.rs +++ b/crates/external_services/src/email.rs @@ -47,6 +47,7 @@ pub trait EmailService: Sync + Send + dyn_clone::DynClone { /// Compose and send email using the email data async fn compose_and_send_email( &self, + base_url: &str, email_data: Box<dyn EmailData + Send>, proxy_url: Option<&String>, ) -> EmailResult<()>; @@ -60,10 +61,11 @@ where { async fn compose_and_send_email( &self, + base_url: &str, email_data: Box<dyn EmailData + Send>, proxy_url: Option<&String>, ) -> EmailResult<()> { - let email_data = email_data.get_email_data(); + let email_data = email_data.get_email_data(base_url); let email_data = email_data.await?; let EmailContents { @@ -113,7 +115,7 @@ pub struct EmailContents { #[async_trait::async_trait] pub trait EmailData { /// Get the email contents - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError>; + async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError>; } dyn_clone::clone_trait_object!(EmailClient<RichText = Body>); diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 4ab2a8fd5c7..ccd43d25b8e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -169,6 +169,12 @@ pub struct Tenant { pub schema: String, pub redis_key_prefix: String, pub clickhouse_database: String, + pub user: TenantUserConfig, +} + +#[derive(Debug, Deserialize, Clone)] +pub struct TenantUserConfig { + pub control_center_url: String, } impl storage_impl::config::TenantConfig for Tenant { @@ -1130,6 +1136,7 @@ impl<'de> Deserialize<'de> for TenantConfig { schema: String, redis_key_prefix: String, clickhouse_database: String, + user: TenantUserConfig, } let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; @@ -1146,6 +1153,7 @@ impl<'de> Deserialize<'de> for TenantConfig { schema: value.schema, redis_key_prefix: value.redis_key_prefix, clickhouse_database: value.clickhouse_database, + user: value.user, }, ) }) diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index c2f289d4cc0..3b2aacd4514 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -80,6 +80,7 @@ pub async fn send_recon_request( state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -179,7 +180,7 @@ pub async fn recon_merchant_account_update( let theme = theme_utils::get_most_specific_theme_using_lineage( &state.clone(), ThemeLineage::Merchant { - tenant_id: state.tenant.tenant_id, + tenant_id: state.tenant.tenant_id.clone(), org_id: auth.merchant_account.get_org_id().clone(), merchant_id: merchant_id.clone(), }, @@ -210,6 +211,7 @@ pub async fn recon_merchant_account_update( let _ = state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 642473bdf8e..19f257ef4f3 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -96,6 +96,7 @@ pub async fn signup_with_merchant_id( let send_email_result = state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -239,6 +240,7 @@ pub async fn connect_account( let send_email_result = state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -294,6 +296,7 @@ pub async fn connect_account( let magic_link_result = state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(magic_link_email), state.conf.proxy.https_url.as_ref(), ) @@ -310,6 +313,7 @@ pub async fn connect_account( let welcome_email_result = state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(welcome_to_community_email), state.conf.proxy.https_url.as_ref(), ) @@ -438,6 +442,7 @@ pub async fn forgot_password( state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -845,6 +850,7 @@ async fn handle_existing_user_invitation( is_email_sent = state .email_client .compose_and_send_email( + email_types::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1000,6 +1006,7 @@ async fn handle_new_user_invitation( let send_email_result = state .email_client .compose_and_send_email( + email_types::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1151,6 +1158,7 @@ pub async fn resend_invite( state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) @@ -1782,6 +1790,7 @@ pub async fn send_verification_mail( state .email_client .compose_and_send_email( + email_types::get_base_url(&state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index 88380363b4e..aa67a70223f 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -496,6 +496,7 @@ async fn insert_metadata( let send_email_result = state .email_client .compose_and_send_email( + email_types::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 128250a61aa..476cd1292f6 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -225,6 +225,14 @@ pub fn get_link_with_token( email_url } +pub fn get_base_url(state: &SessionState) -> &str { + if !state.conf.multitenancy.enabled { + &state.conf.user.base_url + } else { + &state.tenant.user.control_center_url + } +} + pub struct VerifyEmail { pub recipient_email: domain::UserEmail, pub settings: std::sync::Arc<configs::Settings>, @@ -237,7 +245,7 @@ pub struct VerifyEmail { /// Currently only HTML is supported #[async_trait::async_trait] impl EmailData for VerifyEmail { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, @@ -248,7 +256,7 @@ impl EmailData for VerifyEmail { .change_context(EmailError::TokenGenerationFailure)?; let verify_email_link = get_link_with_token( - &self.settings.user.base_url, + base_url, token, "verify_email", &self.auth_id, @@ -279,7 +287,7 @@ pub struct ResetPassword { #[async_trait::async_trait] impl EmailData for ResetPassword { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, @@ -290,7 +298,7 @@ impl EmailData for ResetPassword { .change_context(EmailError::TokenGenerationFailure)?; let reset_password_link = get_link_with_token( - &self.settings.user.base_url, + base_url, token, "set_password", &self.auth_id, @@ -322,7 +330,7 @@ pub struct MagicLink { #[async_trait::async_trait] impl EmailData for MagicLink { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), None, @@ -333,7 +341,7 @@ impl EmailData for MagicLink { .change_context(EmailError::TokenGenerationFailure)?; let magic_link_login = get_link_with_token( - &self.settings.user.base_url, + base_url, token, "verify_email", &self.auth_id, @@ -366,7 +374,7 @@ pub struct InviteUser { #[async_trait::async_trait] impl EmailData for InviteUser { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> { let token = EmailToken::new_token( self.recipient_email.clone(), Some(self.entity.clone()), @@ -377,7 +385,7 @@ impl EmailData for InviteUser { .change_context(EmailError::TokenGenerationFailure)?; let invite_user_link = get_link_with_token( - &self.settings.user.base_url, + base_url, token, "accept_invite_from_email", &self.auth_id, @@ -406,7 +414,7 @@ pub struct ReconActivation { #[async_trait::async_trait] impl EmailData for ReconActivation { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::ReconActivation { user_name: self.user_name.clone().get_secret().expose(), }); @@ -461,7 +469,7 @@ impl BizEmailProd { #[async_trait::async_trait] impl EmailData for BizEmailProd { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::BizEmailProd { user_name: self.user_name.clone().expose(), poc_email: self.poc_email.clone().expose(), @@ -491,7 +499,7 @@ pub struct ProFeatureRequest { #[async_trait::async_trait] impl EmailData for ProFeatureRequest { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let recipient = self.recipient_email.clone().into_inner(); let body = html::get_html_body(EmailBody::ProFeatureRequest { @@ -521,7 +529,7 @@ pub struct ApiKeyExpiryReminder { #[async_trait::async_trait] impl EmailData for ApiKeyExpiryReminder { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let recipient = self.recipient_email.clone().into_inner(); let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder { @@ -545,7 +553,7 @@ pub struct WelcomeToCommunity { #[async_trait::async_trait] impl EmailData for WelcomeToCommunity { - async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> { let body = html::get_html_body(EmailBody::WelcomeToCommunity); Ok(EmailContents { diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index cdc4959c456..2ff527a046e 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -9,7 +9,7 @@ use crate::{ consts, errors, logger::error, routes::{metrics, SessionState}, - services::email::types::ApiKeyExpiryReminder, + services::email::types::{self as email_types, ApiKeyExpiryReminder}, types::{api, domain::UserEmail, storage}, utils::{user::theme as theme_utils, OptionExt}, }; @@ -110,6 +110,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { .email_client .clone() .compose_and_send_email( + email_types::get_base_url(state), Box::new(email_contents), state.conf.proxy.https_url.as_ref(), ) diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 51981a298e3..09b52bc357d 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -385,8 +385,14 @@ keys = "accept-language,user-agent" enabled = false global_tenant = { schema = "public", redis_key_prefix = "" } -[multitenancy.tenants] -public = { base_url = "http://localhost:8080", schema = "public", redis_key_prefix = "", clickhouse_database = "default"} +[multitenancy.tenants.public] +base_url = "http://localhost:8080" +schema = "public" +redis_key_prefix = "" +clickhouse_database = "default" + +[multitenancy.tenants.public.user] +control_center_url = "http://localhost:9000" [email] sender_email = "[email protected]"
2024-12-11T12:20:07Z
## 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 for user in tenants configs. - Handle email URLs for different tenancies ### 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 [#6808](https://github.com/juspay/hyperswitch/issues/6808) ## How did you test it? Tested locally with email feature flag on, for different tenancies the emails we were getting, we were landing onto to the URL specified in the tenant's config. We specified the following in the local configs. ``` [multitenancy] enabled = true global_tenant = { schema = "public", redis_key_prefix = "", clickhouse_database = "default"} [multitenancy.tenants.public] base_url = "http://localhost:8080" schema = "public" redis_key_prefix = "" clickhouse_database = "default" [multitenancy.tenants.public.user] control_center_url = "http://localhost:9000" [multitenancy.tenants.test] base_url = "http://localhost:8080" schema = "public" redis_key_prefix = "" clickhouse_database = "default" [multitenancy.tenants.test.user] control_center_url = "http://localhost:9001" ``` We were getting the mails ![image](https://github.com/user-attachments/assets/af9b9b9e-0968-45c5-a1d1-f76494ca700f) For public Tenant: (**http://localhost:9000**/user/verify_email?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFwb29ydmRpeGl0ODhAZ21haWwuY29tIiwiZmxvdyI6InZlcmlmeV9lbWFpbCIsImV4cCI6MTczNDAwNDg0MSwiZW50aXR5IjpudWxsfQ.j0RlE85yahAALsMccb2uQtt34JIrFV31t3eNYfO5Sdc) For test Tenant: (**http://locatlhost:9001**/user/verify_email?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFwb29ydmRpeGl0ODgrMUBnbWFpbC5jb20iLCJmbG93IjoidmVyaWZ5X2VtYWlsIiwiZXhwIjoxNzM0MDA0OTY4LCJlbnRpdHkiOm51bGx9.KIiSssKT1J0awgOt9C64tx6lSNrc0CbfZPPXpyRXP_8) ## 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
ed276ecc0017f7f98b6f8fa3841e6b8971f609f1
juspay/hyperswitch
juspay__hyperswitch-6814
Bug: [FEATURE] Ephemeral Auth for v2 ### Feature Description We need to support ephemeral auth in v2. This would replace the current client secret auth being used in Payment methods ### Possible Implementation Need to add implementation for ephemeral auth ### 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 58a81caeed3..7a9448a4fd4 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -13696,16 +13696,11 @@ "PaymentMethodIntentConfirm": { "type": "object", "required": [ - "client_secret", "payment_method_data", "payment_method_type", "payment_method_subtype" ], "properties": { - "client_secret": { - "type": "string", - "description": "For SDK based calls, client_secret would be required" - }, "customer_id": { "type": "string", "description": "The unique identifier of the customer.", @@ -13991,7 +13986,7 @@ "example": "2024-02-24T11:04:09.922Z", "nullable": true }, - "client_secret": { + "ephemeral_key": { "type": "string", "description": "For Client based calls", "nullable": true @@ -14140,14 +14135,6 @@ "properties": { "payment_method_data": { "$ref": "#/components/schemas/PaymentMethodUpdateData" - }, - "client_secret": { - "type": "string", - "description": "This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK", - "example": "secret_k2uj3he2893eiu2d", - "nullable": true, - "maxLength": 30, - "minLength": 30 } }, "additionalProperties": false diff --git a/crates/api_models/src/ephemeral_key.rs b/crates/api_models/src/ephemeral_key.rs index d06490d6bac..fa61642e353 100644 --- a/crates/api_models/src/ephemeral_key.rs +++ b/crates/api_models/src/ephemeral_key.rs @@ -1,7 +1,10 @@ use common_utils::id_type; +#[cfg(feature = "v2")] +use masking::Secret; use serde; use utoipa::ToSchema; +#[cfg(feature = "v1")] /// Information required to create an ephemeral key. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct EphemeralKeyCreateRequest { @@ -15,12 +18,52 @@ pub struct EphemeralKeyCreateRequest { pub customer_id: id_type::CustomerId, } +#[cfg(feature = "v2")] +/// Information required to create an ephemeral key. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] +pub struct EphemeralKeyCreateRequest { + /// Customer ID for which an ephemeral key must be created + #[schema( + min_length = 32, + max_length = 64, + value_type = String, + example = "12345_cus_01926c58bc6e77c09e809964e72af8c8" + )] + pub customer_id: id_type::GlobalCustomerId, +} + +#[cfg(feature = "v2")] +/// ephemeral_key for the customer_id mentioned +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] +pub struct EphemeralKeyResponse { + /// Ephemeral key id + #[schema(value_type = String, max_length = 32, min_length = 1)] + pub id: id_type::EphemeralKeyId, + /// customer_id to which this ephemeral key belongs to + #[schema(value_type = String, max_length = 64, min_length = 32, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] + pub customer_id: id_type::GlobalCustomerId, + /// time at which this ephemeral key was created + pub created_at: time::PrimitiveDateTime, + /// time at which this ephemeral key would expire + pub expires: time::PrimitiveDateTime, + #[schema(value_type=String)] + /// ephemeral key + pub secret: Secret<String>, +} + impl common_utils::events::ApiEventMetric for EphemeralKeyCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } +#[cfg(feature = "v2")] +impl common_utils::events::ApiEventMetric for EphemeralKeyResponse { + fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { + Some(common_utils::events::ApiEventsType::Miscellaneous) + } +} + /// ephemeral_key for the customer_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct EphemeralKeyCreateResponse { diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index c821feaff57..fe5cb2933f9 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -163,9 +163,6 @@ pub struct PaymentMethodIntentCreate { #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodIntentConfirm { - /// For SDK based calls, client_secret would be required - pub client_secret: String, - /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, @@ -211,9 +208,6 @@ pub struct PaymentMethodIntentConfirmInternal { #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, - /// For SDK based calls, client_secret would be required - pub client_secret: String, - /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, @@ -226,7 +220,6 @@ pub struct PaymentMethodIntentConfirmInternal { impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm { fn from(item: PaymentMethodIntentConfirmInternal) -> Self { Self { - client_secret: item.client_secret, payment_method_type: item.payment_method_type, payment_method_subtype: item.payment_method_subtype, customer_id: item.customer_id, @@ -408,10 +401,6 @@ pub struct PaymentMethodUpdate { pub struct PaymentMethodUpdate { /// payment method data to be passed 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")] - pub client_secret: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -826,7 +815,8 @@ pub struct PaymentMethodResponse { pub last_used_at: Option<time::PrimitiveDateTime>, /// For Client based calls - pub client_secret: Option<String>, + #[schema(value_type=Option<String>)] + pub ephemeral_key: Option<masking::Secret<String>>, pub payment_method_data: Option<PaymentMethodResponseData>, } diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index b9af92786f5..9494b8209e7 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -102,6 +102,9 @@ pub enum ApiEventsType { poll_id: String, }, Analytics, + EphemeralKey { + key_id: id_type::EphemeralKeyId, + }, } impl ApiEventMetric for serde_json::Value {} diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 594078bb405..da013b3489e 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -3,6 +3,7 @@ mod api_key; mod customer; +mod ephemeral_key; #[cfg(feature = "v2")] mod global_id; mod merchant; @@ -37,6 +38,7 @@ pub use self::global_id::{ pub use self::{ api_key::ApiKeyId, customer::CustomerId, + ephemeral_key::EphemeralKeyId, merchant::MerchantId, merchant_connector_account::MerchantConnectorAccountId, organization::OrganizationId, diff --git a/crates/common_utils/src/id_type/ephemeral_key.rs b/crates/common_utils/src/id_type/ephemeral_key.rs new file mode 100644 index 00000000000..071980fc6a4 --- /dev/null +++ b/crates/common_utils/src/id_type/ephemeral_key.rs @@ -0,0 +1,31 @@ +crate::id_type!( + EphemeralKeyId, + "A type for key_id that can be used for Ephemeral key IDs" +); +crate::impl_id_type_methods!(EphemeralKeyId, "key_id"); + +// This is to display the `EphemeralKeyId` as EphemeralKeyId(abcd) +crate::impl_debug_id_type!(EphemeralKeyId); +crate::impl_try_from_cow_str_id_type!(EphemeralKeyId, "key_id"); + +crate::impl_generate_id_id_type!(EphemeralKeyId, "eki"); +crate::impl_serializable_secret_id_type!(EphemeralKeyId); +crate::impl_queryable_id_type!(EphemeralKeyId); +crate::impl_to_sql_from_sql_id_type!(EphemeralKeyId); + +impl crate::events::ApiEventMetric for EphemeralKeyId { + fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { + Some(crate::events::ApiEventsType::EphemeralKey { + key_id: self.clone(), + }) + } +} + +crate::impl_default_id_type!(EphemeralKeyId, "key"); + +impl EphemeralKeyId { + /// Generate a key for redis + pub fn generate_redis_key(&self) -> String { + format!("epkey_{}", self.get_string_repr()) + } +} diff --git a/crates/diesel_models/src/ephemeral_key.rs b/crates/diesel_models/src/ephemeral_key.rs index d398ecdf784..c7fc103ed09 100644 --- a/crates/diesel_models/src/ephemeral_key.rs +++ b/crates/diesel_models/src/ephemeral_key.rs @@ -1,3 +1,33 @@ +#[cfg(feature = "v2")] +use masking::{PeekInterface, Secret}; +#[cfg(feature = "v2")] +pub struct EphemeralKeyTypeNew { + pub id: common_utils::id_type::EphemeralKeyId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub secret: Secret<String>, + pub resource_type: ResourceType, +} + +#[cfg(feature = "v2")] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +pub struct EphemeralKeyType { + pub id: common_utils::id_type::EphemeralKeyId, + pub merchant_id: common_utils::id_type::MerchantId, + pub customer_id: common_utils::id_type::GlobalCustomerId, + pub resource_type: ResourceType, + pub created_at: time::PrimitiveDateTime, + pub expires: time::PrimitiveDateTime, + pub secret: Secret<String>, +} + +#[cfg(feature = "v2")] +impl EphemeralKeyType { + pub fn generate_secret_key(&self) -> String { + format!("epkey_{}", self.secret.peek()) + } +} + pub struct EphemeralKeyNew { pub id: String, pub merchant_id: common_utils::id_type::MerchantId, @@ -20,3 +50,21 @@ impl common_utils::events::ApiEventMetric for EphemeralKey { Some(common_utils::events::ApiEventsType::Miscellaneous) } } + +#[derive( + Clone, + Copy, + Debug, + serde::Serialize, + serde::Deserialize, + strum::Display, + strum::EnumString, + PartialEq, + Eq, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum ResourceType { + Payment, + PaymentMethod, +} diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 46af78d6d91..912ea96c486 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -288,6 +288,7 @@ pub enum PaymentMethodUpdate { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, + locker_fingerprint_id: Option<String>, }, ConnectorMandateDetailsUpdate { connector_mandate_details: Option<PaymentsMandateReference>, @@ -322,6 +323,7 @@ pub struct PaymentMethodUpdateInternal { network_token_requestor_reference_id: Option<String>, network_token_locker_id: Option<String>, network_token_payment_method_data: Option<Encryption>, + locker_fingerprint_id: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -341,6 +343,7 @@ impl PaymentMethodUpdateInternal { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, + locker_fingerprint_id, } = self; PaymentMethod { @@ -359,7 +362,7 @@ impl PaymentMethodUpdateInternal { client_secret: source.client_secret, payment_method_billing_address: source.payment_method_billing_address, updated_by: updated_by.or(source.updated_by), - locker_fingerprint_id: source.locker_fingerprint_id, + locker_fingerprint_id: locker_fingerprint_id.or(source.locker_fingerprint_id), payment_method_type_v2: payment_method_type_v2.or(source.payment_method_type_v2), payment_method_subtype: payment_method_subtype.or(source.payment_method_subtype), id: source.id, @@ -695,6 +698,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, + locker_fingerprint_id: None, }, PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self { payment_method_data: None, @@ -710,6 +714,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, + locker_fingerprint_id: None, }, PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data, @@ -728,6 +733,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, + locker_fingerprint_id: None, }, PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate { network_transaction_id, @@ -746,6 +752,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, + locker_fingerprint_id: None, }, PaymentMethodUpdate::StatusUpdate { status } => Self { payment_method_data: None, @@ -761,6 +768,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, + locker_fingerprint_id: None, }, PaymentMethodUpdate::AdditionalDataUpdate { payment_method_data, @@ -771,6 +779,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, + locker_fingerprint_id, } => Self { payment_method_data, last_used_at: None, @@ -785,6 +794,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_requestor_reference_id, network_token_locker_id, network_token_payment_method_data, + locker_fingerprint_id, }, PaymentMethodUpdate::ConnectorMandateDetailsUpdate { connector_mandate_details, @@ -802,6 +812,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { network_token_locker_id: None, network_token_requestor_reference_id: None, network_token_payment_method_data: None, + locker_fingerprint_id: None, }, } } diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs index 0243c254920..6772d0de408 100644 --- a/crates/hyperswitch_domain_models/src/payments.rs +++ b/crates/hyperswitch_domain_models/src/payments.rs @@ -29,7 +29,10 @@ pub mod payment_intent; use common_enums as storage_enums; #[cfg(feature = "v2")] -use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount}; +use diesel_models::{ + ephemeral_key, + types::{FeatureMetadata, OrderDetailsWithAmount}, +}; use self::payment_attempt::PaymentAttempt; #[cfg(feature = "v1")] diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 823f0a4bf04..e2784b968ad 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -171,19 +171,19 @@ pub const DEFAULT_SDK_LAYOUT: &str = "tabs"; /// Vault Add request url #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -pub const ADD_VAULT_REQUEST_URL: &str = "/vault/add"; +pub const ADD_VAULT_REQUEST_URL: &str = "/api/v2/vault/add"; /// Vault Get Fingerprint request url #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/fingerprint"; +pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/api/v2/vault/fingerprint"; /// Vault Retrieve request url #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/vault/retrieve"; +pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/api/v2/vault/retrieve"; /// Vault Delete request url #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -pub const VAULT_DELETE_REQUEST_URL: &str = "/vault/delete"; +pub const VAULT_DELETE_REQUEST_URL: &str = "/api/v2/vault/delete"; /// Vault Header content type #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 61dc70ac479..6cdadf07320 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -62,7 +62,7 @@ use crate::{ types::{ api::{self, payment_methods::PaymentMethodCreateExt}, payment_methods as pm_types, - storage::PaymentMethodListContext, + storage::{ephemeral_key, PaymentMethodListContext}, }, utils::ext_traits::OptionExt, }; @@ -851,21 +851,23 @@ pub async fn create_payment_method( let db = &*state.store; let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.to_owned(); + let key_manager_state = &(state).into(); db.find_customer_by_global_id( - &(state.into()), + key_manager_state, &customer_id, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - let key_manager_state = state.into(); + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) + .attach_printable("Customer not found for the payment method")?; + let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| cards::create_encrypted_data(&key_manager_state, key_store, billing)) + .async_map(|billing| cards::create_encrypted_data(key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -877,7 +879,7 @@ pub async fn create_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; - let payment_method = create_payment_method_for_intent( + let (payment_method, ephemeral_key) = create_payment_method_for_intent( state, req.metadata.clone(), &customer_id, @@ -902,14 +904,15 @@ pub async fn create_payment_method( .await; let response = match vaulting_result { - Ok(resp) => { + Ok((vaulting_resp, fingerprint_id)) => { let pm_update = create_pm_additional_data_update( &payment_method_data, state, key_store, - Some(resp.vault_id.get_string_repr().clone()), + Some(vaulting_resp.vault_id.get_string_repr().clone()), Some(req.payment_method_type), Some(req.payment_method_subtype), + Some(fingerprint_id), ) .await .attach_printable("Unable to create Payment method data")?; @@ -926,7 +929,10 @@ pub async fn create_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let resp = pm_transforms::generate_payment_method_response(&payment_method)?; + let resp = pm_transforms::generate_payment_method_response( + &payment_method, + Some(ephemeral_key), + )?; Ok(resp) } @@ -964,21 +970,23 @@ pub async fn payment_method_intent_create( let db = &*state.store; let merchant_id = merchant_account.get_id(); let customer_id = req.customer_id.to_owned(); + let key_manager_state = &(state).into(); db.find_customer_by_global_id( - &(state.into()), + key_manager_state, &customer_id, merchant_account.get_id(), key_store, merchant_account.storage_scheme, ) .await - .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; - let key_manager_state = state.into(); + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound) + .attach_printable("Customer not found for the payment method")?; + let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req .billing .clone() - .async_map(|billing| cards::create_encrypted_data(&key_manager_state, key_store, billing)) + .async_map(|billing| cards::create_encrypted_data(key_manager_state, key_store, billing)) .await .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -991,7 +999,7 @@ pub async fn payment_method_intent_create( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; - let payment_method = create_payment_method_for_intent( + let (payment_method, ephemeral_key) = create_payment_method_for_intent( state, req.metadata.clone(), &customer_id, @@ -1004,7 +1012,8 @@ pub async fn payment_method_intent_create( .await .attach_printable("Failed to add Payment method to DB")?; - let resp = pm_transforms::generate_payment_method_response(&payment_method)?; + let resp = + pm_transforms::generate_payment_method_response(&payment_method, Some(ephemeral_key))?; Ok(services::ApplicationResponse::Json(resp)) } @@ -1018,10 +1027,10 @@ pub async fn payment_method_intent_confirm( key_store: &domain::MerchantKeyStore, pm_id: String, ) -> RouterResponse<api::PaymentMethodResponse> { + let key_manager_state = &(state).into(); req.validate()?; let db = &*state.store; - let client_secret = req.client_secret.clone(); let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to generate GlobalPaymentMethodId")?; @@ -1037,11 +1046,6 @@ pub async fn payment_method_intent_confirm( .change_context(errors::ApiErrorResponse::PaymentMethodNotFound) .attach_printable("Unable to find payment method")?; - when( - cards::authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?, - || Err(errors::ApiErrorResponse::ClientSecretExpired), - )?; - when( payment_method.status != enums::PaymentMethodStatus::AwaitingData, || { @@ -1054,7 +1058,7 @@ pub async fn payment_method_intent_confirm( let customer_id = payment_method.customer_id.to_owned(); db.find_customer_by_global_id( - &(state.into()), + key_manager_state, &customer_id, merchant_account.get_id(), key_store, @@ -1075,14 +1079,15 @@ pub async fn payment_method_intent_confirm( .await; let response = match vaulting_result { - Ok(resp) => { + Ok((vaulting_resp, fingerprint_id)) => { let pm_update = create_pm_additional_data_update( &payment_method_data, state, key_store, - Some(resp.vault_id.get_string_repr().clone()), + Some(vaulting_resp.vault_id.get_string_repr().clone()), Some(req.payment_method_type), Some(req.payment_method_subtype), + Some(fingerprint_id), ) .await .attach_printable("Unable to create Payment method data")?; @@ -1099,7 +1104,7 @@ pub async fn payment_method_intent_confirm( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let resp = pm_transforms::generate_payment_method_response(&payment_method)?; + let resp = pm_transforms::generate_payment_method_response(&payment_method, None)?; Ok(resp) } @@ -1153,7 +1158,6 @@ pub async fn create_payment_method_in_db( card_scheme: Option<String>, ) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { let db = &*state.store; - let client_secret = pm_types::PaymentMethodClientSecret::generate(&payment_method_id); let current_time = common_utils::date_time::now(); let response = db @@ -1170,7 +1174,7 @@ pub async fn create_payment_method_in_db( payment_method_data, connector_mandate_details, customer_acceptance, - client_secret: Some(client_secret), + client_secret: None, status: status.unwrap_or(enums::PaymentMethodStatus::Active), network_transaction_id: network_transaction_id.to_owned(), created_at: current_time, @@ -1205,9 +1209,18 @@ pub async fn create_payment_method_for_intent( key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, payment_method_billing_address: crypto::OptionalEncryptableValue, -) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> { +) -> errors::CustomResult<(domain::PaymentMethod, Secret<String>), errors::ApiErrorResponse> { let db = &*state.store; - let client_secret = pm_types::PaymentMethodClientSecret::generate(&payment_method_id); + let ephemeral_key = payment_helpers::create_ephemeral_key( + state, + customer_id, + merchant_id, + ephemeral_key::ResourceType::PaymentMethod, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to create ephemeral_key")?; + let current_time = common_utils::date_time::now(); let response = db @@ -1224,7 +1237,7 @@ pub async fn create_payment_method_for_intent( payment_method_data: None, connector_mandate_details: None, customer_acceptance: None, - client_secret: Some(client_secret), + client_secret: None, status: enums::PaymentMethodStatus::AwaitingData, network_transaction_id: None, created_at: current_time, @@ -1244,7 +1257,7 @@ pub async fn create_payment_method_for_intent( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in db")?; - Ok(response) + Ok((response, ephemeral_key.secret)) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -1255,15 +1268,16 @@ pub async fn create_pm_additional_data_update( vault_id: Option<String>, payment_method_type: Option<api_enums::PaymentMethod>, payment_method_subtype: Option<api_enums::PaymentMethodType>, + vault_fingerprint_id: Option<String>, ) -> RouterResult<storage::PaymentMethodUpdate> { let card = match pmd { pm_types::PaymentMethodVaultingData::Card(card) => { api::PaymentMethodsData::Card(card.clone().into()) } }; - let key_manager_state = state.into(); + let key_manager_state = &(state).into(); let pmd: Encryptable<Secret<serde_json::Value>> = - cards::create_encrypted_data(&key_manager_state, key_store, card) + cards::create_encrypted_data(key_manager_state, key_store, card) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to encrypt Payment method data")?; @@ -1277,6 +1291,7 @@ pub async fn create_pm_additional_data_update( network_token_requestor_reference_id: None, network_token_locker_id: None, network_token_payment_method_data: None, + locker_fingerprint_id: vault_fingerprint_id, }; Ok(pm_update) @@ -1290,7 +1305,7 @@ pub async fn vault_payment_method( merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, existing_vault_id: Option<domain::VaultId>, -) -> RouterResult<pm_types::AddVaultResponse> { +) -> RouterResult<(pm_types::AddVaultResponse, String)> { let db = &*state.store; // get fingerprint_id from vault @@ -1301,17 +1316,16 @@ pub async fn vault_payment_method( // throw back error if payment method is duplicated when( - Some( - db.find_payment_method_by_fingerprint_id( - &(state.into()), - key_store, - &fingerprint_id_from_vault, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to find payment method by fingerprint_id")?, + db.find_payment_method_by_fingerprint_id( + &(state.into()), + key_store, + &fingerprint_id_from_vault, ) - .is_some(), + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to find payment method by fingerprint_id") + .inspect_err(|e| logger::error!("Vault Fingerprint_id error: {:?}", e)) + .is_ok(), || { Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod) .attach_printable("Cannot vault duplicate payment method")) @@ -1324,7 +1338,7 @@ pub async fn vault_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to add payment method in vault")?; - Ok(resp_from_vault) + Ok((resp_from_vault, fingerprint_id_from_vault)) } #[cfg(all( @@ -1754,6 +1768,11 @@ pub async fn retrieve_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + when( + payment_method.status == enums::PaymentMethodStatus::Inactive, + || Err(errors::ApiErrorResponse::PaymentMethodNotFound), + )?; + let pmd = payment_method .payment_method_data .clone() @@ -1774,7 +1793,7 @@ pub async fn retrieve_payment_method( 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(), + ephemeral_key: None, payment_method_data: pmd, }; @@ -1822,16 +1841,12 @@ pub async fn update_payment_method( .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from vault")? - .data - .expose() - .parse_struct("PaymentMethodVaultingData") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to parse PaymentMethodVaultingData")?; + .data; let vault_request_data = pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, req.payment_method_data); - let vaulting_response = vault_payment_method( + let (vaulting_response, fingerprint_id) = vault_payment_method( &state, &vault_request_data, &merchant_account, @@ -1848,6 +1863,7 @@ pub async fn update_payment_method( Some(vaulting_response.vault_id.get_string_repr().clone()), payment_method.get_payment_method_type(), payment_method.get_payment_method_subtype(), + Some(fingerprint_id), ) .await .attach_printable("Unable to create Payment method data")?; @@ -1864,7 +1880,7 @@ pub async fn update_payment_method( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update payment method in db")?; - let response = pm_transforms::generate_payment_method_response(&payment_method)?; + let response = pm_transforms::generate_payment_method_response(&payment_method, None)?; // Add a PT task to handle payment_method delete from vault @@ -1896,6 +1912,11 @@ pub async fn delete_payment_method( .await .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + when( + payment_method.status == enums::PaymentMethodStatus::Inactive, + || Err(errors::ApiErrorResponse::PaymentMethodNotFound), + )?; + let vault_id = payment_method .locker_id .clone() diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index c3fbfd8afbf..ce95096a0fb 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -551,6 +551,7 @@ pub fn generate_pm_vaulting_req_from_update_request( #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub fn generate_payment_method_response( pm: &domain::PaymentMethod, + ephemeral_key: Option<Secret<String>>, ) -> errors::RouterResult<api::PaymentMethodResponse> { let pmd = pm .payment_method_data @@ -572,7 +573,7 @@ pub fn generate_payment_method_response( created: Some(pm.created_at), recurring_enabled: false, last_used_at: Some(pm.last_used_at), - client_secret: pm.client_secret.clone(), + ephemeral_key, payment_method_data: pmd, }; diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index fcff711f6c9..65ef16cb449 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1186,6 +1186,7 @@ async fn create_vault_request<R: pm_types::VaultingInterface>( jwekey: &settings::Jwekey, locker: &settings::Locker, payload: Vec<u8>, + tenant_id: id_type::TenantId, ) -> CustomResult<request::Request, errors::VaultError> { let private_key = jwekey.vault_private_key.peek().as_bytes(); @@ -1206,6 +1207,10 @@ async fn create_vault_request<R: pm_types::VaultingInterface>( headers::CONTENT_TYPE, consts::VAULT_HEADER_CONTENT_TYPE.into(), ); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); request.set_body(request::RequestContent::Json(Box::new(jwe_payload))); Ok(request) } @@ -1219,7 +1224,9 @@ pub async fn call_to_vault<V: pm_types::VaultingInterface>( let locker = &state.conf.locker; let jwekey = state.conf.jwekey.get_inner(); - let request = create_vault_request::<V>(jwekey, locker, payload).await?; + let request = + create_vault_request::<V>(jwekey, locker, payload, state.tenant.tenant_id.to_owned()) + .await?; let response = services::call_connector_api(state, request, V::get_vaulting_flow_name()) .await .change_context(errors::VaultError::VaultAPIError); diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 78cfdda33b4..c243686a76c 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1,11 +1,15 @@ use std::{borrow::Cow, str::FromStr}; +#[cfg(feature = "v2")] +use api_models::ephemeral_key::EphemeralKeyResponse; use api_models::{ mandates::RecurringDetails, payments::{additional_info as payment_additional_types, RequestSurchargeDetails}, }; use base64::Engine; use common_enums::ConnectorType; +#[cfg(feature = "v2")] +use common_utils::id_type::GenerateId; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt}, @@ -40,6 +44,8 @@ use openssl::{ pkey::PKey, symm::{decrypt_aead, Cipher}, }; +#[cfg(feature = "v2")] +use redis_interface::errors::RedisError; use router_env::{instrument, logger, tracing}; use uuid::Uuid; use x509_parser::parse_x509_certificate; @@ -48,8 +54,6 @@ use super::{ operations::{BoxedOperation, Operation, PaymentResponse}, CustomerDetails, PaymentData, }; -#[cfg(feature = "v2")] -use crate::core::admin as core_admin; use crate::{ configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig}, connector, @@ -84,6 +88,8 @@ use crate::{ OptionExt, StringExt, }, }; +#[cfg(feature = "v2")] +use crate::{core::admin as core_admin, headers}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::{ core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update, @@ -3021,6 +3027,7 @@ pub fn make_merchant_url_with_response( Ok(merchant_url_with_response.to_string()) } +#[cfg(feature = "v1")] pub async fn make_ephemeral_key( state: SessionState, customer_id: id_type::CustomerId, @@ -3043,6 +3050,80 @@ pub async fn make_ephemeral_key( Ok(services::ApplicationResponse::Json(ek)) } +#[cfg(feature = "v2")] +pub async fn make_ephemeral_key( + state: SessionState, + customer_id: id_type::GlobalCustomerId, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + headers: &actix_web::http::header::HeaderMap, +) -> errors::RouterResponse<EphemeralKeyResponse> { + let db = &state.store; + let key_manager_state = &((&state).into()); + db.find_customer_by_global_id( + key_manager_state, + &customer_id, + merchant_account.get_id(), + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?; + + let resource_type = services::authentication::get_header_value_by_key( + headers::X_RESOURCE_TYPE.to_string(), + headers, + )? + .map(ephemeral_key::ResourceType::from_str) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidRequestData { + message: format!("`{}` header is invalid", headers::X_RESOURCE_TYPE), + })? + .get_required_value("ResourceType") + .attach_printable("Failed to convert ResourceType from string")?; + + let ephemeral_key = create_ephemeral_key( + &state, + &customer_id, + merchant_account.get_id(), + resource_type, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create ephemeral key")?; + + let response = EphemeralKeyResponse::foreign_from(ephemeral_key); + Ok(services::ApplicationResponse::Json(response)) +} + +#[cfg(feature = "v2")] +pub async fn create_ephemeral_key( + state: &SessionState, + customer_id: &id_type::GlobalCustomerId, + merchant_id: &id_type::MerchantId, + resource_type: ephemeral_key::ResourceType, +) -> RouterResult<ephemeral_key::EphemeralKeyType> { + use common_utils::generate_time_ordered_id; + + let store = &state.store; + let id = id_type::EphemeralKeyId::generate(); + let secret = masking::Secret::new(generate_time_ordered_id("epk")); + let ephemeral_key = ephemeral_key::EphemeralKeyTypeNew { + id, + customer_id: customer_id.to_owned(), + merchant_id: merchant_id.to_owned(), + secret, + resource_type, + }; + let ephemeral_key = store + .create_ephemeral_key(ephemeral_key, state.conf.eph_key.validity) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to create ephemeral key")?; + Ok(ephemeral_key) +} + +#[cfg(feature = "v1")] pub async fn delete_ephemeral_key( state: SessionState, ek_id: String, @@ -3056,6 +3137,29 @@ pub async fn delete_ephemeral_key( Ok(services::ApplicationResponse::Json(ek)) } +#[cfg(feature = "v2")] +pub async fn delete_ephemeral_key( + state: SessionState, + ephemeral_key_id: String, +) -> errors::RouterResponse<EphemeralKeyResponse> { + let db = state.store.as_ref(); + let ephemeral_key = db + .delete_ephemeral_key(&ephemeral_key_id) + .await + .map_err(|err| match err.current_context() { + errors::StorageError::ValueNotFound(_) => { + err.change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Ephemeral Key not found".to_string(), + }) + } + _ => err.change_context(errors::ApiErrorResponse::InternalServerError), + }) + .attach_printable("Unable to delete ephemeral key")?; + + let response = EphemeralKeyResponse::foreign_from(ephemeral_key); + Ok(services::ApplicationResponse::Json(response)) +} + pub fn make_pg_redirect_response( payment_id: id_type::PaymentId, response: &api::PaymentsResponse, diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs index a1d43e83b87..a77995e4e58 100644 --- a/crates/router/src/db/ephemeral_key.rs +++ b/crates/router/src/db/ephemeral_key.rs @@ -1,5 +1,9 @@ +#[cfg(feature = "v2")] +use common_utils::id_type; use time::ext::NumericalDuration; +#[cfg(feature = "v2")] +use crate::types::storage::ephemeral_key::{EphemeralKeyType, EphemeralKeyTypeNew, ResourceType}; use crate::{ core::errors::{self, CustomResult}, db::MockDb, @@ -8,30 +12,64 @@ use crate::{ #[async_trait::async_trait] pub trait EphemeralKeyInterface { + #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, _ek: EphemeralKeyNew, _validity: i64, ) -> CustomResult<EphemeralKey, errors::StorageError>; + + #[cfg(feature = "v2")] + async fn create_ephemeral_key( + &self, + _ek: EphemeralKeyTypeNew, + _validity: i64, + ) -> CustomResult<EphemeralKeyType, errors::StorageError>; + + #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, _key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; + + #[cfg(feature = "v2")] + async fn get_ephemeral_key( + &self, + _key: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError>; + + #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, _id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError>; + + #[cfg(feature = "v2")] + async fn delete_ephemeral_key( + &self, + _id: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError>; } mod storage { use common_utils::date_time; + #[cfg(feature = "v2")] + use common_utils::id_type; use error_stack::ResultExt; + #[cfg(feature = "v2")] + use masking::PeekInterface; + #[cfg(feature = "v2")] + use redis_interface::errors::RedisError; use redis_interface::HsetnxReply; use router_env::{instrument, tracing}; use storage_impl::redis::kv_store::RedisConnInterface; use time::ext::NumericalDuration; use super::EphemeralKeyInterface; + #[cfg(feature = "v2")] + use crate::types::storage::ephemeral_key::{ + EphemeralKeyType, EphemeralKeyTypeNew, ResourceType, + }; use crate::{ core::errors::{self, CustomResult}, services::Store, @@ -40,6 +78,7 @@ mod storage { #[async_trait::async_trait] impl EphemeralKeyInterface for Store { + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn create_ephemeral_key( &self, @@ -94,6 +133,68 @@ mod storage { Err(er) => Err(er).change_context(errors::StorageError::KVError), } } + + #[cfg(feature = "v2")] + #[instrument(skip_all)] + async fn create_ephemeral_key( + &self, + new: EphemeralKeyTypeNew, + validity: i64, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + let created_at = date_time::now(); + let expires = created_at.saturating_add(validity.hours()); + let id_key = new.id.generate_redis_key(); + + let created_ephemeral_key = EphemeralKeyType { + id: new.id, + created_at, + expires, + customer_id: new.customer_id, + merchant_id: new.merchant_id, + secret: new.secret, + resource_type: new.resource_type, + }; + let secret_key = created_ephemeral_key.generate_secret_key(); + + match self + .get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .serialize_and_set_multiple_hash_field_if_not_exist( + &[ + (&secret_key, &created_ephemeral_key), + (&id_key, &created_ephemeral_key), + ], + "ephkey", + None, + ) + .await + { + Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => { + Err(errors::StorageError::DuplicateValue { + entity: "ephemeral key", + key: None, + } + .into()) + } + Ok(_) => { + let expire_at = expires.assume_utc().unix_timestamp(); + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .set_expire_at(&secret_key, expire_at) + .await + .change_context(errors::StorageError::KVError)?; + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .set_expire_at(&id_key, expire_at) + .await + .change_context(errors::StorageError::KVError)?; + Ok(created_ephemeral_key) + } + Err(er) => Err(er).change_context(errors::StorageError::KVError), + } + } + + #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_ephemeral_key( &self, @@ -106,6 +207,22 @@ mod storage { .await .change_context(errors::StorageError::KVError) } + + #[cfg(feature = "v2")] + #[instrument(skip_all)] + async fn get_ephemeral_key( + &self, + key: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + let key = format!("epkey_{key}"); + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .get_hash_field_and_deserialize(&key, "ephkey", "EphemeralKeyType") + .await + .change_context(errors::StorageError::KVError) + } + + #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, @@ -125,11 +242,45 @@ mod storage { .change_context(errors::StorageError::KVError)?; Ok(ek) } + + #[cfg(feature = "v2")] + async fn delete_ephemeral_key( + &self, + id: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + let ephemeral_key = self.get_ephemeral_key(id).await?; + let redis_id_key = ephemeral_key.id.generate_redis_key(); + let secret_key = ephemeral_key.generate_secret_key(); + + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .delete_key(&redis_id_key) + .await + .map_err(|err| match err.current_context() { + RedisError::NotFound => { + err.change_context(errors::StorageError::ValueNotFound(redis_id_key)) + } + _ => err.change_context(errors::StorageError::KVError), + })?; + + self.get_redis_conn() + .map_err(Into::<errors::StorageError>::into)? + .delete_key(&secret_key) + .await + .map_err(|err| match err.current_context() { + RedisError::NotFound => { + err.change_context(errors::StorageError::ValueNotFound(secret_key)) + } + _ => err.change_context(errors::StorageError::KVError), + })?; + Ok(ephemeral_key) + } } } #[async_trait::async_trait] impl EphemeralKeyInterface for MockDb { + #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, ek: EphemeralKeyNew, @@ -150,6 +301,17 @@ impl EphemeralKeyInterface for MockDb { ephemeral_keys.push(ephemeral_key.clone()); Ok(ephemeral_key) } + + #[cfg(feature = "v2")] + async fn create_ephemeral_key( + &self, + ek: EphemeralKeyTypeNew, + validity: i64, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + todo!() + } + + #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, key: &str, @@ -167,6 +329,16 @@ impl EphemeralKeyInterface for MockDb { ), } } + + #[cfg(feature = "v2")] + async fn get_ephemeral_key( + &self, + key: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + todo!() + } + + #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, @@ -181,4 +353,12 @@ impl EphemeralKeyInterface for MockDb { ); } } + + #[cfg(feature = "v2")] + async fn delete_ephemeral_key( + &self, + id: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + todo!() + } } diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index f49173b3549..4155bbf3ff9 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -6,6 +6,8 @@ use common_utils::{ id_type, types::{keymanager::KeyManagerState, theme::ThemeLineage}, }; +#[cfg(feature = "v2")] +use diesel_models::ephemeral_key::{EphemeralKeyType, EphemeralKeyTypeNew}; use diesel_models::{ enums, enums::ProcessTrackerStatus, @@ -646,6 +648,7 @@ impl DisputeInterface for KafkaStore { #[async_trait::async_trait] impl EphemeralKeyInterface for KafkaStore { + #[cfg(feature = "v1")] async fn create_ephemeral_key( &self, ek: EphemeralKeyNew, @@ -653,18 +656,47 @@ impl EphemeralKeyInterface for KafkaStore { ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.create_ephemeral_key(ek, validity).await } + + #[cfg(feature = "v2")] + async fn create_ephemeral_key( + &self, + ek: EphemeralKeyTypeNew, + validity: i64, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + self.diesel_store.create_ephemeral_key(ek, validity).await + } + + #[cfg(feature = "v1")] async fn get_ephemeral_key( &self, key: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.get_ephemeral_key(key).await } + + #[cfg(feature = "v2")] + async fn get_ephemeral_key( + &self, + key: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + self.diesel_store.get_ephemeral_key(key).await + } + + #[cfg(feature = "v1")] async fn delete_ephemeral_key( &self, id: &str, ) -> CustomResult<EphemeralKey, errors::StorageError> { self.diesel_store.delete_ephemeral_key(id).await } + + #[cfg(feature = "v2")] + async fn delete_ephemeral_key( + &self, + id: &str, + ) -> CustomResult<EphemeralKeyType, errors::StorageError> { + self.diesel_store.delete_ephemeral_key(id).await + } } #[async_trait::async_trait] diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index d43fa054313..05c15b91674 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -90,6 +90,7 @@ pub mod headers { pub const X_REDIRECT_URI: &str = "x-redirect-uri"; pub const X_TENANT_ID: &str = "x-tenant-id"; pub const X_CLIENT_SECRET: &str = "X-Client-Secret"; + pub const X_RESOURCE_TYPE: &str = "X-Resource-Type"; } pub mod pii { @@ -155,15 +156,17 @@ pub fn mk_app( } } + #[cfg(all(feature = "oltp", any(feature = "v1", feature = "v2"),))] + { + server_app = server_app.service(routes::EphemeralKey::server(state.clone())) + } #[cfg(all( feature = "oltp", any(feature = "v1", feature = "v2"), not(feature = "customer_v2") ))] { - server_app = server_app - .service(routes::EphemeralKey::server(state.clone())) - .service(routes::Poll::server(state.clone())) + server_app = server_app.service(routes::Poll::server(state.clone())) } #[cfg(feature = "olap")] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 766679491c5..4192df58d2c 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -27,11 +27,7 @@ use self::settings::Tenant; use super::currency; #[cfg(feature = "dummy_connector")] use super::dummy_connector::*; -#[cfg(all( - any(feature = "v1", feature = "v2"), - not(feature = "customer_v2"), - feature = "oltp" -))] +#[cfg(all(any(feature = "v1", feature = "v2"), feature = "oltp"))] use super::ephemeral_key::*; #[cfg(any(feature = "olap", feature = "oltp"))] use super::payment_methods::*; @@ -1141,8 +1137,11 @@ impl PaymentMethods { 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))) - .service(web::resource("/{id}").route(web::delete().to(payment_method_delete_api))); + .service( + web::resource("/{id}") + .route(web::get().to(payment_method_retrieve_api)) + .route(web::delete().to(payment_method_delete_api)), + ); route } @@ -1416,6 +1415,16 @@ impl EphemeralKey { } } +#[cfg(feature = "v2")] +impl EphemeralKey { + pub fn server(config: AppState) -> Scope { + web::scope("/v2/ephemeral-keys") + .app_data(web::Data::new(config)) + .service(web::resource("").route(web::post().to(ephemeral_key_create))) + .service(web::resource("/{id}").route(web::delete().to(ephemeral_key_delete))) + } +} + pub struct Mandates; #[cfg(all(any(feature = "olap", feature = "oltp"), feature = "v1"))] diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs index e6a33c59192..0330482e81a 100644 --- a/crates/router/src/routes/ephemeral_key.rs +++ b/crates/router/src/routes/ephemeral_key.rs @@ -1,11 +1,7 @@ -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use actix_web::{web, HttpRequest, HttpResponse}; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use router_env::{instrument, tracing, Flow}; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use super::AppState; -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::{ core::{api_locking, payments::helpers}, services::{api, authentication as auth}, @@ -38,7 +34,35 @@ pub async fn ephemeral_key_create( .await } -#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] +#[cfg(feature = "v2")] +#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))] +pub async fn ephemeral_key_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<api_models::ephemeral_key::EphemeralKeyCreateRequest>, +) -> HttpResponse { + let flow = Flow::EphemeralKeyCreate; + let payload = json_payload.into_inner(); + api::server_wrap( + flow, + state, + &req, + payload, + |state, auth: auth::AuthenticationData, payload, _| { + helpers::make_ephemeral_key( + state, + payload.customer_id.to_owned(), + auth.merchant_account, + auth.key_store, + req.headers(), + ) + }, + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + ) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))] pub async fn ephemeral_key_delete( state: web::Data<AppState>, diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index c27a25677af..729a35aa8b7 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -141,8 +141,8 @@ pub async fn confirm_payment_method_intent_api( let pm_id = path.into_inner(); let payload = json_payload.into_inner(); - let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) { - Ok((auth, _auth_flow)) => (auth, _auth_flow), + let auth = match auth::is_ephemeral_or_publishible_auth(req.headers()) { + Ok(auth) => auth, Err(e) => return api::log_and_return_error_response(e), }; @@ -150,7 +150,6 @@ pub async fn confirm_payment_method_intent_api( id: pm_id.clone(), payment_method_type: payload.payment_method_type, payment_method_subtype: payload.payment_method_subtype, - client_secret: payload.client_secret.clone(), customer_id: payload.customer_id.to_owned(), payment_method_data: payload.payment_method_data.clone(), }; @@ -191,6 +190,11 @@ pub async fn payment_method_update_api( let payment_method_id = path.into_inner(); let payload = json_payload.into_inner(); + let auth = match auth::is_ephemeral_or_publishible_auth(req.headers()) { + Ok(auth) => auth, + Err(e) => return api::log_and_return_error_response(e), + }; + Box::pin(api::server_wrap( flow, state, @@ -205,7 +209,7 @@ pub async fn payment_method_update_api( auth.key_store, ) }, - &auth::HeaderAuth(auth::ApiKeyAuth), + &*auth, api_locking::LockAction::NotApplicable, )) .await diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index e8435243ff4..3df0313668c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use actix_web::http::header::HeaderMap; #[cfg(all( any(feature = "v2", feature = "v1"), @@ -11,7 +13,11 @@ use api_models::payouts; use api_models::{payment_methods::PaymentMethodListRequest, payments}; use async_trait::async_trait; use common_enums::TokenPurpose; +#[cfg(feature = "v2")] +use common_utils::fp_utils; use common_utils::{date_time, id_type}; +#[cfg(feature = "v2")] +use diesel_models::ephemeral_key; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use masking::PeekInterface; @@ -1329,6 +1335,32 @@ where #[derive(Debug)] pub struct EphemeralKeyAuth; +#[cfg(feature = "v1")] +#[async_trait] +impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth +where + A: SessionStateInfo + Sync, +{ + async fn authenticate_and_fetch( + &self, + request_headers: &HeaderMap, + state: &A, + ) -> RouterResult<(AuthenticationData, AuthenticationType)> { + let api_key = + get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?; + let ephemeral_key = state + .store() + .get_ephemeral_key(api_key) + .await + .change_context(errors::ApiErrorResponse::Unauthorized)?; + + MerchantIdAuth(ephemeral_key.merchant_id) + .authenticate_and_fetch(request_headers, state) + .await + } +} + +#[cfg(feature = "v2")] #[async_trait] impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth where @@ -1347,6 +1379,20 @@ where .await .change_context(errors::ApiErrorResponse::Unauthorized)?; + let resource_type = HeaderMapStruct::new(request_headers) + .get_mandatory_header_value_by_key(headers::X_RESOURCE_TYPE) + .and_then(|val| { + ephemeral_key::ResourceType::from_str(val).change_context( + errors::ApiErrorResponse::InvalidRequestData { + message: format!("`{}` header is invalid", headers::X_RESOURCE_TYPE), + }, + ) + })?; + + fp_utils::when(resource_type != ephemeral_key.resource_type, || { + Err(errors::ApiErrorResponse::Unauthorized) + })?; + MerchantIdAuth(ephemeral_key.merchant_id) .authenticate_and_fetch(request_headers, state) .await @@ -2938,13 +2984,6 @@ impl ClientSecretFetch for PaymentMethodCreate { } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -impl ClientSecretFetch for PaymentMethodIntentConfirm { - fn get_client_secret(&self) -> Option<&String> { - Some(&self.client_secret) - } -} - impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() @@ -2969,6 +3008,7 @@ impl ClientSecretFetch for api_models::pm_auth::ExchangeTokenCreateRequest { } } +#[cfg(feature = "v1")] impl ClientSecretFetch for api_models::payment_methods::PaymentMethodUpdate { fn get_client_secret(&self) -> Option<&String> { self.client_secret.as_ref() @@ -3059,6 +3099,20 @@ where } } +pub fn is_ephemeral_or_publishible_auth<A: SessionStateInfo + Sync + Send>( + headers: &HeaderMap, +) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { + let api_key = get_api_key(headers)?; + + if api_key.starts_with("epk") { + Ok(Box::new(EphemeralKeyAuth)) + } else if api_key.starts_with("pk_") { + Ok(Box::new(HeaderAuth(PublishableKeyAuth))) + } else { + Ok(Box::new(HeaderAuth(ApiKeyAuth))) + } +} + pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( headers: &HeaderMap, ) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> { @@ -3109,7 +3163,7 @@ pub fn get_header_value_by_key(key: String, headers: &HeaderMap) -> RouterResult }) .transpose() } -pub fn get_id_type_by_key_from_headers<T: std::str::FromStr>( +pub fn get_id_type_by_key_from_headers<T: FromStr>( key: String, headers: &HeaderMap, ) -> RouterResult<Option<T>> { diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index 1a6b9053dcb..c40d6fedfe7 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -126,16 +126,6 @@ impl VaultingDataInterface for PaymentMethodVaultingData { } } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -pub struct PaymentMethodClientSecret; - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -impl PaymentMethodClientSecret { - pub fn generate(payment_method_id: &common_utils::id_type::GlobalPaymentMethodId) -> String { - todo!() - } -} - #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub struct SavedPMLPaymentsInfo { pub payment_intent: storage::PaymentIntent, @@ -155,7 +145,7 @@ pub struct VaultRetrieveRequest { #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveResponse { - pub data: Secret<String>, + pub data: PaymentMethodVaultingData, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] diff --git a/crates/router/src/types/storage/ephemeral_key.rs b/crates/router/src/types/storage/ephemeral_key.rs index 9927e16b3fa..c4b8e2ba701 100644 --- a/crates/router/src/types/storage/ephemeral_key.rs +++ b/crates/router/src/types/storage/ephemeral_key.rs @@ -1 +1,18 @@ pub use diesel_models::ephemeral_key::{EphemeralKey, EphemeralKeyNew}; +#[cfg(feature = "v2")] +pub use diesel_models::ephemeral_key::{EphemeralKeyType, EphemeralKeyTypeNew, ResourceType}; + +#[cfg(feature = "v2")] +use crate::types::transformers::ForeignFrom; +#[cfg(feature = "v2")] +impl ForeignFrom<EphemeralKeyType> for api_models::ephemeral_key::EphemeralKeyResponse { + fn foreign_from(from: EphemeralKeyType) -> Self { + Self { + customer_id: from.customer_id, + created_at: from.created_at, + expires: from.expires, + secret: from.secret, + id: from.id, + } + } +}
2024-12-11T18:52: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 --> This PR contains - - Ephemeral auth support for v2 (including resource type product identifier) - Minor Fixes for Payment methods v2 CRUD APIs - Removed Client secret auth from PaymentMethod CRUD APIs ### 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). --> ## 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 Payment Method Intent ``` curl --location --request POST 'http://localhost:8080/v2/payment-methods/create-intent' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_DMmRBLpkNczeVDPd2EKd' \ --header 'api-key: dev_HVwdf7yWqJ9GGfw1CLDbAgjOFYHrPXoisK8pJcVPfdbc73238GROVpDhN3M9cPe2' \ --data-raw '{ "customer_id": "cus_0193ab7e6cc074939f389817610cd5b1" }' ``` Response ``` { "merchant_id": "cloth_seller_pcGA5SfzTmVUTBKvh2T3", "customer_id": "cus_0193ab7e6cc074939f389817610cd5b1", "payment_method_id": "12345_pm_0193b69ba645716086c0fe21c462cf2d", "payment_method_type": null, "payment_method_subtype": null, "recurring_enabled": false, "created": "2024-12-11T16:44:34.261Z", "last_used_at": "2024-12-11T16:44:34.261Z", "ephemeral_key": "epk_0c6ebab77f51446ab30467640a6f8f02", "payment_method_data": null } ``` 2. Use Ephemeral key to confirm intent ``` curl --location --request POST 'http://localhost:8080/v2/payment-methods/12345_pm_0193b69ba645716086c0fe21c462cf2d/confirm-intent' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_DMmRBLpkNczeVDPd2EKd' \ --header 'X-Resource-Type: payment_method' \ --header 'api-key: epk_0c6ebab77f51446ab30467640a6f8f02' \ --data-raw '{ "payment_method_type": "card", "payment_method_subtype": "credit", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "12", "card_exp_year": "2025", "card_holder_name": "joseph Doe" } }, "customer_id": "cus_0193ab7e6cc074939f389817610cd5b1" }' ``` Response - ``` { "merchant_id": "cloth_seller_pcGA5SfzTmVUTBKvh2T3", "customer_id": "cus_0193ab7e6cc074939f389817610cd5b1", "payment_method_id": "12345_pm_0193b69ba645716086c0fe21c462cf2d", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": false, "created": "2024-12-11T16:44:34.261Z", "last_used_at": "2024-12-11T16:44:34.261Z", "ephemeral_key": null, "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "12", "expiry_year": "2025", "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } } } ``` 3. Retrieve a PM - ``` curl --location --request GET 'http://localhost:8080/v2/payment-methods/12345_pm_0193cec5b7637f33a36b1f9ce34137bd' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_OqoV7IKp695hRjM1zRfE' \ --header 'X-Resource-Type: payment_method' \ --header 'api-key: dev_qxDW3eUAAg8u1Yagzfzur089lWvt4ZwendCYibU4XBTV9Mo6tJ3wi0inMiO9gnTO' ``` Response - ``` { "merchant_id": "cloth_seller_R8JPuhk0GnkqHNDBzs7g", "customer_id": "cus_0193ce809d9e7411bd207c8f85eac45b", "payment_method_id": "12345_pm_0193cec5b7637f33a36b1f9ce34137bd", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": false, "created": "2024-12-16T09:21:24.377Z", "last_used_at": "2024-12-16T09:21:24.377Z", "ephemeral_key": null, "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "12", "expiry_year": "2025", "card_holder_name": "joseph Doe", "card_fingerprint": null, "nick_name": null, "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } } } ``` 4. Update a PM - ``` curl --location --request PATCH 'http://localhost:8080/v2/payment-methods/12345_pm_0193b69ba645716086c0fe21c462cf2d/update-saved-payment-method' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_DMmRBLpkNczeVDPd2EKd' \ --header 'X-Resource-Type: payment_method' \ --header 'api-key: epk_0c6ebab77f51446ab30467640a6f8f02' \ --data-raw '{ "payment_method_data": { "card": { "card_holder_name": "joseph", "nick_name": "some_name11" } } }' ``` Response - ``` { "merchant_id": "cloth_seller_pcGA5SfzTmVUTBKvh2T3", "customer_id": "cus_0193ab7e6cc074939f389817610cd5b1", "payment_method_id": "12345_pm_0193b69ba645716086c0fe21c462cf2d", "payment_method_type": "card", "payment_method_subtype": "credit", "recurring_enabled": false, "created": "2024-12-11T16:44:34.261Z", "last_used_at": "2024-12-11T16:44:34.261Z", "ephemeral_key": null, "payment_method_data": { "card": { "issuer_country": null, "last4_digits": "4242", "expiry_month": "12", "expiry_year": "2025", "card_holder_name": "joseph", "card_fingerprint": null, "nick_name": "some_name11", "card_network": null, "card_isin": null, "card_issuer": null, "card_type": null, "saved_to_locker": true } } } ``` 5. Delete a PM - ``` curl --location --request DELETE 'http://localhost:8080/v2/payment-methods/12345_pm_0193cec5b7637f33a36b1f9ce34137bd' \ --header 'Accept: application/json' \ --header 'X-Profile-Id: pro_OqoV7IKp695hRjM1zRfE' \ --header 'X-Resource-Type: payment_method' \ --header 'api-key: dev_qxDW3eUAAg8u1Yagzfzur089lWvt4ZwendCYibU4XBTV9Mo6tJ3wi0inMiO9gnTO' ``` Response - ``` { "payment_method_id": "12345_pm_0193b69ba645716086c0fe21c462cf2d" } ``` 6. Standalone Ephemeral key create - ``` curl --location --request POST 'http://localhost:8080/v2/ephemeral-keys' \ --header 'Content-Type: application/json' \ --header 'X-Profile-Id: pro_CwrzjgurYtopm4AU4ckw' \ --header 'X-Resource-Type: payment_method' \ --header 'api-key: dev_XhFPyn6hxjHV0kwfx5TuqP01AACTenU00ioSS352L5uUFufVKqfWNAtI1reaYO3S' \ --data-raw '{ "customer_id": "12345_cus_0193d93f0f267882b5b843a648890ede" }' ``` Response - ``` { "id": "eki_TEEmZPBA0XL1jyQYaXVY", "customer_id": "12345_cus_0193d93f0f267882b5b843a648890ede", "created_at": "2024-12-19 12:17:01.909893", "expires": "2024-12-19 13:17:01.909893", "secret": "epk_0193ded995d57fd290ed0ce218e01cf9" } ``` Can use the ephemeral key obtained here to hit the above APIs ## 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
e8bfd0e2270300fff3f051143f34ebb782da5366
juspay/hyperswitch
juspay__hyperswitch-6782
Bug: Adding new logo in API ref and Readme
diff --git a/api-reference-v2/logo/dark.svg b/api-reference-v2/logo/dark.svg index fbf0d89d410..f07be0cea14 100644 --- a/api-reference-v2/logo/dark.svg +++ b/api-reference-v2/logo/dark.svg @@ -1,29 +1,21 @@ -<svg width="766" height="100" viewBox="0 0 766 100" fill="none" xmlns="http://www.w3.org/2000/svg"> -<g clip-path="url(#clip0_1969_1952)"> -<path d="M370.801 53.4399C370.801 70.0799 360.581 79.9999 346.441 79.9999C338.621 79.9999 331.811 76.7899 328.701 71.4799V99.0399H317.771V27.6899H327.791L328.691 35.5099C331.801 30.1999 338.411 26.6899 346.431 26.6899C360.061 26.6899 370.791 36.2099 370.791 53.4499L370.801 53.4399ZM359.471 53.4399C359.471 42.9199 353.261 36.3999 344.231 36.3999C335.611 36.2999 329.001 42.9099 329.001 53.5399C329.001 64.1699 335.621 70.2799 344.231 70.2799C352.841 70.2799 359.471 63.9699 359.471 53.4399Z" fill="white"/> -<path d="M428.931 56.3498H389.641C389.841 65.9698 396.151 70.9798 404.171 70.9798C410.181 70.9798 415.201 68.1698 417.301 62.5598H428.431C425.721 72.9798 416.501 79.9998 403.971 79.9998C388.631 79.9998 378.511 69.3798 378.511 53.2398C378.511 37.0998 388.631 26.5798 403.871 26.5798C419.111 26.5798 428.931 36.7998 428.931 52.2398V56.3498ZM389.741 48.7298H417.801C417.201 39.8098 411.291 35.2998 403.871 35.2998C396.451 35.2998 390.541 39.8098 389.741 48.7298Z" fill="white"/> -<path d="M448.281 27.6899C443.181 27.6899 439.051 31.8199 439.051 36.9199V79.0099H450.081V51.6499V39.8199C450.081 38.5499 451.111 37.5099 452.391 37.5099H469.231V27.6899H448.291H448.281Z" fill="white"/> -<path d="M300.14 27.5898L286.01 70.1898L270.77 27.6898H258.94L278.48 78.3098C279.08 79.9098 279.38 81.2198 279.38 82.5198C279.38 83.2298 279.31 83.8798 279.19 84.4798L279.16 84.5898C279.09 84.9098 279.01 85.2098 278.91 85.4998L278.17 88.2098C277.99 88.8798 277.38 89.3398 276.69 89.3398H261.14V99.0598H272.47C280.09 99.0598 286.4 97.2598 290.01 87.2298L311.56 27.6898L300.13 27.5898H300.14Z" fill="white"/> -<path d="M206.82 78.9999H217.74V51.3399C217.74 42.7199 222.45 36.7099 231.17 36.7099C238.79 36.6099 243.5 41.1199 243.5 51.0399V78.9999H254.43V49.3299C254.43 31.7899 243.71 26.5799 233.98 26.5799C226.56 26.5799 220.75 29.4899 217.74 34.2999V6.63989H206.82V78.9999Z" fill="white"/> -<path d="M483.66 63.4699C483.76 68.7799 488.67 71.8899 495.39 71.8899C502.11 71.8899 506.11 69.3799 506.11 64.8699C506.11 60.9599 504.11 58.8599 498.29 57.9499L487.97 56.1499C477.95 54.4499 474.04 49.2299 474.04 41.9199C474.04 32.6999 483.16 26.6899 494.79 26.6899C507.32 26.6899 516.44 32.6999 516.54 42.9299H505.72C505.62 37.7199 501.11 34.8099 494.8 34.8099C488.49 34.8099 484.98 37.3199 484.98 41.5299C484.98 45.2399 487.59 46.9399 493.3 47.9399L503.42 49.7399C512.94 51.4399 517.35 56.1499 517.35 63.8699C517.35 74.4899 507.53 80.0099 495.6 80.0099C482.07 80.0099 472.95 73.4999 472.75 63.4699H483.68H483.66Z" fill="white"/> -<path d="M542.19 66.9799L553.82 27.6899H565.25L576.68 66.9799L586.4 27.6899H597.93L583.4 79.0099H571.07L559.44 39.9199L547.71 79.0099H535.28L520.65 27.6899H532.18L542.2 66.9799H542.19Z" fill="white"/> -<path d="M604.34 6.63989H616.47V18.0699H604.34V6.63989ZM604.94 27.6899H615.86V79.0099H604.94V27.6899Z" fill="white"/> -<path d="M685.32 36.1099C676.8 36.1099 670.99 42.3199 670.99 53.2499C670.99 64.7799 677 70.3899 685.02 70.3899C691.43 70.3899 696.15 66.7799 698.25 59.9699H709.88C707.27 72.3999 697.85 80.0199 685.22 80.0199C669.99 80.0199 659.76 69.3998 659.76 53.2599C659.76 37.1199 669.98 26.5999 685.32 26.5999C697.85 26.5999 707.17 33.7199 709.88 46.1399H698.05C696.25 39.7299 691.33 36.1199 685.32 36.1199V36.1099Z" fill="white"/> -<path d="M642.87 69.2799C642.23 69.2799 641.72 68.7599 641.72 68.1299V37.41H653.65V27.69H641.72V13.95H630.8V22.87C630.8 26.08 629.8 27.68 626.59 27.68H622.18V37.4H630.8V65.0599C630.8 73.9799 635.71 78.99 644.63 78.99H653.55V69.2699H642.88L642.87 69.2799Z" fill="white"/> -<path d="M745.22 26.5799C737.8 26.5799 731.99 29.4899 728.98 34.2999V6.63989H718.06V78.9999H728.98V51.3399C728.98 42.7199 733.69 36.7099 742.41 36.7099C750.03 36.6099 754.74 41.1199 754.74 51.0399V78.9999H765.67V49.3299C765.67 31.7899 754.95 26.5799 745.22 26.5799Z" fill="white"/> -<g clip-path="url(#clip1_1969_1952)"> -<path d="M135.792 0H42.875C19.1958 0 0 19.1958 0 42.875C0 66.5542 19.1958 85.75 42.875 85.75H135.792C159.471 85.75 178.667 66.5542 178.667 42.875C178.667 19.1958 159.471 0 135.792 0Z" fill="#006DF9"/> -<path d="M140.261 56.4367C147.751 56.4367 153.822 50.3649 153.822 42.8751C153.822 35.3852 147.751 29.3135 140.261 29.3135C132.771 29.3135 126.699 35.3852 126.699 42.8751C126.699 50.3649 132.771 56.4367 140.261 56.4367Z" fill="white"/> -<path d="M53.2718 53.4511L39.0877 31.4253C38.7683 30.9299 38.0448 30.9299 37.7254 31.4253L23.5413 53.4511C23.1925 53.9888 23.5804 54.6993 24.2224 54.6993H52.5907C53.2327 54.6993 53.6206 53.9888 53.2718 53.4511Z" fill="white"/> -<path d="M100.55 30.353H78.1172C77.3972 30.353 76.8135 30.9367 76.8135 31.6567V54.0899C76.8135 54.8099 77.3972 55.3936 78.1172 55.3936H100.55C101.27 55.3936 101.854 54.8099 101.854 54.0899V31.6567C101.854 30.9367 101.27 30.353 100.55 30.353Z" fill="white"/> -</g> -</g> -<defs> -<clipPath id="clip0_1969_1952"> -<rect width="765.66" height="99.05" fill="white"/> -</clipPath> -<clipPath id="clip1_1969_1952"> -<rect width="178.667" height="85.75" fill="white"/> -</clipPath> -</defs> +<svg width="545" height="58" viewBox="0 0 545 58" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M27.2375 54.3079C25.9366 54.3441 24.6718 54.2355 23.3708 54.0545C19.8655 53.5477 16.577 52.4255 13.5414 50.5792C6.81987 46.5246 2.51952 40.6238 0.748782 32.8766C0.35127 31.139 0.170583 29.3651 0.170583 27.5912C0.134446 20.4957 2.44724 14.2691 7.1451 8.98363C11.2286 4.42224 16.2879 1.63472 22.2505 0.476271C23.9129 0.150457 25.5752 -0.0305508 27.2375 0.0418522C27.2375 2.75697 27.2375 5.43588 27.2375 8.15099C27.1652 8.18719 27.093 8.2234 27.0207 8.2958C26.045 8.98363 25.0693 9.70766 24.1297 10.4679C21.9976 12.2056 19.9739 14.0518 18.2754 16.2601C15.9988 19.1925 14.481 22.4144 14.2642 26.2156C14.1558 28.0256 14.3726 29.7995 14.9508 31.501C16.3601 35.7366 20.7328 40.1169 26.8761 40.2255C27.2375 40.2255 27.3098 40.298 27.3098 40.6962C27.2736 42.5424 27.2736 46.235 27.2736 46.235C27.2736 46.235 27.2736 46.4522 27.2736 46.5608C27.2375 49.1311 27.2375 51.7014 27.2375 54.3079Z" fill="#0099FF"/> +<path fill-rule="evenodd" clip-rule="evenodd" d="M27.2368 8.11469C27.2368 8.11469 27.2368 2.72066 27.2368 0.00554404C28.7184 -0.0306575 30.1639 0.114149 31.6094 0.331358C34.3197 0.765776 36.9216 1.56221 39.379 2.82926C44.4743 5.47197 48.4856 9.23693 51.1959 14.3775C52.7498 17.3461 53.7617 20.4956 54.1592 23.7899C54.6289 27.6635 54.2676 31.5009 53.1112 35.2296C51.7741 39.4652 49.5336 43.194 46.3896 46.3435C42.5591 50.1447 38.0057 52.6064 32.7297 53.7286C30.9228 54.0906 29.0798 54.3078 27.2368 54.2716C27.2368 51.6651 27.2368 49.0948 27.2368 46.4883C27.2368 46.3797 27.2368 46.1987 27.2368 46.1987C27.2368 46.1987 27.3452 46.1263 27.3813 46.0901C30.2001 44.099 32.8742 41.9269 35.187 39.3204C36.7048 37.6189 38.0057 35.8088 38.9092 33.7092C40.174 30.7406 40.6799 27.6997 40.0294 24.4778C38.873 18.6131 33.6331 14.2327 27.5982 14.0879C27.2007 14.0879 27.2368 13.7621 27.2368 13.7621V8.11469Z" fill="#0561E2"/> +<path d="M89.2508 35.5966C89.2508 37.0921 89.0055 38.5164 88.55 39.9051C88.0944 41.2937 87.3586 42.5044 86.4475 43.5726C85.5013 44.6408 84.3449 45.4598 82.9432 46.1007C81.5415 46.7061 79.8945 47.0265 78.0723 47.0265C75.1288 47.0265 72.7109 46.3144 70.8536 44.9257C68.9614 43.537 67.7349 41.3293 67.1392 38.3027L73.3416 36.8072C73.5519 38.0535 74.0425 39.0505 74.8485 39.7982C75.6194 40.546 76.6006 40.9021 77.757 40.9021C79.6492 40.9021 80.9458 40.2611 81.6116 38.9437C82.2774 37.6618 82.6278 35.8458 82.6278 33.5669V8.25005H89.2508V35.5966Z" fill="white"/> +<path d="M125.764 32.1782C125.764 34.4571 125.378 36.5223 124.607 38.3383C123.836 40.1899 122.785 41.721 121.453 43.0029C120.122 44.2848 118.545 45.2818 116.723 45.9583C114.901 46.6705 112.903 46.9909 110.766 46.9909C108.628 46.9909 106.631 46.6349 104.843 45.9583C103.021 45.2818 101.444 44.2848 100.078 43.0029C98.711 41.721 97.6597 40.1543 96.9238 38.3383C96.1529 36.5223 95.8025 34.4571 95.8025 32.1782V8.25005H102.425V31.9646C102.425 32.8904 102.566 33.8518 102.846 34.8844C103.126 35.8814 103.582 36.8428 104.248 37.6974C104.878 38.552 105.754 39.2641 106.841 39.7982C107.892 40.3679 109.224 40.6172 110.801 40.6172C112.377 40.6172 113.709 40.3323 114.76 39.7982C115.812 39.2641 116.688 38.552 117.353 37.6974C117.984 36.8428 118.475 35.917 118.755 34.8844C119.036 33.8518 119.176 32.8904 119.176 31.9646V8.25005H125.799V32.1782H125.764Z" fill="white"/> +<path d="M150.854 16.3685C150.153 15.3358 149.207 14.5881 148.051 14.0896C146.859 13.5911 145.633 13.3774 144.336 13.3774C143.565 13.3774 142.83 13.4843 142.094 13.6623C141.358 13.8403 140.727 14.1252 140.166 14.5169C139.571 14.9086 139.115 15.4071 138.765 16.048C138.414 16.6889 138.239 17.4011 138.239 18.2557C138.239 19.5375 138.66 20.5345 139.571 21.1755C140.447 21.852 141.533 22.4573 142.83 22.9202C144.126 23.4187 145.528 23.9172 147.07 24.3801C148.612 24.843 150.013 25.484 151.345 26.3029C152.641 27.1219 153.728 28.2257 154.604 29.5432C155.48 30.8963 155.935 32.7123 155.935 34.9199C155.935 36.9496 155.585 38.7299 154.849 40.2254C154.113 41.7566 153.132 43.0028 151.871 43.9998C150.609 44.9968 149.172 45.7446 147.525 46.2431C145.878 46.7416 144.126 46.9908 142.339 46.9908C140.026 46.9908 137.784 46.5992 135.681 45.8158C133.543 45.0324 131.686 43.715 130.144 41.8634L135.155 36.9496C135.961 38.1958 137.013 39.1572 138.344 39.8694C139.676 40.5815 141.042 40.902 142.514 40.902C143.285 40.902 144.056 40.7952 144.827 40.5815C145.598 40.3679 146.299 40.0474 146.93 39.6201C147.56 39.1928 148.051 38.6587 148.436 37.9822C148.822 37.3412 149.032 36.5579 149.032 35.7033C149.032 34.3146 148.577 33.2464 147.7 32.4986C146.824 31.7509 145.738 31.1099 144.442 30.6114C143.145 30.1129 141.708 29.6144 140.166 29.1515C138.625 28.6886 137.188 28.0477 135.926 27.2643C134.63 26.481 133.543 25.4127 132.667 24.0597C131.791 22.7066 131.336 20.9262 131.336 18.6829C131.336 16.7245 131.721 15.051 132.527 13.6267C133.298 12.2024 134.349 11.0273 135.646 10.0659C136.907 9.14016 138.379 8.42801 140.026 7.96511C141.673 7.50222 143.355 7.28857 145.072 7.28857C147.035 7.28857 148.927 7.60904 150.784 8.17876C152.606 8.78408 154.288 9.78109 155.76 11.1698L150.854 16.3685Z" fill="white"/> +<path d="M173.983 8.25005C175.77 8.25005 177.487 8.42809 179.169 8.78416C180.816 9.14024 182.288 9.74556 183.549 10.5645C184.811 11.4191 185.827 12.5229 186.563 13.9116C187.299 15.3359 187.684 17.0807 187.684 19.1815C187.684 21.5672 187.264 23.49 186.458 24.9499C185.652 26.4098 184.566 27.5493 183.199 28.3326C181.832 29.116 180.255 29.6857 178.433 29.9706C176.611 30.2554 174.754 30.3979 172.791 30.3979H168.061V46.0651H161.438V8.25005H173.983ZM172.091 24.6651C173.037 24.6651 174.018 24.6295 175.034 24.5583C176.05 24.487 176.997 24.2734 177.838 23.9173C178.679 23.5612 179.379 23.0271 179.94 22.315C180.466 21.6028 180.746 20.6058 180.746 19.324C180.746 18.1489 180.501 17.2231 180.01 16.511C179.52 15.7988 178.889 15.2647 178.118 14.9086C177.347 14.517 176.471 14.3033 175.525 14.1965C174.579 14.0897 173.668 14.0185 172.791 14.0185H168.061V24.6651H172.091Z" fill="white"/> +<path d="M200.404 8.25005H206.116L222.166 46.0651H214.596L211.127 37.4125H195.008L191.644 46.0651H184.215L200.404 8.25005ZM208.814 31.6441L203.068 16.2617L197.251 31.6441H208.814Z" fill="white"/> +<path d="M230.225 29.8994L216.243 8.25005H224.548L233.694 23.312L242.945 8.25005H250.83L236.848 29.8994V46.1007H230.225V29.8994Z" fill="white"/> +<path d="M266.826 46.6572V8.06836H271.566V24.5336L270.7 24.0748C271.379 22.3417 272.467 20.9993 273.962 20.0477C275.492 19.0622 277.276 18.5694 279.315 18.5694C281.286 18.5694 283.036 19.0112 284.565 19.8948C286.129 20.7784 287.352 22.0018 288.236 23.5651C289.153 25.1283 289.612 26.8955 289.612 28.8666V46.6572H284.82V30.3959C284.82 28.8666 284.531 27.5752 283.954 26.5217C283.41 25.4682 282.645 24.6526 281.66 24.0748C280.674 23.4631 279.536 23.1573 278.244 23.1573C276.987 23.1573 275.848 23.4631 274.829 24.0748C273.809 24.6526 273.011 25.4852 272.433 26.5727C271.855 27.6262 271.566 28.9006 271.566 30.3959V46.6572H266.826Z" fill="#B1B0B6"/> +<path d="M295.847 57.872C295.235 57.872 294.624 57.821 294.012 57.719C293.4 57.6171 292.822 57.4472 292.279 57.2093V52.9783C292.652 53.0462 293.111 53.1142 293.655 53.1822C294.233 53.2841 294.793 53.3351 295.337 53.3351C296.934 53.3351 298.141 52.9783 298.956 52.2646C299.806 51.5849 300.605 50.3955 301.352 48.6963L303.086 44.5672L302.984 48.6963L291.259 19.1811H296.408L305.532 42.6301H304.003L313.077 19.1811H318.327L305.94 49.9197C305.362 51.381 304.615 52.7064 303.697 53.8958C302.814 55.1193 301.726 56.0878 300.435 56.8015C299.143 57.5151 297.614 57.872 295.847 57.872Z" fill="#B1B0B6"/> +<path d="M321.016 56.8525V19.1811H325.654V25.0944L325.043 23.9219C326.062 22.2907 327.456 20.9993 329.223 20.0477C330.99 19.0622 333.012 18.5694 335.289 18.5694C337.872 18.5694 340.183 19.1981 342.222 20.4555C344.295 21.713 345.926 23.4291 347.115 25.6041C348.305 27.7451 348.899 30.192 348.899 32.9447C348.899 35.6294 348.305 38.0593 347.115 40.2343C345.926 42.4092 344.295 44.1254 342.222 45.3828C340.183 46.6402 337.855 47.269 335.238 47.269C333.029 47.269 331.007 46.7762 329.172 45.7906C327.371 44.8051 325.977 43.4118 324.992 41.6106L325.756 40.795V56.8525H321.016ZM334.881 42.6811C336.614 42.6811 338.161 42.2563 339.52 41.4067C340.879 40.5571 341.933 39.4016 342.68 37.9403C343.462 36.445 343.853 34.7798 343.853 32.9447C343.853 31.0416 343.462 29.3764 342.68 27.949C341.933 26.4877 340.879 25.3323 339.52 24.4827C338.161 23.5991 336.614 23.1573 334.881 23.1573C333.148 23.1573 331.585 23.5821 330.191 24.4317C328.832 25.2813 327.744 26.4537 326.929 27.949C326.147 29.4103 325.756 31.0756 325.756 32.9447C325.756 34.7798 326.147 36.445 326.929 37.9403C327.744 39.4016 328.832 40.5571 330.191 41.4067C331.585 42.2563 333.148 42.6811 334.881 42.6811Z" fill="#B1B0B6"/> +<path d="M366.229 47.269C363.578 47.269 361.216 46.6402 359.143 45.3828C357.07 44.1254 355.439 42.4092 354.249 40.2343C353.06 38.0253 352.465 35.5614 352.465 32.8427C352.465 30.09 353.043 27.6432 354.198 25.5022C355.388 23.3612 356.985 21.679 358.99 20.4555C361.029 19.1981 363.306 18.5694 365.821 18.5694C367.86 18.5694 369.661 18.9433 371.224 19.6909C372.821 20.4046 374.164 21.3901 375.251 22.6475C376.373 23.8709 377.222 25.2813 377.8 26.8785C378.412 28.4418 378.718 30.073 378.718 31.7722C378.718 32.1461 378.684 32.5709 378.616 33.0466C378.582 33.4884 378.531 33.9132 378.463 34.321H355.931V30.2429H375.71L373.467 32.0781C373.773 30.3109 373.603 28.7307 372.957 27.3373C372.312 25.944 371.36 24.8395 370.103 24.0239C368.845 23.2082 367.418 22.8004 365.821 22.8004C364.223 22.8004 362.762 23.2082 361.437 24.0239C360.111 24.8395 359.075 26.0119 358.327 27.5412C357.614 29.0365 357.325 30.8207 357.461 32.8937C357.325 34.8988 357.631 36.6659 358.378 38.1952C359.16 39.6905 360.247 40.863 361.641 41.7126C363.068 42.5282 364.614 42.936 366.28 42.936C368.115 42.936 369.661 42.5112 370.918 41.6616C372.176 40.812 373.195 39.7245 373.977 38.3991L377.953 40.4382C377.409 41.6956 376.56 42.851 375.404 43.9045C374.283 44.924 372.94 45.7397 371.377 46.3514C369.848 46.9631 368.132 47.269 366.229 47.269Z" fill="#B1B0B6"/> +<path d="M383.37 46.6572V19.1811H388.008V24.2278L387.499 23.5141C388.144 21.9508 389.13 20.7954 390.455 20.0477C391.781 19.2661 393.395 18.8753 395.298 18.8753H396.98V23.3612H394.584C392.647 23.3612 391.084 23.9729 389.895 25.1963C388.705 26.3858 388.11 28.085 388.11 30.2939V46.6572H383.37Z" fill="#B1B0B6"/> +<path d="M409.5 47.269C406.748 47.269 404.352 46.5893 402.313 45.2299C400.274 43.8705 398.829 42.0354 397.98 39.7245L401.752 37.8894C402.534 39.5206 403.604 40.812 404.964 41.7635C406.323 42.7151 407.835 43.1909 409.5 43.1909C410.996 43.1909 412.236 42.834 413.222 42.1204C414.207 41.4067 414.7 40.4721 414.7 39.3167C414.7 38.5011 414.462 37.8554 413.986 37.3796C413.545 36.8698 413.001 36.479 412.355 36.2071C411.709 35.9013 411.115 35.6804 410.571 35.5445L406.442 34.372C403.961 33.6583 402.143 32.6388 400.987 31.3134C399.866 29.9881 399.305 28.4418 399.305 26.6746C399.305 25.0434 399.713 23.633 400.529 22.4436C401.378 21.2202 402.517 20.2686 403.944 19.5889C405.405 18.9093 407.037 18.5694 408.838 18.5694C411.251 18.5694 413.409 19.1811 415.312 20.4046C417.249 21.628 418.625 23.3442 419.441 25.5531L415.567 27.3373C414.955 25.91 414.037 24.7885 412.814 23.9729C411.59 23.1233 410.214 22.6985 408.685 22.6985C407.291 22.6985 406.187 23.0553 405.371 23.769C404.556 24.4487 404.148 25.3153 404.148 26.3688C404.148 27.1504 404.352 27.7961 404.76 28.3059C405.167 28.7816 405.66 29.1555 406.238 29.4273C406.816 29.6652 407.376 29.8691 407.92 30.039L412.406 31.3644C414.649 32.0101 416.382 33.0126 417.606 34.372C418.863 35.7314 419.492 37.3626 419.492 39.2657C419.492 40.795 419.067 42.1713 418.217 43.3948C417.368 44.6182 416.195 45.5697 414.7 46.2494C413.205 46.9291 411.472 47.269 409.5 47.269Z" fill="#B1B0B6"/> +<path d="M429.992 46.6572L420.561 19.1811H425.812L433.305 42.1713L431.47 42.1204L438.81 19.1811H443.296L450.637 42.1204L448.802 42.1713L456.346 19.1811H461.546L452.115 46.6572H447.578L440.34 23.718H441.767L434.528 46.6572H429.992Z" fill="#B1B0B6"/> +<path d="M464.256 46.6572V19.1811H468.997V46.6572H464.256ZM464.256 14.7972V8.68007H468.997V14.7972H464.256Z" fill="#B1B0B6"/> +<path d="M485.988 46.9631C483.303 46.9631 481.23 46.1985 479.769 44.6692C478.341 43.1399 477.628 40.9819 477.628 38.1952V23.718H472.632V19.1811H473.651C474.875 19.1811 475.843 18.8073 476.557 18.0597C477.271 17.312 477.628 16.3265 477.628 15.1031V12.8601H482.368V19.1811H488.536V23.718H482.368V38.0423C482.368 38.9599 482.504 39.7585 482.776 40.4382C483.082 41.1178 483.575 41.6616 484.254 42.0694C484.934 42.4432 485.835 42.6301 486.956 42.6301C487.194 42.6301 487.483 42.6131 487.823 42.5792C488.197 42.5452 488.536 42.5112 488.842 42.4772V46.6572C488.401 46.7592 487.908 46.8272 487.364 46.8611C486.82 46.9291 486.361 46.9631 485.988 46.9631Z" fill="#B1B0B6"/> +<path d="M505.503 47.269C502.818 47.269 500.422 46.6402 498.315 45.3828C496.242 44.1254 494.611 42.4092 493.422 40.2343C492.232 38.0593 491.638 35.6124 491.638 32.8937C491.638 30.141 492.232 27.6941 493.422 25.5531C494.611 23.4122 496.242 21.713 498.315 20.4555C500.422 19.1981 502.818 18.5694 505.503 18.5694C507.304 18.5694 508.986 18.8923 510.55 19.538C512.113 20.1837 513.489 21.0503 514.679 22.1378C515.868 23.2252 516.735 24.4996 517.279 25.961L513.048 28C512.402 26.5727 511.416 25.4172 510.091 24.5336C508.766 23.6161 507.236 23.1573 505.503 23.1573C503.838 23.1573 502.326 23.5821 500.966 24.4317C499.641 25.2813 498.587 26.4367 497.806 27.898C497.024 29.3594 496.633 31.0416 496.633 32.9447C496.633 34.7798 497.024 36.445 497.806 37.9403C498.587 39.4016 499.641 40.5571 500.966 41.4067C502.326 42.2563 503.838 42.6811 505.503 42.6811C507.236 42.6811 508.766 42.2393 510.091 41.3557C511.416 40.4382 512.402 39.2317 513.048 37.7364L517.279 39.8774C516.735 41.3048 515.868 42.5792 514.679 43.7006C513.489 44.7881 512.113 45.6547 510.55 46.3004C508.986 46.9461 507.304 47.269 505.503 47.269Z" fill="#B1B0B6"/> +<path d="M521.945 46.6572V8.06836H526.686V24.5336L525.819 24.0748C526.499 22.3417 527.586 20.9993 529.082 20.0477C530.611 19.0622 532.395 18.5694 534.434 18.5694C536.405 18.5694 538.155 19.0112 539.685 19.8948C541.248 20.7784 542.471 22.0018 543.355 23.5651C544.272 25.1283 544.731 26.8955 544.731 28.8666V46.6572H539.939V30.3959C539.939 28.8666 539.651 27.5752 539.073 26.5217C538.529 25.4682 537.764 24.6526 536.779 24.0748C535.793 23.4631 534.655 23.1573 533.363 23.1573C532.106 23.1573 530.968 23.4631 529.948 24.0748C528.929 24.6526 528.13 25.4852 527.552 26.5727C526.975 27.6262 526.686 28.9006 526.686 30.3959V46.6572H521.945Z" fill="#B1B0B6"/> </svg> diff --git a/api-reference-v2/logo/light.svg b/api-reference-v2/logo/light.svg index c951a909dd4..66b2c279d06 100644 --- a/api-reference-v2/logo/light.svg +++ b/api-reference-v2/logo/light.svg @@ -1,29 +1,21 @@ -<svg width="766" height="100" viewBox="0 0 766 100" fill="none" xmlns="http://www.w3.org/2000/svg"> -<g clip-path="url(#clip0_1969_1952)"> -<path d="M370.801 53.4399C370.801 70.0799 360.581 79.9999 346.441 79.9999C338.621 79.9999 331.811 76.7899 328.701 71.4799V99.0399H317.771V27.6899H327.791L328.691 35.5099C331.801 30.1999 338.411 26.6899 346.431 26.6899C360.061 26.6899 370.791 36.2099 370.791 53.4499L370.801 53.4399ZM359.471 53.4399C359.471 42.9199 353.261 36.3999 344.231 36.3999C335.611 36.2999 329.001 42.9099 329.001 53.5399C329.001 64.1699 335.621 70.2799 344.231 70.2799C352.841 70.2799 359.471 63.9699 359.471 53.4399Z" fill="#242628"/> -<path d="M428.931 56.3498H389.641C389.841 65.9698 396.151 70.9798 404.171 70.9798C410.181 70.9798 415.201 68.1698 417.301 62.5598H428.431C425.721 72.9798 416.501 79.9998 403.971 79.9998C388.631 79.9998 378.511 69.3798 378.511 53.2398C378.511 37.0998 388.631 26.5798 403.871 26.5798C419.111 26.5798 428.931 36.7998 428.931 52.2398V56.3498ZM389.741 48.7298H417.801C417.201 39.8098 411.291 35.2998 403.871 35.2998C396.451 35.2998 390.541 39.8098 389.741 48.7298Z" fill="#242628"/> -<path d="M448.281 27.6899C443.181 27.6899 439.051 31.8199 439.051 36.9199V79.0099H450.081V51.6499V39.8199C450.081 38.5499 451.111 37.5099 452.391 37.5099H469.231V27.6899H448.291H448.281Z" fill="#242628"/> -<path d="M300.14 27.5898L286.01 70.1898L270.77 27.6898H258.94L278.48 78.3098C279.08 79.9098 279.38 81.2198 279.38 82.5198C279.38 83.2298 279.31 83.8798 279.19 84.4798L279.16 84.5898C279.09 84.9098 279.01 85.2098 278.91 85.4998L278.17 88.2098C277.99 88.8798 277.38 89.3398 276.69 89.3398H261.14V99.0598H272.47C280.09 99.0598 286.4 97.2598 290.01 87.2298L311.56 27.6898L300.13 27.5898H300.14Z" fill="#242628"/> -<path d="M206.82 78.9999H217.74V51.3399C217.74 42.7199 222.45 36.7099 231.17 36.7099C238.79 36.6099 243.5 41.1199 243.5 51.0399V78.9999H254.43V49.3299C254.43 31.7899 243.71 26.5799 233.98 26.5799C226.56 26.5799 220.75 29.4899 217.74 34.2999V6.63989H206.82V78.9999Z" fill="#242628"/> -<path d="M483.66 63.4699C483.76 68.7799 488.67 71.8899 495.39 71.8899C502.11 71.8899 506.11 69.3799 506.11 64.8699C506.11 60.9599 504.11 58.8599 498.29 57.9499L487.97 56.1499C477.95 54.4499 474.04 49.2299 474.04 41.9199C474.04 32.6999 483.16 26.6899 494.79 26.6899C507.32 26.6899 516.44 32.6999 516.54 42.9299H505.72C505.62 37.7199 501.11 34.8099 494.8 34.8099C488.49 34.8099 484.98 37.3199 484.98 41.5299C484.98 45.2399 487.59 46.9399 493.3 47.9399L503.42 49.7399C512.94 51.4399 517.35 56.1499 517.35 63.8699C517.35 74.4899 507.53 80.0099 495.6 80.0099C482.07 80.0099 472.95 73.4999 472.75 63.4699H483.68H483.66Z" fill="#242628"/> -<path d="M542.19 66.9799L553.82 27.6899H565.25L576.68 66.9799L586.4 27.6899H597.93L583.4 79.0099H571.07L559.44 39.9199L547.71 79.0099H535.28L520.65 27.6899H532.18L542.2 66.9799H542.19Z" fill="#242628"/> -<path d="M604.34 6.63989H616.47V18.0699H604.34V6.63989ZM604.94 27.6899H615.86V79.0099H604.94V27.6899Z" fill="#242628"/> -<path d="M685.32 36.1099C676.8 36.1099 670.99 42.3199 670.99 53.2499C670.99 64.7799 677 70.3899 685.02 70.3899C691.43 70.3899 696.15 66.7799 698.25 59.9699H709.88C707.27 72.3999 697.85 80.0199 685.22 80.0199C669.99 80.0199 659.76 69.3998 659.76 53.2599C659.76 37.1199 669.98 26.5999 685.32 26.5999C697.85 26.5999 707.17 33.7199 709.88 46.1399H698.05C696.25 39.7299 691.33 36.1199 685.32 36.1199V36.1099Z" fill="#242628"/> -<path d="M642.87 69.2799C642.23 69.2799 641.72 68.7599 641.72 68.1299V37.41H653.65V27.69H641.72V13.95H630.8V22.87C630.8 26.08 629.8 27.68 626.59 27.68H622.18V37.4H630.8V65.0599C630.8 73.9799 635.71 78.99 644.63 78.99H653.55V69.2699H642.88L642.87 69.2799Z" fill="#242628"/> -<path d="M745.22 26.5799C737.8 26.5799 731.99 29.4899 728.98 34.2999V6.63989H718.06V78.9999H728.98V51.3399C728.98 42.7199 733.69 36.7099 742.41 36.7099C750.03 36.6099 754.74 41.1199 754.74 51.0399V78.9999H765.67V49.3299C765.67 31.7899 754.95 26.5799 745.22 26.5799Z" fill="#242628"/> -<g clip-path="url(#clip1_1969_1952)"> -<path d="M135.792 0H42.875C19.1958 0 0 19.1958 0 42.875C0 66.5542 19.1958 85.75 42.875 85.75H135.792C159.471 85.75 178.667 66.5542 178.667 42.875C178.667 19.1958 159.471 0 135.792 0Z" fill="#006DF9"/> -<path d="M140.261 56.4367C147.751 56.4367 153.822 50.3649 153.822 42.8751C153.822 35.3852 147.751 29.3135 140.261 29.3135C132.771 29.3135 126.699 35.3852 126.699 42.8751C126.699 50.3649 132.771 56.4367 140.261 56.4367Z" fill="white"/> -<path d="M53.2718 53.4511L39.0877 31.4253C38.7683 30.9299 38.0448 30.9299 37.7254 31.4253L23.5413 53.4511C23.1925 53.9888 23.5804 54.6993 24.2224 54.6993H52.5907C53.2327 54.6993 53.6206 53.9888 53.2718 53.4511Z" fill="white"/> -<path d="M100.55 30.353H78.1172C77.3972 30.353 76.8135 30.9367 76.8135 31.6567V54.0899C76.8135 54.8099 77.3972 55.3936 78.1172 55.3936H100.55C101.27 55.3936 101.854 54.8099 101.854 54.0899V31.6567C101.854 30.9367 101.27 30.353 100.55 30.353Z" fill="white"/> -</g> -</g> -<defs> -<clipPath id="clip0_1969_1952"> -<rect width="765.66" height="99.05" fill="white"/> -</clipPath> -<clipPath id="clip1_1969_1952"> -<rect width="178.667" height="85.75" fill="white"/> -</clipPath> -</defs> +<svg width="545" height="58" viewBox="0 0 545 58" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M27.0673 54.3079C25.7664 54.3441 24.5016 54.2355 23.2006 54.0545C19.6953 53.5477 16.4068 52.4255 13.3713 50.5792C6.6497 46.5246 2.34935 40.6238 0.578616 32.8766C0.181104 31.139 0.000416954 29.3651 0.000416954 27.5912C-0.0357205 20.4957 2.27707 14.2691 6.97494 8.98363C11.0585 4.42224 16.1177 1.63472 22.0804 0.476271C23.7427 0.150457 25.405 -0.0305508 27.0673 0.0418522C27.0673 2.75697 27.0673 5.43588 27.0673 8.15099C26.9951 8.18719 26.9228 8.2234 26.8505 8.2958C25.8748 8.98363 24.8991 9.70766 23.9595 10.4679C21.8274 12.2056 19.8037 14.0518 18.1053 16.2601C15.8286 19.1925 14.3108 22.4144 14.094 26.2156C13.9856 28.0256 14.2024 29.7995 14.7806 31.501C16.19 35.7366 20.5626 40.1169 26.706 40.2255C27.0673 40.2255 27.1396 40.298 27.1396 40.6962C27.1035 42.5424 27.1035 46.235 27.1035 46.235C27.1035 46.235 27.1035 46.4522 27.1035 46.5608C27.0673 49.1311 27.0673 51.7014 27.0673 54.3079Z" fill="#0099FF"/> +<path fill-rule="evenodd" clip-rule="evenodd" d="M27.0666 8.11469C27.0666 8.11469 27.0666 2.72066 27.0666 0.00554404C28.5483 -0.0306575 29.9938 0.114149 31.4393 0.331358C34.1496 0.765776 36.7515 1.56221 39.2088 2.82926C44.3042 5.47197 48.3154 9.23693 51.0257 14.3775C52.5796 17.3461 53.5915 20.4956 53.989 23.7899C54.4588 27.6635 54.0974 31.5009 52.941 35.2296C51.6039 39.4652 49.3634 43.194 46.2195 46.3435C42.3889 50.1447 37.8356 52.6064 32.5595 53.7286C30.7526 54.0906 28.9096 54.3078 27.0666 54.2716C27.0666 51.6651 27.0666 49.0948 27.0666 46.4883C27.0666 46.3797 27.0666 46.1987 27.0666 46.1987C27.0666 46.1987 27.175 46.1263 27.2112 46.0901C30.0299 44.099 32.7041 41.9269 35.0169 39.3204C36.5346 37.6189 37.8356 35.8088 38.739 33.7092C40.0038 30.7406 40.5097 27.6997 39.8593 24.4778C38.7029 18.6131 33.463 14.2327 27.428 14.0879C27.0305 14.0879 27.0666 13.7621 27.0666 13.7621V8.11469Z" fill="#0561E2"/> +<path d="M89.0807 35.5966C89.0807 37.0921 88.8354 38.5164 88.3798 39.9051C87.9243 41.2937 87.1884 42.5044 86.2773 43.5726C85.3311 44.6408 84.1748 45.4598 82.7731 46.1007C81.3714 46.7061 79.7244 47.0265 77.9022 47.0265C74.9586 47.0265 72.5407 46.3144 70.6835 44.9257C68.7912 43.537 67.5647 41.3293 66.969 38.3027L73.1715 36.8072C73.3817 38.0535 73.8723 39.0505 74.6783 39.7982C75.4492 40.546 76.4304 40.9021 77.5868 40.9021C79.4791 40.9021 80.7757 40.2611 81.4415 38.9437C82.1073 37.6618 82.4577 35.8458 82.4577 33.5669V8.25005H89.0807V35.5966Z" fill="#1C1C1C"/> +<path d="M125.593 32.1782C125.593 34.4571 125.208 36.5223 124.437 38.3383C123.666 40.1899 122.615 41.721 121.283 43.0029C119.952 44.2848 118.375 45.2818 116.553 45.9583C114.73 46.6705 112.733 46.9909 110.595 46.9909C108.458 46.9909 106.46 46.6349 104.673 45.9583C102.851 45.2818 101.274 44.2848 99.9075 43.0029C98.5408 41.721 97.4895 40.1543 96.7536 38.3383C95.9827 36.5223 95.6323 34.4571 95.6323 32.1782V8.25005H102.255V31.9646C102.255 32.8904 102.395 33.8518 102.676 34.8844C102.956 35.8814 103.412 36.8428 104.077 37.6974C104.708 38.552 105.584 39.2641 106.671 39.7982C107.722 40.3679 109.053 40.6172 110.63 40.6172C112.207 40.6172 113.539 40.3323 114.59 39.7982C115.641 39.2641 116.518 38.552 117.183 37.6974C117.814 36.8428 118.305 35.917 118.585 34.8844C118.865 33.8518 119.006 32.8904 119.006 31.9646V8.25005H125.629V32.1782H125.593Z" fill="#1C1C1C"/> +<path d="M150.684 16.3685C149.983 15.3358 149.037 14.5881 147.881 14.0896C146.689 13.5911 145.463 13.3774 144.166 13.3774C143.395 13.3774 142.659 13.4843 141.924 13.6623C141.188 13.8403 140.557 14.1252 139.996 14.5169C139.4 14.9086 138.945 15.4071 138.595 16.048C138.244 16.6889 138.069 17.4011 138.069 18.2557C138.069 19.5375 138.489 20.5345 139.4 21.1755C140.277 21.852 141.363 22.4573 142.659 22.9202C143.956 23.4187 145.358 23.9172 146.9 24.3801C148.441 24.843 149.843 25.484 151.175 26.3029C152.471 27.1219 153.558 28.2257 154.434 29.5432C155.31 30.8963 155.765 32.7123 155.765 34.9199C155.765 36.9496 155.415 38.7299 154.679 40.2254C153.943 41.7566 152.962 43.0028 151.7 43.9998C150.439 44.9968 149.002 45.7446 147.355 46.2431C145.708 46.7416 143.956 46.9908 142.169 46.9908C139.856 46.9908 137.613 46.5992 135.511 45.8158C133.373 45.0324 131.516 43.715 129.974 41.8634L134.985 36.9496C135.791 38.1958 136.842 39.1572 138.174 39.8694C139.506 40.5815 140.872 40.902 142.344 40.902C143.115 40.902 143.886 40.7952 144.657 40.5815C145.428 40.3679 146.129 40.0474 146.759 39.6201C147.39 39.1928 147.881 38.6587 148.266 37.9822C148.652 37.3412 148.862 36.5579 148.862 35.7033C148.862 34.3146 148.406 33.2464 147.53 32.4986C146.654 31.7509 145.568 31.1099 144.271 30.6114C142.975 30.1129 141.538 29.6144 139.996 29.1515C138.454 28.6886 137.018 28.0477 135.756 27.2643C134.46 26.481 133.373 25.4127 132.497 24.0597C131.621 22.7066 131.166 20.9262 131.166 18.6829C131.166 16.7245 131.551 15.051 132.357 13.6267C133.128 12.2024 134.179 11.0273 135.476 10.0659C136.737 9.14016 138.209 8.42801 139.856 7.96511C141.503 7.50222 143.185 7.28857 144.902 7.28857C146.865 7.28857 148.757 7.60904 150.614 8.17876C152.436 8.78408 154.118 9.78109 155.59 11.1698L150.684 16.3685Z" fill="#1C1C1C"/> +<path d="M173.813 8.25005C175.6 8.25005 177.317 8.42809 178.999 8.78416C180.646 9.14024 182.118 9.74556 183.379 10.5645C184.641 11.4191 185.657 12.5229 186.393 13.9116C187.129 15.3359 187.514 17.0807 187.514 19.1815C187.514 21.5672 187.094 23.49 186.288 24.9499C185.482 26.4098 184.396 27.5493 183.029 28.3326C181.662 29.116 180.085 29.6857 178.263 29.9706C176.441 30.2554 174.584 30.3979 172.621 30.3979H167.891V46.0651H161.268V8.25005H173.813ZM171.92 24.6651C172.867 24.6651 173.848 24.6295 174.864 24.5583C175.88 24.487 176.826 24.2734 177.667 23.9173C178.508 23.5612 179.209 23.0271 179.77 22.315C180.296 21.6028 180.576 20.6058 180.576 19.324C180.576 18.1489 180.331 17.2231 179.84 16.511C179.349 15.7988 178.719 15.2647 177.948 14.9086C177.177 14.517 176.301 14.3033 175.355 14.1965C174.408 14.0897 173.497 14.0185 172.621 14.0185H167.891V24.6651H171.92Z" fill="#1C1C1C"/> +<path d="M200.234 8.25005H205.946L221.995 46.0651H214.426L210.957 37.4125H194.838L191.474 46.0651H184.045L200.234 8.25005ZM208.644 31.6441L202.897 16.2617L197.08 31.6441H208.644Z" fill="#1C1C1C"/> +<path d="M230.055 29.8994L216.073 8.25005H224.378L233.524 23.312L242.775 8.25005H250.66L236.678 29.8994V46.1007H230.055V29.8994Z" fill="#1C1C1C"/> +<path d="M266.655 46.6572V8.06836H271.396V24.5336L270.53 24.0748C271.209 22.3417 272.297 20.9993 273.792 20.0477C275.321 19.0622 277.106 18.5694 279.145 18.5694C281.116 18.5694 282.866 19.0112 284.395 19.8948C285.958 20.7784 287.182 22.0018 288.065 23.5651C288.983 25.1283 289.442 26.8955 289.442 28.8666V46.6572H284.65V30.3959C284.65 28.8666 284.361 27.5752 283.783 26.5217C283.24 25.4682 282.475 24.6526 281.489 24.0748C280.504 23.4631 279.365 23.1573 278.074 23.1573C276.817 23.1573 275.678 23.4631 274.659 24.0748C273.639 24.6526 272.841 25.4852 272.263 26.5727C271.685 27.6262 271.396 28.9006 271.396 30.3959V46.6572H266.655Z" fill="#7D7B86"/> +<path d="M295.677 57.872C295.065 57.872 294.453 57.821 293.842 57.719C293.23 57.6171 292.652 57.4472 292.108 57.2093V52.9783C292.482 53.0462 292.941 53.1142 293.485 53.1822C294.063 53.2841 294.623 53.3351 295.167 53.3351C296.764 53.3351 297.971 52.9783 298.786 52.2646C299.636 51.5849 300.435 50.3955 301.182 48.6963L302.915 44.5672L302.813 48.6963L291.089 19.1811H296.237L305.362 42.6301H303.833L312.907 19.1811H318.157L305.77 49.9197C305.192 51.381 304.445 52.7064 303.527 53.8958C302.643 55.1193 301.556 56.0878 300.265 56.8015C298.973 57.5151 297.444 57.872 295.677 57.872Z" fill="#7D7B86"/> +<path d="M320.845 56.8525V19.1811H325.484V25.0944L324.873 23.9219C325.892 22.2907 327.285 20.9993 329.053 20.0477C330.82 19.0622 332.842 18.5694 335.119 18.5694C337.701 18.5694 340.012 19.1981 342.051 20.4555C344.124 21.713 345.756 23.4291 346.945 25.6041C348.135 27.7451 348.729 30.192 348.729 32.9447C348.729 35.6294 348.135 38.0593 346.945 40.2343C345.756 42.4092 344.124 44.1254 342.051 45.3828C340.012 46.6402 337.684 47.269 335.068 47.269C332.859 47.269 330.837 46.7762 329.002 45.7906C327.2 44.8051 325.807 43.4118 324.822 41.6106L325.586 40.795V56.8525H320.845ZM334.711 42.6811C336.444 42.6811 337.99 42.2563 339.35 41.4067C340.709 40.5571 341.763 39.4016 342.51 37.9403C343.292 36.445 343.683 34.7798 343.683 32.9447C343.683 31.0416 343.292 29.3764 342.51 27.949C341.763 26.4877 340.709 25.3323 339.35 24.4827C337.99 23.5991 336.444 23.1573 334.711 23.1573C332.978 23.1573 331.414 23.5821 330.021 24.4317C328.662 25.2813 327.574 26.4537 326.759 27.949C325.977 29.4103 325.586 31.0756 325.586 32.9447C325.586 34.7798 325.977 36.445 326.759 37.9403C327.574 39.4016 328.662 40.5571 330.021 41.4067C331.414 42.2563 332.978 42.6811 334.711 42.6811Z" fill="#7D7B86"/> +<path d="M366.058 47.269C363.408 47.269 361.046 46.6402 358.973 45.3828C356.9 44.1254 355.268 42.4092 354.079 40.2343C352.89 38.0253 352.295 35.5614 352.295 32.8427C352.295 30.09 352.873 27.6432 354.028 25.5022C355.217 23.3612 356.815 21.679 358.82 20.4555C360.859 19.1981 363.136 18.5694 365.651 18.5694C367.69 18.5694 369.491 18.9433 371.054 19.6909C372.651 20.4046 373.994 21.3901 375.081 22.6475C376.203 23.8709 377.052 25.2813 377.63 26.8785C378.242 28.4418 378.548 30.073 378.548 31.7722C378.548 32.1461 378.514 32.5709 378.446 33.0466C378.412 33.4884 378.361 33.9132 378.293 34.321H355.761V30.2429H375.54L373.297 32.0781C373.603 30.3109 373.433 28.7307 372.787 27.3373C372.142 25.944 371.19 24.8395 369.933 24.0239C368.675 23.2082 367.248 22.8004 365.651 22.8004C364.053 22.8004 362.592 23.2082 361.267 24.0239C359.941 24.8395 358.905 26.0119 358.157 27.5412C357.443 29.0365 357.155 30.8207 357.29 32.8937C357.155 34.8988 357.46 36.6659 358.208 38.1952C358.99 39.6905 360.077 40.863 361.471 41.7126C362.898 42.5282 364.444 42.936 366.109 42.936C367.944 42.936 369.491 42.5112 370.748 41.6616C372.006 40.812 373.025 39.7245 373.807 38.3991L377.783 40.4382C377.239 41.6956 376.39 42.851 375.234 43.9045C374.113 44.924 372.77 45.7397 371.207 46.3514C369.678 46.9631 367.961 47.269 366.058 47.269Z" fill="#7D7B86"/> +<path d="M383.199 46.6572V19.1811H387.838V24.2278L387.329 23.5141C387.974 21.9508 388.96 20.7954 390.285 20.0477C391.611 19.2661 393.225 18.8753 395.128 18.8753H396.81V23.3612H394.414C392.477 23.3612 390.914 23.9729 389.724 25.1963C388.535 26.3858 387.94 28.085 387.94 30.2939V46.6572H383.199Z" fill="#7D7B86"/> +<path d="M409.33 47.269C406.578 47.269 404.182 46.5893 402.143 45.2299C400.104 43.8705 398.659 42.0354 397.81 39.7245L401.582 37.8894C402.364 39.5206 403.434 40.812 404.793 41.7635C406.153 42.7151 407.665 43.1909 409.33 43.1909C410.826 43.1909 412.066 42.834 413.052 42.1204C414.037 41.4067 414.53 40.4721 414.53 39.3167C414.53 38.5011 414.292 37.8554 413.816 37.3796C413.374 36.8698 412.831 36.479 412.185 36.2071C411.539 35.9013 410.945 35.6804 410.401 35.5445L406.272 34.372C403.791 33.6583 401.973 32.6388 400.817 31.3134C399.696 29.9881 399.135 28.4418 399.135 26.6746C399.135 25.0434 399.543 23.633 400.358 22.4436C401.208 21.2202 402.347 20.2686 403.774 19.5889C405.235 18.9093 406.866 18.5694 408.668 18.5694C411.08 18.5694 413.238 19.1811 415.142 20.4046C417.079 21.628 418.455 23.3442 419.271 25.5531L415.396 27.3373C414.785 25.91 413.867 24.7885 412.644 23.9729C411.42 23.1233 410.044 22.6985 408.515 22.6985C407.121 22.6985 406.017 23.0553 405.201 23.769C404.386 24.4487 403.978 25.3153 403.978 26.3688C403.978 27.1504 404.182 27.7961 404.59 28.3059C404.997 28.7816 405.49 29.1555 406.068 29.4273C406.646 29.6652 407.206 29.8691 407.75 30.039L412.236 31.3644C414.479 32.0101 416.212 33.0126 417.435 34.372C418.693 35.7314 419.322 37.3626 419.322 39.2657C419.322 40.795 418.897 42.1713 418.047 43.3948C417.198 44.6182 416.025 45.5697 414.53 46.2494C413.035 46.9291 411.301 47.269 409.33 47.269Z" fill="#7D7B86"/> +<path d="M429.821 46.6572L420.391 19.1811H425.641L433.135 42.1713L431.3 42.1204L438.64 19.1811H443.126L450.467 42.1204L448.632 42.1713L456.176 19.1811H461.376L451.945 46.6572H447.408L440.17 23.718H441.597L434.358 46.6572H429.821Z" fill="#7D7B86"/> +<path d="M464.086 46.6572V19.1811H468.827V46.6572H464.086ZM464.086 14.7972V8.68007H468.827V14.7972H464.086Z" fill="#7D7B86"/> +<path d="M485.817 46.9631C483.133 46.9631 481.06 46.1985 479.598 44.6692C478.171 43.1399 477.457 40.9819 477.457 38.1952V23.718H472.462V19.1811H473.481C474.705 19.1811 475.673 18.8073 476.387 18.0597C477.101 17.312 477.457 16.3265 477.457 15.1031V12.8601H482.198V19.1811H488.366V23.718H482.198V38.0423C482.198 38.9599 482.334 39.7585 482.606 40.4382C482.912 41.1178 483.405 41.6616 484.084 42.0694C484.764 42.4432 485.665 42.6301 486.786 42.6301C487.024 42.6301 487.313 42.6131 487.653 42.5792C488.026 42.5452 488.366 42.5112 488.672 42.4772V46.6572C488.23 46.7592 487.738 46.8272 487.194 46.8611C486.65 46.9291 486.191 46.9631 485.817 46.9631Z" fill="#7D7B86"/> +<path d="M505.333 47.269C502.648 47.269 500.252 46.6402 498.145 45.3828C496.072 44.1254 494.441 42.4092 493.252 40.2343C492.062 38.0593 491.467 35.6124 491.467 32.8937C491.467 30.141 492.062 27.6941 493.252 25.5531C494.441 23.4122 496.072 21.713 498.145 20.4555C500.252 19.1981 502.648 18.5694 505.333 18.5694C507.134 18.5694 508.816 18.8923 510.38 19.538C511.943 20.1837 513.319 21.0503 514.509 22.1378C515.698 23.2252 516.565 24.4996 517.108 25.961L512.877 28C512.232 26.5727 511.246 25.4172 509.921 24.5336C508.595 23.6161 507.066 23.1573 505.333 23.1573C503.668 23.1573 502.155 23.5821 500.796 24.4317C499.471 25.2813 498.417 26.4367 497.636 27.898C496.854 29.3594 496.463 31.0416 496.463 32.9447C496.463 34.7798 496.854 36.445 497.636 37.9403C498.417 39.4016 499.471 40.5571 500.796 41.4067C502.155 42.2563 503.668 42.6811 505.333 42.6811C507.066 42.6811 508.595 42.2393 509.921 41.3557C511.246 40.4382 512.232 39.2317 512.877 37.7364L517.108 39.8774C516.565 41.3048 515.698 42.5792 514.509 43.7006C513.319 44.7881 511.943 45.6547 510.38 46.3004C508.816 46.9461 507.134 47.269 505.333 47.269Z" fill="#7D7B86"/> +<path d="M521.775 46.6572V8.06836H526.515V24.5336L525.649 24.0748C526.329 22.3417 527.416 20.9993 528.911 20.0477C530.441 19.0622 532.225 18.5694 534.264 18.5694C536.235 18.5694 537.985 19.0112 539.514 19.8948C541.078 20.7784 542.301 22.0018 543.185 23.5651C544.102 25.1283 544.561 26.8955 544.561 28.8666V46.6572H539.769V30.3959C539.769 28.8666 539.48 27.5752 538.903 26.5217C538.359 25.4682 537.594 24.6526 536.609 24.0748C535.623 23.4631 534.485 23.1573 533.193 23.1573C531.936 23.1573 530.797 23.4631 529.778 24.0748C528.758 24.6526 527.96 25.4852 527.382 26.5727C526.804 27.6262 526.515 28.9006 526.515 30.3959V46.6572H521.775Z" fill="#7D7B86"/> </svg>
2024-12-09T21:10:32Z
## 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 #6782 ## 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
05f737309f7fac9f0985fac2948a57398c286317
juspay/hyperswitch
juspay__hyperswitch-6786
Bug: refactor(dynamic_routing): update the authentication for update config to include JWT type Enable JWT to be used for update config for success based routing route, previously it was only admin api key.
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 7ad5645e75a..fc8668905ca 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -159,7 +159,9 @@ Never share your secret api keys. Keep them guarded and secure. routes::routing::routing_retrieve_linked_config, routes::routing::routing_retrieve_default_config_for_profiles, routes::routing::routing_update_default_config_for_profile, + routes::routing::success_based_routing_update_configs, routes::routing::toggle_success_based_routing, + routes::routing::toggle_elimination_routing, // Routes for blocklist routes::blocklist::remove_entry_from_blocklist, @@ -589,6 +591,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::RoutingKind, api_models::routing::RoutableConnectorChoice, api_models::routing::DynamicRoutingFeatures, + api_models::routing::SuccessBasedRoutingConfig, + api_models::routing::DynamicRoutingConfigParams, + api_models::routing::CurrentBlockThreshold, + api_models::routing::SuccessBasedRoutingConfigBody, api_models::routing::LinkedRoutingConfigRetrieveResponse, api_models::routing::RoutingRetrieveResponse, api_models::routing::ProfileDefaultRoutingConfig, diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index b0fcb75fa49..6b968f80172 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -260,7 +260,7 @@ pub async fn routing_update_default_config_for_profile() {} /// Create a success based dynamic routing algorithm #[utoipa::path( post, - path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/success_based/toggle", + path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/toggle", params( ("account_id" = String, Path, description = "Merchant id"), ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), @@ -280,13 +280,40 @@ pub async fn routing_update_default_config_for_profile() {} )] pub async fn toggle_success_based_routing() {} +#[cfg(feature = "v1")] +/// Routing - Update success based dynamic routing config for profile +/// +/// Update success based dynamic routing algorithm +#[utoipa::path( + patch, + path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/config/{algorithm_id}", + params( + ("account_id" = String, Path, description = "Merchant id"), + ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), + ("algorithm_id" = String, Path, description = "Success based routing algorithm id which was last activated to update the config"), + ), + request_body = DynamicRoutingFeatures, + responses( + (status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord), + (status = 400, description = "Update body is malformed"), + (status = 500, description = "Internal server error"), + (status = 404, description = "Resource missing"), + (status = 422, description = "Unprocessable request"), + (status = 403, description = "Forbidden"), + ), + tag = "Routing", + operation_id = "Update success based dynamic routing configs", + security(("api_key" = []), ("jwt_key" = [])) +)] +pub async fn success_based_routing_update_configs() {} + #[cfg(feature = "v1")] /// Routing - Toggle elimination routing for profile /// /// Create a elimination based dynamic routing algorithm #[utoipa::path( post, - path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/elimination/toggle", + path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/elimination/toggle", params( ("account_id" = String, Path, description = "Merchant id"), ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index 19b96a9dc84..76852bf12ef 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -1071,7 +1071,7 @@ pub async fn success_based_routing_update_configs( flow, state, &req, - routing_payload_wrapper, + routing_payload_wrapper.clone(), |state, _, wrapper: routing_types::SuccessBasedRoutingPayloadWrapper, _| async { Box::pin(routing::success_based_routing_update_configs( state, @@ -1081,7 +1081,14 @@ pub async fn success_based_routing_update_configs( )) .await }, - &auth::AdminApiAuth, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuthProfileFromRoute { + profile_id: routing_payload_wrapper.profile_id, + required_permission: Permission::ProfileRoutingWrite, + }, + req.headers(), + ), api_locking::LockAction::NotApplicable, )) .await
2024-12-10T09:10:55Z
## 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 --> This PR will enable JWT to be used for update config for success based routing route, previously it was only admin api key. ### 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). --> ## 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 will be checked with JWT token. ``` curl --location --request PATCH '{base_url}/account/:account_id/business_profile/:profile_id/dynamic_routing/success_based/config/:routing_config_id' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer token' \ --data '{ "params": [ "Currency", "CardBin", "Country", "PaymentMethod", "PaymentMethodType", "AuthenticationType", "CardNetwork" ] } ' ``` ## 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
886e2aacd7dcd8a04a33884ceafb1562aa7c365f
juspay/hyperswitch
juspay__hyperswitch-6778
Bug: Adding support for Tenant ID in Kafka events apart from Transactional events ( API , Connector, Outgoing ) Need to add tenant-id for kafka events for the domains API events, Connector events and Outgoing Webhook Events
diff --git a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs index 5edd8d68c32..bf9eafe5aaf 100644 --- a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs +++ b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs @@ -9,6 +9,7 @@ use time::OffsetDateTime; /// struct ConnectorEvent #[derive(Debug, Serialize)] pub struct ConnectorEvent { + tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: String, request: String, @@ -31,6 +32,7 @@ impl ConnectorEvent { /// fn new ConnectorEvent #[allow(clippy::too_many_arguments)] pub fn new( + tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: &str, request: serde_json::Value, @@ -45,6 +47,7 @@ impl ConnectorEvent { status_code: u16, ) -> Self { Self { + tenant_id, connector_name, flow: flow .rsplit_once("::") diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index fe844ef6d73..320283701ef 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -99,6 +99,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( .attach_printable("Could not convert webhook effect to string")?; let api_event = ApiEvent::new( + state.tenant.tenant_id.clone(), Some(merchant_account.get_id().clone()), flow, &request_id, diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rs index b91a6f0e9a0..2ec17246a6a 100644 --- a/crates/router/src/core/webhooks/incoming_v2.rs +++ b/crates/router/src/core/webhooks/incoming_v2.rs @@ -91,6 +91,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( .attach_printable("Could not convert webhook effect to string")?; let api_event = ApiEvent::new( + state.tenant.tenant_id.clone(), Some(merchant_account.get_id().clone()), flow, &request_id, diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs index 0a9c17ed3a0..4a1f6cbc9a2 100644 --- a/crates/router/src/core/webhooks/outgoing.rs +++ b/crates/router/src/core/webhooks/outgoing.rs @@ -504,6 +504,7 @@ async fn raise_webhooks_analytics_event( }); let webhook_event = OutgoingWebhookEvent::new( + state.tenant.tenant_id.clone(), merchant_id, event_id, event.event_type, diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs index 76cbcb958c8..419164810c3 100644 --- a/crates/router/src/events/api_logs.rs +++ b/crates/router/src/events/api_logs.rs @@ -24,6 +24,7 @@ use crate::{ #[derive(Clone, Debug, Eq, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub struct ApiEvent { + tenant_id: common_utils::id_type::TenantId, merchant_id: Option<common_utils::id_type::MerchantId>, api_flow: String, created_at_timestamp: i128, @@ -47,6 +48,7 @@ pub struct ApiEvent { impl ApiEvent { #[allow(clippy::too_many_arguments)] pub fn new( + tenant_id: common_utils::id_type::TenantId, merchant_id: Option<common_utils::id_type::MerchantId>, api_flow: &impl FlowMetric, request_id: &RequestId, @@ -62,6 +64,7 @@ impl ApiEvent { http_method: &http::Method, ) -> Self { Self { + tenant_id, merchant_id, api_flow: api_flow.to_string(), created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs index 64126ec76d9..b56c473920d 100644 --- a/crates/router/src/events/outgoing_webhook_logs.rs +++ b/crates/router/src/events/outgoing_webhook_logs.rs @@ -10,6 +10,7 @@ use crate::services::kafka::KafkaMessage; #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "snake_case")] pub struct OutgoingWebhookEvent { + tenant_id: common_utils::id_type::TenantId, merchant_id: common_utils::id_type::MerchantId, event_id: String, event_type: OutgoingWebhookEventType, @@ -147,6 +148,7 @@ impl OutgoingWebhookEventMetric for OutgoingWebhookContent { impl OutgoingWebhookEvent { #[allow(clippy::too_many_arguments)] pub fn new( + tenant_id: common_utils::id_type::TenantId, merchant_id: common_utils::id_type::MerchantId, event_id: String, event_type: OutgoingWebhookEventType, @@ -157,6 +159,7 @@ impl OutgoingWebhookEvent { delivery_attempt: Option<WebhookDeliveryAttempt>, ) -> Self { Self { + tenant_id, merchant_id, event_id, event_type, diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 9416ff175a8..c808b29280b 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -228,6 +228,7 @@ where }) .unwrap_or_default(); let mut connector_event = ConnectorEvent::new( + state.tenant.tenant_id.clone(), req.connector.clone(), std::any::type_name::<T>(), masked_request_body, @@ -851,6 +852,7 @@ where }; let api_event = ApiEvent::new( + tenant_id, Some(merchant_id.clone()), flow, &request_id,
2024-12-09T09:51:37Z
## 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 --> The changes are required for pushing tenant ID for API events, Connector events and Outgoing Webhook events ### 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)? --> Attaching screenshots <img width="917" alt="Screenshot 2024-12-09 at 3 20 34 PM" src="https://github.com/user-attachments/assets/b8918318-68b5-426c-aad3-9eed76cd5150"> <img width="925" alt="Screenshot 2024-12-09 at 3 20 08 PM" src="https://github.com/user-attachments/assets/b21c5b4b-359b-4d35-a875-c33154c06e66"> <img width="910" alt="Screenshot 2024-12-09 at 3 20 21 PM" src="https://github.com/user-attachments/assets/771b9b0d-c073-49c6-b711-0c5fa24df49e"> ## 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
05f737309f7fac9f0985fac2948a57398c286317
juspay/hyperswitch
juspay__hyperswitch-6775
Bug: feat(analytics): add support for multiple emails as input to forward reports Currently, while generating reports on the dashboard, the current setup only supports forwarding reports to the email of the account signed in. Should add support to have custom emails in the input text box on the dashboard while generating and forwarding the report, to make the reporting module slightly flexible and convenient.
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 806eb4b6e0e..7f58c6b00d7 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -114,6 +114,7 @@ pub struct RefundDistributionBody { #[serde(rename_all = "camelCase")] pub struct ReportRequest { pub time_range: TimeRange, + pub emails: Option<Vec<Secret<String, EmailStrategy>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
2024-12-09T07:26:15Z
## 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 --> Currently, while generating reports on the dashboard, the current setup only supports forwarding reports to the email of the account signed in. This PR adds support to have custom emails in the input text box on the dashboard while generating and forwarding the report, to make the reporting module slightly flexible and convenient. - Adding the field for taking multiple emails as input in the report request body. - Currently having it as an Option, for 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). --> To make the reporting module slightly flexible and convenient, to send the report to emails entered by the users. ## 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)? --> Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/org/report/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/131.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMzg5OTY3Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.poRn4McNVvd9Yrv2py9FO3HmG1ENu_SqYYc4hfF1Jm8' \ --header 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data-raw '{ "timeRange": { "startTime": "2024-10-31T18:30:00Z", "endTime": "2024-11-30T18:29:59Z" }, "emails": [ "[email protected]", "[email protected]" ] }' ``` Sample request payload: ```bash payload: ReportRequest { time_range: TimeRange { start_time: 2024-10-31 18:30:00.0, end_time: Some(2024-11-30 18:29:59.0) }, emails: Some([****@gmail.com, *****@juspay.in]) } ``` Sample lambda request: ```bash lambda_req: GenerateReportRequest { request: ReportRequest { time_range: TimeRange { start_time: 2024-10-31 18:30:00.0, end_time: Some(2024-11-30 18:29:59.0) }, emails: Some([****@gmail.com, *****@juspay.in]) }, merchant_id: None, auth: OrgLevel { org_id: OrganizationId("org_VpSHOjsYfDvabVYJgCAJ") }, email: *************@juspay.in } ``` - emails is an Option (for backwards compatibility): So its not compulsary as of now to add this field. ```bash curl --location 'http://localhost:8080/analytics/v1/org/report/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/131.0.0.0 Safari/537.36' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMzg5OTY3Nywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.poRn4McNVvd9Yrv2py9FO3HmG1ENu_SqYYc4hfF1Jm8' \ --header 'sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '{ "timeRange": { "startTime": "2024-10-31T18:30:00Z", "endTime": "2024-11-30T18:29:59Z" } }' ``` Sample request payload: ```bash payload: ReportRequest { time_range: TimeRange { start_time: 2024-10-31 18:30:00.0, end_time: Some(2024-11-30 18:29:59.0) }, emails: None } ``` Sample lambda request: ```bash lambda_req: GenerateReportRequest { request: ReportRequest { time_range: TimeRange { start_time: 2024-10-31 18:30:00.0, end_time: Some(2024-11-30 18:29:59.0) }, emails: None }, merchant_id: None, auth: OrgLevel { org_id: OrganizationId("org_VpSHOjsYfDvabVYJgCAJ") }, email: *************@juspay.in } ``` ## 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
079379e7290df47ac2410be50e066d84728a85ad
juspay/hyperswitch
juspay__hyperswitch-6773
Bug: refactor(kafka_message): NanoSecond precision for consolidated logs Due to millisecond level precision earlier , sessionizer was getting updates in same millisecond due to which updates were not getting picked up. Need to change this behaviour to NanoSecond precision
diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs index 92327c044d7..45e7ff2c798 100644 --- a/crates/router/src/services/kafka/dispute_event.rs +++ b/crates/router/src/services/kafka/dispute_event.rs @@ -20,15 +20,15 @@ pub struct KafkaDisputeEvent<'a> { pub connector_dispute_id: &'a String, pub connector_reason: Option<&'a String>, pub connector_reason_code: Option<&'a String>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub challenge_required_by: Option<OffsetDateTime>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_created_at: Option<OffsetDateTime>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_updated_at: Option<OffsetDateTime>, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub connector: &'a String, pub evidence: &'a Secret<serde_json::Value>, diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index 177b211ae89..ec67dc75953 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -25,15 +25,15 @@ pub struct KafkaPaymentAttemptEvent<'a> { pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<&'a String>, pub capture_method: Option<storage_enums::CaptureMethod>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub capture_on: Option<OffsetDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index 7509f711620..195b8679d31 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -22,11 +22,11 @@ pub struct KafkaPaymentIntentEvent<'a> { pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, @@ -60,11 +60,11 @@ pub struct KafkaPaymentIntentEvent<'a> { pub return_url: Option<&'a String>, pub metadata: Option<String>, pub statement_descriptor: Option<&'a String>, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index 74278944b04..b9b3db17b58 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -24,9 +24,9 @@ pub struct KafkaRefundEvent<'a> { pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a String,
2024-12-06T13:16: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 --> Adding nanosecond level precision to kafka messages for sessionizer ### 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). --> So due to millisecond level precision earlier , sessionizer was getting updates in same millisecond due to which updates we not getting picked up ![Screenshot](https://github.com/user-attachments/assets/b1bad009-86db-45d5-8cc5-30b28a8880ae) ## 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)? Post deployment, the timestamp columns would have nano-second based epoch value ![Screenshot](https://github.com/user-attachments/assets/46a3641d-92ae-4cbb-8af6-9e147f8c529d) --> Via Kafka UI ## 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
b5d3d49ceaa2f89284ae5976afec0ff5663a24b0
juspay/hyperswitch
juspay__hyperswitch-6754
Bug: [FEATURE] [INESPAY] Implement Sepa Bank Debit Flow ### Feature Description Implement Sepa Bank Debit Flow ### Possible Implementation Implement Sepa Bank Debit Flow ### 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 41b2c0f80e4..330e504c272 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -6622,6 +6622,7 @@ "gocardless", "gpayments", "helcim", + "inespay", "iatapay", "itaubank", "jpmorgan", @@ -19385,6 +19386,7 @@ "gocardless", "helcim", "iatapay", + "inespay", "itaubank", "jpmorgan", "klarna", diff --git a/config/development.toml b/config/development.toml index 08520a2a859..c5986c7cd94 100644 --- a/config/development.toml +++ b/config/development.toml @@ -567,6 +567,9 @@ debit = { currency = "USD" } [pm_filters.fiuu] duit_now = { country = "MY", currency = "MYR" } +[pm_filters.inespay] +sepa = { currency = "EUR" } + [tokenization] stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } } checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" } diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 0402ae06459..f19c0f2aa8c 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -84,7 +84,7 @@ pub enum RoutableConnectors { Gocardless, Helcim, Iatapay, - // Inespay, + Inespay, Itaubank, Jpmorgan, Klarna, @@ -219,7 +219,7 @@ pub enum Connector { Gocardless, Gpayments, Helcim, - // Inespay, + Inespay, Iatapay, Itaubank, Jpmorgan, @@ -367,7 +367,7 @@ impl Connector { | Self::Gpayments | Self::Helcim | Self::Iatapay - // | Self::Inespay + | Self::Inespay | Self::Itaubank | Self::Jpmorgan | Self::Klarna @@ -537,6 +537,7 @@ impl From<RoutableConnectors> for Connector { RoutableConnectors::Plaid => Self::Plaid, RoutableConnectors::Zsl => Self::Zsl, RoutableConnectors::Xendit => Self::Xendit, + RoutableConnectors::Inespay => Self::Inespay, } } } diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 791a0679ea3..3175bbde8f2 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -196,7 +196,7 @@ pub struct ConnectorConfig { pub gocardless: Option<ConnectorTomlConfig>, pub gpayments: Option<ConnectorTomlConfig>, pub helcim: Option<ConnectorTomlConfig>, - // pub inespay: Option<ConnectorTomlConfig>, + pub inespay: Option<ConnectorTomlConfig>, pub jpmorgan: Option<ConnectorTomlConfig>, pub klarna: Option<ConnectorTomlConfig>, pub mifinity: Option<ConnectorTomlConfig>, @@ -358,7 +358,7 @@ impl ConnectorConfig { Connector::Gocardless => Ok(connector_data.gocardless), Connector::Gpayments => Ok(connector_data.gpayments), Connector::Helcim => Ok(connector_data.helcim), - // Connector::Inespay => Ok(connector_data.inespay), + Connector::Inespay => Ok(connector_data.inespay), Connector::Jpmorgan => Ok(connector_data.jpmorgan), Connector::Klarna => Ok(connector_data.klarna), Connector::Mifinity => Ok(connector_data.mifinity), diff --git a/crates/hyperswitch_connectors/src/connectors/inespay.rs b/crates/hyperswitch_connectors/src/connectors/inespay.rs index 3d3ea346b78..41ae798ade3 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay.rs @@ -1,12 +1,15 @@ pub mod transformers; +use base64::Engine; use common_utils::{ + consts::BASE64_ENGINE, + crypto, errors::CustomResult, - ext_traits::BytesExt, + ext_traits::{ByteSliceExt, BytesExt}, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ @@ -36,7 +39,8 @@ use hyperswitch_interfaces::{ types::{self, Response}, webhooks, }; -use masking::{ExposeInterface, Mask}; +use masking::{ExposeInterface, Mask, Secret}; +use ring::hmac; use transformers as inespay; use crate::{constants::headers, types::ResponseRouterData, utils}; @@ -86,8 +90,8 @@ where 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); + let mut auth_headers = self.get_auth_header(&req.connector_auth_type)?; + header.append(&mut auth_headers); Ok(header) } } @@ -98,10 +102,7 @@ impl ConnectorCommon for Inespay { } 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 + api::CurrencyUnit::Minor } fn common_get_content_type(&self) -> &'static str { @@ -118,10 +119,16 @@ impl ConnectorCommon for Inespay { ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = inespay::InespayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; - Ok(vec![( - headers::AUTHORIZATION.to_string(), - auth.api_key.expose().into_masked(), - )]) + Ok(vec![ + ( + headers::AUTHORIZATION.to_string(), + auth.authorization.expose().into_masked(), + ), + ( + headers::X_API_KEY.to_string(), + auth.api_key.expose().into_masked(), + ), + ]) } fn build_error_response( @@ -139,9 +146,9 @@ impl ConnectorCommon for Inespay { Ok(ErrorResponse { status_code: res.status_code, - code: response.code, - message: response.message, - reason: response.reason, + code: response.status, + message: response.status_desc, + reason: None, attempt_status: None, connector_transaction_id: None, }) @@ -176,9 +183,9 @@ 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!("{}/payins/single/init", self.base_url(connectors))) } fn get_request_body( @@ -192,9 +199,19 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData req.request.currency, )?; - let connector_router_data = inespay::InespayRouterData::from((amount, req)); - let connector_req = inespay::InespayPaymentsRequest::try_from(&connector_router_data)?; - Ok(RequestContent::Json(Box::new(connector_req))) + match req.request.currency { + common_enums::Currency::EUR => { + let connector_router_data = inespay::InespayRouterData::from((amount, req)); + let connector_req = + inespay::InespayPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + _ => Err(errors::ConnectorError::CurrencyNotSupported { + message: req.request.currency.to_string(), + connector: "Inespay", + } + .into()), + } } fn build_request( @@ -262,10 +279,20 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Ine 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 connector_payment_id = req + .request + .connector_transaction_id + .get_connector_transaction_id() + .change_context(errors::ConnectorError::MissingConnectorTransactionID)?; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "/payins/single/", + connector_payment_id, + )) } fn build_request( @@ -289,7 +316,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Ine event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { - let response: inespay::InespayPaymentsResponse = res + let response: inespay::InespayPSyncResponse = res .response .parse_struct("inespay PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -406,9 +433,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Inespay fn get_url( &self, _req: &RefundsRouterData<Execute>, - _connectors: &Connectors, + connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into()) + Ok(format!("{}/refunds/init", self.base_url(connectors))) } fn get_request_body( @@ -452,9 +479,9 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Inespay event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { - let response: inespay::RefundResponse = res + let response: inespay::InespayRefundsResponse = res .response - .parse_struct("inespay RefundResponse") + .parse_struct("inespay InespayRefundsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); @@ -489,10 +516,20 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Inespay { 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 connector_refund_id = req + .request + .connector_refund_id + .clone() + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?; + Ok(format!( + "{}{}{}", + self.base_url(connectors), + "/refunds/", + connector_refund_id, + )) } fn build_request( @@ -519,7 +556,7 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Inespay { event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { - let response: inespay::RefundResponse = res + let response: inespay::InespayRSyncResponse = res .response .parse_struct("inespay RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; @@ -541,27 +578,133 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Inespay { } } +fn get_webhook_body( + body: &[u8], +) -> CustomResult<inespay::InespayWebhookEventData, errors::ConnectorError> { + let notif_item: inespay::InespayWebhookEvent = + serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let encoded_data_return = notif_item.data_return; + let decoded_data_return = BASE64_ENGINE + .decode(encoded_data_return) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + let data_return: inespay::InespayWebhookEventData = decoded_data_return + .parse_struct("inespay InespayWebhookEventData") + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(data_return) +} + #[async_trait::async_trait] impl webhooks::IncomingWebhook for Inespay { - fn get_webhook_object_reference_id( + fn get_webhook_source_verification_algorithm( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, + ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { + Ok(Box::new(crypto::HmacSha256)) + } + + fn get_webhook_source_verification_signature( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let notif_item = serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + Ok(notif_item.signature_data_return.as_bytes().to_owned()) + } + + fn get_webhook_source_verification_message( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + _merchant_id: &common_utils::id_type::MerchantId, + _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, + ) -> CustomResult<Vec<u8>, errors::ConnectorError> { + let notif_item = serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + + Ok(notif_item.data_return.into_bytes()) + } + + async fn verify_webhook_source( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, + merchant_id: &common_utils::id_type::MerchantId, + connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, + _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, + connector_label: &str, + ) -> CustomResult<bool, errors::ConnectorError> { + let connector_webhook_secrets = self + .get_webhook_source_verification_merchant_secret( + merchant_id, + connector_label, + connector_webhook_details, + ) + .await?; + let signature = + self.get_webhook_source_verification_signature(request, &connector_webhook_secrets)?; + + let message = self.get_webhook_source_verification_message( + request, + merchant_id, + &connector_webhook_secrets, + )?; + let secret = connector_webhook_secrets.secret; + + let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &secret); + let signed_message = hmac::sign(&signing_key, &message); + let computed_signature = hex::encode(signed_message.as_ref()); + let payload_sign = BASE64_ENGINE.encode(computed_signature); + Ok(payload_sign.as_bytes().eq(&signature)) + } + + fn get_webhook_object_reference_id( + &self, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let data_return = get_webhook_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + match data_return { + inespay::InespayWebhookEventData::Payment(data) => { + Ok(api_models::webhooks::ObjectReferenceId::PaymentId( + api_models::payments::PaymentIdType::ConnectorTransactionId( + data.single_payin_id, + ), + )) + } + inespay::InespayWebhookEventData::Refund(data) => { + Ok(api_models::webhooks::ObjectReferenceId::RefundId( + api_models::webhooks::RefundIdType::ConnectorRefundId(data.refund_id), + )) + } + } } fn get_webhook_event_type( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let data_return = get_webhook_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(api_models::webhooks::IncomingWebhookEvent::from( + data_return, + )) } fn get_webhook_resource_object( &self, - _request: &webhooks::IncomingWebhookRequestDetails<'_>, + request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { - Err(report!(errors::ConnectorError::WebhooksNotImplemented)) + let data_return = get_webhook_body(request.body) + .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; + Ok(match data_return { + inespay::InespayWebhookEventData::Payment(payment_webhook_data) => { + Box::new(payment_webhook_data) + } + inespay::InespayWebhookEventData::Refund(refund_webhook_data) => { + Box::new(refund_webhook_data) + } + }) } } diff --git a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs index 296d76546c8..2739aa66bee 100644 --- a/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs @@ -1,31 +1,33 @@ use common_enums::enums; -use common_utils::types::StringMinorUnit; +use common_utils::{ + request::Method, + types::{MinorUnit, StringMinorUnit, StringMinorUnitForConnector}, +}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ - payment_method_data::PaymentMethodData, - router_data::{ConnectorAuthType, RouterData}, + payment_method_data::{BankDebitData, PaymentMethodData}, + router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, - router_response_types::{PaymentsResponseData, RefundsResponseData}, + router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; +use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, - utils::PaymentsAuthorizeRequestData, + utils::{self, PaymentsAuthorizeRequestData, RouterData as _}, }; - -//TODO: Fill the struct with respective fields pub struct InespayRouterData<T> { - pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc. + pub amount: StringMinorUnit, pub router_data: T, } impl<T> From<(StringMinorUnit, T)> for InespayRouterData<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, @@ -33,20 +35,15 @@ impl<T> From<(StringMinorUnit, T)> for InespayRouterData<T> { } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct InespayPaymentsRequest { + description: String, amount: StringMinorUnit, - card: InespayCard, -} - -#[derive(Default, Debug, Serialize, Eq, PartialEq)] -pub struct InespayCard { - number: cards::CardNumber, - expiry_month: Secret<String>, - expiry_year: Secret<String>, - cvc: Secret<String>, - complete: bool, + reference: String, + debtor_account: Option<Secret<String>>, + success_link_redirect: Option<String>, + notif_url: Option<String>, } impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymentsRequest { @@ -55,17 +52,17 @@ impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymen item: &InespayRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::Card(req_card) => { - let card = InespayCard { - 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()?, - }; + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => { + let order_id = item.router_data.connector_request_reference_id.clone(); + let webhook_url = item.router_data.request.get_webhook_url()?; + let return_url = item.router_data.request.get_router_return_url()?; Ok(Self { + description: item.router_data.get_description()?, amount: item.amount.clone(), - card, + reference: order_id, + debtor_account: Some(iban), + success_link_redirect: Some(return_url), + notif_url: Some(webhook_url), }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), @@ -73,156 +70,422 @@ impl TryFrom<&InespayRouterData<&PaymentsAuthorizeRouterData>> for InespayPaymen } } -//TODO: Fill the struct with respective fields -// Auth Struct pub struct InespayAuthType { pub(super) api_key: Secret<String>, + pub authorization: Secret<String>, } impl TryFrom<&ConnectorAuthType> for InespayAuthType { 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 { + ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { api_key: api_key.to_owned(), + authorization: key1.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 InespayPaymentStatus { - Succeeded, + +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InespayPaymentsResponseData { + status: String, + status_desc: String, + single_payin_id: String, + single_payin_link: String, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayPaymentsResponse { + InespayPaymentsData(InespayPaymentsResponseData), + InespayPaymentsError(InespayErrorResponse), +} + +impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + let (status, response) = match item.response { + InespayPaymentsResponse::InespayPaymentsData(data) => { + let redirection_url = Url::parse(data.single_payin_link.as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + let redirection_data = RedirectForm::from((redirection_url, Method::Get)); + + ( + common_enums::AttemptStatus::AuthenticationPending, + Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + data.single_payin_id.clone(), + ), + redirection_data: Box::new(Some(redirection_data)), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ) + } + InespayPaymentsResponse::InespayPaymentsError(data) => ( + common_enums::AttemptStatus::Failure, + Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ), + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum InespayPSyncStatus { + Ok, + Created, + Opened, + BankSelected, + Initiated, + Pending, + Aborted, + Unfinished, + Rejected, + Cancelled, + PartiallyAccepted, Failed, - #[default] - Processing, + Settled, + PartRefunded, + Refunded, } -impl From<InespayPaymentStatus> for common_enums::AttemptStatus { - fn from(item: InespayPaymentStatus) -> Self { +impl From<InespayPSyncStatus> for common_enums::AttemptStatus { + fn from(item: InespayPSyncStatus) -> Self { match item { - InespayPaymentStatus::Succeeded => Self::Charged, - InespayPaymentStatus::Failed => Self::Failure, - InespayPaymentStatus::Processing => Self::Authorizing, + InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::Charged, + InespayPSyncStatus::Created + | InespayPSyncStatus::Opened + | InespayPSyncStatus::BankSelected + | InespayPSyncStatus::Initiated + | InespayPSyncStatus::Pending + | InespayPSyncStatus::Unfinished + | InespayPSyncStatus::PartiallyAccepted => Self::AuthenticationPending, + InespayPSyncStatus::Aborted + | InespayPSyncStatus::Rejected + | InespayPSyncStatus::Cancelled + | InespayPSyncStatus::Failed => Self::Failure, + InespayPSyncStatus::PartRefunded | InespayPSyncStatus::Refunded => Self::AutoRefunded, } } } -//TODO: Fill the struct with respective fields -#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct InespayPaymentsResponse { - status: InespayPaymentStatus, - id: String, +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InespayPSyncResponseData { + cod_status: InespayPSyncStatus, + status_desc: String, + single_payin_id: String, + single_payin_link: String, } -impl<F, T> TryFrom<ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>> +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayPSyncResponse { + InespayPSyncData(InespayPSyncResponseData), + InespayPSyncWebhook(InespayPaymentWebhookData), + InespayPSyncError(InespayErrorResponse), +} + +impl<F, T> TryFrom<ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: ResponseRouterData<F, InespayPaymentsResponse, T, PaymentsResponseData>, + item: ResponseRouterData<F, InespayPSyncResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { - Ok(Self { - status: common_enums::AttemptStatus::from(item.response.status), - response: Ok(PaymentsResponseData::TransactionResponse { - resource_id: ResponseId::ConnectorTransactionId(item.response.id), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: None, - incremental_authorization_allowed: None, - charge_id: None, + match item.response { + InespayPSyncResponse::InespayPSyncData(data) => { + let redirection_url = Url::parse(data.single_payin_link.as_str()) + .change_context(errors::ConnectorError::ParsingFailed)?; + let redirection_data = RedirectForm::from((redirection_url, Method::Get)); + + Ok(Self { + status: common_enums::AttemptStatus::from(data.cod_status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + data.single_payin_id.clone(), + ), + redirection_data: Box::new(Some(redirection_data)), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } + InespayPSyncResponse::InespayPSyncWebhook(data) => { + let status = enums::AttemptStatus::from(data.cod_status); + Ok(Self { + status, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId( + data.single_payin_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } + InespayPSyncResponse::InespayPSyncError(data) => Ok(Self { + response: Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data }), - ..item.data - }) + } } } -//TODO: Fill the struct with respective fields -// REFUND : -// Type definition for RefundRequest -#[derive(Default, Debug, Serialize)] +#[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct InespayRefundRequest { - pub amount: StringMinorUnit, + single_payin_id: String, + amount: Option<MinorUnit>, } impl<F> TryFrom<&InespayRouterData<&RefundsRouterData<F>>> for InespayRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &InespayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { + let amount = utils::convert_back_amount_to_minor_units( + &StringMinorUnitForConnector, + item.amount.to_owned(), + item.router_data.request.currency, + )?; Ok(Self { - amount: item.amount.to_owned(), + single_payin_id: item.router_data.request.connector_transaction_id.clone(), + amount: Some(amount), }) } } -// Type definition for Refund Response - -#[allow(dead_code)] -#[derive(Debug, Serialize, Default, Deserialize, Clone)] -pub enum RefundStatus { - Succeeded, - Failed, +#[derive(Debug, Serialize, Default, Deserialize, Clone, PartialEq)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum InespayRSyncStatus { + Confirmed, #[default] - Processing, + Pending, + Rejected, + Denied, + Reversed, + Mistake, } -impl From<RefundStatus> for enums::RefundStatus { - fn from(item: RefundStatus) -> Self { +impl From<InespayRSyncStatus> for enums::RefundStatus { + fn from(item: InespayRSyncStatus) -> Self { match item { - RefundStatus::Succeeded => Self::Success, - RefundStatus::Failed => Self::Failure, - RefundStatus::Processing => Self::Pending, - //TODO: Review mapping + InespayRSyncStatus::Confirmed => Self::Success, + InespayRSyncStatus::Pending => Self::Pending, + InespayRSyncStatus::Rejected + | InespayRSyncStatus::Denied + | InespayRSyncStatus::Reversed + | InespayRSyncStatus::Mistake => Self::Failure, } } } -//TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] -pub struct RefundResponse { - id: String, - status: RefundStatus, +#[serde(rename_all = "camelCase")] +pub struct RefundsData { + status: String, + status_desc: String, + refund_id: String, } -impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayRefundsResponse { + InespayRefundsData(RefundsData), + InespayRefundsError(InespayErrorResponse), +} + +impl TryFrom<RefundsResponseRouterData<Execute, InespayRefundsResponse>> + for RefundsRouterData<Execute> +{ type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<Execute, RefundResponse>, + item: RefundsResponseRouterData<Execute, InespayRefundsResponse>, ) -> 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), + match item.response { + InespayRefundsResponse::InespayRefundsData(data) => Ok(Self { + response: Ok(RefundsResponseData { + connector_refund_id: data.refund_id, + refund_status: enums::RefundStatus::Pending, + }), + ..item.data }), - ..item.data - }) + InespayRefundsResponse::InespayRefundsError(data) => Ok(Self { + response: Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, + }), + ..item.data + }), + } } } -impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InespayRSyncResponseData { + cod_status: InespayRSyncStatus, + status_desc: String, + refund_id: String, +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum InespayRSyncResponse { + InespayRSyncData(InespayRSyncResponseData), + InespayRSyncWebhook(InespayRefundWebhookData), + InespayRSyncError(InespayErrorResponse), +} + +impl TryFrom<RefundsResponseRouterData<RSync, InespayRSyncResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: RefundsResponseRouterData<RSync, RefundResponse>, + item: RefundsResponseRouterData<RSync, InespayRSyncResponse>, ) -> 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), + let response = match item.response { + InespayRSyncResponse::InespayRSyncData(data) => Ok(RefundsResponseData { + connector_refund_id: data.refund_id, + refund_status: enums::RefundStatus::from(data.cod_status), + }), + InespayRSyncResponse::InespayRSyncWebhook(data) => Ok(RefundsResponseData { + connector_refund_id: data.refund_id, + refund_status: enums::RefundStatus::from(data.cod_status), + }), + InespayRSyncResponse::InespayRSyncError(data) => Err(ErrorResponse { + code: data.status.clone(), + message: data.status_desc.clone(), + reason: Some(data.status_desc.clone()), + attempt_status: None, + connector_transaction_id: None, + status_code: item.http_code, }), + }; + Ok(Self { + response, ..item.data }) } } -//TODO: Fill the struct with respective fields +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct InespayPaymentWebhookData { + pub single_payin_id: String, + pub cod_status: InespayPSyncStatus, + pub description: String, + pub amount: MinorUnit, + pub reference: String, + pub creditor_account: Secret<String>, + pub debtor_name: Secret<String>, + pub debtor_account: Secret<String>, + pub custom_data: Option<String>, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct InespayRefundWebhookData { + pub refund_id: String, + pub simple_payin_id: String, + pub cod_status: InespayRSyncStatus, + pub description: String, + pub amount: MinorUnit, + pub reference: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(untagged)] +pub enum InespayWebhookEventData { + Payment(InespayPaymentWebhookData), + Refund(InespayRefundWebhookData), +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct InespayWebhookEvent { + pub data_return: String, + pub signature_data_return: String, +} + #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct InespayErrorResponse { - pub status_code: u16, - pub code: String, - pub message: String, - pub reason: Option<String>, + pub status: String, + pub status_desc: String, +} + +impl From<InespayWebhookEventData> for api_models::webhooks::IncomingWebhookEvent { + fn from(item: InespayWebhookEventData) -> Self { + match item { + InespayWebhookEventData::Payment(payment_data) => match payment_data.cod_status { + InespayPSyncStatus::Ok | InespayPSyncStatus::Settled => Self::PaymentIntentSuccess, + InespayPSyncStatus::Failed | InespayPSyncStatus::Rejected => { + Self::PaymentIntentFailure + } + InespayPSyncStatus::Created + | InespayPSyncStatus::Opened + | InespayPSyncStatus::BankSelected + | InespayPSyncStatus::Initiated + | InespayPSyncStatus::Pending + | InespayPSyncStatus::Unfinished + | InespayPSyncStatus::PartiallyAccepted => Self::PaymentIntentProcessing, + InespayPSyncStatus::Aborted + | InespayPSyncStatus::Cancelled + | InespayPSyncStatus::PartRefunded + | InespayPSyncStatus::Refunded => Self::EventNotSupported, + }, + InespayWebhookEventData::Refund(refund_data) => match refund_data.cod_status { + InespayRSyncStatus::Confirmed => Self::RefundSuccess, + InespayRSyncStatus::Rejected + | InespayRSyncStatus::Denied + | InespayRSyncStatus::Reversed + | InespayRSyncStatus::Mistake => Self::RefundFailure, + InespayRSyncStatus::Pending => Self::EventNotSupported, + }, + } + } } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index fd9f08089af..0d5d1a3fc7a 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1395,10 +1395,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> { iatapay::transformers::IatapayAuthType::try_from(self.auth_type)?; Ok(()) } - // api_enums::Connector::Inespay => { - // inespay::transformers::InespayAuthType::try_from(self.auth_type)?; - // Ok(()) - // } + api_enums::Connector::Inespay => { + inespay::transformers::InespayAuthType::try_from(self.auth_type)?; + Ok(()) + } api_enums::Connector::Itaubank => { itaubank::transformers::ItaubankAuthType::try_from(self.auth_type)?; Ok(()) diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 243b6116e72..add1bd95b56 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -441,9 +441,9 @@ impl ConnectorData { enums::Connector::Iatapay => { Ok(ConnectorEnum::Old(Box::new(connector::Iatapay::new()))) } - // enums::Connector::Inespay => { - // Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new()))) - // } + enums::Connector::Inespay => { + Ok(ConnectorEnum::Old(Box::new(connector::Inespay::new()))) + } enums::Connector::Itaubank => { Ok(ConnectorEnum::Old(Box::new(connector::Itaubank::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 06682f596ed..4d946ca97ad 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -254,7 +254,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { } api_enums::Connector::Helcim => Self::Helcim, api_enums::Connector::Iatapay => Self::Iatapay, - // api_enums::Connector::Inespay => Self::Inespay, + api_enums::Connector::Inespay => Self::Inespay, api_enums::Connector::Itaubank => Self::Itaubank, api_enums::Connector::Jpmorgan => Self::Jpmorgan, api_enums::Connector::Klarna => Self::Klarna,
2024-12-05T08:14:02Z
## 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 payment flows (Auth, PSync, Refund, RSync, and Webhooks) for Inespay Sepa Bank Debit. ### 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. Merchant Account Create 2. API Key Create 3.Inespay Connector Create: ``` curl --location 'http://localhost:8080/account/merchant_1736331946/connectors' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector_type": "payment_processor", "connector_name": "inespay", "connector_account_details": { "auth_type": "BodyKey", "api_key": "abc", "key1": "abc" }, "test_mode": false, "disabled": false, "payment_methods_enabled": [ { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "sepa", "payment_experience": "redirect_to_url", "card_networks": null, "accepted_currencies": null, "accepted_countries": null, "minimum_amount": 0, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": false } ] } ], "connector_webhook_details": { "merchant_secret": "abc", "additional_secret": null } }' ``` 4. Payments Create: ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_t54RQO5Ci3L3J3sV0GFUeySuR0d3zPe66OxpRV8qKD3Th7Pyquxxro6afDNCapom' \ --data '{ "amount": 6540, "currency": "EUR", "confirm": true, "amount_to_capture": 6540, "customer_id": "StripbmnxeCustomer", "description": "Its my first payment request", "return_url": "https://google.com", "payment_method": "bank_debit", "payment_method_type": "sepa", "payment_method_data": { "bank_debit": { "sepa_bank_debit": { "iban": "ES5031831357110123456789" } } } }' ``` Response: ``` { "payment_id": "pay_2hUGMfU0Wv31Gn3unXgG", "merchant_id": "merchant_1736331946", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": null, "connector": "inespay", "client_secret": "pay_2hUGMfU0Wv31Gn3unXgG_secret_iYsSbpRHSGd4bEJ3OBET", "created": "2025-01-09T08:55:12.497Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "ES503**************56789", "bank_account_holder_name": 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": null, "email": "[email protected]", "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_2hUGMfU0Wv31Gn3unXgG/merchant_1736331946/pay_2hUGMfU0Wv31Gn3unXgG_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": "StripeCustomer", "created_at": 1736412912, "expires": 1736416512, "secret": "epk_a8553335e63d4417ba67bfe8301b8799" }, "manual_retry_allowed": null, "connector_transaction_id": "PMWC9HMC-E37E-I83G-FZWOCP9S2GDVX8ZD", "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_oPMGl04eyRD2pY0laexI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RTX0eIQOVWNhcTAeKXQQ", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-09T09:10:12.497Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-01-09T08:55:13.385Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` 5. Payments Retrieve: ``` curl --location 'http://localhost:8080/payments/pay_xoODE5mPdtuN8tr5xyMz?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_t54RQO5Ci3L3J3sV0GFUeySuR0d3zPe66OxpRV8qKD3Th7Pyquxxro6afDNCapom' ``` Response: ``` { "payment_id": "pay_TcadxZAWM2P3PjWJ7PRC", "merchant_id": "merchant_1736331946", "status": "requires_customer_action", "amount": 6540, "net_amount": 6540, "shipping_cost": null, "amount_capturable": 6540, "amount_received": null, "connector": "inespay", "client_secret": "pay_TcadxZAWM2P3PjWJ7PRC_secret_xpi5fQgZ7uqbr42h1uxt", "created": "2025-01-09T08:44:46.048Z", "currency": "EUR", "customer_id": "StripeCustomer", "customer": { "id": "StripeCustomer", "name": "John Doe", "email": "[email protected]", "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_debit", "payment_method_data": { "bank_debit": { "sepa": { "iban": "ES113**************40674", "bank_account_holder_name": 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": null, "email": "[email protected]", "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_TcadxZAWM2P3PjWJ7PRC/merchant_1736331946/pay_TcadxZAWM2P3PjWJ7PRC_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": "BKBBNZ68-17K5-B4SL-LTC0545XW13LKIBK", "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_oPMGl04eyRD2pY0laexI", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_RTX0eIQOVWNhcTAeKXQQ", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2025-01-09T08:59:46.047Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2025-01-09T08:45:37.239Z", "split_payments": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` 6. Refunds: ``` curl --location 'http://localhost:8080/refunds' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: dev_J5g19W9vemKtoeyfLV5hBEovbKns39FLpAxqj8SnuDnFdLCJcIHJX928eOVl8nkd' \ --data '{ "payment_id": "pay_2hUGMfU0Wv31Gn3unXgG", "amount": 600, "reason": "Customer returned product", "refund_type": "instant", "metadata": { "udf1": "value1", "new_customer": "true", "login_date": "2019-09-10T10:11:12Z" } }' ``` 7. Refunds Retrieve: ``` curl --location 'http://localhost:8080/refunds/' \ --header 'Accept: application/json' \ --header 'api-key: dev_J5g19W9vemKtoeyfLV5hBEovbKns39FLpAxqj8SnuDnFdLCJcIHJX928eOVl8nkd' ``` ## 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
062e1d1757ab894d3d7d88534372f8a85e77a8b6
juspay/hyperswitch
juspay__hyperswitch-6751
Bug: [BUG] Description for refunds - list is not apt ### Bug Description https://api-reference.hyperswitch.io/api-reference/refunds/refunds--list This should be - `Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided` Current one implies that it'll return refunds of a payment_id if it is not provided. ### Expected Behavior It should reflect that refunds accociated with a merchant will be returned if payment_id is missing, otherwise only for that payment_id. ### Actual Behavior Incorrect message being shown. ### Steps To Reproduce Visit - https://api-reference.hyperswitch.io/api-reference/refunds/refunds--list ### Context For The Bug _No response_ ### Environment Are you using hyperswitch hosted version? Yes ### 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/openapi/src/routes/refunds.rs b/crates/openapi/src/routes/refunds.rs index 4e096e243a8..0ff0891ee54 100644 --- a/crates/openapi/src/routes/refunds.rs +++ b/crates/openapi/src/routes/refunds.rs @@ -115,7 +115,7 @@ pub async fn refunds_update() {} /// Refunds - List /// -/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided +/// Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided #[utoipa::path( post, path = "/refunds/list",
2024-10-27T18:30:36Z
## Type of Change - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [x] Documentation - [ ] CI/CD ## Description The current description for refund - list is incorrect. Newer one looks more apt. ### 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 #6751. ## 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` - [x] I reviewed the submitted code - [ ] I added unit tests for my changes where possible
086115f47379b06185a1753979fc6dd9dc945afd
juspay/hyperswitch
juspay__hyperswitch-6750
Bug: [BUG] Network token data is being fetched in CIT repeat irrespective of connector Currently, Network token data is being fetched in CIT repeat irrespective of connector decided by routing. this would to lead to failure of payments with "payment method not implemented". New Implementation - connector decide should be validated whether it is present in network_token_connector_list. if present, network token data should be fetched else card details should be fetched from card vault to make a transaction
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 599d696ec06..39889bf7577 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -588,6 +588,7 @@ pub async fn retrieve_payment_method_with_token( mandate_id, payment_method_info, business_profile, + payment_attempt.connector.clone(), ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? @@ -622,6 +623,7 @@ pub async fn retrieve_payment_method_with_token( mandate_id, payment_method_info, business_profile, + payment_attempt.connector.clone(), ) .await .map(|card| Some((card, enums::PaymentMethod::Card)))? diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index e7de03804d1..f061977e28a 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -1915,6 +1915,7 @@ pub async fn retrieve_card_with_permanent_token( mandate_id: Option<api_models::payments::MandateIds>, payment_method_info: Option<domain::PaymentMethod>, business_profile: &domain::Profile, + connector: Option<String>, ) -> RouterResult<domain::PaymentMethodData> { let customer_id = payment_intent .customer_id @@ -1985,7 +1986,28 @@ pub async fn retrieve_card_with_permanent_token( .attach_printable("Payment method data is not present"), (Some(ref pm_data), None) => { // Regular (non-mandate) Payment flow - if let Some(token_ref) = pm_data.network_token_requestor_reference_id.clone() { + let network_tokenization_supported_connectors = &state + .conf + .network_tokenization_supported_connectors + .connector_list; + let connector_variant = connector + .as_ref() + .map(|conn| { + api_enums::Connector::from_str(conn.as_str()) + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "connector", + }) + .attach_printable_lazy(|| { + format!("unable to parse connector name {connector:?}") + }) + }) + .transpose()?; + if let (Some(_conn), Some(token_ref)) = ( + connector_variant + .filter(|conn| network_tokenization_supported_connectors.contains(conn)), + pm_data.network_token_requestor_reference_id.clone(), + ) { + logger::info!("Fetching network token data from tokenization service"); match network_tokenization::get_token_from_tokenization_service( state, token_ref, pm_data, ) @@ -2015,6 +2037,8 @@ pub async fn retrieve_card_with_permanent_token( } } } else { + logger::info!("Either the connector is not in the NT supported list or token requestor reference ID is absent"); + logger::info!("Falling back to fetch card details from locker"); fetch_card_details_from_locker( state, customer_id, @@ -5776,6 +5800,7 @@ pub async fn get_payment_method_details_from_payment_token( None, None, business_profile, + payment_attempt.connector.clone(), ) .await .map(|card| Some((card, enums::PaymentMethod::Card))), @@ -5794,6 +5819,7 @@ pub async fn get_payment_method_details_from_payment_token( None, None, business_profile, + payment_attempt.connector.clone(), ) .await .map(|card| Some((card, enums::PaymentMethod::Card))),
2024-12-04T22:09:10Z
## 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 --> Currently we always fetch network token for the connector that does not support network tokenization. Fix: we ll only fetch network token if the connector supports network tokenization else fetch card details to make CIT repeat. ### 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 cases - Create two MCA ex - Cybersource(network tokenization supported conn), Adyen enable network tokenization for business profile Make saved card flow transaction. when routable connector list - [Cybersource, Adyen] -> payment should happen with Network token + cryptogram when routable connector list - [ Adyen, Cybersource] -> payment should happen with card+cvc CIT - ``` curl --location 'http://localhost:8080/payments' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: api-key' \ --data-raw '{ "amount": 10, "amount_to_capture": 10, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "customer1733733309", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+1", "description": "Its my first payment request", "authentication_type": "no_three_ds", "setup_future_usage": "off_session", "return_url": "http://127.0.0.1:4040/", "customer_acceptance": { "acceptance_type": "offline", "accepted_at": "1963-05-03T04:07:52.723Z", "online": { "ip_address": "in sit", "user_agent": "amet irure esse" } }, "payment_method": "card", "payment_method_data": { "card": { "card_number": "card_number", "card_exp_month": "card_exp_month", "card_exp_year": "card_exp_year", "card_holder_name": "joseph Doe", "card_cvc": "947" } }, "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US" }, "email": "[email protected]" }, "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": { "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 - [ ] I added unit tests for my changes where possible
086115f47379b06185a1753979fc6dd9dc945afd
juspay/hyperswitch
juspay__hyperswitch-6780
Bug: feat(users): Introduce themes in user APIs Currently there is no themes context in the user and email related APIs where the themes should be reflected. We should change the APIs which would have the theme context.
diff --git a/config/config.example.toml b/config/config.example.toml index 5aa9e543fb2..0fe6b8caa2c 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -797,5 +797,12 @@ host = "localhost" # Client Host port = 7000 # Client Port service = "dynamo" # Service name -[theme_storage] +[theme.storage] file_storage_backend = "file_system" # Theme storage backend to be used + +[theme.email_config] +entity_name = "Hyperswitch" # Name of the entity to be showed in emails +entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails +foreground_color = "#000000" # Foreground color of email text +primary_color = "#006DF9" # Primary color of email body +background_color = "#FFFFFF" # Background color of email body diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 5cadc66ddfc..848a2305ae4 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -328,9 +328,16 @@ host = "localhost" # Client Host port = 7000 # Client Port service = "dynamo" # Service name -[theme_storage] +[theme.storage] file_storage_backend = "aws_s3" # Theme storage backend to be used -[theme_storage.aws_s3] +[theme.storage.aws_s3] region = "bucket_region" # AWS region where the S3 bucket for theme storage is located bucket_name = "bucket" # AWS S3 bucket name for theme storage + +[theme.email_config] +entity_name = "Hyperswitch" # Name of the entity to be showed in emails +entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails +foreground_color = "#000000" # Foreground color of email text +primary_color = "#006DF9" # Primary color of email body +background_color = "#FFFFFF" # Background color of email body diff --git a/config/development.toml b/config/development.toml index fa577a78e6a..077e09f0463 100644 --- a/config/development.toml +++ b/config/development.toml @@ -797,5 +797,12 @@ host = "localhost" port = 7000 service = "dynamo" -[theme_storage] -file_storage_backend = "file_system" +[theme.storage] +file_storage_backend = "file_system" # Theme storage backend to be used + +[theme.email_config] +entity_name = "Hyperswitch" # Name of the entity to be showed in emails +entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails +foreground_color = "#000000" # Foreground color of email text +primary_color = "#006DF9" # Primary color of email body +background_color = "#FFFFFF" # Background color of email body diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 3cc690203e6..dbd5286b290 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -694,5 +694,12 @@ prod_intent_recipient_email = "[email protected]" # Recipient email for prod 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. -[theme_storage] +[theme.storage] file_storage_backend = "file_system" # Theme storage backend to be used + +[theme.email_config] +entity_name = "Hyperswitch" # Name of the entity to be showed in emails +entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails +foreground_color = "#000000" # Foreground color of email text +primary_color = "#006DF9" # Primary color of email body +background_color = "#FFFFFF" # Background color of email body diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index e61696803a2..7b5911cf1a8 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -150,6 +150,7 @@ pub struct GetUserDetailsResponse { pub recovery_codes_left: Option<usize>, pub profile_id: id_type::ProfileId, pub entity_type: EntityType, + pub theme_id: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] @@ -345,8 +346,9 @@ pub struct SsoSignInRequest { } #[derive(Debug, serde::Deserialize, serde::Serialize)] -pub struct AuthIdQueryParam { +pub struct AuthIdAndThemeIdQueryParam { pub auth_id: Option<String>, + pub theme_id: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] diff --git a/crates/api_models/src/user/theme.rs b/crates/api_models/src/user/theme.rs index 23218c4a163..c79da307b9a 100644 --- a/crates/api_models/src/user/theme.rs +++ b/crates/api_models/src/user/theme.rs @@ -1,6 +1,9 @@ use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm}; use common_enums::EntityType; -use common_utils::{id_type, types::theme::ThemeLineage}; +use common_utils::{ + id_type, + types::theme::{EmailThemeConfig, ThemeLineage}, +}; use masking::Secret; use serde::{Deserialize, Serialize}; @@ -13,6 +16,7 @@ pub struct GetThemeResponse { pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, + pub email_config: EmailThemeConfig, pub theme_data: ThemeData, } @@ -35,12 +39,14 @@ pub struct CreateThemeRequest { pub lineage: ThemeLineage, pub theme_name: String, pub theme_data: ThemeData, + pub email_config: Option<EmailThemeConfig>, } #[derive(Serialize, Deserialize, Debug)] pub struct UpdateThemeRequest { pub lineage: ThemeLineage, pub theme_data: ThemeData, + // TODO: Add support to update email config } // All the below structs are for the theme.json file, diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs index 239cffc40d4..05ae26b565a 100644 --- a/crates/common_utils/src/types/theme.rs +++ b/crates/common_utils/src/types/theme.rs @@ -1,4 +1,5 @@ use common_enums::EntityType; +use serde::{Deserialize, Serialize}; use crate::{ events::{ApiEventMetric, ApiEventsType}, @@ -7,15 +8,14 @@ use crate::{ /// Enum for having all the required lineage for every level. /// Currently being used for theme related APIs and queries. -#[derive(Debug, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Deserialize, Serialize)] #[serde(tag = "entity_type", rename_all = "snake_case")] pub enum ThemeLineage { - // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType - // /// Tenant lineage variant - // Tenant { - // /// tenant_id: String - // tenant_id: String, - // }, + /// Tenant lineage variant + Tenant { + /// tenant_id: TenantId + tenant_id: id_type::TenantId, + }, /// Org lineage variant Organization { /// tenant_id: TenantId @@ -48,9 +48,35 @@ pub enum ThemeLineage { impl_api_event_type!(Miscellaneous, (ThemeLineage)); impl ThemeLineage { + /// Constructor for ThemeLineage + pub fn new( + entity_type: EntityType, + tenant_id: id_type::TenantId, + org_id: id_type::OrganizationId, + merchant_id: id_type::MerchantId, + profile_id: id_type::ProfileId, + ) -> Self { + match entity_type { + EntityType::Tenant => Self::Tenant { tenant_id }, + EntityType::Organization => Self::Organization { tenant_id, org_id }, + EntityType::Merchant => Self::Merchant { + tenant_id, + org_id, + merchant_id, + }, + EntityType::Profile => Self::Profile { + tenant_id, + org_id, + merchant_id, + profile_id, + }, + } + } + /// Get the entity_type from the lineage pub fn entity_type(&self) -> EntityType { match self { + Self::Tenant { .. } => EntityType::Tenant, Self::Organization { .. } => EntityType::Organization, Self::Merchant { .. } => EntityType::Merchant, Self::Profile { .. } => EntityType::Profile, @@ -60,7 +86,8 @@ impl ThemeLineage { /// Get the tenant_id from the lineage pub fn tenant_id(&self) -> &id_type::TenantId { match self { - Self::Organization { tenant_id, .. } + Self::Tenant { tenant_id } + | Self::Organization { tenant_id, .. } | Self::Merchant { tenant_id, .. } | Self::Profile { tenant_id, .. } => tenant_id, } @@ -69,6 +96,7 @@ impl ThemeLineage { /// Get the org_id from the lineage pub fn org_id(&self) -> Option<&id_type::OrganizationId> { match self { + Self::Tenant { .. } => None, Self::Organization { org_id, .. } | Self::Merchant { org_id, .. } | Self::Profile { org_id, .. } => Some(org_id), @@ -78,7 +106,7 @@ impl ThemeLineage { /// Get the merchant_id from the lineage pub fn merchant_id(&self) -> Option<&id_type::MerchantId> { match self { - Self::Organization { .. } => None, + Self::Tenant { .. } | Self::Organization { .. } => None, Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => { Some(merchant_id) } @@ -88,8 +116,72 @@ impl ThemeLineage { /// Get the profile_id from the lineage pub fn profile_id(&self) -> Option<&id_type::ProfileId> { match self { - Self::Organization { .. } | Self::Merchant { .. } => None, + Self::Tenant { .. } | Self::Organization { .. } | Self::Merchant { .. } => None, Self::Profile { profile_id, .. } => Some(profile_id), } } + + /// Get higher lineages from the current lineage + pub fn get_same_and_higher_lineages(self) -> Vec<Self> { + match &self { + Self::Tenant { .. } => vec![self], + Self::Organization { tenant_id, .. } => vec![ + Self::Tenant { + tenant_id: tenant_id.clone(), + }, + self, + ], + Self::Merchant { + tenant_id, org_id, .. + } => vec![ + Self::Tenant { + tenant_id: tenant_id.clone(), + }, + Self::Organization { + tenant_id: tenant_id.clone(), + org_id: org_id.clone(), + }, + self, + ], + Self::Profile { + tenant_id, + org_id, + merchant_id, + .. + } => vec![ + Self::Tenant { + tenant_id: tenant_id.clone(), + }, + Self::Organization { + tenant_id: tenant_id.clone(), + org_id: org_id.clone(), + }, + Self::Merchant { + tenant_id: tenant_id.clone(), + org_id: org_id.clone(), + merchant_id: merchant_id.clone(), + }, + self, + ], + } + } +} + +/// Struct for holding the theme settings for email +#[derive(Debug, Clone, Default, Deserialize, Serialize)] +pub struct EmailThemeConfig { + /// The entity name to be used in the email + pub entity_name: String, + + /// The URL of the entity logo to be used in the email + pub entity_logo_url: String, + + /// The primary color to be used in the email + pub primary_color: String, + + /// The foreground color to be used in the email + pub foreground_color: String, + + /// The background color to be used in the email + pub background_color: String, } diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs index a26e401ffbb..945ce1a9bb2 100644 --- a/crates/diesel_models/src/query/user/theme.rs +++ b/crates/diesel_models/src/query/user/theme.rs @@ -1,13 +1,22 @@ +use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::types::theme::ThemeLineage; use diesel::{ associations::HasTable, + debug_query, pg::Pg, + result::Error as DieselError, sql_types::{Bool, Nullable}, - BoolExpressionMethods, ExpressionMethods, + BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl, }; +use error_stack::{report, ResultExt}; +use router_env::logger; use crate::{ - query::generics, + errors::DatabaseError, + query::generics::{ + self, + db_metrics::{track_database_call, DatabaseOperation}, + }, schema::themes::dsl, user::theme::{Theme, ThemeNew}, PgPooledConn, StorageResult, @@ -27,15 +36,14 @@ impl Theme { + 'static, > { match lineage { - // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType - // ThemeLineage::Tenant { tenant_id } => Box::new( - // dsl::tenant_id - // .eq(tenant_id) - // .and(dsl::org_id.is_null()) - // .and(dsl::merchant_id.is_null()) - // .and(dsl::profile_id.is_null()) - // .nullable(), - // ), + ThemeLineage::Tenant { tenant_id } => Box::new( + dsl::tenant_id + .eq(tenant_id) + .and(dsl::org_id.is_null()) + .and(dsl::merchant_id.is_null()) + .and(dsl::profile_id.is_null()) + .nullable(), + ), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) @@ -77,6 +85,41 @@ impl Theme { .await } + pub async fn find_most_specific_theme_in_lineage( + conn: &PgPooledConn, + lineage: ThemeLineage, + ) -> StorageResult<Self> { + let query = <Self as HasTable>::table().into_boxed(); + + let query = + lineage + .get_same_and_higher_lineages() + .into_iter() + .fold(query, |mut query, lineage| { + query = query.or_filter(Self::lineage_filter(lineage)); + query + }); + + logger::debug!(query = %debug_query::<Pg,_>(&query).to_string()); + + let data: Vec<Self> = match track_database_call::<Self, _, _>( + query.get_results_async(conn), + DatabaseOperation::Filter, + ) + .await + { + Ok(value) => Ok(value), + Err(err) => match err { + DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound), + _ => Err(report!(err)).change_context(DatabaseError::Others), + }, + }?; + + data.into_iter() + .min_by_key(|theme| theme.entity_type) + .ok_or(report!(DatabaseError::NotFound)) + } + pub async fn find_by_lineage( conn: &PgPooledConn, lineage: ThemeLineage, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index c30562de991..bff808f6c50 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1317,6 +1317,15 @@ diesel::table! { entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, + #[max_length = 64] + email_primary_color -> Varchar, + #[max_length = 64] + email_foreground_color -> Varchar, + #[max_length = 64] + email_background_color -> Varchar, + #[max_length = 64] + email_entity_name -> Varchar, + email_entity_logo_url -> Text, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 12bb19c0a7f..211df46e7ac 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1264,6 +1264,15 @@ diesel::table! { entity_type -> Varchar, #[max_length = 64] theme_name -> Varchar, + #[max_length = 64] + email_primary_color -> Varchar, + #[max_length = 64] + email_foreground_color -> Varchar, + #[max_length = 64] + email_background_color -> Varchar, + #[max_length = 64] + email_entity_name -> Varchar, + email_entity_logo_url -> Text, } } diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs index e43a182126b..46cc90a45ec 100644 --- a/crates/diesel_models/src/user/theme.rs +++ b/crates/diesel_models/src/user/theme.rs @@ -1,5 +1,8 @@ use common_enums::EntityType; -use common_utils::{date_time, id_type, types::theme::ThemeLineage}; +use common_utils::{ + date_time, id_type, + types::theme::{EmailThemeConfig, ThemeLineage}, +}; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; @@ -17,6 +20,11 @@ pub struct Theme { pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, + pub email_primary_color: String, + pub email_foreground_color: String, + pub email_background_color: String, + pub email_entity_name: String, + pub email_entity_logo_url: String, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -31,10 +39,20 @@ pub struct ThemeNew { pub last_modified_at: PrimitiveDateTime, pub entity_type: EntityType, pub theme_name: String, + pub email_primary_color: String, + pub email_foreground_color: String, + pub email_background_color: String, + pub email_entity_name: String, + pub email_entity_logo_url: String, } impl ThemeNew { - pub fn new(theme_id: String, theme_name: String, lineage: ThemeLineage) -> Self { + pub fn new( + theme_id: String, + theme_name: String, + lineage: ThemeLineage, + email_config: EmailThemeConfig, + ) -> Self { let now = date_time::now(); Self { @@ -47,6 +65,23 @@ impl ThemeNew { entity_type: lineage.entity_type(), created_at: now, last_modified_at: now, + email_primary_color: email_config.primary_color, + email_foreground_color: email_config.foreground_color, + email_background_color: email_config.background_color, + email_entity_name: email_config.entity_name, + email_entity_logo_url: email_config.entity_logo_url, + } + } +} + +impl Theme { + pub fn email_config(&self) -> EmailThemeConfig { + EmailThemeConfig { + primary_color: self.email_primary_color.clone(), + foreground_color: self.email_foreground_color.clone(), + background_color: self.email_background_color.clone(), + entity_name: self.email_entity_name.clone(), + entity_logo_url: self.email_entity_logo_url.clone(), } } } diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index 3ab56266b55..3862f70536f 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -545,6 +545,6 @@ pub(crate) async fn fetch_raw_secrets( .network_tokenization_supported_card_networks, network_tokenization_service, network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors, - theme_storage: conf.theme_storage, + theme: conf.theme, } } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 1da4a33f5f3..4ab2a8fd5c7 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, id_type}; +use common_utils::{ext_traits::ConfigExt, id_type, types::theme::EmailThemeConfig}; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] @@ -128,7 +128,7 @@ pub struct Settings<S: SecretState> { pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks, pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>, pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors, - pub theme_storage: FileStorageConfig, + pub theme: ThemeSettings, } #[derive(Debug, Deserialize, Clone, Default)] @@ -887,7 +887,8 @@ impl Settings<SecuredSecret> { .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; - self.theme_storage + self.theme + .storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; @@ -992,6 +993,12 @@ impl Default for CellInformation { } } +#[derive(Debug, Deserialize, Clone, Default)] +pub struct ThemeSettings { + pub storage: FileStorageConfig, + pub email_config: EmailThemeConfig, +} + fn deserialize_hashmap_inner<K, V>( value: HashMap<String, String>, ) -> Result<HashMap<K, HashSet<V>>, String> diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs index 33477df6330..fa5f185ab82 100644 --- a/crates/router/src/core/errors/user.rs +++ b/crates/router/src/core/errors/user.rs @@ -106,6 +106,8 @@ pub enum UserErrors { ThemeAlreadyExists, #[error("Invalid field: {0} in lineage")] InvalidThemeLineage(String), + #[error("Missing required field: email_config")] + MissingEmailConfig, } impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors { @@ -275,6 +277,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon Self::InvalidThemeLineage(_) => { AER::BadRequest(ApiError::new(sub_code, 55, self.get_error_message(), None)) } + Self::MissingEmailConfig => { + AER::BadRequest(ApiError::new(sub_code, 56, self.get_error_message(), None)) + } } } } @@ -341,6 +346,7 @@ impl UserErrors { Self::InvalidThemeLineage(field_name) => { format!("Invalid field: {} in lineage", field_name) } + Self::MissingEmailConfig => "Missing required field: email_config".to_string(), } } } diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs index 13cf4c488ec..c2f289d4cc0 100644 --- a/crates/router/src/core/recon.rs +++ b/crates/router/src/core/recon.rs @@ -1,12 +1,14 @@ use api_models::recon as recon_api; #[cfg(feature = "email")] -use common_utils::ext_traits::AsyncExt; +use common_utils::{ext_traits::AsyncExt, types::theme::ThemeLineage}; use error_stack::ResultExt; #[cfg(feature = "email")] use masking::{ExposeInterface, PeekInterface, Secret}; #[cfg(feature = "email")] -use crate::{consts, services::email::types as email_types, types::domain}; +use crate::{ + consts, services::email::types as email_types, types::domain, utils::user::theme as theme_utils, +}; use crate::{ core::errors::{self, RouterResponse, UserErrors, UserResponse}, services::{api as service_api, authentication}, @@ -35,6 +37,21 @@ pub async fn send_recon_request( let user_in_db = &auth_data.user; let merchant_id = auth_data.merchant_account.get_id().clone(); + let theme = theme_utils::get_most_specific_theme_using_lineage( + &state.clone(), + ThemeLineage::Merchant { + tenant_id: state.tenant.tenant_id.clone(), + org_id: auth_data.merchant_account.get_org_id().clone(), + merchant_id: merchant_id.clone(), + }, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable(format!( + "Failed to fetch theme for merchant_id = {:?}", + merchant_id + ))?; + let user_email = user_in_db.email.clone(); let email_contents = email_types::ProFeatureRequest { feature_name: consts::RECON_FEATURE_TAG.to_string(), @@ -55,6 +72,10 @@ pub async fn send_recon_request( consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST, user_email.expose().peek() ), + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; state .email_client @@ -141,7 +162,7 @@ pub async fn recon_merchant_account_update( let updated_merchant_account = db .update_merchant( key_manager_state, - auth.merchant_account, + auth.merchant_account.clone(), updated_merchant_account, &auth.key_store, ) @@ -154,6 +175,22 @@ pub async fn recon_merchant_account_update( #[cfg(feature = "email")] { let user_email = &req.user_email.clone(); + + let theme = theme_utils::get_most_specific_theme_using_lineage( + &state.clone(), + ThemeLineage::Merchant { + tenant_id: state.tenant.tenant_id, + org_id: auth.merchant_account.get_org_id().clone(), + merchant_id: merchant_id.clone(), + }, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable(format!( + "Failed to fetch theme for merchant_id = {:?}", + merchant_id + ))?; + let email_contents = email_types::ReconActivation { recipient_email: domain::UserEmail::from_pii_email(user_email.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) @@ -164,6 +201,10 @@ pub async fn recon_merchant_account_update( .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to form username")?, subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST, + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; if req.recon_status == enums::ReconStatus::Active { let _ = state diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 629476b2591..642473bdf8e 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -42,7 +42,10 @@ use crate::{ routes::{app::ReqState, SessionState}, services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse}, types::{domain, transformers::ForeignInto}, - utils::{self, user::two_factor_auth as tfa_utils}, + utils::{ + self, + user::{theme as theme_utils, two_factor_auth as tfa_utils}, + }, }; pub mod dashboard_metadata; @@ -55,6 +58,7 @@ pub async fn signup_with_merchant_id( state: SessionState, request: user_api::SignUpWithMerchantIdRequest, auth_id: Option<String>, + theme_id: Option<String>, ) -> UserResponse<user_api::SignUpWithMerchantIdResponse> { let new_user = domain::NewUser::try_from(request.clone())?; new_user @@ -75,12 +79,18 @@ pub async fn signup_with_merchant_id( ) .await?; + let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; + let email_contents = email_types::ResetPassword { recipient_email: user_from_db.get_email().try_into()?, user_name: domain::UserName::new(user_from_db.get_name())?, settings: state.conf.clone(), subject: consts::user::EMAIL_SUBJECT_RESET_PASSWORD, auth_id, + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state @@ -112,6 +122,13 @@ pub async fn get_user_details( .await .change_context(UserErrors::InternalServerError)?; + let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( + &state, + &user_from_token, + EntityType::Profile, + ) + .await?; + Ok(ApplicationResponse::Json( user_api::GetUserDetailsResponse { merchant_id: user_from_token.merchant_id, @@ -125,6 +142,7 @@ pub async fn get_user_details( recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()), profile_id: user_from_token.profile_id, entity_type: role_info.get_entity_type(), + theme_id: theme.map(|theme| theme.theme_id), }, )) } @@ -194,6 +212,7 @@ pub async fn connect_account( state: SessionState, request: user_api::ConnectAccountRequest, auth_id: Option<String>, + theme_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { let find_user = state .global_store @@ -203,12 +222,18 @@ pub async fn connect_account( if let Ok(found_user) = find_user { let user_from_db: domain::UserFromStorage = found_user.into(); + let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; + let email_contents = email_types::MagicLink { 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: consts::user::EMAIL_SUBJECT_MAGIC_LINK, auth_id, + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state @@ -253,11 +278,17 @@ pub async fn connect_account( ) .await?; + let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; + let magic_link_email = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), subject: consts::user::EMAIL_SUBJECT_SIGNUP, auth_id, + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; let magic_link_result = state @@ -270,20 +301,22 @@ pub async fn connect_account( logger::info!(?magic_link_result); - let welcome_to_community_email = email_types::WelcomeToCommunity { - recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, - subject: consts::user::EMAIL_SUBJECT_WELCOME_TO_COMMUNITY, - }; + if state.tenant.tenant_id.get_string_repr() == common_utils::consts::DEFAULT_TENANT { + let welcome_to_community_email = email_types::WelcomeToCommunity { + recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, + subject: consts::user::EMAIL_SUBJECT_WELCOME_TO_COMMUNITY, + }; - let welcome_email_result = state - .email_client - .compose_and_send_email( - Box::new(welcome_to_community_email), - state.conf.proxy.https_url.as_ref(), - ) - .await; + let welcome_email_result = state + .email_client + .compose_and_send_email( + Box::new(welcome_to_community_email), + state.conf.proxy.https_url.as_ref(), + ) + .await; - logger::info!(?welcome_email_result); + logger::info!(?welcome_email_result); + } return Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { @@ -371,6 +404,7 @@ pub async fn forgot_password( state: SessionState, request: user_api::ForgotPasswordRequest, auth_id: Option<String>, + theme_id: Option<String>, ) -> UserResponse<()> { let user_email = domain::UserEmail::from_pii_email(request.email)?; @@ -387,12 +421,18 @@ pub async fn forgot_password( }) .map(domain::UserFromStorage::from)?; + let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; + let email_contents = email_types::ResetPassword { 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: consts::user::EMAIL_SUBJECT_RESET_PASSWORD, auth_id, + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; state @@ -782,6 +822,13 @@ async fn handle_existing_user_invitation( }, }; + let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( + state, + user_from_token, + role_info.get_entity_type(), + ) + .await?; + let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(invitee_user_from_db.get_name())?, @@ -789,6 +836,10 @@ async fn handle_existing_user_invitation( subject: consts::user::EMAIL_SUBJECT_INVITATION, entity, auth_id: auth_id.clone(), + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; is_email_sent = state @@ -927,6 +978,13 @@ async fn handle_new_user_invitation( }, }; + let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( + state, + user_from_token, + role_info.get_entity_type(), + ) + .await?; + let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(new_user.get_name())?, @@ -934,6 +992,10 @@ async fn handle_new_user_invitation( subject: consts::user::EMAIL_SUBJECT_INVITATION, entity, auth_id: auth_id.clone(), + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; let send_email_result = state .email_client @@ -1055,6 +1117,21 @@ pub async fn resend_invite( .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; + let invitee_role_info = roles::RoleInfo::from_role_id_and_org_id( + &state, + &user_role.role_id, + &user_from_token.org_id, + ) + .await + .change_context(UserErrors::InternalServerError)?; + + let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( + &state, + &user_from_token, + invitee_role_info.get_entity_type(), + ) + .await?; + let email_contents = email_types::InviteUser { recipient_email: invitee_email, user_name: domain::UserName::new(user.get_name())?, @@ -1065,6 +1142,10 @@ pub async fn resend_invite( entity_type, }, auth_id: auth_id.clone(), + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; state @@ -1666,6 +1747,7 @@ pub async fn send_verification_mail( state: SessionState, req: user_api::SendVerifyEmailRequest, auth_id: Option<String>, + theme_id: Option<String>, ) -> UserResponse<()> { let user_email = domain::UserEmail::try_from(req.email)?; let user = state @@ -1684,11 +1766,17 @@ pub async fn send_verification_mail( return Err(UserErrors::UserAlreadyVerified.into()); } + let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?; + let email_contents = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user.email)?, settings: state.conf.clone(), subject: consts::user::EMAIL_SUBJECT_SIGNUP, auth_id, + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; state diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index a64b0f39dc0..88380363b4e 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -1,4 +1,6 @@ use api_models::user::dashboard_metadata::{self as api, GetMultipleMetaDataPayload}; +#[cfg(feature = "email")] +use common_enums::EntityType; use diesel_models::{ enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata, }; @@ -8,8 +10,6 @@ use masking::ExposeInterface; #[cfg(feature = "email")] use router_env::logger; -#[cfg(feature = "email")] -use crate::services::email::types as email_types; use crate::{ core::errors::{UserErrors, UserResponse, UserResult}, routes::{app::ReqState, SessionState}, @@ -17,6 +17,8 @@ use crate::{ types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore}, utils::user::dashboard_metadata as utils, }; +#[cfg(feature = "email")] +use crate::{services::email::types as email_types, utils::user::theme as theme_utils}; pub async fn set_metadata( state: SessionState, @@ -476,7 +478,21 @@ async fn insert_metadata( .expose(); if utils::is_prod_email_required(&data, user_email) { - let email_contents = email_types::BizEmailProd::new(state, data)?; + let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity( + state, + &user, + EntityType::Merchant, + ) + .await?; + + let email_contents = email_types::BizEmailProd::new( + state, + data, + theme.as_ref().map(|theme| theme.theme_id.clone()), + theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), + )?; let send_email_result = state .email_client .compose_and_send_email( diff --git a/crates/router/src/core/user/theme.rs b/crates/router/src/core/user/theme.rs index dbf11256a50..27b342d9053 100644 --- a/crates/router/src/core/user/theme.rs +++ b/crates/router/src/core/user/theme.rs @@ -38,6 +38,7 @@ pub async fn get_theme_using_lineage( .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json(theme_api::GetThemeResponse { + email_config: theme.email_config(), theme_id: theme.theme_id, theme_name: theme.theme_name, entity_type: theme.entity_type, @@ -71,6 +72,7 @@ pub async fn get_theme_using_theme_id( .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json(theme_api::GetThemeResponse { + email_config: theme.email_config(), theme_id: theme.theme_id, theme_name: theme.theme_name, entity_type: theme.entity_type, @@ -113,10 +115,19 @@ pub async fn create_theme( ) -> UserResponse<theme_api::GetThemeResponse> { theme_utils::validate_lineage(&state, &request.lineage).await?; + let email_config = if cfg!(feature = "email") { + request.email_config.ok_or(UserErrors::MissingEmailConfig)? + } else { + request + .email_config + .unwrap_or(state.conf.theme.email_config.clone()) + }; + let new_theme = ThemeNew::new( Uuid::new_v4().to_string(), request.theme_name, request.lineage, + email_config, ); let db_theme = state @@ -147,6 +158,7 @@ pub async fn create_theme( .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json(theme_api::GetThemeResponse { + email_config: db_theme.email_config(), theme_id: db_theme.theme_id, entity_type: db_theme.entity_type, tenant_id: db_theme.tenant_id, @@ -195,6 +207,7 @@ pub async fn update_theme( .change_context(UserErrors::InternalServerError)?; Ok(ApplicationResponse::Json(theme_api::GetThemeResponse { + email_config: db_theme.email_config(), theme_id: db_theme.theme_id, entity_type: db_theme.entity_type, tenant_id: db_theme.tenant_id, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 2fd30a3610b..a7e71284aaf 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3755,6 +3755,15 @@ impl ThemeInterface for KafkaStore { self.diesel_store.find_theme_by_theme_id(theme_id).await } + async fn find_most_specific_theme_in_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<diesel_models::user::theme::Theme, errors::StorageError> { + self.diesel_store + .find_most_specific_theme_in_lineage(lineage) + .await + } + async fn find_theme_by_lineage( &self, lineage: ThemeLineage, diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs index 9b55a98d0ad..51c0a52b3a0 100644 --- a/crates/router/src/db/user/theme.rs +++ b/crates/router/src/db/user/theme.rs @@ -21,6 +21,11 @@ pub trait ThemeInterface { theme_id: String, ) -> CustomResult<storage::Theme, errors::StorageError>; + async fn find_most_specific_theme_in_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError>; + async fn find_theme_by_lineage( &self, lineage: ThemeLineage, @@ -56,6 +61,16 @@ impl ThemeInterface for Store { .map_err(|error| report!(errors::StorageError::from(error))) } + async fn find_most_specific_theme_in_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Theme::find_most_specific_theme_in_lineage(&conn, lineage) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + async fn find_theme_by_lineage( &self, lineage: ThemeLineage, @@ -80,13 +95,12 @@ impl ThemeInterface for Store { fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { match lineage { - // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType - // ThemeLineage::Tenant { tenant_id } => { - // &theme.tenant_id == tenant_id - // && theme.org_id.is_none() - // && theme.merchant_id.is_none() - // && theme.profile_id.is_none() - // } + ThemeLineage::Tenant { tenant_id } => { + &theme.tenant_id == tenant_id + && theme.org_id.is_none() + && theme.merchant_id.is_none() + && theme.profile_id.is_none() + } ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme @@ -174,6 +188,11 @@ impl ThemeInterface for MockDb { last_modified_at: new_theme.last_modified_at, entity_type: new_theme.entity_type, theme_name: new_theme.theme_name, + email_primary_color: new_theme.email_primary_color, + email_foreground_color: new_theme.email_foreground_color, + email_background_color: new_theme.email_background_color, + email_entity_name: new_theme.email_entity_name, + email_entity_logo_url: new_theme.email_entity_logo_url, }; themes.push(theme.clone()); @@ -198,6 +217,27 @@ impl ThemeInterface for MockDb { ) } + async fn find_most_specific_theme_in_lineage( + &self, + lineage: ThemeLineage, + ) -> CustomResult<storage::Theme, errors::StorageError> { + let themes = self.themes.lock().await; + let lineages = lineage.get_same_and_higher_lineages(); + + themes + .iter() + .filter(|theme| { + lineages + .iter() + .any(|lineage| check_theme_with_lineage(theme, lineage)) + }) + .min_by_key(|theme| theme.entity_type) + .ok_or( + errors::StorageError::ValueNotFound("No theme found in lineage".to_string()).into(), + ) + .cloned() + } + async fn find_theme_by_lineage( &self, lineage: ThemeLineage, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index ca7c4847ad4..5f04581fbb3 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -369,7 +369,7 @@ impl AppState { let email_client = Arc::new(create_email_client(&conf).await); let file_storage_client = conf.file_storage.get_file_storage_client().await; - let theme_storage_client = conf.theme_storage.get_file_storage_client().await; + let theme_storage_client = conf.theme.storage.get_file_storage_client().await; let grpc_client = conf.grpc_client.get_grpc_client_interface().await; diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index c32746c8718..d075048ddb6 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -41,18 +41,23 @@ pub async fn user_signup_with_merchant_id( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SignUpWithMerchantIdRequest>, - query: web::Query<user_api::AuthIdQueryParam>, + query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::UserSignUpWithMerchantId; let req_payload = json_payload.into_inner(); - let auth_id = query.into_inner().auth_id; + let query_params = query.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), |state, _, req_body, _| { - user_core::signup_with_merchant_id(state, req_body, auth_id.clone()) + user_core::signup_with_merchant_id( + state, + req_body, + query_params.auth_id.clone(), + query_params.theme_id.clone(), + ) }, &auth::AdminApiAuth, api_locking::LockAction::NotApplicable, @@ -107,17 +112,24 @@ pub async fn user_connect_account( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::ConnectAccountRequest>, - query: web::Query<user_api::AuthIdQueryParam>, + query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::UserConnectAccount; let req_payload = json_payload.into_inner(); - let auth_id = query.into_inner().auth_id; + let query_params = query.into_inner(); Box::pin(api::server_wrap( flow.clone(), state, &http_req, req_payload.clone(), - |state, _: (), req_body, _| user_core::connect_account(state, req_body, auth_id.clone()), + |state, _: (), req_body, _| { + user_core::connect_account( + state, + req_body, + query_params.auth_id.clone(), + query_params.theme_id.clone(), + ) + }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -381,16 +393,23 @@ pub async fn forgot_password( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ForgotPasswordRequest>, - query: web::Query<user_api::AuthIdQueryParam>, + query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::ForgotPassword; - let auth_id = query.into_inner().auth_id; + let query_params = query.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &req, payload.into_inner(), - |state, _: (), payload, _| user_core::forgot_password(state, payload, auth_id.clone()), + |state, _: (), payload, _| { + user_core::forgot_password( + state, + payload, + query_params.auth_id.clone(), + query_params.theme_id.clone(), + ) + }, &auth::NoAuth, api_locking::LockAction::NotApplicable, )) @@ -420,7 +439,7 @@ pub async fn invite_multiple_user( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<Vec<user_api::InviteUserRequest>>, - auth_id_query_param: web::Query<user_api::AuthIdQueryParam>, + auth_id_query_param: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::InviteMultipleUser; let auth_id = auth_id_query_param.into_inner().auth_id; @@ -445,7 +464,7 @@ pub async fn resend_invite( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<user_api::ReInviteUserRequest>, - query: web::Query<user_api::AuthIdQueryParam>, + query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::ReInviteUser; let auth_id = query.into_inner().auth_id; @@ -512,17 +531,22 @@ pub async fn verify_email_request( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::SendVerifyEmailRequest>, - query: web::Query<user_api::AuthIdQueryParam>, + query: web::Query<user_api::AuthIdAndThemeIdQueryParam>, ) -> HttpResponse { let flow = Flow::VerifyEmailRequest; - let auth_id = query.into_inner().auth_id; + let query_params = query.into_inner(); Box::pin(api::server_wrap( flow, state.clone(), &http_req, json_payload.into_inner(), |state, _: (), req_body, _| { - user_core::send_verification_mail(state, req_body, auth_id.clone()) + user_core::send_verification_mail( + state, + req_body, + query_params.auth_id.clone(), + query_params.theme_id.clone(), + ) }, &auth::NoAuth, api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 66e730f0824..128250a61aa 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,6 +1,6 @@ use api_models::user::dashboard_metadata::ProdIntent; use common_enums::EntityType; -use common_utils::{errors::CustomResult, pii}; +use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; use masking::{ExposeInterface, Secret}; @@ -212,13 +212,17 @@ pub fn get_link_with_token( token: impl std::fmt::Display, action: impl std::fmt::Display, auth_id: &Option<impl std::fmt::Display>, + theme_id: &Option<impl std::fmt::Display>, ) -> String { - let email_url = format!("{base_url}/user/{action}?token={token}"); + let mut email_url = format!("{base_url}/user/{action}?token={token}"); if let Some(auth_id) = auth_id { - format!("{email_url}&auth_id={auth_id}") - } else { - email_url + email_url = format!("{email_url}&auth_id={auth_id}"); } + if let Some(theme_id) = theme_id { + email_url = format!("{email_url}&theme_id={theme_id}"); + } + + email_url } pub struct VerifyEmail { @@ -226,6 +230,8 @@ pub struct VerifyEmail { pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, pub auth_id: Option<String>, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } /// Currently only HTML is supported @@ -246,6 +252,7 @@ impl EmailData for VerifyEmail { token, "verify_email", &self.auth_id, + &self.theme_id, ); let body = html::get_html_body(EmailBody::Verify { @@ -266,6 +273,8 @@ pub struct ResetPassword { pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, pub auth_id: Option<String>, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] @@ -285,6 +294,7 @@ impl EmailData for ResetPassword { token, "set_password", &self.auth_id, + &self.theme_id, ); let body = html::get_html_body(EmailBody::Reset { @@ -306,6 +316,8 @@ pub struct MagicLink { pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, pub auth_id: Option<String>, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] @@ -325,6 +337,7 @@ impl EmailData for MagicLink { token, "verify_email", &self.auth_id, + &self.theme_id, ); let body = html::get_html_body(EmailBody::MagicLink { @@ -347,6 +360,8 @@ pub struct InviteUser { pub subject: &'static str, pub entity: Entity, pub auth_id: Option<String>, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] @@ -366,6 +381,7 @@ impl EmailData for InviteUser { token, "accept_invite_from_email", &self.auth_id, + &self.theme_id, ); let body = html::get_html_body(EmailBody::AcceptInviteFromEmail { link: invite_user_link, @@ -384,6 +400,8 @@ pub struct ReconActivation { pub recipient_email: domain::UserEmail, pub user_name: domain::UserName, pub subject: &'static str, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] @@ -410,10 +428,17 @@ pub struct BizEmailProd { pub business_website: String, pub settings: std::sync::Arc<configs::Settings>, pub subject: &'static str, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } impl BizEmailProd { - pub fn new(state: &SessionState, data: ProdIntent) -> UserResult<Self> { + pub fn new( + state: &SessionState, + data: ProdIntent, + theme_id: Option<String>, + theme_config: EmailThemeConfig, + ) -> UserResult<Self> { Ok(Self { recipient_email: domain::UserEmail::from_pii_email( state.conf.email.prod_intent_recipient_email.clone(), @@ -428,6 +453,8 @@ impl BizEmailProd { .unwrap_or(common_enums::CountryAlpha2::AD) .to_string(), business_website: data.business_website.unwrap_or_default(), + theme_id, + theme_config, }) } } @@ -458,6 +485,8 @@ pub struct ProFeatureRequest { pub user_name: domain::UserName, pub user_email: domain::UserEmail, pub subject: String, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] @@ -486,6 +515,8 @@ pub struct ApiKeyExpiryReminder { pub expires_in: u8, pub api_key_name: String, pub prefix: String, + pub theme_id: Option<String>, + pub theme_config: EmailThemeConfig, } #[async_trait::async_trait] diff --git a/crates/router/src/utils/user/theme.rs b/crates/router/src/utils/user/theme.rs index 13452380d9d..1c8b76989ae 100644 --- a/crates/router/src/utils/user/theme.rs +++ b/crates/router/src/utils/user/theme.rs @@ -1,12 +1,15 @@ use std::path::PathBuf; -use common_utils::{id_type, types::theme::ThemeLineage}; +use common_enums::EntityType; +use common_utils::{ext_traits::AsyncExt, id_type, types::theme::ThemeLineage}; +use diesel_models::user::theme::Theme; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use crate::{ core::errors::{StorageErrorExt, UserErrors, UserResult}, routes::SessionState, + services::authentication::UserFromToken, }; fn get_theme_dir_key(theme_id: &str) -> PathBuf { @@ -54,6 +57,10 @@ pub async fn upload_file_to_theme_bucket( pub async fn validate_lineage(state: &SessionState, lineage: &ThemeLineage) -> UserResult<()> { match lineage { + ThemeLineage::Tenant { tenant_id } => { + validate_tenant(state, tenant_id)?; + Ok(()) + } ThemeLineage::Organization { tenant_id, org_id } => { validate_tenant(state, tenant_id)?; validate_org(state, org_id).await?; @@ -96,8 +103,8 @@ async fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> .store .find_organization_by_org_id(org_id) .await - .to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string()))?; - Ok(()) + .to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string())) + .map(|_| ()) } async fn validate_merchant_and_get_key_store( @@ -153,6 +160,67 @@ async fn validate_profile( profile_id, ) .await - .to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string()))?; - Ok(()) + .to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string())) + .map(|_| ()) +} + +pub async fn get_most_specific_theme_using_token_and_min_entity( + state: &SessionState, + user_from_token: &UserFromToken, + min_entity: EntityType, +) -> UserResult<Option<Theme>> { + get_most_specific_theme_using_lineage( + state, + ThemeLineage::new( + min_entity, + user_from_token + .tenant_id + .clone() + .unwrap_or(state.tenant.tenant_id.clone()), + user_from_token.org_id.clone(), + user_from_token.merchant_id.clone(), + user_from_token.profile_id.clone(), + ), + ) + .await +} + +pub async fn get_most_specific_theme_using_lineage( + state: &SessionState, + lineage: ThemeLineage, +) -> UserResult<Option<Theme>> { + match state + .global_store + .find_most_specific_theme_in_lineage(lineage) + .await + { + Ok(theme) => Ok(Some(theme)), + Err(e) => { + if e.current_context().is_db_not_found() { + Ok(None) + } else { + Err(e.change_context(UserErrors::InternalServerError)) + } + } + } +} + +pub async fn get_theme_using_optional_theme_id( + state: &SessionState, + theme_id: Option<String>, +) -> UserResult<Option<Theme>> { + match theme_id + .async_map(|theme_id| state.global_store.find_theme_by_theme_id(theme_id)) + .await + .transpose() + { + Ok(theme) => Ok(theme), + Err(e) => { + if e.current_context().is_db_not_found() { + Ok(None) + } else { + Err(e.change_context(UserErrors::InternalServerError)) + } + } + } } diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index bf6100179bf..cdc4959c456 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -1,4 +1,4 @@ -use common_utils::{errors::ValidationError, ext_traits::ValueExt}; +use common_utils::{errors::ValidationError, ext_traits::ValueExt, types::theme::ThemeLineage}; use diesel_models::{ enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData, }; @@ -11,7 +11,7 @@ use crate::{ routes::{metrics, SessionState}, services::email::types::ApiKeyExpiryReminder, types::{api, domain::UserEmail, storage}, - utils::OptionExt, + utils::{user::theme as theme_utils, OptionExt}, }; pub struct ApiKeyExpiryWorkflow; @@ -48,6 +48,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { let email_id = merchant_account .merchant_details + .clone() .parse_value::<api::MerchantDetails>("MerchantDetails")? .primary_email .ok_or(errors::ProcessTrackerError::EValidationError( @@ -73,6 +74,20 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { ) .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; + let theme = theme_utils::get_most_specific_theme_using_lineage( + state, + ThemeLineage::Merchant { + tenant_id: state.tenant.tenant_id.clone(), + org_id: merchant_account.get_org_id().clone(), + merchant_id: merchant_account.get_id().clone(), + }, + ) + .await + .map_err(|err| { + logger::error!(?err, "Failed to get theme"); + errors::ProcessTrackerError::EApiErrorResponse + })?; + let email_contents = ApiKeyExpiryReminder { recipient_email: UserEmail::from_pii_email(email_id).map_err(|error| { logger::error!( @@ -85,6 +100,10 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow { expires_in: *expires_in, api_key_name, prefix, + theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()), + theme_config: theme + .map(|theme| theme.email_config()) + .unwrap_or(state.conf.theme.email_config.clone()), }; state diff --git a/migrations/2024-12-05-131123_add-email-theme-data-in-themes/down.sql b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/down.sql new file mode 100644 index 00000000000..34732b5dd69 --- /dev/null +++ b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/down.sql @@ -0,0 +1,6 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE themes DROP COLUMN IF EXISTS email_primary_color; +ALTER TABLE themes DROP COLUMN IF EXISTS email_foreground_color; +ALTER TABLE themes DROP COLUMN IF EXISTS email_background_color; +ALTER TABLE themes DROP COLUMN IF EXISTS email_entity_name; +ALTER TABLE themes DROP COLUMN IF EXISTS email_entity_logo_url; diff --git a/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql new file mode 100644 index 00000000000..1004302ab7f --- /dev/null +++ b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_primary_color VARCHAR(64) NOT NULL DEFAULT '#006DF9'; +ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_foreground_color VARCHAR(64) NOT NULL DEFAULT '#000000'; +ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_background_color VARCHAR(64) NOT NULL DEFAULT '#FFFFFF'; +ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_name VARCHAR(64) NOT NULL DEFAULT 'Hyperswitch'; +ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_logo_url TEXT NOT NULL DEFAULT 'https://app.hyperswitch.io/email-assets/HyperswitchLogo.png';
2024-12-06T14:42:13Z
## 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 will introduce theme context in user APIs and email related APIs. - The User APIs which are affected are 1. User Info 2. Invite 3. Resend Invite 4. Reset Password 5. Connect Account 6. Signup with merchant id - Non User flows 1. Request for Recon 2. Recon merchant update 3. API Key expiry reminder ### Additional Changes - [x] This PR modifies the API contract - [x] 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` 4. `crates/router/src/configs` 5. `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 #6780 ## 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. User Info API will send `theme_id` in the response if a theme exists in your lineage. ``` curl --location 'http://localhost:8080/user' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMzAwMjAwN2UtZWE3NC00NzVlLWJmNWQtMzYxNzIwNTk4YzA3IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzMzNDkyMzU3Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMzY2NTMzOSwib3JnX2lkIjoib3JnX3Z5VDVDb3BEdnpPT3g5V211TTdMIiwicHJvZmlsZV9pZCI6InByb180cHE4ZVVFREJDc1YyaDN5Mk9iSSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.YsKkaY8aFDWz_1CLrZEZWNxmO2rSCk-yTe77OmHP_ZE' ``` ```json { "merchant_id": "merchant_1733492357", "name": "name", "email": "email", "verification_days_left": null, "role_id": "org_admin", "org_id": "org_vyT5CopDvzOOx9WmuM7L", "is_two_factor_auth_setup": false, "recovery_codes_left": null, "profile_id": "pro_4pq8eUEDBCsV2h3y2ObI", "entity_type": "organization", "theme_id": "7792a4e5-bd7c-498d-8478-c4e0a9a0a984" } ``` 2. All the other user specific APIs mentioned above will have `theme_id` in the return URL and also accept `theme_id` in the request. 3. Other flows will reflect the email themes once the email templates are changed to use the theme 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
08ab3ad7a2e60bc35332be606941793bc6a8a32f
juspay/hyperswitch
juspay__hyperswitch-6828
Bug: [FEATURE] Contract Routing Integration ### Feature Description Integration of Contract based routing in Router ### Possible Implementation Need to build interface, perform core integration and populate metrics for contract routing ### 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/events/routing.rs b/crates/api_models/src/events/routing.rs index f3e169336bf..122d1f8d3c8 100644 --- a/crates/api_models/src/events/routing.rs +++ b/crates/api_models/src/events/routing.rs @@ -1,12 +1,13 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::routing::{ - LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, - RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, - RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, + ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper, + DynamicRoutingUpdateConfigQuery, LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, + ProfileDefaultRoutingConfig, RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, + RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplitWrapper, - SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, - SuccessBasedRoutingUpdateConfigQuery, ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, + SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingQuery, + ToggleDynamicRoutingWrapper, }; impl ApiEventMetric for RoutingKind { @@ -97,13 +98,25 @@ impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper { } } +impl ApiEventMetric for ContractBasedRoutingPayloadWrapper { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + +impl ApiEventMetric for ContractBasedRoutingSetupPayloadWrapper { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Routing) + } +} + impl ApiEventMetric for ToggleDynamicRoutingWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } -impl ApiEventMetric for SuccessBasedRoutingUpdateConfigQuery { +impl ApiEventMetric for DynamicRoutingUpdateConfigQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 8e502767575..d4b4f76e178 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -513,17 +513,27 @@ pub struct RoutingLinkWrapper { pub algorithm_id: RoutingAlgorithmId, } -#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicAlgorithmWithTimestamp<T> { pub algorithm_id: Option<T>, pub timestamp: i64, } +impl<T> DynamicAlgorithmWithTimestamp<T> { + pub fn new(algorithm_id: Option<T>) -> Self { + Self { + algorithm_id, + timestamp: common_utils::date_time::now_unix_timestamp(), + } + } +} + #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicRoutingAlgorithmRef { pub success_based_algorithm: Option<SuccessBasedAlgorithm>, pub dynamic_routing_volume_split: Option<u8>, pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>, + pub contract_based_routing: Option<ContractRoutingAlgorithm>, } pub trait DynamicRoutingAlgoAccessor { @@ -555,6 +565,43 @@ impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm { } } +impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm { + fn get_algorithm_id_with_timestamp( + self, + ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { + self.algorithm_id_with_timestamp + } + fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { + &mut self.enabled_feature + } +} + +impl EliminationRoutingAlgorithm { + pub fn new( + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< + common_utils::id_type::RoutingId, + >, + ) -> Self { + Self { + algorithm_id_with_timestamp, + enabled_feature: DynamicRoutingFeatures::None, + } + } +} + +impl SuccessBasedAlgorithm { + pub fn new( + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< + common_utils::id_type::RoutingId, + >, + ) -> Self { + Self { + algorithm_id_with_timestamp, + enabled_feature: DynamicRoutingFeatures::None, + } + } +} + impl DynamicRoutingAlgorithmRef { pub fn update(&mut self, new: Self) { if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm { @@ -563,9 +610,12 @@ impl DynamicRoutingAlgorithmRef { if let Some(success_based_algorithm) = new.success_based_algorithm { self.success_based_algorithm = Some(success_based_algorithm) } + if let Some(contract_based_routing) = new.contract_based_routing { + self.contract_based_routing = Some(contract_based_routing) + } } - pub fn update_specific_ref( + pub fn update_enabled_features( &mut self, algo_type: DynamicRoutingType, feature_to_enable: DynamicRoutingFeatures, @@ -581,6 +631,11 @@ impl DynamicRoutingAlgorithmRef { .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } + DynamicRoutingType::ContractBasedRouting => { + self.contract_based_routing + .as_mut() + .map(|algo| algo.enabled_feature = feature_to_enable); + } } } @@ -589,32 +644,6 @@ impl DynamicRoutingAlgorithmRef { } } -impl EliminationRoutingAlgorithm { - pub fn new( - algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< - common_utils::id_type::RoutingId, - >, - ) -> Self { - Self { - algorithm_id_with_timestamp, - enabled_feature: DynamicRoutingFeatures::None, - } - } -} - -impl SuccessBasedAlgorithm { - pub fn new( - algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< - common_utils::id_type::RoutingId, - >, - ) -> Self { - Self { - algorithm_id_with_timestamp, - enabled_feature: DynamicRoutingFeatures::None, - } - } -} - #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplit { pub routing_type: RoutingType, @@ -648,6 +677,14 @@ pub struct SuccessBasedAlgorithm { pub enabled_feature: DynamicRoutingFeatures, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ContractRoutingAlgorithm { + pub algorithm_id_with_timestamp: + DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, + #[serde(default)] + pub enabled_feature: DynamicRoutingFeatures, +} + #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingAlgorithm { pub algorithm_id_with_timestamp: @@ -678,24 +715,53 @@ impl DynamicRoutingAlgorithmRef { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { - algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp { - algorithm_id: Some(new_id), - timestamp: common_utils::date_time::now_unix_timestamp(), - }, + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { - algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp { - algorithm_id: Some(new_id), - timestamp: common_utils::date_time::now_unix_timestamp(), - }, + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), + enabled_feature, + }) + } + DynamicRoutingType::ContractBasedRouting => { + self.contract_based_routing = Some(ContractRoutingAlgorithm { + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } }; } + + pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) { + match dynamic_routing_type { + DynamicRoutingType::SuccessRateBasedRouting => { + if let Some(success_based_algo) = &self.success_based_algorithm { + self.success_based_algorithm = Some(SuccessBasedAlgorithm { + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), + enabled_feature: success_based_algo.enabled_feature, + }); + } + } + DynamicRoutingType::EliminationRouting => { + if let Some(elimination_based_algo) = &self.elimination_routing_algorithm { + self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), + enabled_feature: elimination_based_algo.enabled_feature, + }); + } + } + DynamicRoutingType::ContractBasedRouting => { + if let Some(contract_based_algo) = &self.contract_based_routing { + self.contract_based_routing = Some(ContractRoutingAlgorithm { + algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), + enabled_feature: contract_based_algo.enabled_feature, + }); + } + } + } + } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] @@ -708,7 +774,9 @@ pub struct DynamicRoutingVolumeSplitQuery { pub split: u8, } -#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] +#[derive( + Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema, +)] #[serde(rename_all = "snake_case")] pub enum DynamicRoutingFeatures { Metrics, @@ -718,7 +786,7 @@ pub enum DynamicRoutingFeatures { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] -pub struct SuccessBasedRoutingUpdateConfigQuery { +pub struct DynamicRoutingUpdateConfigQuery { #[schema(value_type = String)] pub algorithm_id: common_utils::id_type::RoutingId, #[schema(value_type = String)] @@ -827,10 +895,27 @@ pub struct SuccessBasedRoutingPayloadWrapper { pub profile_id: common_utils::id_type::ProfileId, } -#[derive(Debug, Clone, strum::Display, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ContractBasedRoutingPayloadWrapper { + pub updated_config: ContractBasedRoutingConfig, + pub algorithm_id: common_utils::id_type::RoutingId, + pub profile_id: common_utils::id_type::ProfileId, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ContractBasedRoutingSetupPayloadWrapper { + pub config: Option<ContractBasedRoutingConfig>, + pub profile_id: common_utils::id_type::ProfileId, + pub features_to_enable: DynamicRoutingFeatures, +} + +#[derive( + Debug, Clone, Copy, strum::Display, serde::Serialize, serde::Deserialize, PartialEq, Eq, +)] pub enum DynamicRoutingType { SuccessRateBasedRouting, EliminationRouting, + ContractBasedRouting, } impl SuccessBasedRoutingConfig { @@ -872,6 +957,91 @@ impl CurrentBlockThreshold { } } +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct ContractBasedRoutingConfig { + pub config: Option<ContractBasedRoutingConfigBody>, + pub label_info: Option<Vec<LabelInformation>>, +} + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct ContractBasedRoutingConfigBody { + pub constants: Option<Vec<f64>>, + pub time_scale: Option<ContractBasedTimeScale>, +} + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub struct LabelInformation { + pub label: String, + pub target_count: u64, + pub target_time: u64, + #[schema(value_type = String)] + pub mca_id: common_utils::id_type::MerchantConnectorAccountId, +} + +impl LabelInformation { + pub fn update_target_time(&mut self, new: &Self) { + self.target_time = new.target_time; + } + + pub fn update_target_count(&mut self, new: &Self) { + self.target_count = new.target_count; + } +} + +#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] +#[serde(rename_all = "snake_case")] +pub enum ContractBasedTimeScale { + Day, + Month, +} + +impl Default for ContractBasedRoutingConfig { + fn default() -> Self { + Self { + config: Some(ContractBasedRoutingConfigBody { + constants: Some(vec![0.7, 0.35]), + time_scale: Some(ContractBasedTimeScale::Day), + }), + label_info: None, + } + } +} + +impl ContractBasedRoutingConfig { + pub fn update(&mut self, new: Self) { + if let Some(new_config) = new.config { + self.config.as_mut().map(|config| config.update(new_config)); + } + if let Some(new_label_info) = new.label_info { + new_label_info.iter().for_each(|new_label_info| { + if let Some(existing_label_infos) = &mut self.label_info { + for existing_label_info in existing_label_infos { + if existing_label_info.mca_id == new_label_info.mca_id { + existing_label_info.update_target_time(new_label_info); + existing_label_info.update_target_count(new_label_info); + } + } + } else { + self.label_info = Some(vec![new_label_info.clone()]); + } + }); + } + } +} + +impl ContractBasedRoutingConfigBody { + pub fn update(&mut self, new: Self) { + if let Some(new_cons) = new.constants { + self.constants = Some(new_cons) + } + if let Some(new_time_scale) = new.time_scale { + self.time_scale = Some(new_time_scale) + } + } +} #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithBucketName { pub routable_connector_choice: RoutableConnectorChoice, diff --git a/crates/external_services/build.rs b/crates/external_services/build.rs index b3fa1a8fed2..8dba0bb3e98 100644 --- a/crates/external_services/build.rs +++ b/crates/external_services/build.rs @@ -6,6 +6,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { let proto_path = router_env::workspace_path().join("proto"); let success_rate_proto_file = proto_path.join("success_rate.proto"); + let contract_routing_proto_file = proto_path.join("contract_routing.proto"); let elimination_proto_file = proto_path.join("elimination_rate.proto"); let health_check_proto_file = proto_path.join("health_check.proto"); let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR")?); @@ -16,8 +17,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> { .compile( &[ success_rate_proto_file, - elimination_proto_file, health_check_proto_file, + elimination_proto_file, + contract_routing_proto_file, ], &[proto_path], ) diff --git a/crates/external_services/src/grpc_client/dynamic_routing.rs b/crates/external_services/src/grpc_client/dynamic_routing.rs index e5050227fa8..e34f721b30e 100644 --- a/crates/external_services/src/grpc_client/dynamic_routing.rs +++ b/crates/external_services/src/grpc_client/dynamic_routing.rs @@ -1,14 +1,18 @@ +/// Module for Contract based routing +pub mod contract_routing_client; + use std::fmt::Debug; use common_utils::errors::CustomResult; use router_env::logger; use serde; /// Elimination Routing Client Interface Implementation -pub mod elimination_rate_client; +pub mod elimination_based_client; /// Success Routing Client Interface Implementation pub mod success_rate_client; -pub use elimination_rate_client::EliminationAnalyserClient; +pub use contract_routing_client::ContractScoreCalculatorClient; +pub use elimination_based_client::EliminationAnalyserClient; pub use success_rate_client::SuccessRateCalculatorClient; use super::Client; @@ -27,6 +31,10 @@ pub enum DynamicRoutingError { /// Error from Dynamic Routing Server while performing success_rate analysis #[error("Error from Dynamic Routing Server while perfrming success_rate analysis : {0}")] SuccessRateBasedRoutingFailure(String), + + /// Error from Dynamic Routing Server while performing contract based routing + #[error("Error from Dynamic Routing Server while performing contract based routing: {0}")] + ContractBasedRoutingFailure(String), /// Error from Dynamic Routing Server while perfrming elimination #[error("Error from Dynamic Routing Server while perfrming elimination : {0}")] EliminationRateRoutingFailure(String), @@ -37,8 +45,10 @@ pub enum DynamicRoutingError { pub struct RoutingStrategy { /// success rate service for Dynamic Routing pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>, + /// contract based routing service for Dynamic Routing + pub contract_based_client: Option<ContractScoreCalculatorClient<Client>>, /// elimination service for Dynamic Routing - pub elimination_rate_client: Option<EliminationAnalyserClient<Client>>, + pub elimination_based_client: Option<EliminationAnalyserClient<Client>>, } /// Contains the Dynamic Routing Client Config @@ -65,7 +75,7 @@ impl DynamicRoutingClientConfig { self, client: Client, ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> { - let (success_rate_client, elimination_rate_client) = match self { + let (success_rate_client, contract_based_client, elimination_based_client) = match self { Self::Enabled { host, port, .. } => { let uri = format!("http://{}:{}", host, port).parse::<tonic::transport::Uri>()?; logger::info!("Connection established with dynamic routing gRPC Server"); @@ -74,14 +84,19 @@ impl DynamicRoutingClientConfig { client.clone(), uri.clone(), )), + Some(ContractScoreCalculatorClient::with_origin( + client.clone(), + uri.clone(), + )), Some(EliminationAnalyserClient::with_origin(client, uri)), ) } - Self::Disabled => (None, None), + Self::Disabled => (None, None, None), }; Ok(RoutingStrategy { success_rate_client, - elimination_rate_client, + contract_based_client, + elimination_based_client, }) } } diff --git a/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs new file mode 100644 index 00000000000..b210d996bc0 --- /dev/null +++ b/crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs @@ -0,0 +1,192 @@ +use api_models::routing::{ + ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale, + LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus, +}; +use common_utils::{ + ext_traits::OptionExt, + transformers::{ForeignFrom, ForeignTryFrom}, +}; +pub use contract_routing::{ + contract_score_calculator_client::ContractScoreCalculatorClient, CalContractScoreConfig, + CalContractScoreRequest, CalContractScoreResponse, InvalidateContractRequest, + InvalidateContractResponse, LabelInformation as ProtoLabelInfo, TimeScale, + UpdateContractRequest, UpdateContractResponse, +}; +use error_stack::ResultExt; +use router_env::logger; + +use crate::grpc_client::{self, GrpcHeaders}; +#[allow( + missing_docs, + unused_qualifications, + clippy::unwrap_used, + clippy::as_conversions, + clippy::use_self +)] +pub mod contract_routing { + tonic::include_proto!("contract_routing"); +} +use super::{Client, DynamicRoutingError, DynamicRoutingResult}; +/// The trait ContractBasedDynamicRouting would have the functions required to support the calculation and updation window +#[async_trait::async_trait] +pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync { + /// To calculate the contract scores for the list of chosen connectors + async fn calculate_contract_score( + &self, + id: String, + config: ContractBasedRoutingConfig, + params: String, + label_input: Vec<RoutableConnectorChoice>, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<CalContractScoreResponse>; + /// To update the contract scores with the given labels + async fn update_contracts( + &self, + id: String, + label_info: Vec<LabelInformation>, + params: String, + response: Vec<RoutableConnectorChoiceWithStatus>, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<UpdateContractResponse>; + /// To invalidates the contract scores against the id + async fn invalidate_contracts( + &self, + id: String, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<InvalidateContractResponse>; +} + +#[async_trait::async_trait] +impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> { + async fn calculate_contract_score( + &self, + id: String, + config: ContractBasedRoutingConfig, + params: String, + label_input: Vec<RoutableConnectorChoice>, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<CalContractScoreResponse> { + let labels = label_input + .into_iter() + .map(|conn_choice| conn_choice.to_string()) + .collect::<Vec<_>>(); + + let config = config + .config + .map(ForeignTryFrom::foreign_try_from) + .transpose()?; + + let request = grpc_client::create_grpc_request( + CalContractScoreRequest { + id, + params, + labels, + config, + }, + headers, + ); + + let response = self + .clone() + .fetch_contract_score(request) + .await + .change_context(DynamicRoutingError::ContractBasedRoutingFailure( + "Failed to fetch the contract score".to_string(), + ))? + .into_inner(); + + logger::info!(dynamic_routing_response=?response); + + Ok(response) + } + + async fn update_contracts( + &self, + id: String, + label_info: Vec<LabelInformation>, + params: String, + _response: Vec<RoutableConnectorChoiceWithStatus>, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<UpdateContractResponse> { + let labels_information = label_info + .into_iter() + .map(ProtoLabelInfo::foreign_from) + .collect::<Vec<_>>(); + + let request = grpc_client::create_grpc_request( + UpdateContractRequest { + id, + params, + labels_information, + }, + headers, + ); + + let response = self + .clone() + .update_contract(request) + .await + .change_context(DynamicRoutingError::ContractBasedRoutingFailure( + "Failed to update the contracts".to_string(), + ))? + .into_inner(); + + logger::info!(dynamic_routing_response=?response); + + Ok(response) + } + async fn invalidate_contracts( + &self, + id: String, + headers: GrpcHeaders, + ) -> DynamicRoutingResult<InvalidateContractResponse> { + let request = grpc_client::create_grpc_request(InvalidateContractRequest { id }, headers); + + let response = self + .clone() + .invalidate_contract(request) + .await + .change_context(DynamicRoutingError::ContractBasedRoutingFailure( + "Failed to invalidate the contracts".to_string(), + ))? + .into_inner(); + Ok(response) + } +} + +impl ForeignFrom<ContractBasedTimeScale> for TimeScale { + fn foreign_from(scale: ContractBasedTimeScale) -> Self { + Self { + time_scale: match scale { + ContractBasedTimeScale::Day => 0, + _ => 1, + }, + } + } +} + +impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig { + type Error = error_stack::Report<DynamicRoutingError>; + fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> { + Ok(Self { + constants: config + .constants + .get_required_value("constants") + .change_context(DynamicRoutingError::MissingRequiredField { + field: "constants".to_string(), + })?, + time_scale: config.time_scale.clone().map(TimeScale::foreign_from), + }) + } +} + +impl ForeignFrom<LabelInformation> for ProtoLabelInfo { + fn foreign_from(config: LabelInformation) -> Self { + Self { + label: config.label, + target_count: config.target_count, + target_time: config.target_time, + current_count: 1, + } + } +} diff --git a/crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs b/crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs similarity index 100% rename from crates/external_services/src/grpc_client/dynamic_routing/elimination_rate_client.rs rename to crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client.rs diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 7102c23d17e..026eae764c4 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -166,6 +166,8 @@ Never share your secret api keys. Keep them guarded and secure. routes::routing::success_based_routing_update_configs, routes::routing::toggle_success_based_routing, routes::routing::toggle_elimination_routing, + routes::routing::contract_based_routing_setup_config, + routes::routing::contract_based_routing_update_configs, // Routes for blocklist routes::blocklist::remove_entry_from_blocklist, @@ -615,6 +617,10 @@ Never share your secret api keys. Keep them guarded and secure. api_models::routing::DynamicRoutingConfigParams, api_models::routing::CurrentBlockThreshold, api_models::routing::SuccessBasedRoutingConfigBody, + api_models::routing::ContractBasedRoutingConfig, + api_models::routing::ContractBasedRoutingConfigBody, + api_models::routing::LabelInformation, + api_models::routing::ContractBasedTimeScale, api_models::routing::LinkedRoutingConfigRetrieveResponse, api_models::routing::RoutingRetrieveResponse, api_models::routing::ProfileDefaultRoutingConfig, diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index 6b968f80172..c21669a9932 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -292,7 +292,7 @@ pub async fn toggle_success_based_routing() {} ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), ("algorithm_id" = String, Path, description = "Success based routing algorithm id which was last activated to update the config"), ), - request_body = DynamicRoutingFeatures, + request_body = SuccessBasedRoutingConfig, responses( (status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord), (status = 400, description = "Update body is malformed"), @@ -317,7 +317,7 @@ pub async fn success_based_routing_update_configs() {} params( ("account_id" = String, Path, description = "Merchant id"), ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), - ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"), + ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for elimination based routing"), ), responses( (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord), @@ -332,3 +332,57 @@ pub async fn success_based_routing_update_configs() {} security(("api_key" = []), ("jwt_key" = [])) )] pub async fn toggle_elimination_routing() {} + +#[cfg(feature = "v1")] +/// Routing - Toggle Contract routing for profile +/// +/// Create a Contract based dynamic routing algorithm +#[utoipa::path( + post, + path = "/account/:account_id/business_profile/:profile_id/dynamic_routing/contracts/toggle", + params( + ("account_id" = String, Path, description = "Merchant id"), + ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), + ("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for contract based routing"), + ), + request_body = ContractBasedRoutingConfig, + responses( + (status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord), + (status = 400, description = "Request body is malformed"), + (status = 500, description = "Internal server error"), + (status = 404, description = "Resource missing"), + (status = 422, description = "Unprocessable request"), + (status = 403, description = "Forbidden"), + ), + tag = "Routing", + operation_id = "Toggle contract routing algorithm", + security(("api_key" = []), ("jwt_key" = [])) +)] +pub async fn contract_based_routing_setup_config() {} + +#[cfg(feature = "v1")] +/// Routing - Update contract based dynamic routing config for profile +/// +/// Update contract based dynamic routing algorithm +#[utoipa::path( + patch, + path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/config/{algorithm_id}", + params( + ("account_id" = String, Path, description = "Merchant id"), + ("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"), + ("algorithm_id" = String, Path, description = "Contract based routing algorithm id which was last activated to update the config"), + ), + request_body = ContractBasedRoutingConfig, + responses( + (status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord), + (status = 400, description = "Update body is malformed"), + (status = 500, description = "Internal server error"), + (status = 404, description = "Resource missing"), + (status = 422, description = "Unprocessable request"), + (status = 403, description = "Forbidden"), + ), + tag = "Routing", + operation_id = "Update contract based dynamic routing configs", + security(("api_key" = []), ("jwt_key" = [])) +)] +pub async fn contract_based_routing_update_configs() {} diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index b4c1c1c2c03..54cae42ceb3 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -398,6 +398,16 @@ pub enum RoutingError { GenericNotFoundError { field: String }, #[error("Unable to deserialize from '{from}' to '{to}'")] DeserializationError { from: String, to: String }, + #[error("Unable to retrieve contract based routing config")] + ContractBasedRoutingConfigError, + #[error("Params not found in contract based routing config")] + ContractBasedRoutingParamsNotFoundError, + #[error("Unable to calculate contract score from dynamic routing service")] + ContractScoreCalculationError, + #[error("contract routing client from dynamic routing gRPC service not initialized")] + ContractRoutingClientInitializationError, + #[error("Invalid contract based connector label received from dynamic routing service: '{0}'")] + InvalidContractBasedConnectorLabel(String), } #[derive(Debug, Clone, thiserror::Error)] diff --git a/crates/router/src/core/metrics.rs b/crates/router/src/core/metrics.rs index a98a4ffb259..efb463b3a37 100644 --- a/crates/router/src/core/metrics.rs +++ b/crates/router/src/core/metrics.rs @@ -82,6 +82,7 @@ counter_metric!( GLOBAL_METER ); counter_metric!(DYNAMIC_SUCCESS_BASED_ROUTING, GLOBAL_METER); +counter_metric!(DYNAMIC_CONTRACT_BASED_ROUTING, GLOBAL_METER); #[cfg(feature = "partial-auth")] counter_metric!(PARTIAL_AUTH_FAILURE, GLOBAL_METER); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index dce89107afd..f86072fdcc2 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -6599,8 +6599,8 @@ where .attach_printable("failed to perform volume split on routing type")?; if routing_choice.routing_type.is_dynamic_routing() { - let success_based_routing_config_params_interpolator = - routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new( + let dynamic_routing_config_params_interpolator = + routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_data.get_payment_attempt().payment_method, payment_data.get_payment_attempt().payment_method_type, payment_data.get_payment_attempt().authentication_type, @@ -6630,14 +6630,15 @@ where .and_then(|card_isin| card_isin.as_str()) .map(|card_isin| card_isin.to_string()), ); - routing::perform_success_based_routing( + + routing::perform_dynamic_routing( state, connectors.clone(), business_profile, - success_based_routing_config_params_interpolator, + dynamic_routing_config_params_interpolator, ) .await - .map_err(|e| logger::error!(success_rate_routing_error=?e)) + .map_err(|e| logger::error!(dynamic_routing_error=?e)) .unwrap_or(connectors) } else { connectors diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 748b71469ba..abbefd793d7 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -5,6 +5,8 @@ use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId}; use api_models::routing::RoutableConnectorChoice; use async_trait::async_trait; use common_enums::{AuthorizationStatus, SessionUpdateStatus}; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use common_utils::ext_traits::ValueExt; use common_utils::{ ext_traits::{AsyncExt, Encode}, types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit}, @@ -1963,11 +1965,22 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( if payment_intent.status.is_in_terminal_state() && business_profile.dynamic_routing_algorithm.is_some() { + let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef = + business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("DynamicRoutingAlgorithmRef not found in profile")?; + let state = state.clone(); - let business_profile = business_profile.clone(); + let profile_id = business_profile.get_id().to_owned(); let payment_attempt = payment_attempt.clone(); - let success_based_routing_config_params_interpolator = - routing_helpers::SuccessBasedRoutingConfigParamsInterpolator::new( + let dynamic_routing_config_params_interpolator = + routing_helpers::DynamicRoutingConfigParamsInterpolator::new( payment_attempt.payment_method, payment_attempt.payment_method_type, payment_attempt.authentication_type, @@ -1999,14 +2012,27 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( tokio::spawn( async move { routing_helpers::push_metrics_with_update_window_for_success_based_routing( + &state, + &payment_attempt, + routable_connectors.clone(), + &profile_id, + dynamic_routing_algo_ref.clone(), + dynamic_routing_config_params_interpolator.clone(), + ) + .await + .map_err(|e| logger::error!(success_based_routing_metrics_error=?e)) + .ok(); + + routing_helpers::push_metrics_with_update_window_for_contract_based_routing( &state, &payment_attempt, routable_connectors, - &business_profile, - success_based_routing_config_params_interpolator, + &profile_id, + dynamic_routing_algo_ref, + dynamic_routing_config_params_interpolator, ) .await - .map_err(|e| logger::error!(dynamic_routing_metrics_error=?e)) + .map_err(|e| logger::error!(contract_based_routing_metrics_error=?e)) .ok(); } .in_current_span(), diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index dd592bc3064..41be7e6e2d3 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -14,6 +14,8 @@ use api_models::{ enums::{self as api_enums, CountryAlpha2}, routing::ConnectorSelection, }; +#[cfg(feature = "dynamic_routing")] +use common_utils::ext_traits::AsyncExt; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use euclid::{ @@ -23,8 +25,9 @@ use euclid::{ frontend::{ast, dir as euclid_dir}, }; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use external_services::grpc_client::dynamic_routing::success_rate_client::{ - CalSuccessRateResponse, SuccessBasedDynamicRouting, +use external_services::grpc_client::dynamic_routing::{ + contract_routing_client::{CalContractScoreResponse, ContractBasedDynamicRouting}, + success_rate_client::{CalSuccessRateResponse, SuccessBasedDynamicRouting}, }; use hyperswitch_domain_models::address::Address; use kgraph_utils::{ @@ -1281,41 +1284,93 @@ pub fn make_dsl_input_for_surcharge( Ok(backend_input) } -/// success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -#[instrument(skip_all)] -pub async fn perform_success_based_routing( +pub async fn perform_dynamic_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, - business_profile: &domain::Profile, - success_based_routing_config_params_interpolator: routing::helpers::SuccessBasedRoutingConfigParamsInterpolator, + profile: &domain::Profile, + dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { - let success_based_dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = - business_profile - .dynamic_routing_algorithm - .clone() - .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) - .transpose() - .change_context(errors::RoutingError::DeserializationError { - from: "JSON".to_string(), - to: "DynamicRoutingAlgorithmRef".to_string(), - }) - .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? - .unwrap_or_default(); + let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::RoutingError::DeserializationError { + from: "JSON".to_string(), + to: "DynamicRoutingAlgorithmRef".to_string(), + }) + .attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")? + .ok_or(errors::RoutingError::GenericNotFoundError { + field: "dynamic_routing_algorithm".to_string(), + })?; + + logger::debug!( + "performing dynamic_routing for profile {}", + profile.get_id().get_string_repr() + ); - let success_based_algo_ref = success_based_dynamic_routing_algo_ref + let connector_list = match dynamic_routing_algo_ref .success_based_algorithm - .ok_or(errors::RoutingError::GenericNotFoundError { field: "success_based_algorithm".to_string() }) - .attach_printable( - "success_based_algorithm not found in dynamic_routing_algorithm from business_profile table", - )?; + .as_ref() + .async_map(|algorithm| { + perform_success_based_routing( + state, + routable_connectors.clone(), + profile.get_id(), + dynamic_routing_config_params_interpolator.clone(), + algorithm.clone(), + ) + }) + .await + .transpose() + .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) + .ok() + .flatten() + { + Some(success_based_list) => success_based_list, + None => { + // Only run contract based if success based returns None + dynamic_routing_algo_ref + .contract_based_routing + .as_ref() + .async_map(|algorithm| { + perform_contract_based_routing( + state, + routable_connectors.clone(), + profile.get_id(), + dynamic_routing_config_params_interpolator, + algorithm.clone(), + ) + }) + .await + .transpose() + .inspect_err(|e| logger::error!(dynamic_routing_error=?e)) + .ok() + .flatten() + .unwrap_or(routable_connectors) + } + }; + Ok(connector_list) +} + +/// success based dynamic routing +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn perform_success_based_routing( + state: &SessionState, + routable_connectors: Vec<api_routing::RoutableConnectorChoice>, + profile_id: &common_utils::id_type::ProfileId, + success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, + success_based_algo_ref: api_routing::SuccessBasedAlgorithm, +) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { if success_based_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection { logger::debug!( "performing success_based_routing for profile {}", - business_profile.get_id().get_string_repr() + profile_id.get_string_repr() ); let client = state .grpc_client @@ -1325,18 +1380,18 @@ pub async fn perform_success_based_routing( .ok_or(errors::RoutingError::SuccessRateClientInitializationError) .attach_printable("success_rate gRPC client not found")?; - let success_based_routing_configs = routing::helpers::fetch_success_based_routing_configs( + let success_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::< + api_routing::SuccessBasedRoutingConfig, + >( state, - business_profile, + profile_id, success_based_algo_ref .algorithm_id_with_timestamp .algorithm_id .ok_or(errors::RoutingError::GenericNotFoundError { field: "success_based_routing_algorithm_id".to_string(), }) - .attach_printable( - "success_based_routing_algorithm_id not found in business_profile", - )?, + .attach_printable("success_based_routing_algorithm_id not found in profile_id")?, ) .await .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) @@ -1352,7 +1407,7 @@ pub async fn perform_success_based_routing( let success_based_connectors: CalSuccessRateResponse = client .calculate_success_rate( - business_profile.get_id().get_string_repr().into(), + profile_id.get_string_repr().into(), success_based_routing_configs, success_based_routing_config_params, routable_connectors, @@ -1398,3 +1453,95 @@ pub async fn perform_success_based_routing( Ok(routable_connectors) } } + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn perform_contract_based_routing( + state: &SessionState, + routable_connectors: Vec<api_routing::RoutableConnectorChoice>, + profile_id: &common_utils::id_type::ProfileId, + _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, + contract_based_algo_ref: api_routing::ContractRoutingAlgorithm, +) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { + if contract_based_algo_ref.enabled_feature + == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection + { + logger::debug!( + "performing contract_based_routing for profile {}", + profile_id.get_string_repr() + ); + let client = state + .grpc_client + .dynamic_routing + .contract_based_client + .as_ref() + .ok_or(errors::RoutingError::ContractRoutingClientInitializationError) + .attach_printable("contract routing gRPC client not found")?; + + let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::< + api_routing::ContractBasedRoutingConfig, + >( + state, + profile_id, + contract_based_algo_ref + .algorithm_id_with_timestamp + .algorithm_id + .ok_or(errors::RoutingError::GenericNotFoundError { + field: "contract_based_routing_algorithm_id".to_string(), + }) + .attach_printable("contract_based_routing_algorithm_id not found in profile_id")?, + ) + .await + .change_context(errors::RoutingError::ContractBasedRoutingConfigError) + .attach_printable("unable to fetch contract based dynamic routing configs")?; + + let contract_based_connectors: CalContractScoreResponse = client + .calculate_contract_score( + profile_id.get_string_repr().into(), + contract_based_routing_configs, + "".to_string(), + routable_connectors, + state.get_grpc_headers(), + ) + .await + .change_context(errors::RoutingError::ContractScoreCalculationError) + .attach_printable( + "unable to calculate/fetch contract score from dynamic routing service", + )?; + + let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len()); + + for label_with_score in contract_based_connectors.labels_with_score { + let (connector, merchant_connector_id) = label_with_score.label + .split_once(':') + .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string())) + .attach_printable( + "unable to split connector_name and mca_id from the label obtained by the dynamic routing service", + )?; + + connectors.push(api_routing::RoutableConnectorChoice { + choice_kind: api_routing::RoutableChoiceKind::FullStruct, + connector: common_enums::RoutableConnectors::from_str(connector) + .change_context(errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "RoutableConnectors".to_string(), + }) + .attach_printable("unable to convert String to RoutableConnectors")?, + merchant_connector_id: Some( + common_utils::id_type::MerchantConnectorAccountId::wrap( + merchant_connector_id.to_string(), + ) + .change_context(errors::RoutingError::GenericConversionError { + from: "String".to_string(), + to: "MerchantConnectorAccountId".to_string(), + }) + .attach_printable("unable to convert MerchantConnectorAccountId from string")?, + ), + }); + } + + logger::debug!(contract_based_routing_connectors=?connectors); + Ok(connectors) + } else { + Ok(routable_connectors) + } +} diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs index 99bd2b00209..8d03e82a328 100644 --- a/crates/router/src/core/routing.rs +++ b/crates/router/src/core/routing.rs @@ -2,6 +2,8 @@ pub mod helpers; pub mod transformers; use std::collections::HashSet; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use api_models::routing::DynamicRoutingAlgoAccessor; use api_models::{ enums, mandates as mandates_api, routing, routing::{self as routing_types, RoutingRetrieveQuery}, @@ -12,7 +14,10 @@ use common_utils::ext_traits::AsyncExt; use diesel_models::routing_algorithm::RoutingAlgorithm; use error_stack::ResultExt; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -use external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting; +use external_services::grpc_client::dynamic_routing::{ + contract_routing_client::ContractBasedDynamicRouting, + success_rate_client::SuccessBasedDynamicRouting, +}; use hyperswitch_domain_models::{mandates, payment_address}; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use router_env::logger; @@ -462,6 +467,16 @@ pub async fn link_routing_config( }, enabled_feature: _ }) if id == &algorithm_id + ) || matches!( + dynamic_routing_ref.contract_based_routing, + Some(routing::ContractRoutingAlgorithm { + algorithm_id_with_timestamp: + routing_types::DynamicAlgorithmWithTimestamp { + algorithm_id: Some(ref id), + timestamp: _ + }, + enabled_feature: _ + }) if id == &algorithm_id ), || { Err(errors::ApiErrorResponse::PreconditionFailed { @@ -470,7 +485,8 @@ pub async fn link_routing_config( }, )?; - dynamic_routing_ref.update_algorithm_id( + if routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM { + dynamic_routing_ref.update_algorithm_id( algorithm_id, dynamic_routing_ref .success_based_algorithm @@ -482,6 +498,34 @@ pub async fn link_routing_config( .enabled_feature, routing_types::DynamicRoutingType::SuccessRateBasedRouting, ); + } else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM + { + dynamic_routing_ref.update_algorithm_id( + algorithm_id, + dynamic_routing_ref + .elimination_routing_algorithm + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table", + )? + .enabled_feature, + routing_types::DynamicRoutingType::EliminationRouting, + ); + } else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM { + dynamic_routing_ref.update_algorithm_id( + algorithm_id, + dynamic_routing_ref + .contract_based_routing + .clone() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "missing contract_based_routing in dynamic_algorithm_ref from business_profile table", + )? + .enabled_feature, + routing_types::DynamicRoutingType::ContractBasedRouting, + ); + } helpers::update_business_profile_active_dynamic_algorithm_ref( db, @@ -1419,6 +1463,304 @@ pub async fn success_based_routing_update_configs( Ok(service_api::ApplicationResponse::Json(new_record)) } +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn contract_based_dynamic_routing_setup( + state: SessionState, + key_store: domain::MerchantKeyStore, + merchant_account: domain::MerchantAccount, + profile_id: common_utils::id_type::ProfileId, + feature_to_enable: routing_types::DynamicRoutingFeatures, + config: Option<routing_types::ContractBasedRoutingConfig>, +) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + let business_profile: domain::Profile = core_utils::validate_and_get_business_profile( + db, + key_manager_state, + &key_store, + Some(&profile_id), + merchant_account.get_id(), + ) + .await? + .get_required_value("Profile") + .change_context(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + + let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> = + business_profile + .dynamic_routing_algorithm + .clone() + .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to deserialize dynamic routing algorithm ref from business profile", + ) + .ok() + .flatten(); + + utils::when( + dynamic_routing_algo_ref + .as_mut() + .and_then(|algo| { + algo.contract_based_routing.as_mut().map(|contract_algo| { + *contract_algo.get_enabled_features() == feature_to_enable + && contract_algo + .clone() + .get_algorithm_id_with_timestamp() + .algorithm_id + .is_some() + }) + }) + .unwrap_or(false), + || { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Contract Routing with specified features is already enabled".to_string(), + }) + }, + )?; + + if feature_to_enable == routing::DynamicRoutingFeatures::None { + let algorithm = dynamic_routing_algo_ref + .clone() + .get_required_value("dynamic_routing_algo_ref") + .attach_printable("Failed to get dynamic_routing_algo_ref")?; + return helpers::disable_dynamic_routing_algorithm( + &state, + key_store, + business_profile, + algorithm, + routing_types::DynamicRoutingType::ContractBasedRouting, + ) + .await; + } + + let config = config + .get_required_value("ContractBasedRoutingConfig") + .attach_printable("Failed to get ContractBasedRoutingConfig from request")?; + + let merchant_id = business_profile.merchant_id.clone(); + let algorithm_id = common_utils::generate_routing_id_of_default_length(); + let timestamp = common_utils::date_time::now(); + + let algo = RoutingAlgorithm { + algorithm_id: algorithm_id.clone(), + profile_id: profile_id.clone(), + merchant_id, + name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(), + description: None, + kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic, + algorithm_data: serde_json::json!(config), + created_at: timestamp, + modified_at: timestamp, + algorithm_for: common_enums::TransactionType::Payment, + }; + + // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based + // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up + let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref { + algo.update_algorithm_id( + algorithm_id, + feature_to_enable, + routing_types::DynamicRoutingType::ContractBasedRouting, + ); + if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection { + algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting); + } + algo + } else { + let contract_algo = routing_types::ContractRoutingAlgorithm { + algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some( + algorithm_id.clone(), + )), + enabled_feature: feature_to_enable, + }; + routing_types::DynamicRoutingAlgorithmRef { + success_based_algorithm: None, + elimination_routing_algorithm: None, + dynamic_routing_volume_split: None, + contract_based_routing: Some(contract_algo), + } + }; + + // validate the contained mca_ids + if let Some(info_vec) = &config.label_info { + let validation_futures: Vec<_> = info_vec + .iter() + .map(|info| async { + let mca_id = info.mca_id.clone(); + let label = info.label.clone(); + let mca = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, + merchant_account.get_id(), + &mca_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: mca_id.get_string_repr().to_owned(), + })?; + + utils::when(mca.connector_name != label, || { + Err(error_stack::Report::new( + errors::ApiErrorResponse::InvalidRequestData { + message: "Incorrect mca configuration received".to_string(), + }, + )) + })?; + + Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(()) + }) + .collect(); + + futures::future::try_join_all(validation_futures).await?; + } + + let record = db + .insert_routing_algorithm(algo) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to insert record in routing algorithm table")?; + + helpers::update_business_profile_active_dynamic_algorithm_ref( + db, + key_manager_state, + &key_store, + business_profile, + final_algorithm, + ) + .await?; + + let new_record = record.foreign_into(); + + metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add( + 1, + router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_string())), + ); + Ok(service_api::ApplicationResponse::Json(new_record)) +} + +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +pub async fn contract_based_routing_update_configs( + state: SessionState, + request: routing_types::ContractBasedRoutingConfig, + merchant_account: domain::MerchantAccount, + key_store: domain::MerchantKeyStore, + algorithm_id: common_utils::id_type::RoutingId, + profile_id: common_utils::id_type::ProfileId, +) -> RouterResponse<routing_types::RoutingDictionaryRecord> { + metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add( + 1, + router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())), + ); + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + let dynamic_routing_algo_to_update = db + .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?; + + let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update + .algorithm_data + .parse_value::<routing::ContractBasedRoutingConfig>("ContractBasedRoutingConfig") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig")?; + + // validate the contained mca_ids + if let Some(info_vec) = &request.label_info { + for info in info_vec { + let mca = db + .find_by_merchant_connector_account_merchant_id_merchant_connector_id( + key_manager_state, + merchant_account.get_id(), + &info.mca_id, + &key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: info.mca_id.get_string_repr().to_owned(), + })?; + + utils::when(mca.connector_name != info.label, || { + Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Incorrect mca configuration received".to_string(), + }) + })?; + } + } + + config_to_update.update(request); + + let updated_algorithm_id = common_utils::generate_routing_id_of_default_length(); + let timestamp = common_utils::date_time::now(); + let algo = RoutingAlgorithm { + algorithm_id: updated_algorithm_id, + profile_id: dynamic_routing_algo_to_update.profile_id, + merchant_id: dynamic_routing_algo_to_update.merchant_id, + name: dynamic_routing_algo_to_update.name, + description: dynamic_routing_algo_to_update.description, + kind: dynamic_routing_algo_to_update.kind, + algorithm_data: serde_json::json!(config_to_update), + created_at: timestamp, + modified_at: timestamp, + algorithm_for: dynamic_routing_algo_to_update.algorithm_for, + }; + let record = db + .insert_routing_algorithm(algo) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to insert record in routing algorithm table")?; + + // redact cache for contract based routing configs + let cache_key = format!( + "{}_{}", + profile_id.get_string_repr(), + algorithm_id.get_string_repr() + ); + let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache( + cache_key.into(), + )]; + let _ = cache::redact_from_redis_and_publish( + state.store.get_cache_store().as_ref(), + cache_entries_to_redact, + ) + .await + .map_err(|e| logger::error!("unable to publish into the redact channel for evicting the contract based routing config cache {e:?}")); + + let new_record = record.foreign_into(); + + metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add( + 1, + router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())), + ); + + state + .grpc_client + .clone() + .dynamic_routing + .contract_based_client + .clone() + .async_map(|ct_client| async move { + ct_client + .invalidate_contracts( + profile_id.get_string_repr().into(), + state.get_grpc_headers(), + ) + .await + .change_context(errors::ApiErrorResponse::GenericNotFoundError { + message: "Failed to invalidate the contract based routing keys".to_string(), + }) + }) + .await + .transpose()?; + + Ok(service_api::ApplicationResponse::Json(new_record)) +} + #[async_trait] pub trait GetRoutableConnectorsForChoice { async fn get_routable_connectors( diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 84de32483a8..9b6396013f4 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -2,6 +2,7 @@ //! //! Functions that are used to perform the retrieval of merchant's //! routing dict, configs, defaults +use std::fmt::Debug; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use std::str::FromStr; #[cfg(any(feature = "dynamic_routing", feature = "v1"))] @@ -18,7 +19,10 @@ use diesel_models::dynamic_routing_stats::DynamicRoutingStatsNew; use diesel_models::routing_algorithm; use error_stack::ResultExt; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] -use external_services::grpc_client::dynamic_routing::success_rate_client::SuccessBasedDynamicRouting; +use external_services::grpc_client::dynamic_routing::{ + contract_routing_client::ContractBasedDynamicRouting, + success_rate_client::SuccessBasedDynamicRouting, +}; #[cfg(feature = "v1")] use hyperswitch_domain_models::api::ApplicationResponse; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] @@ -26,7 +30,7 @@ use router_env::logger; #[cfg(any(feature = "dynamic_routing", feature = "v1"))] use router_env::{instrument, tracing}; use rustc_hash::FxHashSet; -use storage_impl::redis::cache; +use storage_impl::redis::cache::{self, Cacheable}; #[cfg(all(feature = "dynamic_routing", feature = "v1"))] use crate::db::errors::StorageErrorExt; @@ -45,6 +49,8 @@ pub const SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = "Success rate based dynamic routing algorithm"; pub const ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = "Elimination based dynamic routing algorithm"; +pub const CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM: &str = + "Contract based dynamic routing algorithm"; /// Provides us with all the configured configs of the Merchant in the ascending time configured /// manner and chooses the first of them @@ -562,78 +568,146 @@ pub fn get_default_config_key( } } -/// Retrieves cached success_based routing configs specific to tenant and profile -#[cfg(all(feature = "v1", feature = "dynamic_routing"))] -pub async fn get_cached_success_based_routing_config_for_profile( - state: &SessionState, - key: &str, -) -> Option<Arc<routing_types::SuccessBasedRoutingConfig>> { - cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE - .get_val::<Arc<routing_types::SuccessBasedRoutingConfig>>(cache::CacheKey { - key: key.to_string(), - prefix: state.tenant.redis_key_prefix.clone(), - }) +#[async_trait::async_trait] +pub trait DynamicRoutingCache { + async fn get_cached_dynamic_routing_config_for_profile( + state: &SessionState, + key: &str, + ) -> Option<Arc<Self>>; + + async fn refresh_dynamic_routing_cache<T, F, Fut>( + state: &SessionState, + key: &str, + func: F, + ) -> RouterResult<T> + where + F: FnOnce() -> Fut + Send, + T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone, + Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send; +} + +#[async_trait::async_trait] +impl DynamicRoutingCache for routing_types::SuccessBasedRoutingConfig { + async fn get_cached_dynamic_routing_config_for_profile( + state: &SessionState, + key: &str, + ) -> Option<Arc<Self>> { + cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE + .get_val::<Arc<Self>>(cache::CacheKey { + key: key.to_string(), + prefix: state.tenant.redis_key_prefix.clone(), + }) + .await + } + + async fn refresh_dynamic_routing_cache<T, F, Fut>( + state: &SessionState, + key: &str, + func: F, + ) -> RouterResult<T> + where + F: FnOnce() -> Fut + Send, + T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone, + Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send, + { + cache::get_or_populate_in_memory( + state.store.get_cache_store().as_ref(), + key, + func, + &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, + ) .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to populate SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE") + } } -/// Refreshes the cached success_based routing configs specific to tenant and profile -#[cfg(feature = "v1")] -pub async fn refresh_success_based_routing_cache( - state: &SessionState, - key: &str, - success_based_routing_config: routing_types::SuccessBasedRoutingConfig, -) -> Arc<routing_types::SuccessBasedRoutingConfig> { - let config = Arc::new(success_based_routing_config); - cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE - .push( - cache::CacheKey { +#[async_trait::async_trait] +impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig { + async fn get_cached_dynamic_routing_config_for_profile( + state: &SessionState, + key: &str, + ) -> Option<Arc<Self>> { + cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE + .get_val::<Arc<Self>>(cache::CacheKey { key: key.to_string(), prefix: state.tenant.redis_key_prefix.clone(), - }, - config.clone(), + }) + .await + } + + async fn refresh_dynamic_routing_cache<T, F, Fut>( + state: &SessionState, + key: &str, + func: F, + ) -> RouterResult<T> + where + F: FnOnce() -> Fut + Send, + T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone, + Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send, + { + cache::get_or_populate_in_memory( + state.store.get_cache_store().as_ref(), + key, + func, + &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, ) - .await; - config + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to populate CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE") + } } -/// Checked fetch of success based routing configs +/// Cfetch dynamic routing configs #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] -pub async fn fetch_success_based_routing_configs( +pub async fn fetch_dynamic_routing_configs<T>( state: &SessionState, - business_profile: &domain::Profile, - success_based_routing_id: id_type::RoutingId, -) -> RouterResult<routing_types::SuccessBasedRoutingConfig> { + profile_id: &id_type::ProfileId, + routing_id: id_type::RoutingId, +) -> RouterResult<T> +where + T: serde::de::DeserializeOwned + + Clone + + DynamicRoutingCache + + Cacheable + + serde::Serialize + + Debug, +{ let key = format!( "{}_{}", - business_profile.get_id().get_string_repr(), - success_based_routing_id.get_string_repr() + profile_id.get_string_repr(), + routing_id.get_string_repr() ); if let Some(config) = - get_cached_success_based_routing_config_for_profile(state, key.as_str()).await + T::get_cached_dynamic_routing_config_for_profile(state, key.as_str()).await { Ok(config.as_ref().clone()) } else { - let success_rate_algorithm = state - .store - .find_routing_algorithm_by_profile_id_algorithm_id( - business_profile.get_id(), - &success_based_routing_id, - ) - .await - .change_context(errors::ApiErrorResponse::ResourceIdNotFound) - .attach_printable("unable to retrieve success_rate_algorithm for profile from db")?; - - let success_rate_config = success_rate_algorithm - .algorithm_data - .parse_value::<routing_types::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to parse success_based_routing_config struct")?; + let func = || async { + let routing_algorithm = state + .store + .find_routing_algorithm_by_profile_id_algorithm_id(profile_id, &routing_id) + .await + .change_context(errors::StorageError::ValueNotFound( + "RoutingAlgorithm".to_string(), + )) + .attach_printable("unable to retrieve routing_algorithm for profile from db")?; + + let dynamic_routing_config = routing_algorithm + .algorithm_data + .parse_value::<T>("dynamic_routing_config") + .change_context(errors::StorageError::DeserializationFailed) + .attach_printable("unable to parse dynamic_routing_config")?; + + Ok(dynamic_routing_config) + }; - refresh_success_based_routing_cache(state, key.as_str(), success_rate_config.clone()).await; + let dynamic_routing_config = + T::refresh_dynamic_routing_cache(state, key.as_str(), func).await?; - Ok(success_rate_config) + Ok(dynamic_routing_config) } } @@ -644,20 +718,11 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( state: &SessionState, payment_attempt: &storage::PaymentAttempt, routable_connectors: Vec<routing_types::RoutableConnectorChoice>, - business_profile: &domain::Profile, - success_based_routing_config_params_interpolator: SuccessBasedRoutingConfigParamsInterpolator, + profile_id: &id_type::ProfileId, + dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, + dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator, ) -> RouterResult<()> { - let success_based_dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = - business_profile - .dynamic_routing_algorithm - .clone() - .map(|val| val.parse_value("DynamicRoutingAlgorithmRef")) - .transpose() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to deserialize DynamicRoutingAlgorithmRef from JSON")? - .unwrap_or_default(); - - let success_based_algo_ref = success_based_dynamic_routing_algo_ref + let success_based_algo_ref = dynamic_routing_algo_ref .success_based_algorithm .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("success_based_algorithm not found in dynamic_routing_algorithm from business_profile table")?; @@ -678,22 +743,23 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( }, )?; - let success_based_routing_configs = fetch_success_based_routing_configs( - state, - business_profile, - success_based_algo_ref - .algorithm_id_with_timestamp - .algorithm_id - .ok_or(errors::ApiErrorResponse::InternalServerError) - .attach_printable( - "success_based_routing_algorithm_id not found in business_profile", - )?, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("unable to retrieve success_rate based dynamic routing configs")?; + let success_based_routing_configs = + fetch_dynamic_routing_configs::<routing_types::SuccessBasedRoutingConfig>( + state, + profile_id, + success_based_algo_ref + .algorithm_id_with_timestamp + .algorithm_id + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "success_based_routing_algorithm_id not found in business_profile", + )?, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to retrieve success_rate based dynamic routing configs")?; - let success_based_routing_config_params = success_based_routing_config_params_interpolator + let success_based_routing_config_params = dynamic_routing_config_params_interpolator .get_string_val( success_based_routing_configs .params @@ -704,7 +770,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( let success_based_connectors = client .calculate_entity_and_global_success_rate( - business_profile.get_id().get_string_repr().into(), + profile_id.get_string_repr().into(), success_based_routing_configs.clone(), success_based_routing_config_params.clone(), routable_connectors.clone(), @@ -717,7 +783,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( )?; let payment_status_attribute = - get_desired_payment_status_for_success_routing_metrics(payment_attempt.status); + get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); let first_merchant_success_based_connector = &success_based_connectors .entity_scores_with_labels @@ -743,7 +809,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( "unable to fetch the first global connector from list of connectors obtained from dynamic routing service", )?; - let outcome = get_success_based_metrics_outcome_for_payment( + let outcome = get_dynamic_routing_based_metrics_outcome_for_payment( payment_status_attribute, payment_connector.to_string(), first_merchant_success_based_connector_label.to_string(), @@ -852,7 +918,7 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( client .update_success_rate( - business_profile.get_id().get_string_repr().into(), + profile_id.get_string_repr().into(), success_based_routing_configs, success_based_routing_config_params, vec![routing_types::RoutableConnectorChoiceWithStatus::new( @@ -880,8 +946,212 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( } } +/// metrics for contract based dynamic routing +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn push_metrics_with_update_window_for_contract_based_routing( + state: &SessionState, + payment_attempt: &storage::PaymentAttempt, + routable_connectors: Vec<routing_types::RoutableConnectorChoice>, + profile_id: &id_type::ProfileId, + dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, + _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator, +) -> RouterResult<()> { + let contract_routing_algo_ref = dynamic_routing_algo_ref + .contract_based_routing + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table")?; + + if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None { + let client = state + .grpc_client + .dynamic_routing + .contract_based_client + .clone() + .ok_or(errors::ApiErrorResponse::GenericNotFoundError { + message: "contract_routing gRPC client not found".to_string(), + })?; + + let payment_connector = &payment_attempt.connector.clone().ok_or( + errors::ApiErrorResponse::GenericNotFoundError { + message: "unable to derive payment connector from payment attempt".to_string(), + }, + )?; + + let contract_based_routing_config = + fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>( + state, + profile_id, + contract_routing_algo_ref + .algorithm_id_with_timestamp + .algorithm_id + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "contract_based_routing_algorithm_id not found in business_profile", + )?, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to retrieve contract based dynamic routing configs")?; + + let mut existing_label_info = None; + + contract_based_routing_config + .label_info + .as_ref() + .map(|label_info_vec| { + for label_info in label_info_vec { + if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() { + existing_label_info = Some(label_info.clone()); + } + } + }); + + let final_label_info = existing_label_info + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("unable to get LabelInformation from ContractBasedRoutingConfig")?; + + logger::debug!( + "contract based routing: matched LabelInformation - {:?}", + final_label_info + ); + + let request_label_info = routing_types::LabelInformation { + label: format!( + "{}:{}", + final_label_info.label.clone(), + final_label_info.mca_id.get_string_repr() + ), + target_count: final_label_info.target_count, + target_time: final_label_info.target_time, + mca_id: final_label_info.mca_id.to_owned(), + }; + + let payment_status_attribute = + get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status); + + if payment_status_attribute == common_enums::AttemptStatus::Charged { + client + .update_contracts( + profile_id.get_string_repr().into(), + vec![request_label_info], + "".to_string(), + vec![], + state.get_grpc_headers(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to update contract based routing window in dynamic routing service", + )?; + } + + let contract_scores = client + .calculate_contract_score( + profile_id.get_string_repr().into(), + contract_based_routing_config.clone(), + "".to_string(), + routable_connectors.clone(), + state.get_grpc_headers(), + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to calculate/fetch contract scores from dynamic routing service", + )?; + + let first_contract_based_connector = &contract_scores + .labels_with_score + .first() + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "unable to fetch the first connector from list of connectors obtained from dynamic routing service", + )?; + + let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label + .split_once(':') + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable(format!( + "unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service", + first_contract_based_connector + ))? + .0, first_contract_based_connector.score, first_contract_based_connector.current_count ); + + core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add( + 1, + router_env::metric_attributes!( + ( + "tenant", + state.tenant.tenant_id.get_string_repr().to_owned(), + ), + ( + "merchant_profile_id", + format!( + "{}:{}", + payment_attempt.merchant_id.get_string_repr(), + payment_attempt.profile_id.get_string_repr() + ), + ), + ( + "contract_based_routing_connector", + first_contract_based_connector.to_string(), + ), + ( + "contract_based_routing_connector_score", + connector_score.to_string(), + ), + ( + "current_payment_count_contract_based_routing_connector", + current_payment_cnt.to_string(), + ), + ("payment_connector", payment_connector.to_string()), + ( + "currency", + payment_attempt + .currency + .map_or_else(|| "None".to_string(), |currency| currency.to_string()), + ), + ( + "payment_method", + payment_attempt.payment_method.map_or_else( + || "None".to_string(), + |payment_method| payment_method.to_string(), + ), + ), + ( + "payment_method_type", + payment_attempt.payment_method_type.map_or_else( + || "None".to_string(), + |payment_method_type| payment_method_type.to_string(), + ), + ), + ( + "capture_method", + payment_attempt.capture_method.map_or_else( + || "None".to_string(), + |capture_method| capture_method.to_string(), + ), + ), + ( + "authentication_type", + payment_attempt.authentication_type.map_or_else( + || "None".to_string(), + |authentication_type| authentication_type.to_string(), + ), + ), + ("payment_status", payment_attempt.status.to_string()), + ), + ); + logger::debug!("successfully pushed contract_based_routing metrics"); + + Ok(()) + } else { + Ok(()) + } +} + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -fn get_desired_payment_status_for_success_routing_metrics( +fn get_desired_payment_status_for_dynamic_routing_metrics( attempt_status: common_enums::AttemptStatus, ) -> common_enums::AttemptStatus { match attempt_status { @@ -917,7 +1187,7 @@ fn get_desired_payment_status_for_success_routing_metrics( } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] -fn get_success_based_metrics_outcome_for_payment( +fn get_dynamic_routing_based_metrics_outcome_for_payment( payment_status_attribute: common_enums::AttemptStatus, payment_connector: String, first_success_based_connector: String, @@ -957,7 +1227,6 @@ pub async fn disable_dynamic_routing_algorithm( ) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { let db = state.store.as_ref(); let key_manager_state = &state.into(); - let timestamp = common_utils::date_time::now_unix_timestamp(); let profile_id = business_profile.get_id().clone(); let (algorithm_id, dynamic_routing_algorithm, cache_entries_to_redact) = match dynamic_routing_type { @@ -988,14 +1257,12 @@ pub async fn disable_dynamic_routing_algorithm( routing_types::DynamicRoutingAlgorithmRef { success_based_algorithm: Some(routing_types::SuccessBasedAlgorithm { algorithm_id_with_timestamp: - routing_types::DynamicAlgorithmWithTimestamp { - algorithm_id: None, - timestamp, - }, + routing_types::DynamicAlgorithmWithTimestamp::new(None), enabled_feature: routing_types::DynamicRoutingFeatures::None, }), elimination_routing_algorithm: dynamic_routing_algo_ref .elimination_routing_algorithm, + contract_based_routing: dynamic_routing_algo_ref.contract_based_routing, dynamic_routing_volume_split: dynamic_routing_algo_ref .dynamic_routing_volume_split, }, @@ -1033,13 +1300,49 @@ pub async fn disable_dynamic_routing_algorithm( elimination_routing_algorithm: Some( routing_types::EliminationRoutingAlgorithm { algorithm_id_with_timestamp: - routing_types::DynamicAlgorithmWithTimestamp { - algorithm_id: None, - timestamp, - }, + routing_types::DynamicAlgorithmWithTimestamp::new(None), enabled_feature: routing_types::DynamicRoutingFeatures::None, }, ), + contract_based_routing: dynamic_routing_algo_ref.contract_based_routing, + }, + cache_entries_to_redact, + ) + } + routing_types::DynamicRoutingType::ContractBasedRouting => { + let Some(algorithm_ref) = dynamic_routing_algo_ref.contract_based_routing else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Contract routing is already disabled".to_string(), + })? + }; + let Some(algorithm_id) = algorithm_ref.algorithm_id_with_timestamp.algorithm_id + else { + Err(errors::ApiErrorResponse::PreconditionFailed { + message: "Algorithm is already inactive".to_string(), + })? + }; + let cache_key = format!( + "{}_{}", + business_profile.get_id().get_string_repr(), + algorithm_id.get_string_repr() + ); + let cache_entries_to_redact = + vec![cache::CacheKind::ContractBasedDynamicRoutingCache( + cache_key.into(), + )]; + ( + algorithm_id, + routing_types::DynamicRoutingAlgorithmRef { + success_based_algorithm: dynamic_routing_algo_ref.success_based_algorithm, + elimination_routing_algorithm: dynamic_routing_algo_ref + .elimination_routing_algorithm, + dynamic_routing_volume_split: dynamic_routing_algo_ref + .dynamic_routing_volume_split, + contract_based_routing: Some(routing_types::ContractRoutingAlgorithm { + algorithm_id_with_timestamp: + routing_types::DynamicAlgorithmWithTimestamp::new(None), + enabled_feature: routing_types::DynamicRoutingFeatures::None, + }), }, cache_entries_to_redact, ) @@ -1088,15 +1391,18 @@ pub async fn enable_dynamic_routing_algorithm( dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef, dynamic_routing_type: routing_types::DynamicRoutingType, ) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> { - let dynamic_routing = dynamic_routing_algo_ref.clone(); + let mut dynamic_routing = dynamic_routing_algo_ref.clone(); match dynamic_routing_type { routing_types::DynamicRoutingType::SuccessRateBasedRouting => { + dynamic_routing + .disable_algorithm_id(routing_types::DynamicRoutingType::ContractBasedRouting); + enable_specific_routing_algorithm( state, key_store, business_profile, feature_to_enable, - dynamic_routing_algo_ref, + dynamic_routing.clone(), dynamic_routing_type, dynamic_routing.success_based_algorithm, ) @@ -1108,12 +1414,18 @@ pub async fn enable_dynamic_routing_algorithm( key_store, business_profile, feature_to_enable, - dynamic_routing_algo_ref, + dynamic_routing.clone(), dynamic_routing_type, dynamic_routing.elimination_routing_algorithm, ) .await } + routing_types::DynamicRoutingType::ContractBasedRouting => { + Err((errors::ApiErrorResponse::InvalidRequestData { + message: "Contract routing cannot be set as default".to_string(), + }) + .into()) + } } } @@ -1128,7 +1440,7 @@ pub async fn enable_specific_routing_algorithm<A>( algo_type: Option<A>, ) -> RouterResult<ApplicationResponse<routing_types::RoutingDictionaryRecord>> where - A: routing_types::DynamicRoutingAlgoAccessor + Clone + std::fmt::Debug, + A: routing_types::DynamicRoutingAlgoAccessor + Clone + Debug, { // Algorithm wasn't created yet let Some(mut algo_type) = algo_type else { @@ -1169,9 +1481,8 @@ where } .into()); }; - *algo_type_enabled_features = feature_to_enable.clone(); - dynamic_routing_algo_ref - .update_specific_ref(dynamic_routing_type.clone(), feature_to_enable.clone()); + *algo_type_enabled_features = feature_to_enable; + dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable); update_business_profile_active_dynamic_algorithm_ref( db, &state.into(), @@ -1242,6 +1553,13 @@ pub async fn default_specific_dynamic_routing_setup( algorithm_for: common_enums::TransactionType::Payment, } } + + routing_types::DynamicRoutingType::ContractBasedRouting => { + return Err((errors::ApiErrorResponse::InvalidRequestData { + message: "Contract routing cannot be set as default".to_string(), + }) + .into()) + } }; let record = db @@ -1273,7 +1591,8 @@ pub async fn default_specific_dynamic_routing_setup( Ok(ApplicationResponse::Json(new_record)) } -pub struct SuccessBasedRoutingConfigParamsInterpolator { +#[derive(Debug, Clone)] +pub struct DynamicRoutingConfigParamsInterpolator { pub payment_method: Option<common_enums::PaymentMethod>, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub authentication_type: Option<common_enums::AuthenticationType>, @@ -1283,7 +1602,7 @@ pub struct SuccessBasedRoutingConfigParamsInterpolator { pub card_bin: Option<String>, } -impl SuccessBasedRoutingConfigParamsInterpolator { +impl DynamicRoutingConfigParamsInterpolator { pub fn new( payment_method: Option<common_enums::PaymentMethod>, payment_method_type: Option<common_enums::PaymentMethodType>, diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 7f7ea767108..c2363500c04 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1870,6 +1870,10 @@ impl Profile { }), )), ) + .service( + web::resource("/set_volume_split") + .route(web::post().to(routing::set_dynamic_routing_volume_split)), + ) .service( web::scope("/elimination").service( web::resource("/toggle") @@ -1877,8 +1881,17 @@ impl Profile { ), ) .service( - web::resource("/set_volume_split") - .route(web::post().to(routing::set_dynamic_routing_volume_split)), + web::scope("/contracts") + .service(web::resource("/toggle").route( + web::post().to(routing::contract_based_routing_setup_config), + )) + .service(web::resource("/config/{algorithm_id}").route( + web::patch().to(|state, req, path, payload| { + routing::contract_based_routing_update_configs( + state, req, path, payload, + ) + }), + )), ), ); } diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs index f3ba7076e53..c0f4062e15d 100644 --- a/crates/router/src/routes/metrics/bg_metrics_collector.rs +++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs @@ -14,6 +14,9 @@ pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) &cache::PM_FILTERS_CGRAPH_CACHE, &cache::DECISION_MANAGER_CACHE, &cache::SURCHARGE_CACHE, + &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, + &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, + &cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, ]; tokio::spawn(async move { diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs index e7227e1f752..ac0f997a278 100644 --- a/crates/router/src/routes/routing.rs +++ b/crates/router/src/routes/routing.rs @@ -1130,7 +1130,7 @@ pub async fn toggle_success_based_routing( pub async fn success_based_routing_update_configs( state: web::Data<AppState>, req: HttpRequest, - path: web::Path<routing_types::SuccessBasedRoutingUpdateConfigQuery>, + path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, json_payload: web::Json<routing_types::SuccessBasedRoutingConfig>, ) -> impl Responder { let flow = Flow::UpdateDynamicRoutingConfigs; @@ -1165,6 +1165,100 @@ pub async fn success_based_routing_update_configs( )) .await } + +#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn contract_based_routing_setup_config( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<routing_types::ToggleDynamicRoutingPath>, + query: web::Query<api_models::routing::ToggleDynamicRoutingQuery>, + json_payload: Option<web::Json<routing_types::ContractBasedRoutingConfig>>, +) -> impl Responder { + let flow = Flow::ToggleDynamicRouting; + let routing_payload_wrapper = routing_types::ContractBasedRoutingSetupPayloadWrapper { + config: json_payload.map(|json| json.into_inner()), + profile_id: path.into_inner().profile_id, + features_to_enable: query.into_inner().enable, + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + routing_payload_wrapper.clone(), + |state, + auth: auth::AuthenticationData, + wrapper: routing_types::ContractBasedRoutingSetupPayloadWrapper, + _| async move { + Box::pin(routing::contract_based_dynamic_routing_setup( + state, + auth.key_store, + auth.merchant_account, + wrapper.profile_id, + wrapper.features_to_enable, + wrapper.config, + )) + .await + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuthProfileFromRoute { + profile_id: routing_payload_wrapper.profile_id, + required_permission: Permission::ProfileRoutingWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] +#[instrument(skip_all)] +pub async fn contract_based_routing_update_configs( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<routing_types::DynamicRoutingUpdateConfigQuery>, + json_payload: web::Json<routing_types::ContractBasedRoutingConfig>, +) -> impl Responder { + let flow = Flow::UpdateDynamicRoutingConfigs; + let routing_payload_wrapper = routing_types::ContractBasedRoutingPayloadWrapper { + updated_config: json_payload.into_inner(), + algorithm_id: path.algorithm_id.clone(), + profile_id: path.profile_id.clone(), + }; + Box::pin(oss_api::server_wrap( + flow, + state, + &req, + routing_payload_wrapper.clone(), + |state, + auth: auth::AuthenticationData, + wrapper: routing_types::ContractBasedRoutingPayloadWrapper, + _| async { + Box::pin(routing::contract_based_routing_update_configs( + state, + wrapper.updated_config, + auth.merchant_account, + auth.key_store, + wrapper.algorithm_id, + wrapper.profile_id, + )) + .await + }, + auth::auth_type( + &auth::HeaderAuth(auth::ApiKeyAuth), + &auth::JWTAuthProfileFromRoute { + profile_id: routing_payload_wrapper.profile_id, + required_permission: Permission::ProfileRoutingWrite, + }, + req.headers(), + ), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[cfg(all(feature = "olap", feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] pub async fn toggle_elimination_routing( diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 8302b5bf933..fb752e64b09 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -92,6 +92,16 @@ pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| ) }); +/// Contract Routing based Dynamic Algorithm Cache +pub static CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE: Lazy<Cache> = Lazy::new(|| { + Cache::new( + "CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE", + CACHE_TTL, + CACHE_TTI, + Some(MAX_CAPACITY), + ) +}); + /// Trait which defines the behaviour of types that's gonna be stored in Cache pub trait Cacheable: Any + Send + Sync + DynClone { fn as_any(&self) -> &dyn Any; @@ -113,6 +123,7 @@ pub enum CacheKind<'a> { CGraph(Cow<'a, str>), SuccessBasedDynamicRoutingCache(Cow<'a, str>), EliminationBasedDynamicRoutingCache(Cow<'a, str>), + ContractBasedDynamicRoutingCache(Cow<'a, str>), PmFiltersCGraph(Cow<'a, str>), All(Cow<'a, str>), } @@ -128,6 +139,7 @@ impl CacheKind<'_> { | CacheKind::CGraph(key) | CacheKind::SuccessBasedDynamicRoutingCache(key) | CacheKind::EliminationBasedDynamicRoutingCache(key) + | CacheKind::ContractBasedDynamicRoutingCache(key) | CacheKind::PmFiltersCGraph(key) | CacheKind::All(key) => key, } diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs index 373ac370e2f..28b76148765 100644 --- a/crates/storage_impl/src/redis/pub_sub.rs +++ b/crates/storage_impl/src/redis/pub_sub.rs @@ -6,8 +6,9 @@ use router_env::{logger, tracing::Instrument}; use crate::redis::cache::{ CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, - DECISION_MANAGER_CACHE, ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, - ROUTING_CACHE, SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE, + CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, DECISION_MANAGER_CACHE, + ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, + SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE, }; #[async_trait::async_trait] @@ -147,6 +148,15 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { .await; key } + CacheKind::ContractBasedDynamicRoutingCache(key) => { + CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: message.tenant.clone(), + }) + .await; + key + } CacheKind::SuccessBasedDynamicRoutingCache(key) => { SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { @@ -220,6 +230,12 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { prefix: message.tenant.clone(), }) .await; + CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE + .remove(CacheKey { + key: key.to_string(), + prefix: message.tenant.clone(), + }) + .await; ROUTING_CACHE .remove(CacheKey { key: key.to_string(), diff --git a/proto/contract_routing.proto b/proto/contract_routing.proto new file mode 100644 index 00000000000..6b842e3096e --- /dev/null +++ b/proto/contract_routing.proto @@ -0,0 +1,76 @@ +syntax = "proto3"; +package contract_routing; + +service ContractScoreCalculator { + rpc FetchContractScore (CalContractScoreRequest) returns (CalContractScoreResponse); + + rpc UpdateContract (UpdateContractRequest) returns (UpdateContractResponse); + + rpc InvalidateContract (InvalidateContractRequest) returns (InvalidateContractResponse); +} + +// API-1 types +message CalContractScoreRequest { + string id = 1; + string params = 2; + repeated string labels = 3; + CalContractScoreConfig config = 4; +} + +message CalContractScoreConfig { + repeated double constants = 1; + TimeScale time_scale = 2; +} + +message TimeScale { + enum Scale { + Day = 0; + Month = 1; + } + Scale time_scale = 1; +} + +message CalContractScoreResponse { + repeated ScoreData labels_with_score = 1; +} + +message ScoreData { + double score = 1; + string label = 2; + uint64 current_count = 3; +} + +// API-2 types +message UpdateContractRequest { + string id = 1; + string params = 2; + repeated LabelInformation labels_information = 3; +} + +message LabelInformation { + string label = 1; + uint64 target_count = 2; + uint64 target_time = 3; + uint64 current_count = 4; +} + +message UpdateContractResponse { + enum UpdationStatus { + CONTRACT_UPDATION_SUCCEEDED = 0; + CONTRACT_UPDATION_FAILED = 1; + } + UpdationStatus status = 1; +} + +// API-3 types +message InvalidateContractRequest { + string id = 1; +} + +message InvalidateContractResponse { + enum InvalidationStatus { + CONTRACT_INVALIDATION_SUCCEEDED = 0; + CONTRACT_INVALIDATION_FAILED = 1; + } + InvalidationStatus status = 1; +} \ No newline at end of file
2024-12-05T20:19:52Z
## 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 --> - Built an interface for Contract based routing - Integrated Contract based routing with hyperswitch - Built new APIs for contract routing config setup - Refactored some existing dynamic routing code ### 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). --> ## 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. Enable Contract routing config ``` curl --location --request POST 'http://localhost:8080/account/sarthak2/business_profile/pro_YozTgS8HebvBlk0UaeWW/dynamic_routing/contracts/toggle?enable=dynamic_connector_selection' \ --header 'api-key: dev_1aD8YuFd6Ovanf3oOtAYobqI6qw4ZBRSfw6BgYbifWHpaopkisBtm8obNXkFbVJn' \ --header 'Content-Type: application/json' \ --data-raw '{ "config": { "constants": [0.7,0.35], "time_scale": "day" }, "label_info": [{ "label": "stripe", "target_count": 10000, "incremental_count": 0, "target_time": 1780486655, "mca_id": "mca_5Mk0Qcum2tnbmKoyqeuL" }] }' ``` Response - ``` { "id": "routing_FlQ49V71J8ZCXEwPzFy9", "profile_id": "pro_YozTgS8HebvBlk0UaeWW", "name": "Contract based dynamic routing algorithm", "kind": "dynamic", "description": "", "created_at": 1734009361, "modified_at": 1734009361, "algorithm_for": "payment" } ``` 2. Set Volume split for dynamic routing ``` curl --location --request POST 'http://localhost:8080/account/sarthak2/business_profile/pro_YozTgS8HebvBlk0UaeWW/dynamic_routing/set_volume_split?split=80' \ --header 'api-key: dev_1aD8YuFd6Ovanf3oOtAYobqI6qw4ZBRSfw6BgYbifWHpaopkisBtm8obNXkFbVJn' ``` 3. Create a Payment Metrics Population post payment - <img width="1512" alt="image" src="https://github.com/user-attachments/assets/3d21293d-7e2c-4b8f-8758-cf5fecf5c528" /> ## 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
22072fd750940ac7fec6ea971737409518600891
juspay/hyperswitch
juspay__hyperswitch-6748
Bug: fix(api_models): `wasm` build problems caused by `actix-multipart` `wasm` build is failing because of adding `actix-multipart` dependency in `api-models`. As we cannot change any dependencies in `wasm`, we will have to make changes to `api_models` to fix this.
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index eb706dc913c..e5bf74c20c6 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -errors = ["dep:reqwest"] +errors = ["dep:actix-web", "dep:reqwest"] dummy_connector = ["euclid/dummy_connector", "common_enums/dummy_connector"] detailed_errors = [] payouts = ["common_enums/payouts"] @@ -21,10 +21,11 @@ v2 = ["common_utils/v2", "customer_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2"] dynamic_routing = [] +control_center_theme = ["dep:actix-web", "dep:actix-multipart"] [dependencies] -actix-multipart = "0.6.1" -actix-web = "4.5.1" +actix-multipart = { version = "0.6.1", optional = true } +actix-web = { version = "4.5.1", optional = true } error-stack = "0.4.1" indexmap = "2.3.0" mime = "0.3.17" diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 15146e304af..88c084d2f0b 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -2,11 +2,14 @@ use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "dummy_connector")] use crate::user::sample_data::SampleDataRequest; +#[cfg(feature = "control_center_theme")] +use crate::user::theme::{ + CreateThemeRequest, GetThemeResponse, UpdateThemeRequest, UploadFileRequest, +}; use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, - theme::{CreateThemeRequest, GetThemeResponse, UpdateThemeRequest, UploadFileRequest}, AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest, @@ -62,7 +65,14 @@ common_utils::impl_api_event_type!( UpdateUserAuthenticationMethodRequest, GetSsoAuthUrlRequest, SsoSignInRequest, - AuthSelectRequest, + AuthSelectRequest + ) +); + +#[cfg(feature = "control_center_theme")] +common_utils::impl_api_event_type!( + Miscellaneous, + ( GetThemeResponse, UploadFileRequest, CreateThemeRequest, diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 82291ddc92a..de0116058cb 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -8,6 +8,7 @@ use crate::user_role::UserStatus; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] pub mod sample_data; +#[cfg(feature = "control_center_theme")] pub mod theme; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f6e1f0efc69..c752e99e979 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -124,7 +124,7 @@ x509-parser = "0.16.0" # First party crates analytics = { version = "0.1.0", path = "../analytics", optional = true, default-features = false } -api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } +api_models = { version = "0.1.0", path = "../api_models", features = ["errors", "control_center_theme"] } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] }
2024-12-04T13:49: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 --> Wasm build is failing because of adding `actix-multipart` dependency in `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 <!-- 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 #6748. ## 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)? --> Checked by building `wasm` locally. It worked. ![Image from Jeeva Ramachandran via Slack](https://github.com/user-attachments/assets/966948cb-ff45-4d02-b885-f878d59ae90d) No need to run any other tests as this is an internal change. ## 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
3a3e93cb3be3fc3ffabef2a708b49defabf338a5
juspay/hyperswitch
juspay__hyperswitch-6715
Bug: fix(opensearch): fix empty filter array query addition in globalsearch query Fix the opensearch query building, when free-text query is empty, no case-sensitive filters are passed and time-range is also not mentioned
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index e8726840a2e..246a0f4e8bb 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -705,9 +705,7 @@ impl OpenSearchQueryBuilder { let should_array = self.build_auth_array(); - if !bool_obj.is_empty() { - query_obj.insert("bool".to_string(), Value::Object(bool_obj)); - } + query_obj.insert("bool".to_string(), Value::Object(bool_obj)); let mut sort_obj = Map::new(); sort_obj.insert(
2024-12-02T09:29: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 --> The opensearch query should be built manually in the code, based on the request body. There is a component called `filter_array` which comprises of the free-text search query, addition of case sensitive filters and also the time_range (if provided). When all the three sub parts are empty (empty query string, no case-sensitive filters and missing time_range) in the request, the filter_array will not be created, and the logic for integrating the rest of the filters is affected. Making minor fixes to the query builder to update the opensearch query even if all the above mentioned components are empty. ### 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). --> Give out correct results by building the opensearch query through the request body. ## 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)? --> Should test the case when free-text query is empty, case-sensitive filters are not provided, and time-range filter is also not applied. Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMzI5ODcwMywib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.y9FI-AvvzNKd4DbJiGT7LmwfzxNjZDdOZfQ40TGTh3w' \ --header 'Referer: http://localhost:9000/' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --data '{ "query": "", "filters": { "currency": [ "USD" ] } }' ``` The response should now give out all the results based on the filter applied. Sample opensearch query structure: ```json { "query": { "bool": { "must": [ { "bool": { "must": [ { "bool": { "should": [ { "term": { "currency.keyword": { "value": "USD", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "bool": { "must": [ { "term": { "organization_id.keyword": { "value": "org_VpSHOjsYfDvabVYJgCAJ" } } } ] } } ], "minimum_should_match": 1 } } ] } } ] } }, "sort": [ { "@timestamp": { "order": "desc" } } ] } ``` ## 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
797a0db7733c5b387564fb1bbc106d054c8dffa6
juspay/hyperswitch
juspay__hyperswitch-6742
Bug: Updating logo in API ref
2024-12-04T12:36:25Z
## 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 --> ### 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 - #6742 ## 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
dc26317e9bc1aa82666e978c5e824ccb9b016d31
juspay/hyperswitch
juspay__hyperswitch-6702
Bug: refactor(users): remove lineage checks in roles get operations refactor find_by_role_id_in_merchant_scope query to support profile level custom roles
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs index 065a5b6e114..6f6a1404ee2 100644 --- a/crates/diesel_models/src/query/role.rs +++ b/crates/diesel_models/src/query/role.rs @@ -26,6 +26,7 @@ impl Role { .await } + // TODO: Remove once find_by_role_id_in_lineage is stable pub async fn find_by_role_id_in_merchant_scope( conn: &PgPooledConn, role_id: &str, @@ -43,7 +44,27 @@ impl Role { .await } - pub async fn find_by_role_id_in_org_scope( + pub async fn find_by_role_id_in_lineage( + conn: &PgPooledConn, + role_id: &str, + merchant_id: &id_type::MerchantId, + 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())) + .and( + dsl::scope.eq(RoleScope::Organization).or(dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::scope.eq(RoleScope::Merchant))), + ), + ) + .await + } + + pub async fn find_by_role_id_and_org_id( conn: &PgPooledConn, role_id: &str, org_id: &id_type::OrganizationId, @@ -88,9 +109,11 @@ impl Role { merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> StorageResult<Vec<Self>> { - let predicate = dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id - .eq(org_id.to_owned()) - .and(dsl::scope.eq(RoleScope::Organization))); + let predicate = dsl::org_id.eq(org_id.to_owned()).and( + dsl::scope.eq(RoleScope::Organization).or(dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::scope.eq(RoleScope::Merchant))), + ); generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, @@ -115,9 +138,10 @@ impl Role { if let Some(merchant_id) = merchant_id { query = query.filter( - dsl::merchant_id + (dsl::merchant_id .eq(merchant_id) - .or(dsl::scope.eq(RoleScope::Organization)), + .and(dsl::scope.eq(RoleScope::Merchant))) + .or(dsl::scope.eq(RoleScope::Organization)), ); } diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index 04f3264b45e..08449685b29 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -29,16 +29,19 @@ pub struct UserRole { impl UserRole { pub fn get_entity_id_and_type(&self) -> Option<(String, EntityType)> { - match (self.version, self.role_id.as_str()) { - (enums::UserRoleVersion::V1, consts::ROLE_ID_ORGANIZATION_ADMIN) => { + match (self.version, self.entity_type, self.role_id.as_str()) { + (enums::UserRoleVersion::V1, None, consts::ROLE_ID_ORGANIZATION_ADMIN) => { let org_id = self.org_id.clone()?.get_string_repr().to_string(); Some((org_id, EntityType::Organization)) } - (enums::UserRoleVersion::V1, _) => { + (enums::UserRoleVersion::V1, None, _) => { let merchant_id = self.merchant_id.clone()?.get_string_repr().to_string(); Some((merchant_id, EntityType::Merchant)) } - (enums::UserRoleVersion::V2, _) => self.entity_id.clone().zip(self.entity_type), + (enums::UserRoleVersion::V1, Some(_), _) => { + self.entity_id.clone().zip(self.entity_type) + } + (enums::UserRoleVersion::V2, _, _) => self.entity_id.clone().zip(self.entity_type), } } } diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 752c3a52284..ff2744b824e 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1847,15 +1847,10 @@ 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_in_merchant_scope( - &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_and_org_id(&state, &role_id, &auth.org_id) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; let permission_groups = role_info.get_permission_groups(); if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { return Err(OpenSearchError::AccessForbiddenError)?; @@ -1887,7 +1882,7 @@ pub mod routes { 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) + RoleInfo::from_role_id_and_org_id(&state, &role_id, &org_id) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError) @@ -1974,15 +1969,10 @@ pub mod routes { indexed_req, |state, auth: UserFromToken, req, _| async move { let role_id = auth.role_id; - 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 role_info = RoleInfo::from_role_id_and_org_id(&state, &role_id, &auth.org_id) + .await + .change_context(UserErrors::InternalServerError) + .change_context(OpenSearchError::UnknownError)?; let permission_groups = role_info.get_permission_groups(); if !permission_groups.contains(&common_enums::PermissionGroup::OperationsView) { return Err(OpenSearchError::AccessForbiddenError)?; @@ -2013,7 +2003,7 @@ pub mod routes { 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) + RoleInfo::from_role_id_and_org_id(&state, &role_id, &org_id) .await .change_context(UserErrors::InternalServerError) .change_context(OpenSearchError::UnknownError) diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index f99c44cf298..629476b2591 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -104,10 +104,9 @@ 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_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -553,7 +552,7 @@ async fn handle_invitation( .into()); } - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_in_lineage( state, &request.role_id, &user_from_token.merchant_id, @@ -1371,10 +1370,9 @@ pub async fn list_user_roles_details( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; - let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let requestor_role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -1526,7 +1524,7 @@ pub async fn list_user_roles_details( .collect::<HashSet<_>>() .into_iter() .map(|role_id| async { - let role_info = roles::RoleInfo::from_role_id_in_org_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &role_id, &user_from_token.org_id, @@ -2533,10 +2531,9 @@ 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_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -2611,10 +2608,9 @@ 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_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -2687,10 +2683,9 @@ 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_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -2780,10 +2775,9 @@ pub async fn switch_org_for_user( .into()); } - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -2876,13 +2870,8 @@ pub async fn switch_org_for_user( ) .await?; - utils::user_role::set_role_permissions_in_cache_by_role_id_merchant_id_org_id( - &state, - &role_id, - &merchant_id, - &request.org_id, - ) - .await; + utils::user_role::set_role_info_in_cache_by_role_id_org_id(&state, &role_id, &request.org_id) + .await; let response = user_api::TokenResponse { token: token.clone(), @@ -2905,10 +2894,9 @@ pub async fn switch_merchant_for_user_in_org( } let key_manager_state = &(&state).into(); - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -3065,13 +3053,7 @@ pub async fn switch_merchant_for_user_in_org( ) .await?; - utils::user_role::set_role_permissions_in_cache_by_role_id_merchant_id_org_id( - &state, - &role_id, - &merchant_id, - &org_id, - ) - .await; + utils::user_role::set_role_info_in_cache_by_role_id_org_id(&state, &role_id, &org_id).await; let response = user_api::TokenResponse { token: token.clone(), @@ -3094,10 +3076,9 @@ 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_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -3175,10 +3156,9 @@ pub async fn switch_profile_for_user_in_org_and_merchant( ) .await?; - utils::user_role::set_role_permissions_in_cache_by_role_id_merchant_id_org_id( + utils::user_role::set_role_info_in_cache_by_role_id_org_id( &state, &role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 31ec665b2ab..d8fdff0e623 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -83,10 +83,9 @@ pub async fn get_parent_group_info( state: SessionState, user_from_token: auth::UserFromToken, ) -> UserResponse<Vec<role_api::ParentGroupInfo>> { - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -119,7 +118,7 @@ pub async fn update_user_role( req: user_role_api::UpdateUserRoleRequest, _req_state: ReqState, ) -> UserResponse<()> { - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &req.role_id, &user_from_token.merchant_id, @@ -144,10 +143,9 @@ pub async fn update_user_role( .attach_printable("User Changing their own role"); } - let updator_role = roles::RoleInfo::from_role_id_in_merchant_scope( + let updator_role = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -181,10 +179,9 @@ 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_in_merchant_scope( + let role_to_be_updated = roles::RoleInfo::from_role_id_and_org_id( &state, &user_role.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -262,10 +259,9 @@ 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_in_merchant_scope( + let role_to_be_updated = roles::RoleInfo::from_role_id_and_org_id( &state, &user_role.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -489,10 +485,9 @@ pub async fn delete_user_role( .attach_printable("User deleting himself"); } - let deletion_requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let deletion_requestor_role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -527,7 +522,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_in_merchant_scope( + let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, @@ -597,7 +592,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_in_merchant_scope( + let target_role_info = roles::RoleInfo::from_role_id_in_lineage( &state, &role_to_be_deleted.role_id, &user_from_token.merchant_id, @@ -685,10 +680,9 @@ pub async fn list_users_in_lineage( 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( + let requestor_role_info = roles::RoleInfo::from_role_id_and_org_id( &state, &user_from_token.role_id, - &user_from_token.merchant_id, &user_from_token.org_id, ) .await @@ -783,7 +777,7 @@ pub async fn list_users_in_lineage( 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( + roles::RoleInfo::from_role_id_and_org_id( &state, &user_role.role_id, &user_from_token.org_id, diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 9f251f55bdf..714bf9fed3c 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -76,8 +76,10 @@ pub async fn create_role( ) .await?; + let user_role_info = user_from_token.get_role_info_from_db(&state).await?; + if matches!(req.role_scope, RoleScope::Organization) - && user_from_token.role_id != common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN + && user_role_info.get_entity_type() != EntityType::Organization { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Non org admin user creating org level role"); @@ -116,14 +118,10 @@ 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_in_merchant_scope( - &state, - &role.role_id, - &user_from_token.merchant_id, - &user_from_token.org_id, - ) - .await - .to_not_found_response(UserErrors::InvalidRoleId)?; + let role_info = + roles::RoleInfo::from_role_id_and_org_id(&state, &role.role_id, &user_from_token.org_id) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleId.into()); @@ -144,14 +142,10 @@ pub async fn get_parent_info_for_role( user_from_token: UserFromToken, role: role_api::GetRoleRequest, ) -> UserResponse<role_api::RoleInfoWithParents> { - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( - &state, - &role.role_id, - &user_from_token.merchant_id, - &user_from_token.org_id, - ) - .await - .to_not_found_response(UserErrors::InvalidRoleId)?; + let role_info = + roles::RoleInfo::from_role_id_and_org_id(&state, &role.role_id, &user_from_token.org_id) + .await + .to_not_found_response(UserErrors::InvalidRoleId)?; if role_info.is_internal() { return Err(UserErrors::InvalidRoleId.into()); @@ -207,7 +201,7 @@ pub async fn update_role( utils::user_role::validate_role_groups(groups)?; } - let role_info = roles::RoleInfo::from_role_id_in_merchant_scope( + let role_info = roles::RoleInfo::from_role_id_in_lineage( &state, role_id, &user_from_token.merchant_id, @@ -216,8 +210,10 @@ pub async fn update_role( .await .to_not_found_response(UserErrors::InvalidRoleOperation)?; + let user_role_info = user_from_token.get_role_info_from_db(&state).await?; + if matches!(role_info.get_scope(), RoleScope::Organization) - && user_from_token.role_id != common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN + && user_role_info.get_entity_type() != EntityType::Organization { return Err(report!(UserErrors::InvalidRoleOperation)) .attach_printable("Non org admin user changing org level role"); diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 47c9adafb71..2fd30a3610b 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3521,6 +3521,7 @@ impl RoleInterface for KafkaStore { self.diesel_store.find_role_by_role_id(role_id).await } + //TODO:Remove once find_by_role_id_in_lineage is stable async fn find_role_by_role_id_in_merchant_scope( &self, role_id: &str, @@ -3532,13 +3533,24 @@ impl RoleInterface for KafkaStore { .await } - async fn find_role_by_role_id_in_org_scope( + async fn find_role_by_role_id_in_lineage( + &self, + role_id: &str, + merchant_id: &id_type::MerchantId, + org_id: &id_type::OrganizationId, + ) -> CustomResult<storage::Role, errors::StorageError> { + self.diesel_store + .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id) + .await + } + + async fn find_by_role_id_and_org_id( &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) + .find_by_role_id_and_org_id(role_id, org_id) .await } diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index d13508356e5..877a4c54077 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -23,6 +23,7 @@ pub trait RoleInterface { role_id: &str, ) -> CustomResult<storage::Role, errors::StorageError>; + //TODO:Remove once find_by_role_id_in_lineage is stable async fn find_role_by_role_id_in_merchant_scope( &self, role_id: &str, @@ -30,7 +31,14 @@ pub trait RoleInterface { org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Role, errors::StorageError>; - async fn find_role_by_role_id_in_org_scope( + async fn find_role_by_role_id_in_lineage( + &self, + role_id: &str, + merchant_id: &id_type::MerchantId, + org_id: &id_type::OrganizationId, + ) -> CustomResult<storage::Role, errors::StorageError>; + + async fn find_by_role_id_and_org_id( &self, role_id: &str, org_id: &id_type::OrganizationId, @@ -86,6 +94,7 @@ impl RoleInterface for Store { .map_err(|error| report!(errors::StorageError::from(error))) } + //TODO:Remove once find_by_role_id_in_lineage is stable #[instrument(skip_all)] async fn find_role_by_role_id_in_merchant_scope( &self, @@ -100,13 +109,26 @@ impl RoleInterface for Store { } #[instrument(skip_all)] - async fn find_role_by_role_id_in_org_scope( + async fn find_role_by_role_id_in_lineage( &self, role_id: &str, + merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> CustomResult<storage::Role, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::Role::find_by_role_id_in_org_scope(&conn, role_id, org_id) + storage::Role::find_by_role_id_in_lineage(&conn, role_id, merchant_id, org_id) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } + + #[instrument(skip_all)] + async fn find_by_role_id_and_org_id( + &self, + role_id: &str, + org_id: &id_type::OrganizationId, + ) -> CustomResult<storage::Role, errors::StorageError> { + let conn = connection::pg_connection_read(self).await?; + storage::Role::find_by_role_id_and_org_id(&conn, role_id, org_id) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -217,6 +239,7 @@ impl RoleInterface for MockDb { ) } + // TODO: Remove once find_by_role_id_in_lineage is stable async fn find_role_by_role_id_in_merchant_scope( &self, role_id: &str, @@ -241,7 +264,33 @@ impl RoleInterface for MockDb { ) } - async fn find_role_by_role_id_in_org_scope( + async fn find_role_by_role_id_in_lineage( + &self, + role_id: &str, + merchant_id: &id_type::MerchantId, + 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 + && ((role.scope == enums::RoleScope::Organization) + || (role.merchant_id == *merchant_id + && role.scope == enums::RoleScope::Merchant)) + }) + .cloned() + .ok_or( + errors::StorageError::ValueNotFound(format!( + "No role available in merchant scope for role_id = {role_id}, \ + merchant_id = {merchant_id:?} and org_id = {org_id:?}" + )) + .into(), + ) + } + + async fn find_by_role_id_and_org_id( &self, role_id: &str, org_id: &id_type::OrganizationId, diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index e0feaa5e817..2b7e8bd7340 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -33,8 +33,7 @@ where return Ok(role_info.clone()); } - let role_info = - get_role_info_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.org_id).await?; let token_expiry = i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; @@ -68,7 +67,6 @@ pub fn get_cache_key_from_role_id(role_id: &str) -> String { async fn get_role_info_from_db<A>( state: &A, role_id: &str, - merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> RouterResult<roles::RoleInfo> where @@ -76,7 +74,7 @@ where { state .store() - .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .find_by_role_id_and_org_id(role_id, org_id) .await .map(roles::RoleInfo::from) .to_not_found_response(ApiErrorResponse::InvalidJwtToken) diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs index a6c5cee1c4e..dcffa3107c9 100644 --- a/crates/router/src/services/authorization/roles.rs +++ b/crates/router/src/services/authorization/roles.rs @@ -116,7 +116,7 @@ impl RoleInfo { acl } - pub async fn from_role_id_in_merchant_scope( + pub async fn from_role_id_in_lineage( state: &SessionState, role_id: &str, merchant_id: &id_type::MerchantId, @@ -127,13 +127,13 @@ impl RoleInfo { } else { state .store - .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id) + .find_role_by_role_id_in_lineage(role_id, merchant_id, org_id) .await .map(Self::from) } } - pub async fn from_role_id_in_org_scope( + pub async fn from_role_id_and_org_id( state: &SessionState, role_id: &str, org_id: &id_type::OrganizationId, @@ -143,7 +143,7 @@ impl RoleInfo { } else { state .store - .find_role_by_role_id_in_org_scope(role_id, org_id) + .find_by_role_id_and_org_id(role_id, org_id) .await .map(Self::from) } diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 519edf4e9ce..bf5556dd9a7 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -337,8 +337,7 @@ impl NextFlow { .change_context(UserErrors::InternalServerError)? .pop() .ok_or(UserErrors::InternalServerError)?; - utils::user_role::set_role_permissions_in_cache_by_user_role(state, &user_role) - .await; + utils::user_role::set_role_info_in_cache_by_user_role(state, &user_role).await; jwt_flow.generate_jwt(state, self, &user_role).await } @@ -357,8 +356,7 @@ impl NextFlow { { self.user.get_verification_days_left(state)?; } - utils::user_role::set_role_permissions_in_cache_by_user_role(state, user_role) - .await; + utils::user_role::set_role_info_in_cache_by_user_role(state, 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 9886705ec66..abd59684243 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -77,14 +77,9 @@ impl UserFromToken { } pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> { - RoleInfo::from_role_id_in_merchant_scope( - state, - &self.role_id, - &self.merchant_id, - &self.org_id, - ) - .await - .change_context(UserErrors::InternalServerError) + RoleInfo::from_role_id_and_org_id(state, &self.role_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 3412219d0e9..b8f93bff943 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -71,55 +71,43 @@ pub async fn validate_role_name( Ok(()) } -pub async fn set_role_permissions_in_cache_by_user_role( +pub async fn set_role_info_in_cache_by_user_role( state: &SessionState, user_role: &UserRole, ) -> bool { - let Some(ref merchant_id) = user_role.merchant_id else { - return false; - }; - let Some(ref org_id) = user_role.org_id else { return false; }; - set_role_permissions_in_cache_if_required( - state, - user_role.role_id.as_str(), - merchant_id, - org_id, - ) - .await - .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) - .is_ok() + set_role_info_in_cache_if_required(state, user_role.role_id.as_str(), org_id) + .await + .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) + .is_ok() } -pub async fn set_role_permissions_in_cache_by_role_id_merchant_id_org_id( +pub async fn set_role_info_in_cache_by_role_id_org_id( state: &SessionState, role_id: &str, - merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> bool { - set_role_permissions_in_cache_if_required(state, role_id, merchant_id, org_id) + set_role_info_in_cache_if_required(state, role_id, org_id) .await .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e)) .is_ok() } -pub async fn set_role_permissions_in_cache_if_required( +pub async fn set_role_info_in_cache_if_required( state: &SessionState, role_id: &str, - merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> UserResult<()> { if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) { return Ok(()); } - 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")?; + let role_info = roles::RoleInfo::from_role_id_and_org_id(state, role_id, org_id) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error getting role_info from role_id")?; authz::set_role_info_in_cache( state, diff --git a/migrations/2024-12-02-110129_update-user-role-entity-type/down.sql b/migrations/2024-12-02-110129_update-user-role-entity-type/down.sql new file mode 100644 index 00000000000..c7c9cbeb401 --- /dev/null +++ b/migrations/2024-12-02-110129_update-user-role-entity-type/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +SELECT 1; \ No newline at end of file diff --git a/migrations/2024-12-02-110129_update-user-role-entity-type/up.sql b/migrations/2024-12-02-110129_update-user-role-entity-type/up.sql new file mode 100644 index 00000000000..f2759f030d5 --- /dev/null +++ b/migrations/2024-12-02-110129_update-user-role-entity-type/up.sql @@ -0,0 +1,10 @@ +-- Your SQL goes here +UPDATE user_roles +SET + entity_type = CASE + WHEN role_id = 'org_admin' THEN 'organization' + ELSE 'merchant' + END +WHERE + version = 'v1' + AND entity_type IS NULL; \ No newline at end of file
2024-11-29T06:19:36Z
## 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 --> - Refactor the find_by_role_id_in_merchant_scope query to make it a generic query that uses only org_id and role_id as parameters. - This PR also includes backfilling user_roles entity_type column based on user_role ### 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 [6702](https://github.com/juspay/hyperswitch/issues/6702) ## 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)? --> Using dashboard . All the below should work as before Cases to test : - Create a custom role from dashboard - Invite someone for that custom role - signin via that custom-role-user - List roles and list roles at entity level - List users ## 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
6eb7cc14613d94f4711e39e16dc015a30b02cf0e
juspay/hyperswitch
juspay__hyperswitch-6713
Bug: ci: update expiry year to a later date ntid checks are failing because of expired cards
2024-12-02T09:21:32Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [x] CI/CD ## Description <!-- Describe your changes in detail --> this pr increments expiry year to a later date closes https://github.com/juspay/hyperswitch/issues/6713 ### 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). --> 4xx ## 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)? --> ci should pass ## 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
22b5a93e02156cd92adf5e24a3fd8d0e39e8d429
juspay/hyperswitch
juspay__hyperswitch-6698
Bug: refactor(users): Use domain email type in DB functions Currently lowercase email check is there in `UserEmail` type. But DB is using `pii::Email` type, which might cause unexpected behaviour in some cases.
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index b02da396075..850cc470316 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -274,6 +274,11 @@ pub enum ApiErrorResponse { LinkConfigurationError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")] PayoutFailed { data: Option<serde_json::Value> }, + #[error( + error_type = ErrorType::InvalidRequestError, code = "IR_42", + message = "Cookies are not found in the request" + )] + CookieNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] WebhookAuthenticationFailed, @@ -627,6 +632,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::PayoutFailed { data } => { AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()}))) }, + Self::CookieNotFound => { + AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None)) + }, Self::WebhookAuthenticationFailed => { AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index efe0ac157e0..6cf078b5f81 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -444,7 +444,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie - | errors::ApiErrorResponse::InvalidEphemeralKey => Self::Unauthorized, + | errors::ApiErrorResponse::InvalidEphemeralKey + | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 2087d01dbb4..20fea3ac362 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -166,7 +166,7 @@ pub async fn signin_token_only_flow( ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email(&request.email) + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .to_not_found_response(UserErrors::InvalidCredentials)? .into(); @@ -191,7 +191,10 @@ pub async fn connect_account( request: user_api::ConnectAccountRequest, auth_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { - let find_user = state.global_store.find_user_by_email(&request.email).await; + let find_user = state + .global_store + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email.clone())?) + .await; if let Ok(found_user) = find_user { let user_from_db: domain::UserFromStorage = found_user.into(); @@ -369,7 +372,7 @@ pub async fn forgot_password( let user_from_db = state .global_store - .find_user_by_email(&user_email.into_inner()) + .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -453,11 +456,7 @@ pub async fn reset_password_token_only_flow( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -564,10 +563,7 @@ async fn handle_invitation( } let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; - let invitee_user = state - .global_store - .find_user_by_email(&invitee_email.into_inner()) - .await; + let invitee_user = state.global_store.find_user_by_email(&invitee_email).await; if let Ok(invitee_user) = invitee_user { handle_existing_user_invitation( @@ -946,7 +942,7 @@ pub async fn resend_invite( let invitee_email = domain::UserEmail::from_pii_email(request.email)?; let user: domain::UserFromStorage = state .global_store - .find_user_by_email(&invitee_email.clone().into_inner()) + .find_user_by_email(&invitee_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1045,11 +1041,7 @@ pub async fn accept_invite_from_email_token_only_flow( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -1493,11 +1485,7 @@ pub async fn verify_email_token_only_flow( let user_from_email = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)?; @@ -1540,7 +1528,7 @@ pub async fn send_verification_mail( let user_email = domain::UserEmail::try_from(req.email)?; let user = state .global_store - .find_user_by_email(&user_email.into_inner()) + .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1637,11 +1625,7 @@ pub async fn user_from_email( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -2347,7 +2331,7 @@ pub async fn sso_sign( // TODO: Use config to handle not found error let user_from_db = state .global_store - .find_user_by_email(&email.into_inner()) + .find_user_by_email(&email) .await .map(Into::into) .to_not_found_response(UserErrors::UserNotFound)?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 6641e553fd8..df4771dbe70 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -440,7 +440,7 @@ pub async fn delete_user_role( ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?.into_inner()) + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .map_err(|e| { if e.current_context().is_db_not_found() { diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index a9df1abbc08..5d6fac3b130 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use common_enums::enums::MerchantStorageScheme; use common_utils::{ errors::CustomResult, - id_type, pii, + id_type, types::{keymanager::KeyManagerState, theme::ThemeLineage}, }; use diesel_models::{ @@ -2983,7 +2983,7 @@ impl UserInterface for KafkaStore { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.find_user_by_email(user_email).await } @@ -3007,7 +3007,7 @@ impl UserInterface for KafkaStore { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index 14bed15fa45..089c9fc6eb7 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -3,11 +3,10 @@ use error_stack::report; use masking::Secret; use router_env::{instrument, tracing}; -use super::MockDb; +use super::{domain, MockDb}; use crate::{ connection, core::errors::{self, CustomResult}, - pii, services::Store, }; pub mod sample_data; @@ -22,7 +21,7 @@ pub trait UserInterface { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_id( @@ -38,7 +37,7 @@ pub trait UserInterface { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; @@ -70,10 +69,10 @@ impl UserInterface for Store { #[instrument(skip_all)] async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::User::find_by_user_email(&conn, user_email) + storage::User::find_by_user_email(&conn, user_email.get_inner()) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -104,11 +103,11 @@ impl UserInterface for Store { #[instrument(skip_all)] async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::User::update_by_user_email(&conn, user_email, user) + storage::User::update_by_user_email(&conn, user_email.get_inner(), user) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -171,12 +170,12 @@ impl UserInterface for MockDb { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() - .find(|user| user.email.eq(user_email)) + .find(|user| user.email.eq(user_email.get_inner())) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( @@ -253,13 +252,13 @@ impl UserInterface for MockDb { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; users .iter_mut() - .find(|user| user.email.eq(user_email)) + .find(|user| user.email.eq(user_email.get_inner())) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index c05e4514aaa..2d5f81e980c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -2545,7 +2545,8 @@ where T: serde::de::DeserializeOwned, A: SessionStateInfo + Sync, { - let cookie_token_result = get_cookie_from_header(headers).and_then(cookies::parse_cookie); + let cookie_token_result = + get_cookie_from_header(headers).and_then(cookies::get_jwt_from_cookies); let auth_header_token_result = get_jwt_from_authorization_header(headers); let force_cookie = state.conf().user.force_cookies; @@ -3112,7 +3113,7 @@ pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( pub fn is_jwt_auth(headers: &HeaderMap) -> bool { headers.get(headers::AUTHORIZATION).is_some() || get_cookie_from_header(headers) - .and_then(cookies::parse_cookie) + .and_then(cookies::get_jwt_from_cookies) .is_ok() } @@ -3174,10 +3175,13 @@ pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&s } pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> { - headers + let cookie = headers .get(cookies::get_cookie_header()) - .and_then(|header_value| header_value.to_str().ok()) - .ok_or(errors::ApiErrorResponse::InvalidCookie.into()) + .ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?; + + cookie + .to_str() + .change_context(errors::ApiErrorResponse::InvalidCookie) } pub fn strip_jwt_token(token: &str) -> RouterResult<&str> { diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rs index 96518840800..4a297c0f0eb 100644 --- a/crates/router/src/services/authentication/cookies.rs +++ b/crates/router/src/services/authentication/cookies.rs @@ -49,7 +49,7 @@ pub fn remove_cookie_response() -> UserResponse<()> { Ok(ApplicationResponse::JsonWithHeaders(((), header))) } -pub fn parse_cookie(cookies: &str) -> RouterResult<String> { +pub fn get_jwt_from_cookies(cookies: &str) -> RouterResult<String> { Cookie::split_parse(cookies) .find_map(|cookie| { cookie @@ -57,8 +57,8 @@ pub fn parse_cookie(cookies: &str) -> RouterResult<String> { .filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME) .map(|parsed_cookie| parsed_cookie.value().to_owned()) }) - .ok_or(report!(ApiErrorResponse::InvalidCookie)) - .attach_printable("Cookie Parsing Failed") + .ok_or(report!(ApiErrorResponse::InvalidJwtToken)) + .attach_printable("Unable to find JWT token in cookies") } #[cfg(feature = "olap")] diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 87ff9f6abd5..8f48ef068ce 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -40,10 +40,12 @@ where i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp(); - set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) - .await - .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) - .ok(); + if cache_ttl > 0 { + set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) + .await + .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) + .ok(); + } Ok(role_info) } diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index d092afdc5de..8c966d79d80 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,9 +1,6 @@ use api_models::user::dashboard_metadata::ProdIntent; use common_enums::EntityType; -use common_utils::{ - errors::{self, CustomResult}, - pii, -}; +use common_utils::{errors::CustomResult, pii}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; use masking::{ExposeInterface, Secret}; @@ -183,7 +180,7 @@ impl EmailToken { entity: Option<Entity>, flow: domain::Origin, settings: &configs::Settings, - ) -> CustomResult<String, UserErrors> { + ) -> UserResult<String> { let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(expiration_duration)?.as_secs(); let token_payload = Self { @@ -195,8 +192,10 @@ impl EmailToken { jwt::generate_jwt(&token_payload, settings).await } - pub fn get_email(&self) -> CustomResult<pii::Email, errors::ParsingError> { + pub fn get_email(&self) -> UserResult<domain::UserEmail> { pii::Email::try_from(self.email.clone()) + .change_context(UserErrors::InternalServerError) + .and_then(domain::UserEmail::from_pii_email) } pub fn get_entity(&self) -> Option<&Entity> { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 6d0d2a4ea07..21212bf6b62 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -131,6 +131,10 @@ impl UserEmail { self.0 } + pub fn get_inner(&self) -> &pii::Email { + &self.0 + } + pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> { (*self.0).clone() } @@ -617,7 +621,7 @@ impl NewUser { pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .global_store - .find_user_by_email(&self.get_email().into_inner()) + .find_user_by_email(&self.get_email()) .await .is_ok() { diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index f115a16c062..443db741ae3 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -124,7 +124,7 @@ pub async fn get_user_from_db_by_email( ) -> CustomResult<UserFromStorage, StorageError> { state .global_store - .find_user_by_email(&email.into_inner()) + .find_user_by_email(&email) .await .map(UserFromStorage::from) }
2024-11-28T13:49:22Z
## 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 does 3 things. 1. Throw 401 if cookies are not found in request or if JWT is not found in cookies. 2. Cache role info only if the ttl is greater than or equal to 0. 3. Use `UserEmail` type in DB functions. ### 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` 4. `crates/router/src/configs` 5. `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 #6696. Closes #6697. Closes #6698. ## 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)? --> todo!() ## 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
707f48ceda789185187d23e35f483e117c67b81b
juspay/hyperswitch
juspay__hyperswitch-6707
Bug: feat(users): support tenant level users - Add api to create tenant_admin - Create org by tenant level user - Support tenant entity: tenant level roles/permission
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs index 15146e304af..a244f69f543 100644 --- a/crates/api_models/src/events/user.rs +++ b/crates/api_models/src/events/user.rs @@ -9,15 +9,15 @@ use crate::user::{ theme::{CreateThemeRequest, GetThemeResponse, UpdateThemeRequest, UploadFileRequest}, AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, - CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest, - GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, - GetUserRoleDetailsResponseV2, InviteUserRequest, ReInviteUserRequest, RecoveryCodes, - ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, - SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest, - SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse, - TwoFactorStatus, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, - UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, - VerifyTotpRequest, + CreateTenantUserRequest, CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, + GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, + GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, InviteUserRequest, + ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, + SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, + SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, + TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest, + UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate, + UserOrgMerchantCreateRequest, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; common_utils::impl_api_event_type!( @@ -34,6 +34,8 @@ common_utils::impl_api_event_type!( SwitchMerchantRequest, SwitchProfileRequest, CreateInternalUserRequest, + CreateTenantUserRequest, + UserOrgMerchantCreateRequest, UserMerchantCreate, AuthorizeResponse, ConnectAccountRequest, diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs index 82291ddc92a..da4f7c3cd2c 100644 --- a/crates/api_models/src/user.rs +++ b/crates/api_models/src/user.rs @@ -114,6 +114,21 @@ pub struct CreateInternalUserRequest { pub password: Secret<String>, } +#[derive(serde::Deserialize, Debug, serde::Serialize)] +pub struct CreateTenantUserRequest { + pub name: Secret<String>, + pub email: pii::Email, + pub password: Secret<String>, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct UserOrgMerchantCreateRequest { + pub organization_name: Secret<String>, + pub organization_details: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub merchant_name: Secret<String>, +} + #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index d966902af89..f32fc71265d 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3205,6 +3205,7 @@ pub enum ApiVersion { #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum EntityType { + Tenant = 3, Organization = 2, Merchant = 1, Profile = 0, diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index b43efcb1feb..e430d59e54d 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -119,6 +119,8 @@ pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64; /// Default locale pub const DEFAULT_LOCALE: &str = "en"; +/// Role ID for Tenant Admin +pub const ROLE_ID_TENANT_ADMIN: &str = "tenant_admin"; /// Role ID for Org Admin pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin"; /// Role ID for Internal View Only diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs index fd5a171b7eb..03945646014 100644 --- a/crates/diesel_models/src/query/merchant_account.rs +++ b/crates/diesel_models/src/query/merchant_account.rs @@ -121,6 +121,26 @@ impl MerchantAccount { .await } + pub async fn list_all_merchant_accounts( + conn: &PgPooledConn, + limit: u32, + offset: Option<u32>, + ) -> StorageResult<Vec<Self>> { + generics::generic_filter::< + <Self as HasTable>::Table, + _, + <<Self as HasTable>::Table as Table>::PrimaryKey, + _, + >( + conn, + dsl_identifier.ne_all(vec![""]), + Some(i64::from(limit)), + offset.map(i64::from), + None, + ) + .await + } + pub async fn update_all_merchant_accounts( conn: &PgPooledConn, merchant_account: MerchantAccountUpdateInternal, diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index d957c3071ff..752c3a52284 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1931,6 +1931,9 @@ pub mod routes { EntityType::Organization => Some(AuthInfo::OrgLevel { org_id: user_role.org_id.clone()?, }), + EntityType::Tenant => Some(AuthInfo::OrgLevel { + org_id: auth.org_id.clone(), + }), }) }) .collect(); @@ -2054,6 +2057,9 @@ pub mod routes { EntityType::Organization => Some(AuthInfo::OrgLevel { org_id: user_role.org_id.clone()?, }), + EntityType::Tenant => Some(AuthInfo::OrgLevel { + org_id: auth.org_id.clone(), + }), }) }) .collect(); diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index 32ca4ad31d7..d4eb12e39bf 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -19,6 +19,8 @@ pub const TOTP_TOLERANCE: u8 = 1; pub const TOTP_MAX_ATTEMPTS: u8 = 4; /// Number of maximum attempts user has for recovery code pub const RECOVERY_CODE_MAX_ATTEMPTS: u8 = 4; +/// The default number of organizations to fetch for a tenant-level user +pub const ORG_LIST_LIMIT_FOR_TENANT: u32 = 20; pub const MAX_PASSWORD_LENGTH: usize = 70; pub const MIN_PASSWORD_LENGTH: usize = 8; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 4f77b219044..d1cd6f21d91 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -25,9 +25,13 @@ use router_env::logger; #[cfg(not(feature = "email"))] use user_api::dashboard_metadata::SetMetaDataRequest; +#[cfg(feature = "v1")] +use super::admin; use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult}; #[cfg(feature = "email")] use crate::services::email::types as email_types; +#[cfg(feature = "v1")] +use crate::types::transformers::ForeignFrom; use crate::{ consts, core::encryption::send_request_to_key_service_for_user, @@ -648,6 +652,12 @@ async fn handle_existing_user_invitation( } let (org_id, merchant_id, profile_id) = match role_info.get_entity_type() { + EntityType::Tenant => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Tenant roles are not allowed for this operation".to_string(), + ) + .into()); + } EntityType::Organization => (Some(&user_from_token.org_id), None, None), EntityType::Merchant => ( Some(&user_from_token.org_id), @@ -701,6 +711,12 @@ async fn handle_existing_user_invitation( }; let _user_role = match role_info.get_entity_type() { + EntityType::Tenant => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Tenant roles are not allowed for this operation".to_string(), + ) + .into()); + } EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { @@ -747,6 +763,12 @@ 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::Tenant => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Tenant roles are not allowed for this operation".to_string(), + ) + .into()); + } EntityType::Organization => email_types::Entity { entity_id: user_from_token.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, @@ -830,6 +852,12 @@ async fn handle_new_user_invitation( }; let _user_role = match role_info.get_entity_type() { + EntityType::Tenant => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Tenant roles are not allowed for this operation".to_string(), + ) + .into()); + } EntityType::Organization => { user_role .add_entity(domain::OrganizationLevel { @@ -880,6 +908,12 @@ 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::Tenant => { + return Err(UserErrors::InvalidRoleOperationWithMessage( + "Tenant roles are not allowed for this operation".to_string(), + ) + .into()); + } EntityType::Organization => email_types::Entity { entity_id: user_from_token.org_id.get_string_repr().to_owned(), entity_type: EntityType::Organization, @@ -1235,6 +1269,83 @@ pub async fn create_internal_user( Ok(ApplicationResponse::StatusOk) } +pub async fn create_tenant_user( + state: SessionState, + request: user_api::CreateTenantUserRequest, +) -> UserResponse<()> { + let key_manager_state = &(&state).into(); + + let (merchant_id, org_id) = state + .store + .list_merchant_and_org_ids(key_manager_state, 1, None) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get merchants list for org")? + .pop() + .ok_or(UserErrors::InternalServerError) + .attach_printable("No merchants found in the tenancy")?; + + let new_user = domain::NewUser::try_from(( + request, + domain::MerchantAccountIdentifier { + merchant_id, + org_id, + }, + ))?; + let mut store_user: storage_user::UserNew = new_user.clone().try_into()?; + store_user.set_is_verified(true); + + state + .global_store + .insert_user(store_user) + .await + .map_err(|e| { + if e.current_context().is_db_unique_violation() { + e.change_context(UserErrors::UserExists) + } else { + e.change_context(UserErrors::InternalServerError) + } + }) + .map(domain::user::UserFromStorage::from)?; + + new_user + .get_no_level_user_role( + common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(), + UserStatus::Active, + ) + .add_entity(domain::TenantLevel { + tenant_id: state.tenant.tenant_id.clone(), + }) + .insert_in_v2(&state) + .await + .change_context(UserErrors::InternalServerError)?; + + Ok(ApplicationResponse::StatusOk) +} + +#[cfg(feature = "v1")] +pub async fn create_org_merchant_for_user( + state: SessionState, + req: user_api::UserOrgMerchantCreateRequest, +) -> UserResponse<()> { + let db_organization = ForeignFrom::foreign_from(req.clone()); + let org: diesel_models::organization::Organization = state + .store + .insert_organization(db_organization) + .await + .change_context(UserErrors::InternalServerError)?; + + let merchant_account_create_request = + utils::user::create_merchant_account_request_for_org(req, org)?; + + admin::create_merchant_account(state.clone(), merchant_account_create_request) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Error while creating a merchant")?; + + Ok(ApplicationResponse::StatusOk) +} + pub async fn create_merchant_account( state: SessionState, user_from_token: auth::UserFromToken, @@ -1352,7 +1463,7 @@ pub async fn list_user_roles_details( merchant.push(merchant_id.clone()); merchant_profile.push((merchant_id, profile_id)) } - EntityType::Organization => (), + EntityType::Tenant | EntityType::Organization => (), }; Ok::<_, error_stack::Report<UserErrors>>((merchant, merchant_profile)) @@ -1438,7 +1549,7 @@ pub async fn list_user_roles_details( .ok_or(UserErrors::InternalServerError)?; let (merchant, profile) = match entity_type { - EntityType::Organization => (None, None), + EntityType::Tenant | EntityType::Organization => (None, None), EntityType::Merchant => { let merchant_id = &user_role .merchant_id @@ -2437,28 +2548,44 @@ pub async fn list_orgs_for_user( ) .into()); } - - let orgs = state - .global_store - .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { - user_id: user_from_token.user_id.as_str(), - tenant_id: user_from_token - .tenant_id - .as_ref() - .unwrap_or(&state.tenant.tenant_id), - 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 orgs = match role_info.get_entity_type() { + EntityType::Tenant => { + let key_manager_state = &(&state).into(); + state + .store + .list_merchant_and_org_ids( + key_manager_state, + consts::user::ORG_LIST_LIMIT_FOR_TENANT, + None, + ) + .await + .change_context(UserErrors::InternalServerError)? + .into_iter() + .map(|(_, org_id)| org_id) + .collect::<HashSet<_>>() + } + EntityType::Organization | EntityType::Merchant | EntityType::Profile => state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: user_from_token.user_id.as_str(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + 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() @@ -2501,7 +2628,7 @@ pub async fn list_merchants_for_user_in_org( } let merchant_accounts = match role_info.get_entity_type() { - EntityType::Organization => state + EntityType::Tenant | EntityType::Organization => state .store .list_merchant_accounts_by_organization_id(&(&state).into(), &user_from_token.org_id) .await @@ -2580,7 +2707,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 => state + EntityType::Tenant | EntityType::Organization | EntityType::Merchant => state .store .list_profile_by_merchant_id( key_manager_state, @@ -2670,39 +2797,80 @@ pub async fn switch_org_for_user( .into()); } - let user_role = state - .global_store - .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { - user_id: &user_from_token.user_id, - tenant_id: user_from_token - .tenant_id - .as_ref() - .unwrap_or(&state.tenant.tenant_id), - org_id: Some(&request.org_id), - merchant_id: None, - 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 by user_id and org_id")? - .pop() - .ok_or(UserErrors::InvalidRoleOperationWithMessage( - "No user role found for the requested org_id".to_string(), - ))?; + let (merchant_id, profile_id, role_id) = match role_info.get_entity_type() { + EntityType::Tenant => { + let merchant_id = state + .store + .list_merchant_accounts_by_organization_id(&(&state).into(), &request.org_id) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get merchant list for org")? + .pop() + .ok_or(UserErrors::InvalidRoleOperation) + .attach_printable("No merchants found for the org 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 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)?; + + let profile_id = state + .store + .list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id) + .await + .change_context(UserErrors::InternalServerError)? + .pop() + .ok_or(UserErrors::InternalServerError)? + .get_id() + .to_owned(); + + (merchant_id, profile_id, user_from_token.role_id) + } + EntityType::Organization | EntityType::Merchant | EntityType::Profile => { + let user_role = state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: &user_from_token.user_id, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + org_id: Some(&request.org_id), + merchant_id: None, + 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 by user_id and org_id")? + .pop() + .ok_or(UserErrors::InvalidRoleOperationWithMessage( + "No user role found for the requested org_id".to_string(), + ))?; + + let (merchant_id, profile_id) = + utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?; + + (merchant_id, profile_id, user_role.role_id) + } + }; let token = utils::user::generate_jwt_auth_token_with_attributes( &state, user_from_token.user_id, merchant_id.clone(), request.org_id.clone(), - user_role.role_id.clone(), + role_id.clone(), profile_id.clone(), user_from_token.tenant_id, ) @@ -2710,7 +2878,7 @@ pub async fn switch_org_for_user( utils::user_role::set_role_permissions_in_cache_by_role_id_merchant_id_org_id( &state, - &user_role.role_id, + &role_id, &merchant_id, &request.org_id, ) @@ -2794,7 +2962,7 @@ pub async fn switch_merchant_for_user_in_org( } else { // Match based on the other entity types match role_info.get_entity_type() { - EntityType::Organization => { + EntityType::Tenant | EntityType::Organization => { let merchant_key_store = state .store .get_merchant_key_store_by_merchant_id( @@ -2937,7 +3105,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::Organization | EntityType::Merchant => { + EntityType::Tenant | 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 273b863afe8..31ec665b2ab 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -698,7 +698,7 @@ pub async fn list_users_in_lineage( requestor_role_info.get_entity_type(), request.entity_type, )? { - EntityType::Organization => { + EntityType::Tenant | EntityType::Organization => { utils::user_role::fetch_user_roles_by_payload( &state, ListUserRolesByOrgIdPayload { @@ -871,6 +871,10 @@ pub async fn list_invitations_for_user( .attach_printable("Failed to compute entity id and type")?; match entity_type { + EntityType::Tenant => { + return Err(report!(UserErrors::InternalServerError)) + .attach_printable("Tenant roles are not allowed for this operation"); + } EntityType::Organization => org_ids.push( user_role .org_id @@ -975,6 +979,10 @@ pub async fn list_invitations_for_user( .attach_printable("Failed to compute entity id and type")?; let entity_name = match entity_type { + EntityType::Tenant => { + return Err(report!(UserErrors::InternalServerError)) + .attach_printable("Tenant roles are not allowed for this operation"); + } EntityType::Organization => user_role .org_id .as_ref() diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index c01d585feb7..9f251f55bdf 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -274,7 +274,7 @@ pub async fn list_roles_with_info( let user_role_entity = user_role_info.get_entity_type(); let custom_roles = match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? { - EntityType::Organization => state + EntityType::Tenant | EntityType::Organization => state .store .list_roles_for_org_by_parameters( &user_from_token.org_id, @@ -347,7 +347,7 @@ pub async fn list_roles_at_entity_level( .collect::<Vec<_>>(); let custom_roles = match req.entity_type { - EntityType::Organization => state + EntityType::Tenant | EntityType::Organization => state .store .list_roles_for_org_by_parameters( &user_from_token.org_id, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index 9a284f1399d..47c9adafb71 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -1048,6 +1048,19 @@ impl MerchantAccountInterface for KafkaStore { .list_multiple_merchant_accounts(state, merchant_ids) .await } + + #[cfg(feature = "olap")] + async fn list_merchant_and_org_ids( + &self, + state: &KeyManagerState, + limit: u32, + offset: Option<u32>, + ) -> CustomResult<Vec<(id_type::MerchantId, id_type::OrganizationId)>, errors::StorageError> + { + self.diesel_store + .list_merchant_and_org_ids(state, limit, offset) + .await + } } #[async_trait::async_trait] diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 6eb355e4434..4f4a3f1cf00 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -87,6 +87,20 @@ where state: &KeyManagerState, merchant_ids: Vec<common_utils::id_type::MerchantId>, ) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>; + + #[cfg(feature = "olap")] + async fn list_merchant_and_org_ids( + &self, + state: &KeyManagerState, + limit: u32, + offset: Option<u32>, + ) -> CustomResult< + Vec<( + common_utils::id_type::MerchantId, + common_utils::id_type::OrganizationId, + )>, + errors::StorageError, + >; } #[async_trait::async_trait] @@ -411,6 +425,37 @@ impl MerchantAccountInterface for Store { Ok(merchant_accounts) } + #[cfg(feature = "olap")] + #[instrument(skip_all)] + async fn list_merchant_and_org_ids( + &self, + _state: &KeyManagerState, + limit: u32, + offset: Option<u32>, + ) -> CustomResult< + Vec<( + common_utils::id_type::MerchantId, + common_utils::id_type::OrganizationId, + )>, + errors::StorageError, + > { + let conn = connection::pg_connection_read(self).await?; + let encrypted_merchant_accounts = + storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset) + .await + .map_err(|error| report!(errors::StorageError::from(error)))?; + + let merchant_and_org_ids = encrypted_merchant_accounts + .into_iter() + .map(|merchant_account| { + let merchant_id = merchant_account.get_id().clone(); + let org_id = merchant_account.organization_id; + (merchant_id, org_id) + }) + .collect(); + Ok(merchant_and_org_ids) + } + async fn update_all_merchant_account( &self, merchant_account: storage::MerchantAccountUpdate, @@ -694,6 +739,33 @@ impl MerchantAccountInterface for MockDb { .into_iter() .collect() } + + #[cfg(feature = "olap")] + async fn list_merchant_and_org_ids( + &self, + _state: &KeyManagerState, + limit: u32, + offset: Option<u32>, + ) -> CustomResult< + Vec<( + common_utils::id_type::MerchantId, + common_utils::id_type::OrganizationId, + )>, + errors::StorageError, + > { + let accounts = self.merchant_accounts.lock().await; + let limit = limit.try_into().unwrap_or(accounts.len()); + let offset = offset.unwrap_or(0).try_into().unwrap_or(0); + + let merchant_and_org_ids = accounts + .iter() + .skip(offset) + .take(limit) + .map(|account| (account.get_id().clone(), account.organization_id.clone())) + .collect::<Vec<_>>(); + + Ok(merchant_and_org_ids) + } } #[cfg(feature = "accounts_cache")] diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 0fca984cc57..6353489e81e 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1883,6 +1883,10 @@ impl User { .service( web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)), ) + .service( + web::resource("/tenant_signup").route(web::post().to(user::create_tenant_user)), + ) + .service(web::resource("/create_org").route(web::post().to(user::user_org_create))) .service( web::resource("/create_merchant") .route(web::post().to(user::user_merchant_account_create)), diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 1c7db127ffc..adb619f3f26 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -223,9 +223,11 @@ impl From<Flow> for ApiIdentifier { | Flow::GetMultipleDashboardMetadata | Flow::VerifyPaymentConnector | Flow::InternalUserSignup + | Flow::TenantUserCreate | Flow::SwitchOrg | Flow::SwitchMerchantV2 | Flow::SwitchProfile + | Flow::UserOrgMerchantCreate | Flow::UserMerchantAccountCreate | Flow::GenerateSampleData | Flow::DeleteSampleData diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs index d5f31be3965..c32746c8718 100644 --- a/crates/router/src/routes/user.rs +++ b/crates/router/src/routes/user.rs @@ -229,6 +229,47 @@ pub async fn internal_user_signup( .await } +pub async fn create_tenant_user( + state: web::Data<AppState>, + http_req: HttpRequest, + json_payload: web::Json<user_api::CreateTenantUserRequest>, +) -> HttpResponse { + let flow = Flow::TenantUserCreate; + Box::pin(api::server_wrap( + flow, + state.clone(), + &http_req, + json_payload.into_inner(), + |state, _, req, _| user_core::create_tenant_user(state, req), + &auth::AdminApiAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} + +#[cfg(feature = "v1")] +pub async fn user_org_create( + state: web::Data<AppState>, + req: HttpRequest, + json_payload: web::Json<user_api::UserOrgMerchantCreateRequest>, +) -> HttpResponse { + let flow = Flow::UserOrgMerchantCreate; + Box::pin(api::server_wrap( + flow, + state, + &req, + json_payload.into_inner(), + |state, _auth: auth::UserFromToken, json_payload, _| { + user_core::create_org_merchant_for_user(state, json_payload) + }, + &auth::JWTAuth { + permission: Permission::TenantAccountWrite, + }, + api_locking::LockAction::NotApplicable, + )) + .await +} + pub async fn user_merchant_account_create( state: web::Data<AppState>, req: HttpRequest, diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs index 6f612007425..578ccdcf9d4 100644 --- a/crates/router/src/services/authorization/permissions.rs +++ b/crates/router/src/services/authorization/permissions.rs @@ -33,7 +33,7 @@ generate_permissions! { }, Account: { scopes: [Read, Write], - entities: [Profile, Merchant, Organization] + entities: [Profile, Merchant, Organization, Tenant] }, Connector: { scopes: [Read, Write], @@ -125,6 +125,7 @@ pub fn get_resource_name(resource: &Resource, entity_type: &EntityType) -> &'sta (Resource::Account, EntityType::Profile) => "Business Profile Account", (Resource::Account, EntityType::Merchant) => "Merchant Account", (Resource::Account, EntityType::Organization) => "Organization Account", + (Resource::Account, EntityType::Tenant) => "Tenant Account", } } diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs index 9c67c12f527..fe7498de9eb 100644 --- a/crates/router/src/services/authorization/roles/predefined_roles.rs +++ b/crates/router/src/services/authorization/roles/predefined_roles.rs @@ -68,7 +68,42 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(| }, ); - // Merchant Roles + // Tenant Roles + roles.insert( + common_utils::consts::ROLE_ID_TENANT_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::AccountView, + PermissionGroup::MerchantDetailsManage, + PermissionGroup::AccountManage, + PermissionGroup::OrganizationManage, + PermissionGroup::ReconOpsView, + PermissionGroup::ReconOpsManage, + PermissionGroup::ReconReportsView, + PermissionGroup::ReconReportsManage, + ], + role_id: common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(), + role_name: "tenant_admin".to_string(), + scope: RoleScope::Organization, + entity_type: EntityType::Tenant, + is_invitable: false, + is_deletable: false, + is_updatable: false, + is_internal: false, + }, + ); + + // Organization Roles roles.insert( common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN, RoleInfo { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 21212bf6b62..6efaac7bfed 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -312,6 +312,40 @@ impl From<InviteeUserRequestWithInvitedUserToken> for NewUserOrganization { } } +impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserOrganization { + fn from( + (_value, merchant_account_identifier): ( + user_api::CreateTenantUserRequest, + MerchantAccountIdentifier, + ), + ) -> Self { + let new_organization = api_org::OrganizationNew { + org_id: merchant_account_identifier.org_id, + org_name: None, + }; + let db_organization = ForeignFrom::foreign_from(new_organization); + Self(db_organization) + } +} + +impl ForeignFrom<api_models::user::UserOrgMerchantCreateRequest> + for diesel_models::organization::OrganizationNew +{ + fn foreign_from(item: api_models::user::UserOrgMerchantCreateRequest) -> Self { + let org_id = id_type::OrganizationId::default(); + let api_models::user::UserOrgMerchantCreateRequest { + organization_name, + organization_details, + metadata, + .. + } = item; + let mut org_new_db = Self::new(org_id, Some(organization_name.expose())); + org_new_db.organization_details = organization_details; + org_new_db.metadata = metadata; + org_new_db + } +} + #[derive(Clone)] pub struct MerchantId(String); @@ -535,6 +569,18 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUserMerchant { } } +impl From<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUserMerchant { + fn from(value: (user_api::CreateTenantUserRequest, MerchantAccountIdentifier)) -> Self { + let merchant_id = value.1.merchant_id.clone(); + let new_organization = NewUserOrganization::from(value); + Self { + company_name: None, + merchant_id, + new_organization, + } + } +} + type UserMerchantCreateRequestWithToken = (UserFromStorage, user_api::UserMerchantCreate, UserFromToken); @@ -555,6 +601,12 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant { } } +#[derive(Debug, Clone)] +pub struct MerchantAccountIdentifier { + pub merchant_id: id_type::MerchantId, + pub org_id: id_type::OrganizationId, +} + #[derive(Clone)] pub struct NewUser { user_id: String, @@ -856,6 +908,34 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { } } +impl TryFrom<(user_api::CreateTenantUserRequest, MerchantAccountIdentifier)> for NewUser { + type Error = error_stack::Report<UserErrors>; + + fn try_from( + (value, merchant_account_identifier): ( + user_api::CreateTenantUserRequest, + MerchantAccountIdentifier, + ), + ) -> UserResult<Self> { + let user_id = uuid::Uuid::new_v4().to_string(); + let email = value.email.clone().try_into()?; + let name = UserName::new(value.name.clone())?; + let password = NewUserPassword { + password: UserPassword::new(value.password.clone())?, + is_temporary: false, + }; + let new_merchant = NewUserMerchant::from((value, merchant_account_identifier)); + + Ok(Self { + user_id, + name, + email, + password: Some(password), + new_merchant, + }) + } +} + #[derive(Clone)] pub struct UserFromStorage(pub storage_user::User); @@ -1108,6 +1188,11 @@ impl RecoveryCodes { #[derive(Clone)] pub struct NoLevel; +#[derive(Clone)] +pub struct TenantLevel { + pub tenant_id: id_type::TenantId, +} + #[derive(Clone)] pub struct OrganizationLevel { pub tenant_id: id_type::TenantId, @@ -1161,20 +1246,33 @@ impl NewUserRole<NoLevel> { pub struct EntityInfo { tenant_id: id_type::TenantId, - org_id: id_type::OrganizationId, + org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, entity_id: String, entity_type: EntityType, } +impl From<TenantLevel> for EntityInfo { + fn from(value: TenantLevel) -> Self { + Self { + entity_id: value.tenant_id.get_string_repr().to_owned(), + entity_type: EntityType::Tenant, + tenant_id: value.tenant_id, + org_id: None, + merchant_id: None, + profile_id: None, + } + } +} + 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, tenant_id: value.tenant_id, - org_id: value.org_id, + org_id: Some(value.org_id), merchant_id: None, profile_id: None, } @@ -1187,9 +1285,9 @@ impl From<MerchantLevel> for EntityInfo { entity_id: value.merchant_id.get_string_repr().to_owned(), entity_type: EntityType::Merchant, tenant_id: value.tenant_id, - org_id: value.org_id, - profile_id: None, + org_id: Some(value.org_id), merchant_id: Some(value.merchant_id), + profile_id: None, } } } @@ -1200,7 +1298,7 @@ impl From<ProfileLevel> for EntityInfo { entity_id: value.profile_id.get_string_repr().to_owned(), entity_type: EntityType::Profile, tenant_id: value.tenant_id, - org_id: value.org_id, + org_id: Some(value.org_id), merchant_id: Some(value.merchant_id), profile_id: Some(value.profile_id), } @@ -1220,7 +1318,7 @@ where last_modified_by: self.last_modified_by, created_at: self.created_at, last_modified: self.last_modified, - org_id: Some(entity.org_id), + org_id: entity.org_id, merchant_id: entity.merchant_id, profile_id: entity.profile_id, entity_id: Some(entity.entity_id), diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 10990da6ccb..519edf4e9ce 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,7 +1,7 @@ use common_enums::TokenPurpose; use common_utils::id_type; use diesel_models::{enums::UserStatus, user_role::UserRole}; -use error_stack::{report, ResultExt}; +use error_stack::ResultExt; use masking::Secret; use super::UserFromStorage; @@ -124,18 +124,18 @@ impl JWTFlow { 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?; + let org_id = utils::user_role::get_single_org_id(state, user_role).await?; + let merchant_id = + utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?; + let profile_id = + utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?; + auth::AuthToken::new_token( next_flow.user.get_user_id().to_string(), merchant_id, user_role.role_id.clone(), &state.conf, - user_role - .org_id - .clone() - .ok_or(report!(UserErrors::InternalServerError)) - .attach_printable("org_id not found")?, + org_id, profile_id, Some(user_role.tenant_id.clone()), ) diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 281b95255c8..48b1c28a525 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -5,9 +5,11 @@ use common_enums::UserAuthType; use common_utils::{ encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier, }; +use diesel_models::{organization, organization::OrganizationBridge}; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use redis_interface::RedisConnectionPool; +use router_env::env; use crate::{ consts::user::{REDIS_SSO_PREFIX, REDIS_SSO_TTL}, @@ -279,3 +281,39 @@ pub fn is_sso_auth_type(auth_type: &UserAuthType) -> bool { UserAuthType::Password | UserAuthType::MagicLink => false, } } + +#[cfg(feature = "v1")] +pub fn create_merchant_account_request_for_org( + req: user_api::UserOrgMerchantCreateRequest, + org: organization::Organization, +) -> UserResult<api_models::admin::MerchantAccountCreate> { + let merchant_id = if matches!(env::which(), env::Env::Production) { + id_type::MerchantId::try_from(domain::MerchantId::new(req.merchant_name.clone().expose())?)? + } else { + id_type::MerchantId::new_from_unix_timestamp() + }; + + let company_name = domain::UserCompanyName::new(req.merchant_name.expose())?; + Ok(api_models::admin::MerchantAccountCreate { + merchant_id, + metadata: None, + locker_id: None, + return_url: None, + merchant_name: Some(Secret::new(company_name.get_secret())), + webhook_details: None, + publishable_key: None, + organization_id: Some(org.get_organization_id()), + merchant_details: None, + routing_algorithm: None, + parent_merchant_id: None, + sub_merchants_enabled: None, + frm_routing_algorithm: None, + #[cfg(feature = "payouts")] + payout_routing_algorithm: None, + primary_business_details: None, + payment_response_hash_key: None, + enable_payment_response_hash: None, + redirect_to_merchant_with_http_post: None, + pm_collect_link_config: None, + }) +} diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 8acab436491..3412219d0e9 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -13,7 +13,10 @@ use storage_impl::errors::StorageError; use crate::{ consts, core::errors::{UserErrors, UserResult}, - db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, + db::{ + errors::StorageErrorExt, + user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload}, + }, routes::SessionState, services::authorization::{self as authz, roles}, types::domain, @@ -179,30 +182,54 @@ pub async fn update_v1_and_v2_user_roles_in_db( (updated_v1_role, updated_v2_role) } +pub async fn get_single_org_id( + state: &SessionState, + user_role: &UserRole, +) -> UserResult<id_type::OrganizationId> { + let (_, entity_type) = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError)?; + match entity_type { + EntityType::Tenant => Ok(state + .store + .list_merchant_and_org_ids(&state.into(), 1, None) + .await + .change_context(UserErrors::InternalServerError) + .attach_printable("Failed to get merchants list for org")? + .pop() + .ok_or(UserErrors::InternalServerError) + .attach_printable("No merchants to get merchant or org id")? + .1), + EntityType::Organization | EntityType::Merchant | EntityType::Profile => user_role + .org_id + .clone() + .ok_or(UserErrors::InternalServerError) + .attach_printable("Org_id not found"), + } +} + pub async fn get_single_merchant_id( state: &SessionState, user_role: &UserRole, + org_id: &id_type::OrganizationId, ) -> UserResult<id_type::MerchantId> { - match user_role.entity_type { - Some(EntityType::Organization) => Ok(state + let (_, entity_type) = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError)?; + match entity_type { + EntityType::Tenant | EntityType::Organization => Ok(state .store - .list_merchant_accounts_by_organization_id( - &state.into(), - user_role - .org_id - .as_ref() - .ok_or(UserErrors::InternalServerError) - .attach_printable("org_id not found")?, - ) + .list_merchant_accounts_by_organization_id(&state.into(), org_id) .await - .change_context(UserErrors::InternalServerError) - .attach_printable("Failed to get merchant list for org")? + .to_not_found_response(UserErrors::InvalidRoleOperationWithMessage( + "Invalid Org Id".to_string(), + ))? .first() .ok_or(UserErrors::InternalServerError) .attach_printable("No merchants found for org_id")? .get_id() .clone()), - Some(EntityType::Merchant) | Some(EntityType::Profile) | None => user_role + EntityType::Merchant | EntityType::Profile => user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) @@ -210,6 +237,44 @@ pub async fn get_single_merchant_id( } } +pub async fn get_single_profile_id( + state: &SessionState, + user_role: &UserRole, + merchant_id: &id_type::MerchantId, +) -> UserResult<id_type::ProfileId> { + let (_, entity_type) = user_role + .get_entity_id_and_type() + .ok_or(UserErrors::InternalServerError)?; + match entity_type { + EntityType::Tenant | EntityType::Organization | EntityType::Merchant => { + 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)?; + + Ok(state + .store + .list_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) + .attach_printable("profile_id not found"), + } +} + pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( state: &SessionState, user_id: &str, @@ -224,6 +289,10 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( )>, > { match entity_type { + EntityType::Tenant => Err(UserErrors::InvalidRoleOperationWithMessage( + "Tenant roles are not allowed for this operation".to_string(), + ) + .into()), EntityType::Organization => { let Ok(org_id) = id_type::OrganizationId::try_from(std::borrow::Cow::from(entity_id.clone())) @@ -373,37 +442,9 @@ 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 => { - 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_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)?, - }; + let org_id = get_single_org_id(state, user_role).await?; + let merchant_id = get_single_merchant_id(state, user_role, &org_id).await?; + let profile_id = get_single_profile_id(state, user_role, &merchant_id).await?; Ok((merchant_id, profile_id)) } diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 0330c43aa45..ff6a9b75cc2 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -361,6 +361,8 @@ pub enum Flow { VerifyPaymentConnector, /// Internal user signup InternalUserSignup, + /// Create tenant level user + TenantUserCreate, /// Switch org SwitchOrg, /// Switch merchant v2 @@ -391,6 +393,8 @@ pub enum Flow { UpdateUserRole, /// Create merchant account for user in a org UserMerchantAccountCreate, + /// Create Org in a given tenancy + UserOrgMerchantCreate, /// Generate Sample Data GenerateSampleData, /// Delete Sample Data
2024-12-01T21:16:10Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description - Add api to create tenant users - Add api to create orgs - Support tenant level entity for the user hierarchy A tenant level user should see dashboard as seen by the org admin. He will be pinned to one org, merchant and profile. And he can switch between any org in the given tenancy. ### 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 #6707 ## How did you test it? Api for create tenant: ``` curl --location 'http://localhost:8080/user/tenant_signup' \ --header 'api-key: test_admin' \ --header 'Content-Type: application/json' \ --header 'x-tenant-id: test' \ --header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTJhMmViYzItOWZiZS00MDI0LThjODEtOWYwMzMyZTJlZDMxIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX3VwIiwicGF0aCI6W10sImV4cCI6MTczMzMwOTI2NSwidGVuYW50X2lkIjoicHVibGljIn0.3B918rdY_XM0dRH4yx9O7Nujd3FbLdmKUmBY52KVKAo' \ --data-raw '{ "name" : "tf2", "email" : "[email protected]", "password": "Pass@321" }' ``` Response: 200 Ok, if tenant_admin got created successfully A tenant can login with email and password and continue with 2FA, he will land into any one of organization existing for tenant. Create Org Api, (works for tenant users only) ``` curl --location 'http://localhost:8080/user/create_org' \ --header 'x-tenant-id: test' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer JWT' \ --header 'Cookie: Cookie' \ --data '{ "organization_name": "ten", "merchant_name": "pp_ten" }' ``` Response will be 200 OK if the org got created success fully (1 org with 1 merchant and 1 profile) After getting the login token tenant admin can switch to any org in the tenancy. ## 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
3a3e93cb3be3fc3ffabef2a708b49defabf338a5
juspay/hyperswitch
juspay__hyperswitch-6697
Bug: bug(authz): cache `role_info` only if ttl >= 0 There is a race condition in BE, where application is putting role info into cache when the ttl is negative. Redis is throwing error when this happens.
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index b02da396075..850cc470316 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -274,6 +274,11 @@ pub enum ApiErrorResponse { LinkConfigurationError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")] PayoutFailed { data: Option<serde_json::Value> }, + #[error( + error_type = ErrorType::InvalidRequestError, code = "IR_42", + message = "Cookies are not found in the request" + )] + CookieNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] WebhookAuthenticationFailed, @@ -627,6 +632,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::PayoutFailed { data } => { AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()}))) }, + Self::CookieNotFound => { + AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None)) + }, Self::WebhookAuthenticationFailed => { AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index efe0ac157e0..6cf078b5f81 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -444,7 +444,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie - | errors::ApiErrorResponse::InvalidEphemeralKey => Self::Unauthorized, + | errors::ApiErrorResponse::InvalidEphemeralKey + | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 2087d01dbb4..20fea3ac362 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -166,7 +166,7 @@ pub async fn signin_token_only_flow( ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email(&request.email) + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .to_not_found_response(UserErrors::InvalidCredentials)? .into(); @@ -191,7 +191,10 @@ pub async fn connect_account( request: user_api::ConnectAccountRequest, auth_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { - let find_user = state.global_store.find_user_by_email(&request.email).await; + let find_user = state + .global_store + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email.clone())?) + .await; if let Ok(found_user) = find_user { let user_from_db: domain::UserFromStorage = found_user.into(); @@ -369,7 +372,7 @@ pub async fn forgot_password( let user_from_db = state .global_store - .find_user_by_email(&user_email.into_inner()) + .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -453,11 +456,7 @@ pub async fn reset_password_token_only_flow( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -564,10 +563,7 @@ async fn handle_invitation( } let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; - let invitee_user = state - .global_store - .find_user_by_email(&invitee_email.into_inner()) - .await; + let invitee_user = state.global_store.find_user_by_email(&invitee_email).await; if let Ok(invitee_user) = invitee_user { handle_existing_user_invitation( @@ -946,7 +942,7 @@ pub async fn resend_invite( let invitee_email = domain::UserEmail::from_pii_email(request.email)?; let user: domain::UserFromStorage = state .global_store - .find_user_by_email(&invitee_email.clone().into_inner()) + .find_user_by_email(&invitee_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1045,11 +1041,7 @@ pub async fn accept_invite_from_email_token_only_flow( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -1493,11 +1485,7 @@ pub async fn verify_email_token_only_flow( let user_from_email = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)?; @@ -1540,7 +1528,7 @@ pub async fn send_verification_mail( let user_email = domain::UserEmail::try_from(req.email)?; let user = state .global_store - .find_user_by_email(&user_email.into_inner()) + .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1637,11 +1625,7 @@ pub async fn user_from_email( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -2347,7 +2331,7 @@ pub async fn sso_sign( // TODO: Use config to handle not found error let user_from_db = state .global_store - .find_user_by_email(&email.into_inner()) + .find_user_by_email(&email) .await .map(Into::into) .to_not_found_response(UserErrors::UserNotFound)?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 6641e553fd8..df4771dbe70 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -440,7 +440,7 @@ pub async fn delete_user_role( ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?.into_inner()) + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .map_err(|e| { if e.current_context().is_db_not_found() { diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index a9df1abbc08..5d6fac3b130 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use common_enums::enums::MerchantStorageScheme; use common_utils::{ errors::CustomResult, - id_type, pii, + id_type, types::{keymanager::KeyManagerState, theme::ThemeLineage}, }; use diesel_models::{ @@ -2983,7 +2983,7 @@ impl UserInterface for KafkaStore { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.find_user_by_email(user_email).await } @@ -3007,7 +3007,7 @@ impl UserInterface for KafkaStore { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index 14bed15fa45..089c9fc6eb7 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -3,11 +3,10 @@ use error_stack::report; use masking::Secret; use router_env::{instrument, tracing}; -use super::MockDb; +use super::{domain, MockDb}; use crate::{ connection, core::errors::{self, CustomResult}, - pii, services::Store, }; pub mod sample_data; @@ -22,7 +21,7 @@ pub trait UserInterface { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_id( @@ -38,7 +37,7 @@ pub trait UserInterface { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; @@ -70,10 +69,10 @@ impl UserInterface for Store { #[instrument(skip_all)] async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::User::find_by_user_email(&conn, user_email) + storage::User::find_by_user_email(&conn, user_email.get_inner()) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -104,11 +103,11 @@ impl UserInterface for Store { #[instrument(skip_all)] async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::User::update_by_user_email(&conn, user_email, user) + storage::User::update_by_user_email(&conn, user_email.get_inner(), user) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -171,12 +170,12 @@ impl UserInterface for MockDb { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() - .find(|user| user.email.eq(user_email)) + .find(|user| user.email.eq(user_email.get_inner())) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( @@ -253,13 +252,13 @@ impl UserInterface for MockDb { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; users .iter_mut() - .find(|user| user.email.eq(user_email)) + .find(|user| user.email.eq(user_email.get_inner())) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index c05e4514aaa..2d5f81e980c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -2545,7 +2545,8 @@ where T: serde::de::DeserializeOwned, A: SessionStateInfo + Sync, { - let cookie_token_result = get_cookie_from_header(headers).and_then(cookies::parse_cookie); + let cookie_token_result = + get_cookie_from_header(headers).and_then(cookies::get_jwt_from_cookies); let auth_header_token_result = get_jwt_from_authorization_header(headers); let force_cookie = state.conf().user.force_cookies; @@ -3112,7 +3113,7 @@ pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( pub fn is_jwt_auth(headers: &HeaderMap) -> bool { headers.get(headers::AUTHORIZATION).is_some() || get_cookie_from_header(headers) - .and_then(cookies::parse_cookie) + .and_then(cookies::get_jwt_from_cookies) .is_ok() } @@ -3174,10 +3175,13 @@ pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&s } pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> { - headers + let cookie = headers .get(cookies::get_cookie_header()) - .and_then(|header_value| header_value.to_str().ok()) - .ok_or(errors::ApiErrorResponse::InvalidCookie.into()) + .ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?; + + cookie + .to_str() + .change_context(errors::ApiErrorResponse::InvalidCookie) } pub fn strip_jwt_token(token: &str) -> RouterResult<&str> { diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rs index 96518840800..4a297c0f0eb 100644 --- a/crates/router/src/services/authentication/cookies.rs +++ b/crates/router/src/services/authentication/cookies.rs @@ -49,7 +49,7 @@ pub fn remove_cookie_response() -> UserResponse<()> { Ok(ApplicationResponse::JsonWithHeaders(((), header))) } -pub fn parse_cookie(cookies: &str) -> RouterResult<String> { +pub fn get_jwt_from_cookies(cookies: &str) -> RouterResult<String> { Cookie::split_parse(cookies) .find_map(|cookie| { cookie @@ -57,8 +57,8 @@ pub fn parse_cookie(cookies: &str) -> RouterResult<String> { .filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME) .map(|parsed_cookie| parsed_cookie.value().to_owned()) }) - .ok_or(report!(ApiErrorResponse::InvalidCookie)) - .attach_printable("Cookie Parsing Failed") + .ok_or(report!(ApiErrorResponse::InvalidJwtToken)) + .attach_printable("Unable to find JWT token in cookies") } #[cfg(feature = "olap")] diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 87ff9f6abd5..8f48ef068ce 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -40,10 +40,12 @@ where i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp(); - set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) - .await - .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) - .ok(); + if cache_ttl > 0 { + set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) + .await + .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) + .ok(); + } Ok(role_info) } diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index d092afdc5de..8c966d79d80 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,9 +1,6 @@ use api_models::user::dashboard_metadata::ProdIntent; use common_enums::EntityType; -use common_utils::{ - errors::{self, CustomResult}, - pii, -}; +use common_utils::{errors::CustomResult, pii}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; use masking::{ExposeInterface, Secret}; @@ -183,7 +180,7 @@ impl EmailToken { entity: Option<Entity>, flow: domain::Origin, settings: &configs::Settings, - ) -> CustomResult<String, UserErrors> { + ) -> UserResult<String> { let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(expiration_duration)?.as_secs(); let token_payload = Self { @@ -195,8 +192,10 @@ impl EmailToken { jwt::generate_jwt(&token_payload, settings).await } - pub fn get_email(&self) -> CustomResult<pii::Email, errors::ParsingError> { + pub fn get_email(&self) -> UserResult<domain::UserEmail> { pii::Email::try_from(self.email.clone()) + .change_context(UserErrors::InternalServerError) + .and_then(domain::UserEmail::from_pii_email) } pub fn get_entity(&self) -> Option<&Entity> { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 6d0d2a4ea07..21212bf6b62 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -131,6 +131,10 @@ impl UserEmail { self.0 } + pub fn get_inner(&self) -> &pii::Email { + &self.0 + } + pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> { (*self.0).clone() } @@ -617,7 +621,7 @@ impl NewUser { pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .global_store - .find_user_by_email(&self.get_email().into_inner()) + .find_user_by_email(&self.get_email()) .await .is_ok() { diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index f115a16c062..443db741ae3 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -124,7 +124,7 @@ pub async fn get_user_from_db_by_email( ) -> CustomResult<UserFromStorage, StorageError> { state .global_store - .find_user_by_email(&email.into_inner()) + .find_user_by_email(&email) .await .map(UserFromStorage::from) }
2024-11-28T13:49:22Z
## 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 does 3 things. 1. Throw 401 if cookies are not found in request or if JWT is not found in cookies. 2. Cache role info only if the ttl is greater than or equal to 0. 3. Use `UserEmail` type in DB functions. ### 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` 4. `crates/router/src/configs` 5. `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 #6696. Closes #6697. Closes #6698. ## 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)? --> todo!() ## 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
707f48ceda789185187d23e35f483e117c67b81b
juspay/hyperswitch
juspay__hyperswitch-6704
Bug: chore: address Rust 1.83.0 clippy lints ### Description Address the clippy lints stabilized / enabled in Rust version 1.83.0. See #3391 for more information.
diff --git a/.clippy.toml b/.clippy.toml new file mode 100644 index 00000000000..4296655a040 --- /dev/null +++ b/.clippy.toml @@ -0,0 +1 @@ +allow-dbg-in-tests = true diff --git a/Cargo.toml b/Cargo.toml index 90eb996b82b..38d895d767a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,12 +18,16 @@ unused_qualifications = "warn" [workspace.lints.clippy] as_conversions = "warn" +cloned_instead_of_copied = "warn" +dbg_macro = "warn" expect_used = "warn" +fn_params_excessive_bools = "warn" index_refutable_slice = "warn" indexing_slicing = "warn" large_futures = "warn" match_on_vec_items = "warn" missing_panics_doc = "warn" +mod_module_files = "warn" out_of_bounds_indexing = "warn" panic = "warn" panic_in_result_fn = "warn" @@ -32,10 +36,12 @@ print_stderr = "warn" print_stdout = "warn" todo = "warn" unimplemented = "warn" +unnecessary_self_imports = "warn" unreachable = "warn" unwrap_in_result = "warn" unwrap_used = "warn" use_self = "warn" +wildcard_dependencies = "warn" # Lints to allow option_map_unit_fn = "allow" diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 2b66d1755ff..3973252115f 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -4176,7 +4176,7 @@ }, "bank_account_bic": { "type": "string", - "description": "Bank account details for Giropay\nBank account bic code", + "description": "Bank account bic code", "nullable": true }, "bank_account_iban": { diff --git a/crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/disputes/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/disputes/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/disputes/metrics/sessionized_metrics.rs diff --git a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payment_intents/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/payment_intents/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/payment_intents/metrics/sessionized_metrics.rs diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/payments/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/payments/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/payments/metrics/sessionized_metrics.rs diff --git a/crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs b/crates/analytics/src/refunds/metrics/sessionized_metrics.rs similarity index 100% rename from crates/analytics/src/refunds/metrics/sessionized_metrics/mod.rs rename to crates/analytics/src/refunds/metrics/sessionized_metrics.rs diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index 7e1465c9d92..f0a8c999438 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1531,7 +1531,6 @@ pub struct MerchantConnectorUpdate { #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] - pub struct ConnectorWalletDetails { /// This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index d25f35589b6..b6d4044c5f3 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -277,7 +277,6 @@ pub struct PaymentIntentFilterValue { #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] - pub struct GetRefundFilterRequest { pub time_range: TimeRange, #[serde(default)] @@ -292,7 +291,6 @@ pub struct RefundFiltersResponse { #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] - pub struct RefundFilterValue { pub dimension: RefundDimensions, pub values: Vec<String>, @@ -435,7 +433,6 @@ pub struct DisputeFiltersResponse { #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] - pub struct DisputeFilterValue { pub dimension: DisputeDimensions, pub values: Vec<String>, diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs index d25cd989b0f..3c4d566f235 100644 --- a/crates/api_models/src/api_keys.rs +++ b/crates/api_models/src/api_keys.rs @@ -212,7 +212,7 @@ mod never { { struct NeverVisitor; - impl<'de> serde::de::Visitor<'de> for NeverVisitor { + impl serde::de::Visitor<'_> for NeverVisitor { type Value = (); fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { diff --git a/crates/api_models/src/conditional_configs.rs b/crates/api_models/src/conditional_configs.rs index 555e7bd955f..3aed34e47a7 100644 --- a/crates/api_models/src/conditional_configs.rs +++ b/crates/api_models/src/conditional_configs.rs @@ -92,7 +92,6 @@ pub struct ConditionalConfigReq { pub algorithm: Option<Program<ConditionalConfigs>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] - pub struct DecisionManagerRequest { pub name: Option<String>, pub program: Option<Program<ConditionalConfigs>>, diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 646ad122d7c..c00afac6462 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -141,7 +141,6 @@ pub enum FrmConnectors { )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] - pub enum TaxConnectors { Taxjar, } diff --git a/crates/api_models/src/errors/mod.rs b/crates/api_models/src/errors.rs similarity index 100% rename from crates/api_models/src/errors/mod.rs rename to crates/api_models/src/errors.rs diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index fb60937e9b1..f46fd450bd4 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -2457,7 +2457,6 @@ pub enum AdditionalPaymentData { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] - pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } @@ -2504,7 +2503,6 @@ pub enum BankRedirectData { Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, - /// Bank account details for Giropay #[schema(value_type = Option<String>)] /// Bank account bic code @@ -3682,7 +3680,6 @@ pub enum WalletResponseData { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] - pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } @@ -4196,7 +4193,6 @@ pub struct ReceiverDetails { #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] - pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. @@ -6355,7 +6351,7 @@ mod payment_id_type { struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; - impl<'de> Visitor<'de> for PaymentIdVisitor { + impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -6433,7 +6429,7 @@ mod payment_id_type { struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; - impl<'de> Visitor<'de> for PaymentIdVisitor { + impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -6507,7 +6503,7 @@ pub mod amount { // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally - impl<'de> de::Visitor<'de> for AmountVisitor { + impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -6707,7 +6703,6 @@ pub struct PaymentLinkStatusDetails { #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] - pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, diff --git a/crates/api_models/src/pm_auth.rs b/crates/api_models/src/pm_auth.rs index 8ed52907da8..e97efcf92d3 100644 --- a/crates/api_models/src/pm_auth.rs +++ b/crates/api_models/src/pm_auth.rs @@ -22,7 +22,6 @@ pub struct LinkTokenCreateResponse { #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] - pub struct ExchangeTokenCreateRequest { pub public_token: String, pub client_secret: Option<String>, diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index 389af3dab7b..dbfa770cbf1 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -473,7 +473,6 @@ impl RoutingAlgorithmRef { } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] - pub struct RoutingDictionaryRecord { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, diff --git a/crates/api_models/src/user/sample_data.rs b/crates/api_models/src/user/sample_data.rs index dc95de913fa..bfcbcb046c5 100644 --- a/crates/api_models/src/user/sample_data.rs +++ b/crates/api_models/src/user/sample_data.rs @@ -1,5 +1,4 @@ use common_enums::{AuthenticationType, CountryAlpha2}; -use common_utils::{self}; use time::PrimitiveDateTime; use crate::enums::Connector; diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs index d3515ef02f0..d3a27da4823 100644 --- a/crates/cards/src/validate.rs +++ b/crates/cards/src/validate.rs @@ -10,14 +10,10 @@ use router_env::{logger, which as router_env_which, Env}; use serde::{Deserialize, Deserializer, Serialize}; use thiserror::Error; -/// /// Minimum limit of a card number will not be less than 8 by ISO standards -/// pub const MIN_CARD_NUMBER_LENGTH: usize = 8; -/// /// Maximum limit of a card number will not exceed 19 by ISO standards -/// pub const MAX_CARD_NUMBER_LENGTH: usize = 19; #[derive(Debug, Deserialize, Serialize, Error)] @@ -138,11 +134,9 @@ pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidat Ok(is_card_number_valid) } -/// /// # Panics /// /// Never, as a single character will never be greater than 10, or `u8` -/// pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> { let data = number.chars().try_fold( Vec::with_capacity(MAX_CARD_NUMBER_LENGTH), diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs index f5f7ba3decd..ddf55d29371 100644 --- a/crates/common_enums/src/transformers.rs +++ b/crates/common_enums/src/transformers.rs @@ -1914,7 +1914,7 @@ mod custom_serde { struct FieldVisitor; - impl<'de> Visitor<'de> for FieldVisitor { + impl Visitor<'_> for FieldVisitor { type Value = CountryAlpha2; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { @@ -1946,7 +1946,7 @@ mod custom_serde { struct FieldVisitor; - impl<'de> Visitor<'de> for FieldVisitor { + impl Visitor<'_> for FieldVisitor { type Value = CountryAlpha3; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { @@ -1978,7 +1978,7 @@ mod custom_serde { struct FieldVisitor; - impl<'de> Visitor<'de> for FieldVisitor { + impl Visitor<'_> for FieldVisitor { type Value = u32; fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result { diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs index c7f1c286c59..e8c2b2d5a0b 100644 --- a/crates/common_utils/src/crypto.rs +++ b/crates/common_utils/src/crypto.rs @@ -238,7 +238,6 @@ impl VerifySignature for HmacSha512 { } } -/// /// Blake3 #[derive(Debug)] pub struct Blake3(String); @@ -437,9 +436,7 @@ pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; bytes } -/// /// A wrapper type to store the encrypted data for sensitive pii domain data types -/// #[derive(Debug, Clone)] pub struct Encryptable<T: Clone> { inner: T, @@ -447,9 +444,7 @@ pub struct Encryptable<T: Clone> { } impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> { - /// /// constructor function to be used by the encryptor and decryptor to generate the data type - /// pub fn new( masked_data: Secret<T, S>, encrypted_data: Secret<Vec<u8>, EncryptionStrategy>, @@ -462,33 +457,25 @@ impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> { } impl<T: Clone> Encryptable<T> { - /// /// Get the inner data while consuming self - /// #[inline] pub fn into_inner(self) -> T { self.inner } - /// /// Get the reference to inner value - /// #[inline] pub fn get_inner(&self) -> &T { &self.inner } - /// /// Get the inner encrypted data while consuming self - /// #[inline] pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.encrypted } - /// /// Deserialize inner value and return new Encryptable object - /// pub fn deserialize_inner_value<U, F>( self, f: F, diff --git a/crates/common_utils/src/custom_serde.rs b/crates/common_utils/src/custom_serde.rs index 79e0c5b85e7..63ef30011f7 100644 --- a/crates/common_utils/src/custom_serde.rs +++ b/crates/common_utils/src/custom_serde.rs @@ -202,7 +202,6 @@ pub mod timestamp { } /// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860> - pub mod json_string { use serde::de::{self, Deserialize, DeserializeOwned, Deserializer}; use serde_json; diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rs index 38b89cbfaf7..e62606b4585 100644 --- a/crates/common_utils/src/errors.rs +++ b/crates/common_utils/src/errors.rs @@ -7,7 +7,6 @@ use crate::types::MinorUnit; /// error_stack::Report<E> specific extendability /// /// Effectively, equivalent to `Result<T, error_stack::Report<E>>` -/// pub type CustomResult<T, E> = error_stack::Result<T, E>; /// Parsing Errors diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 5ad53ec8533..945056aafef 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -1,7 +1,5 @@ -//! //! This module holds traits for extending functionalities for existing datatypes //! & inbuilt datatypes. -//! use error_stack::ResultExt; use masking::{ExposeInterface, PeekInterface, Secret, Strategy}; @@ -14,10 +12,8 @@ use crate::{ fp_utils::when, }; -/// /// Encode interface /// An interface for performing type conversions and serialization -/// pub trait Encode<'e> where Self: 'e + std::fmt::Debug, @@ -27,62 +23,49 @@ where /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically to convert into json, by using `serde_json` - /// fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; - /// /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` - /// fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; - /// /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` - /// fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into JSON `String`. - /// fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. - /// fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` - /// fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; - /// /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize` - /// fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize; @@ -165,13 +148,9 @@ where } } -/// /// Extending functionalities of `bytes::Bytes` -/// pub trait BytesExt { - /// /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` - /// fn parse_struct<'de, T>( &'de self, type_name: &'static str, @@ -199,13 +178,9 @@ impl BytesExt for bytes::Bytes { } } -/// /// Extending functionalities of `[u8]` for performing parsing -/// pub trait ByteSliceExt { - /// /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` - /// fn parse_struct<'de, T>( &'de self, type_name: &'static str, @@ -229,13 +204,9 @@ impl ByteSliceExt for [u8] { } } -/// /// Extending functionalities of `serde_json::Value` for performing parsing -/// pub trait ValueExt { - /// /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` - /// fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: serde::de::DeserializeOwned; @@ -277,22 +248,16 @@ impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> { } } -/// /// Extending functionalities of `String` for performing parsing -/// pub trait StringExt<T> { - /// /// Convert `String` into type `<T>` (which being an `enum`) - /// fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError> where T: std::str::FromStr, // Requirement for converting the `Err` variant of `FromStr` to `Report<Err>` <T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static; - /// /// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize` - /// fn parse_struct<'de>( &'de self, type_name: &'static str, @@ -327,25 +292,20 @@ impl<T> StringExt<T> for String { } } -/// /// Extending functionalities of Wrapper types for idiomatic -/// #[cfg(feature = "async_ext")] #[cfg_attr(feature = "async_ext", async_trait::async_trait)] pub trait AsyncExt<A, B> { /// Output type of the map function type WrappedSelf<T>; - /// + /// Extending map by allowing functions which are async - /// async fn async_map<F, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, Fut: futures::Future<Output = B> + Send; - /// /// Extending the `and_then` by allowing functions which are async - /// async fn async_and_then<F, Fut>(self, func: F) -> Self::WrappedSelf<B> where F: FnOnce(A) -> Fut + Send, @@ -469,9 +429,7 @@ where /// Extension trait for deserializing XML strings using `quick-xml` crate pub trait XmlExt { - /// /// Deserialize an XML string into the specified type `<T>`. - /// fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned; diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index 9d4b96200ba..5fd0e8078a2 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -348,7 +348,6 @@ where } /// Strategy for masking UPI VPA's - #[derive(Debug)] pub enum UpiVpaMaskingStrategy {} diff --git a/crates/common_utils/src/signals.rs b/crates/common_utils/src/signals.rs index 5bde366bf3c..d008aef290e 100644 --- a/crates/common_utils/src/signals.rs +++ b/crates/common_utils/src/signals.rs @@ -6,10 +6,8 @@ use futures::StreamExt; use router_env::logger; use tokio::sync::mpsc; -/// /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received -/// #[cfg(not(target_os = "windows"))] pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) { if let Some(signal) = sig.next().await { @@ -34,47 +32,35 @@ pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::S } } -/// /// This functions is meant to run in parallel to the application. /// It will send a signal to the receiver when a SIGTERM or SIGINT is received -/// #[cfg(target_os = "windows")] pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {} -/// /// This function is used to generate a list of signals that the signal_handler should listen for -/// #[cfg(not(target_os = "windows"))] pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> { signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT]) } -/// /// This function is used to generate a list of signals that the signal_handler should listen for -/// #[cfg(target_os = "windows")] pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> { Ok(DummySignal) } -/// /// Dummy Signal Handler for windows -/// #[cfg(target_os = "windows")] #[derive(Debug, Clone)] pub struct DummySignal; #[cfg(target_os = "windows")] impl DummySignal { - /// /// Dummy handler for signals in windows (empty) - /// pub fn handle(&self) -> Self { self.clone() } - /// /// Hollow implementation, for windows compatibility - /// pub fn close(self) {} } diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs index 2a271acb62b..1e547a49713 100644 --- a/crates/common_utils/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -334,7 +334,6 @@ impl AmountConvertor for FloatMajorUnitForConnector { } /// Connector required amount type - #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)] pub struct MinorUnitForConnector; @@ -503,7 +502,6 @@ impl Sum for MinorUnit { } /// Connector specific types to send - #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq)] pub struct StringMinorUnit(String); @@ -749,7 +747,7 @@ mod client_secret_type { { struct ClientSecretVisitor; - impl<'de> Visitor<'de> for ClientSecretVisitor { + impl Visitor<'_> for ClientSecretVisitor { type Value = ClientSecret; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs index 078f1f3fcd8..09d26bd91ef 100644 --- a/crates/common_utils/src/types/keymanager.rs +++ b/crates/common_utils/src/types/keymanager.rs @@ -393,7 +393,7 @@ impl<'de> Deserialize<'de> for DecryptedData { { struct DecryptedDataVisitor; - impl<'de> Visitor<'de> for DecryptedDataVisitor { + impl Visitor<'_> for DecryptedDataVisitor { type Value = DecryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -449,7 +449,7 @@ impl<'de> Deserialize<'de> for EncryptedData { { struct EncryptedDataVisitor; - impl<'de> Visitor<'de> for EncryptedDataVisitor { + impl Visitor<'_> for EncryptedDataVisitor { type Value = EncryptedData; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index 26c9d33f405..8f6e03fb398 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -106,7 +106,6 @@ pub struct ApiModelMetaData { #[serde_with::skip_serializing_none] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] - pub enum KlarnaEndpoint { Europe, NorthAmerica, diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 0e68b04d27b..524bfa71709 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -73,7 +73,6 @@ pub enum ApplePayTomlConfig { #[serde_with::skip_serializing_none] #[derive(Debug, Clone, serde::Serialize, Deserialize)] - pub enum KlarnaEndpoint { Europe, NorthAmerica, diff --git a/crates/diesel_models/src/configs.rs b/crates/diesel_models/src/configs.rs index 2b30aa6a972..37381961d96 100644 --- a/crates/diesel_models/src/configs.rs +++ b/crates/diesel_models/src/configs.rs @@ -7,7 +7,6 @@ use crate::schema::configs; #[derive(Default, Clone, Debug, Insertable, Serialize, Deserialize)] #[diesel(table_name = configs)] - pub struct ConfigNew { pub key: String, pub config: String, diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index c7a3818d5fe..7e476662ea7 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -75,7 +75,6 @@ pub use self::{ /// `Option<T>` values. /// /// [diesel-2.0-array-nullability]: https://diesel.rs/guides/migration_guide.html#2-0-0-nullability-of-array-elements - #[doc(hidden)] pub(crate) mod diesel_impl { use diesel::{ diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs index bd4fd119201..6a3cad24e1c 100644 --- a/crates/diesel_models/src/organization.rs +++ b/crates/diesel_models/src/organization.rs @@ -197,8 +197,8 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal { } } } -#[cfg(feature = "v2")] +#[cfg(feature = "v2")] impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 7760ea76c50..6ddc26d49bd 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -6,7 +6,7 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; -use crate::enums::{self as storage_enums}; +use crate::enums as storage_enums; #[cfg(feature = "v1")] use crate::schema::payment_attempt; #[cfg(feature = "v2")] diff --git a/crates/diesel_models/src/reverse_lookup.rs b/crates/diesel_models/src/reverse_lookup.rs index 87fca344078..974851f966a 100644 --- a/crates/diesel_models/src/reverse_lookup.rs +++ b/crates/diesel_models/src/reverse_lookup.rs @@ -2,7 +2,6 @@ use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::reverse_lookup; -/// /// This reverse lookup table basically looks up id's and get result_id that you want. This is /// useful for KV where you can't lookup without key #[derive( diff --git a/crates/diesel_models/src/services/logger.rs b/crates/diesel_models/src/services/logger.rs deleted file mode 100644 index 9c1b20c9d28..00000000000 --- a/crates/diesel_models/src/services/logger.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! -//! Logger of the system. -//! - -pub use crate::env::logger::*; diff --git a/crates/drainer/src/services.rs b/crates/drainer/src/services.rs index 55ffe0c4e7f..87057ebeff2 100644 --- a/crates/drainer/src/services.rs +++ b/crates/drainer/src/services.rs @@ -29,7 +29,6 @@ impl Store { /// /// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration. /// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client. - /// pub async fn new(config: &crate::Settings, test_transaction: bool, tenant: &Tenant) -> Self { let redis_conn = crate::connection::redis_connection(config).await; Self { diff --git a/crates/euclid/src/dssa/analyzer.rs b/crates/euclid/src/dssa/analyzer.rs index a81e7be351f..7aeb850e1bb 100644 --- a/crates/euclid/src/dssa/analyzer.rs +++ b/crates/euclid/src/dssa/analyzer.rs @@ -87,7 +87,7 @@ pub fn analyze_exhaustive_negations( .cloned() .unwrap_or_default() .iter() - .cloned() + .copied() .cloned() .collect(), }; @@ -121,12 +121,12 @@ fn analyze_negated_assertions( value: (*val).clone(), assertion_metadata: assertion_metadata .get(*val) - .cloned() + .copied() .cloned() .unwrap_or_default(), negation_metadata: negation_metadata .get(*val) - .cloned() + .copied() .cloned() .unwrap_or_default(), }; diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs index 30d71090f36..7ef9bb244d9 100644 --- a/crates/euclid/src/dssa/graph.rs +++ b/crates/euclid/src/dssa/graph.rs @@ -421,7 +421,7 @@ impl CgraphExt for cgraph::ConstraintGraph<dir::DirValue> { for (key, negation_set) in keywise_negation { let all_metadata = keywise_metadata.remove(&key).unwrap_or_default(); - let first_metadata = all_metadata.first().cloned().cloned().unwrap_or_default(); + let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default(); self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains) .map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?; diff --git a/crates/euclid/src/dssa/types.rs b/crates/euclid/src/dssa/types.rs index df54de2dd99..f8340c31509 100644 --- a/crates/euclid/src/dssa/types.rs +++ b/crates/euclid/src/dssa/types.rs @@ -18,7 +18,7 @@ pub enum CtxValueKind<'a> { Negation(&'a [dir::DirValue]), } -impl<'a> CtxValueKind<'a> { +impl CtxValueKind<'_> { pub fn get_assertion(&self) -> Option<&dir::DirValue> { if let Self::Assertion(val) = self { Some(val) diff --git a/crates/euclid/src/frontend/ast.rs b/crates/euclid/src/frontend/ast.rs index 5a7b88acfbc..7c75ad000bf 100644 --- a/crates/euclid/src/frontend/ast.rs +++ b/crates/euclid/src/frontend/ast.rs @@ -135,7 +135,6 @@ pub struct IfStatement { /// } /// } /// ``` - #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] #[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)] diff --git a/crates/euclid/src/frontend/ast/lowering.rs b/crates/euclid/src/frontend/ast/lowering.rs index 24fc1e80428..ec629358d5f 100644 --- a/crates/euclid/src/frontend/ast/lowering.rs +++ b/crates/euclid/src/frontend/ast/lowering.rs @@ -25,7 +25,6 @@ use crate::{ /// This serves for the purpose were we have the DirKey as an explicit Enum type and value as one /// of the member of the same Enum. /// So particularly it lowers a predefined Enum from DirKey to an Enum of DirValue. - macro_rules! lower_enum { ($key:ident, $value:ident) => { match $value { @@ -70,7 +69,6 @@ macro_rules! lower_enum { /// This is for the cases in which there are numerical values involved and they are lowered /// accordingly on basis of the supplied key, currently payment_amount is the only key having this /// use case - macro_rules! lower_number { ($key:ident, $value:ident, $comp:ident) => { match $value { @@ -117,7 +115,6 @@ macro_rules! lower_number { /// /// This serves for the purpose were we have the DirKey as Card_bin and value as an arbitrary string /// So particularly it lowers an arbitrary value to a predefined key. - macro_rules! lower_str { ($key:ident, $value:ident $(, $validation_closure:expr)?) => { match $value { @@ -155,7 +152,6 @@ macro_rules! lower_metadata { /// by throwing required errors for comparisons that can't be performed for a certain value type /// for example /// can't have greater/less than operations on enum types - fn lower_comparison_inner<O: EuclidDirFilter>( comp: ast::Comparison, ) -> Result<Vec<dir::DirValue>, AnalysisErrorType> { diff --git a/crates/euclid/src/frontend/ast/parser.rs b/crates/euclid/src/frontend/ast/parser.rs index 0c586e178e6..63a0ea08b8b 100644 --- a/crates/euclid/src/frontend/ast/parser.rs +++ b/crates/euclid/src/frontend/ast/parser.rs @@ -51,9 +51,9 @@ impl EuclidParsable for DummyOutput { )(input) } } -pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&str, O> +pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&'a str, O> where - F: FnMut(&'a str) -> ParseResult<&str, O> + 'a, + F: FnMut(&'a str) -> ParseResult<&'a str, O> + 'a, { sequence::preceded(pchar::multispace0, inner) } diff --git a/crates/events/src/lib.rs b/crates/events/src/lib.rs index 3d333ec54b9..38a597e030b 100644 --- a/crates/events/src/lib.rs +++ b/crates/events/src/lib.rs @@ -2,14 +2,12 @@ #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![warn(missing_docs)] -//! //! A generic event handler system. //! This library consists of 4 parts: //! Event Sink: A trait that defines how events are published. This could be a simple logger, a message queue, or a database. //! EventContext: A struct that holds the event sink and metadata about the event. This is used to create events. This can be used to add metadata to all events, such as the user who triggered the event. //! EventInfo: A trait that defines the metadata that is sent with the event. It works with the EventContext to add metadata to all events. //! Event: A trait that defines the event itself. This trait is used to define the data that is sent with the event and defines the event's type & identifier. -//! mod actix; diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs index e551cfee2af..479b7c5f386 100644 --- a/crates/external_services/src/file_storage.rs +++ b/crates/external_services/src/file_storage.rs @@ -1,6 +1,4 @@ -//! //! Module for managing file storage operations with support for multiple storage schemes. -//! use std::{ fmt::{Display, Formatter}, diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs index e3986abf0f8..19b3185e81b 100644 --- a/crates/external_services/src/file_storage/file_system.rs +++ b/crates/external_services/src/file_storage/file_system.rs @@ -1,6 +1,4 @@ -//! //! Module for local file system storage operations -//! use std::{ fs::{remove_file, File}, diff --git a/crates/external_services/src/hashicorp_vault/core.rs b/crates/external_services/src/hashicorp_vault/core.rs index 15edcb6418c..3cc03b4330b 100644 --- a/crates/external_services/src/hashicorp_vault/core.rs +++ b/crates/external_services/src/hashicorp_vault/core.rs @@ -103,7 +103,6 @@ impl HashiCorpVault { /// # Parameters /// /// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details. - /// pub fn new(config: &HashiCorpVaultConfig) -> error_stack::Result<Self, HashiCorpError> { VaultClient::new( VaultClientSettingsBuilder::default() @@ -129,7 +128,6 @@ impl HashiCorpVault { /// /// - `En`: The engine type that implements the `Engine` trait. /// - `I`: The type that can be constructed from the retrieved encoded data. - /// pub async fn fetch<En, I>(&self, data: String) -> error_stack::Result<I, HashiCorpError> where for<'a> En: Engine< diff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rs index 678239c60b1..a0add638235 100644 --- a/crates/external_services/src/managers/encryption_management.rs +++ b/crates/external_services/src/managers/encryption_management.rs @@ -1,6 +1,4 @@ -//! //! Encryption management util module -//! use std::sync::Arc; diff --git a/crates/external_services/src/managers/secrets_management.rs b/crates/external_services/src/managers/secrets_management.rs index b79046b4c75..7b27e74bf34 100644 --- a/crates/external_services/src/managers/secrets_management.rs +++ b/crates/external_services/src/managers/secrets_management.rs @@ -1,6 +1,4 @@ -//! //! Secrets management util module -//! use common_utils::errors::CustomResult; #[cfg(feature = "hashicorp-vault")] diff --git a/crates/external_services/src/no_encryption.rs b/crates/external_services/src/no_encryption.rs index 17c29618f89..6f805fc7a10 100644 --- a/crates/external_services/src/no_encryption.rs +++ b/crates/external_services/src/no_encryption.rs @@ -1,6 +1,4 @@ -//! //! No encryption functionalities -//! pub mod core; diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 180db626864..479abf13b13 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -916,7 +916,6 @@ pub struct Data { } #[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] - pub struct MultisafepayPaymentDetails { pub account_holder_name: Option<Secret<String>>, pub account_id: Option<Secret<String>>, diff --git a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs index 6297b97ee98..8d6dc42926b 100644 --- a/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs @@ -122,7 +122,6 @@ pub struct NexinetsBankRedirects { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] - pub struct NexinetsAsyncDetails { pub success_url: Option<String>, pub cancel_url: Option<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index b2bf76944c0..18783c64a01 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -80,7 +80,6 @@ pub struct NovalnetPaymentsRequestCustomer { no_nc: i64, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] - pub struct NovalnetCard { card_number: CardNumber, card_expiry_month: Secret<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs index 3b2164dfc97..c799cf2594e 100644 --- a/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/razorpay/transformers.rs @@ -58,7 +58,6 @@ pub struct RazorpayPaymentsRequest { #[derive(Default, Debug, Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] - pub struct SecondFactor { txn_id: String, id: String, @@ -981,7 +980,6 @@ pub struct RazorpaySyncResponse { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] - pub enum PsyncStatus { Charged, Pending, @@ -1054,7 +1052,6 @@ pub struct Refund { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] - pub enum RefundStatus { Success, Failure, @@ -1221,7 +1218,6 @@ impl From<RefundStatus> for enums::RefundStatus { #[derive(Default, Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] - pub struct RefundResponse { txn_id: Option<String>, refund: RefundRes, diff --git a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs index cd9fe63e4a7..27b9daaa579 100644 --- a/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs @@ -457,7 +457,6 @@ pub struct TsysCaptureRequest { #[derive(Debug, Serialize)] #[serde(rename_all = "PascalCase")] - pub struct TsysPaymentsCaptureRequest { capture: TsysCaptureRequest, } diff --git a/crates/hyperswitch_connectors/src/connectors/worldpay.rs b/crates/hyperswitch_connectors/src/connectors/worldpay.rs index be8f9bca352..266fcc7d659 100644 --- a/crates/hyperswitch_connectors/src/connectors/worldpay.rs +++ b/crates/hyperswitch_connectors/src/connectors/worldpay.rs @@ -54,8 +54,8 @@ use response::{ WP_CORRELATION_ID, }; use ring::hmac; -use transformers::{self as worldpay}; +use self::transformers as worldpay; use crate::{ constants::headers, types::ResponseRouterData, diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index a7fe1cc4cd9..181f46a2052 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -119,7 +119,7 @@ where pub(crate) fn missing_field_err( message: &'static str, -) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + '_> { +) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs index 7c435fee290..8d56406d2a3 100644 --- a/crates/hyperswitch_constraint_graph/src/graph.rs +++ b/crates/hyperswitch_constraint_graph/src/graph.rs @@ -120,7 +120,7 @@ where already_memo .clone() .map_err(|err| GraphError::AnalysisError(Arc::downgrade(&err))) - } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).cloned() + } else if let Some((initial_strength, initial_relation)) = cycle_map.get(&node_id).copied() { let strength_relation = Strength::get_resolved_strength(initial_strength, strength); let relation_resolve = @@ -197,7 +197,7 @@ where if !unsatisfied.is_empty() { let err = Arc::new(AnalysisTrace::AllAggregation { unsatisfied, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -264,7 +264,7 @@ where } else { let err = Arc::new(AnalysisTrace::AnyAggregation { unsatisfied: unsatisfied.clone(), - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -305,7 +305,7 @@ where expected: expected.iter().cloned().collect(), found: None, relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -324,7 +324,7 @@ where expected: expected.iter().cloned().collect(), found: Some(ctx_value.clone()), relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), }); @@ -402,7 +402,7 @@ where let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::Mandatory(Box::new( trace.get_analysis_trace()?, @@ -437,7 +437,7 @@ where let err = Arc::new(AnalysisTrace::Value { value: val.clone(), relation: vald.relation, - info: self.node_info.get(vald.node_id).cloned().flatten(), + info: self.node_info.get(vald.node_id).copied().flatten(), metadata: self.node_metadata.get(vald.node_id).cloned().flatten(), predecessors: Some(error::ValueTracePredecessor::OneOf(errors.clone())), }); @@ -469,7 +469,7 @@ where value: val.clone(), relation, predecessors: None, - info: self.node_info.get(node_id).cloned().flatten(), + info: self.node_info.get(node_id).copied().flatten(), metadata: self.node_metadata.get(node_id).cloned().flatten(), }); memo.insert((node_id, relation, strength), Err(Arc::clone(&err))); diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index 1e3302dab4a..a6d2114f0fe 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -255,7 +255,6 @@ pub enum MerchantAccountUpdate { } #[cfg(feature = "v1")] - impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal { fn from(merchant_account_update: MerchantAccountUpdate) -> Self { let now = date_time::now(); diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index ea994946ca8..820959a5963 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -161,7 +161,6 @@ pub enum PayLaterData { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] - pub enum WalletData { AliPayQr(Box<AliPayQr>), AliPayRedirect(AliPayRedirection), @@ -234,7 +233,6 @@ pub struct SamsungPayTokenData { } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] - pub struct GooglePayWalletData { /// The type of payment method pub pm_type: String, @@ -304,7 +302,6 @@ pub struct MobilePayRedirection {} pub struct MbWayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)] - pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, @@ -361,7 +358,6 @@ pub struct ApplepayPaymentMethod { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] - pub enum RealTimePaymentData { DuitNow {}, Fps {}, @@ -370,7 +366,6 @@ pub enum RealTimePaymentData { } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] - pub enum BankRedirectData { BancontactCard { card_number: Option<cards::CardNumber>, diff --git a/crates/hyperswitch_interfaces/src/secrets_interface.rs b/crates/hyperswitch_interfaces/src/secrets_interface.rs index 761981bedda..6944729191a 100644 --- a/crates/hyperswitch_interfaces/src/secrets_interface.rs +++ b/crates/hyperswitch_interfaces/src/secrets_interface.rs @@ -10,11 +10,13 @@ use masking::Secret; /// Trait defining the interface for managing application secrets #[async_trait::async_trait] pub trait SecretManagementInterface: Send + Sync { + /* /// Given an input, encrypt/store the secret - // async fn store_secret( - // &self, - // input: Secret<String>, - // ) -> CustomResult<String, SecretsManagementError>; + async fn store_secret( + &self, + input: Secret<String>, + ) -> CustomResult<String, SecretsManagementError>; + */ /// Given an input, decrypt/retrieve the secret async fn get_secret( diff --git a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs index d1da6a8c8b6..9573dfa12cb 100644 --- a/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs +++ b/crates/hyperswitch_interfaces/src/secrets_interface/secret_state.rs @@ -26,17 +26,13 @@ pub struct SecretStateContainer<T, S: SecretState> { } impl<T: Clone, S: SecretState> SecretStateContainer<T, S> { - /// /// Get the inner data while consuming self - /// #[inline] pub fn into_inner(self) -> T { self.inner } - /// /// Get the reference to inner value - /// #[inline] pub fn get_inner(&self) -> &T { &self.inner diff --git a/crates/kgraph_utils/src/types.rs b/crates/kgraph_utils/src/types.rs index 26f27896e0a..9ff55b68ab7 100644 --- a/crates/kgraph_utils/src/types.rs +++ b/crates/kgraph_utils/src/types.rs @@ -2,8 +2,8 @@ use std::collections::{HashMap, HashSet}; use api_models::enums as api_enums; use serde::Deserialize; -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone, Default)] pub struct CountryCurrencyFilter { pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>, pub default_configs: Option<PaymentMethodFilters>, diff --git a/crates/masking/src/abs.rs b/crates/masking/src/abs.rs index f50725d9f23..6501f89c9db 100644 --- a/crates/masking/src/abs.rs +++ b/crates/masking/src/abs.rs @@ -1,6 +1,4 @@ -//! //! Abstract data types. -//! use crate::Secret; diff --git a/crates/masking/src/boxed.rs b/crates/masking/src/boxed.rs index 67397ec3c07..42dda0873a1 100644 --- a/crates/masking/src/boxed.rs +++ b/crates/masking/src/boxed.rs @@ -1,4 +1,3 @@ -//! //! `Box` types containing secrets //! //! There is not alias type by design. diff --git a/crates/masking/src/diesel.rs b/crates/masking/src/diesel.rs index ea60a861c9d..148e50ed823 100644 --- a/crates/masking/src/diesel.rs +++ b/crates/masking/src/diesel.rs @@ -1,6 +1,4 @@ -//! //! Diesel-related. -//! use diesel::{ backend::Backend, @@ -13,7 +11,7 @@ use diesel::{ use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret}; -impl<'expr, S, I, T> AsExpression<T> for &'expr Secret<S, I> +impl<S, I, T> AsExpression<T> for &Secret<S, I> where T: sql_types::SingleValue, I: Strategy<S>, @@ -24,7 +22,7 @@ where } } -impl<'expr2, 'expr, S, I, T> AsExpression<T> for &'expr2 &'expr Secret<S, I> +impl<S, I, T> AsExpression<T> for &&Secret<S, I> where T: sql_types::SingleValue, I: Strategy<S>, @@ -81,7 +79,7 @@ where } } -impl<'expr, S, I, T> AsExpression<T> for &'expr StrongSecret<S, I> +impl<S, I, T> AsExpression<T> for &StrongSecret<S, I> where T: sql_types::SingleValue, S: ZeroizableSecret, @@ -93,7 +91,7 @@ where } } -impl<'expr2, 'expr, S, I, T> AsExpression<T> for &'expr2 &'expr StrongSecret<S, I> +impl<S, I, T> AsExpression<T> for &&StrongSecret<S, I> where T: sql_types::SingleValue, S: ZeroizableSecret, diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index d376e935bd6..49e9cbf54f7 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -2,10 +2,8 @@ #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![warn(missing_docs)] -//! //! Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped. //! Secret-keeping library inspired by secrecy. -//! #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] @@ -49,7 +47,6 @@ pub use crate::serde::{ /// This module should be included with asterisk. /// /// `use masking::prelude::*;` -/// pub mod prelude { pub use super::{ExposeInterface, ExposeOptionInterface, PeekInterface}; } diff --git a/crates/masking/src/maskable.rs b/crates/masking/src/maskable.rs index 7969c9ab8e4..e957e89b351 100644 --- a/crates/masking/src/maskable.rs +++ b/crates/masking/src/maskable.rs @@ -1,13 +1,9 @@ -//! //! This module contains Masking objects and traits -//! use crate::{ExposeInterface, Secret}; -/// /// An Enum that allows us to optionally mask data, based on which enum variant that data is stored /// in. -/// #[derive(Clone, Eq, PartialEq)] pub enum Maskable<T: Eq + PartialEq + Clone> { /// Variant which masks the data by wrapping in a Secret @@ -35,9 +31,7 @@ impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T } impl<T: Eq + PartialEq + Clone> Maskable<T> { - /// /// Get the inner data while consuming self - /// pub fn into_inner(self) -> T { match self { Self::Masked(inner_secret) => inner_secret.expose(), @@ -45,49 +39,37 @@ impl<T: Eq + PartialEq + Clone> Maskable<T> { } } - /// /// Create a new Masked data - /// pub fn new_masked(item: Secret<T>) -> Self { Self::Masked(item) } - /// /// Create a new non-masked data - /// pub fn new_normal(item: T) -> Self { Self::Normal(item) } - /// /// Checks whether the data is masked. /// Returns `true` if the data is wrapped in the `Masked` variant, /// returns `false` otherwise. - /// pub fn is_masked(&self) -> bool { matches!(self, Self::Masked(_)) } - /// /// Checks whether the data is normal (not masked). /// Returns `true` if the data is wrapped in the `Normal` variant, /// returns `false` otherwise. - /// pub fn is_normal(&self) -> bool { matches!(self, Self::Normal(_)) } } /// Trait for providing a method on custom types for constructing `Maskable` - pub trait Mask { /// The type returned by the `into_masked()` method. Must implement `PartialEq`, `Eq` and `Clone` - type Output: Eq + Clone + PartialEq; - /// /// Construct a `Maskable` instance that wraps `Self::Output` by consuming `self` - /// fn into_masked(self) -> Maskable<Self::Output>; } diff --git a/crates/masking/src/secret.rs b/crates/masking/src/secret.rs index a813829d63d..0bd28c3af92 100644 --- a/crates/masking/src/secret.rs +++ b/crates/masking/src/secret.rs @@ -1,12 +1,9 @@ -//! //! Structure describing secret. -//! use std::{fmt, marker::PhantomData}; use crate::{strategy::Strategy, PeekInterface, StrongSecret}; -/// /// Secret thing. /// /// To get access to value use method `expose()` of trait [`crate::ExposeInterface`]. @@ -39,7 +36,6 @@ use crate::{strategy::Strategy, PeekInterface, StrongSecret}; /// /// assert_eq!("hello", &format!("{:?}", my_secret)); /// ``` -/// pub struct Secret<Secret, MaskingStrategy = crate::WithType> where MaskingStrategy: Strategy<Secret>, diff --git a/crates/masking/src/serde.rs b/crates/masking/src/serde.rs index 0c5782ae04d..48514df8c6c 100644 --- a/crates/masking/src/serde.rs +++ b/crates/masking/src/serde.rs @@ -1,6 +1,4 @@ -//! //! Serde-related. -//! pub use erased_serde::Serialize as ErasedSerialize; pub use serde::{de, Deserialize, Serialize, Serializer}; @@ -17,7 +15,6 @@ use crate::{Secret, Strategy, StrongSecret, ZeroizableSecret}; /// /// This is done deliberately to prevent accidental exfiltration of secrets /// via `serde` serialization. -/// #[cfg_attr(docsrs, cfg(feature = "serde"))] pub trait SerializableSecret: Serialize {} @@ -87,7 +84,6 @@ where } } -/// /// Masked serialization. /// /// the default behaviour for secrets is to serialize in exposed format since the common use cases @@ -99,7 +95,6 @@ pub fn masked_serialize<T: Serialize>(value: &T) -> Result<Value, serde_json::Er }) } -/// /// Masked serialization. /// /// Trait object for supporting serialization to Value while accounting for masking @@ -118,7 +113,7 @@ impl<T: Serialize + ErasedSerialize> ErasedMaskSerialize for T { } } -impl<'a> Serialize for dyn ErasedMaskSerialize + 'a { +impl Serialize for dyn ErasedMaskSerialize + '_ { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, @@ -127,7 +122,7 @@ impl<'a> Serialize for dyn ErasedMaskSerialize + 'a { } } -impl<'a> Serialize for dyn ErasedMaskSerialize + 'a + Send { +impl Serialize for dyn ErasedMaskSerialize + '_ + Send { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, diff --git a/crates/masking/src/string.rs b/crates/masking/src/string.rs index 2638fbd282e..be6e90a2155 100644 --- a/crates/masking/src/string.rs +++ b/crates/masking/src/string.rs @@ -1,4 +1,3 @@ -//! //! Secret strings //! //! There is not alias type by design. diff --git a/crates/masking/src/strong_secret.rs b/crates/masking/src/strong_secret.rs index 51c0f2cb3fe..300b5463d25 100644 --- a/crates/masking/src/strong_secret.rs +++ b/crates/masking/src/strong_secret.rs @@ -1,6 +1,4 @@ -//! //! Structure describing secret. -//! use std::{fmt, marker::PhantomData}; @@ -9,11 +7,9 @@ use zeroize::{self, Zeroize as ZeroizableSecret}; use crate::{strategy::Strategy, PeekInterface}; -/// /// Secret thing. /// /// To get access to value use method `expose()` of trait [`crate::ExposeInterface`]. -/// pub struct StrongSecret<Secret: ZeroizableSecret, MaskingStrategy = crate::WithType> { /// Inner secret value pub(crate) inner_secret: Secret, diff --git a/crates/masking/src/vec.rs b/crates/masking/src/vec.rs index 1f8c1c671e0..2a077be9943 100644 --- a/crates/masking/src/vec.rs +++ b/crates/masking/src/vec.rs @@ -1,4 +1,3 @@ -//! //! Secret `Vec` types //! //! There is not alias type by design. diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index 2ffd4f4cdc7..4c9d069a458 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -549,8 +549,6 @@ pub fn payments_incremental_authorization() {} pub fn payments_external_authentication() {} /// Payments - Complete Authorize -/// -/// #[utoipa::path( post, path = "/{payment_id}/complete_authorize", @@ -569,8 +567,6 @@ pub fn payments_external_authentication() {} pub fn payments_complete_authorize() {} /// Dynamic Tax Calculation -/// -/// #[utoipa::path( post, path = "/payments/{payment_id}/calculate_tax", @@ -587,8 +583,6 @@ pub fn payments_complete_authorize() {} pub fn payments_dynamic_tax_calculation() {} /// Payments - Post Session Tokens -/// -/// #[utoipa::path( post, path = "/payments/{payment_id}/post_session_tokens", diff --git a/crates/openapi/src/routes/routing.rs b/crates/openapi/src/routes/routing.rs index b144fd046ad..9b8f56aeb81 100644 --- a/crates/openapi/src/routes/routing.rs +++ b/crates/openapi/src/routes/routing.rs @@ -68,7 +68,6 @@ pub async fn routing_link_config() {} /// Routing - Retrieve /// /// Retrieve a routing algorithm - #[utoipa::path( get, path = "/routing/{routing_algorithm_id}", @@ -91,7 +90,6 @@ pub async fn routing_retrieve_config() {} /// Routing - Retrieve /// /// Retrieve a routing algorithm with its algorithm id - #[utoipa::path( get, path = "/v2/routing-algorithm/{id}", diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs index a91aa57a1e4..a10ff0d60e5 100644 --- a/crates/pm_auth/src/connector/plaid/transformers.rs +++ b/crates/pm_auth/src/connector/plaid/transformers.rs @@ -20,7 +20,6 @@ pub struct PlaidLinkTokenRequest { } #[derive(Debug, Serialize, Eq, PartialEq)] - pub struct User { pub client_user_id: id_type::CustomerId, } @@ -94,7 +93,6 @@ pub struct PlaidExchangeTokenRequest { } #[derive(Debug, Deserialize, Eq, PartialEq)] - pub struct PlaidExchangeTokenResponse { pub access_token: String, } @@ -236,7 +234,6 @@ pub struct PlaidBankAccountCredentialsRequest { } #[derive(Debug, Deserialize, PartialEq)] - pub struct PlaidBankAccountCredentialsResponse { pub accounts: Vec<PlaidBankAccountCredentialsAccounts>, pub numbers: PlaidBankAccountCredentialsNumbers, @@ -251,7 +248,6 @@ pub struct BankAccountCredentialsOptions { } #[derive(Debug, Deserialize, PartialEq)] - pub struct PlaidBankAccountCredentialsAccounts { pub account_id: String, pub name: String, diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 9fd07a473d4..746b424abc8 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -3,8 +3,6 @@ //! The folder provides generic functions for providing serialization //! and deserialization while calling redis. //! It also includes instruments to provide tracing. -//! -//! use std::fmt::Debug; diff --git a/crates/redis_interface/src/errors.rs b/crates/redis_interface/src/errors.rs index 0e2a4b8d63b..9e0fb4639a5 100644 --- a/crates/redis_interface/src/errors.rs +++ b/crates/redis_interface/src/errors.rs @@ -1,6 +1,4 @@ -//! //! Errors specific to this custom redis interface -//! #[derive(Debug, thiserror::Error, PartialEq)] pub enum RedisError { diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index f40b81af68e..92429f617d1 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -1,7 +1,5 @@ -//! //! Data types and type conversions //! from `fred`'s internal data-types to custom data-types -//! use common_utils::errors::CustomResult; use fred::types::RedisValue as FredRedisValue; diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 12cef3aa9f7..7daee6e73d7 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -1448,7 +1448,7 @@ pub enum OpenBankingUKIssuer { pub struct AdyenTestBankNames<'a>(&'a str); -impl<'a> TryFrom<&common_enums::BankNames> for AdyenTestBankNames<'a> { +impl TryFrom<&common_enums::BankNames> for AdyenTestBankNames<'_> { type Error = Error; fn try_from(bank: &common_enums::BankNames) -> Result<Self, Self::Error> { Ok(match bank { @@ -1501,7 +1501,7 @@ impl<'a> TryFrom<&common_enums::BankNames> for AdyenTestBankNames<'a> { pub struct AdyenBankNames<'a>(&'a str); -impl<'a> TryFrom<&common_enums::BankNames> for AdyenBankNames<'a> { +impl TryFrom<&common_enums::BankNames> for AdyenBankNames<'_> { type Error = Error; fn try_from(bank: &common_enums::BankNames) -> Result<Self, Self::Error> { Ok(match bank { @@ -1550,9 +1550,7 @@ impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType { } } -impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> - for AdyenPaymentRequest<'a> -{ +impl TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( item: &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, @@ -1612,7 +1610,7 @@ impl<'a> TryFrom<&AdyenRouterData<&types::PaymentsAuthorizeRouterData>> } } -impl<'a> TryFrom<&types::PaymentsPreProcessingRouterData> for AdyenBalanceRequest<'a> { +impl TryFrom<&types::PaymentsPreProcessingRouterData> for AdyenBalanceRequest<'_> { type Error = Error; fn try_from(item: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> { let payment_method = match &item.request.payment_method_data { @@ -1863,8 +1861,8 @@ fn build_shopper_reference( }) } -impl<'a> TryFrom<(&domain::BankDebitData, &types::PaymentsAuthorizeRouterData)> - for AdyenPaymentMethod<'a> +impl TryFrom<(&domain::BankDebitData, &types::PaymentsAuthorizeRouterData)> + for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -1911,8 +1909,8 @@ impl<'a> TryFrom<(&domain::BankDebitData, &types::PaymentsAuthorizeRouterData)> } } -impl<'a> TryFrom<(&domain::VoucherData, &types::PaymentsAuthorizeRouterData)> - for AdyenPaymentMethod<'a> +impl TryFrom<(&domain::VoucherData, &types::PaymentsAuthorizeRouterData)> + for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -1958,7 +1956,7 @@ impl<'a> TryFrom<(&domain::VoucherData, &types::PaymentsAuthorizeRouterData)> } } -impl<'a> TryFrom<&domain::GiftCardData> for AdyenPaymentMethod<'a> { +impl TryFrom<&domain::GiftCardData> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from(gift_card_data: &domain::GiftCardData) -> Result<Self, Self::Error> { match gift_card_data { @@ -1992,7 +1990,7 @@ fn get_adyen_card_network(card_network: common_enums::CardNetwork) -> Option<Car } } -impl<'a> TryFrom<(&domain::Card, Option<Secret<String>>)> for AdyenPaymentMethod<'a> { +impl TryFrom<(&domain::Card, Option<Secret<String>>)> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( (card, card_holder_name): (&domain::Card, Option<Secret<String>>), @@ -2068,8 +2066,8 @@ impl TryFrom<&utils::CardIssuer> for CardBrand { } } -impl<'a> TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> - for AdyenPaymentMethod<'a> +impl TryFrom<(&domain::WalletData, &types::PaymentsAuthorizeRouterData)> + for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2206,7 +2204,7 @@ pub fn check_required_field<'a, T>( }) } -impl<'a> +impl TryFrom<( &domain::PayLaterData, &Option<api_enums::CountryAlpha2>, @@ -2216,7 +2214,7 @@ impl<'a> &Option<Secret<String>>, &Option<Address>, &Option<Address>, - )> for AdyenPaymentMethod<'a> + )> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2329,12 +2327,12 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &domain::BankRedirectData, Option<bool>, &types::PaymentsAuthorizeRouterData, - )> for AdyenPaymentMethod<'a> + )> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2492,11 +2490,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &domain::BankTransferData, &types::PaymentsAuthorizeRouterData, - )> for AdyenPaymentMethod<'a> + )> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( @@ -2564,7 +2562,7 @@ fn get_optional_shopper_email(item: &types::PaymentsAuthorizeRouterData) -> Opti } } -impl<'a> TryFrom<&domain::payments::CardRedirectData> for AdyenPaymentMethod<'a> { +impl TryFrom<&domain::payments::CardRedirectData> for AdyenPaymentMethod<'_> { type Error = Error; fn try_from( card_redirect_data: &domain::payments::CardRedirectData, @@ -2583,11 +2581,11 @@ impl<'a> TryFrom<&domain::payments::CardRedirectData> for AdyenPaymentMethod<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, payments::MandateReferenceId, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -2719,11 +2717,11 @@ impl<'a> }) } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::Card, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -2784,11 +2782,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::BankDebitData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -2842,11 +2840,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::VoucherData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -2903,11 +2901,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::BankTransferData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -2956,11 +2954,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::GiftCardData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; @@ -3009,11 +3007,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::BankRedirectData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -3117,11 +3115,11 @@ fn get_shopper_email( } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::WalletData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -3192,11 +3190,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::PayLaterData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -3268,11 +3266,11 @@ impl<'a> } } -impl<'a> +impl TryFrom<( &AdyenRouterData<&types::PaymentsAuthorizeRouterData>, &domain::payments::CardRedirectData, - )> for AdyenPaymentRequest<'a> + )> for AdyenPaymentRequest<'_> { type Error = Error; fn try_from( @@ -5098,7 +5096,6 @@ impl TryFrom<&types::DefendDisputeRouterData> for AdyenDefendDisputeRequest { #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] - pub struct Evidence { defense_documents: Vec<DefenseDocuments>, merchant_account_code: Secret<String>, @@ -5107,7 +5104,6 @@ pub struct Evidence { #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] - pub struct DefenseDocuments { content: Secret<String>, content_type: Option<String>, diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 24c6118e44a..00624ce0f9b 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -67,13 +67,11 @@ pub struct GenericVariableInput<T> { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct BraintreeApiErrorResponse { pub api_error_response: ApiErrorResponse, } #[derive(Debug, Deserialize, Serialize)] - pub struct ErrorsObject { pub errors: Vec<ErrorObject>, @@ -82,7 +80,6 @@ pub struct ErrorsObject { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct TransactionError { pub errors: Vec<ErrorObject>, pub credit_card: Option<CreditCardError>, @@ -122,7 +119,6 @@ pub struct BraintreeErrorResponse { #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] #[serde(untagged)] - pub enum ErrorResponses { BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>), BraintreeErrorResponse(Box<BraintreeErrorResponse>), @@ -907,7 +903,6 @@ pub struct BraintreeRefundResponseData { } #[derive(Debug, Clone, Deserialize, Serialize)] - pub struct RefundResponse { pub data: BraintreeRefundResponseData, } diff --git a/crates/router/src/connector/datatrans.rs b/crates/router/src/connector/datatrans.rs index 9c7772c5b3e..e6f0ebd0985 100644 --- a/crates/router/src/connector/datatrans.rs +++ b/crates/router/src/connector/datatrans.rs @@ -4,8 +4,8 @@ use base64::Engine; use common_utils::types::{AmountConvertor, MinorUnit, MinorUnitForConnector}; use error_stack::{report, ResultExt}; use masking::PeekInterface; -use transformers::{self as datatrans}; +use self::transformers as datatrans; use super::{utils as connector_utils, utils::RefundsRequestData}; use crate::{ configs::settings, diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index 9ccfcd90be3..223be54d3fd 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -99,7 +99,6 @@ pub struct GlobalpayRefreshTokenRequest { } #[derive(Debug, Serialize, Deserialize)] - pub struct CurrencyConversion { /// A unique identifier generated by Global Payments to identify the currency conversion. It /// can be used to reference a currency conversion when processing a sale or a refund @@ -108,7 +107,6 @@ pub struct CurrencyConversion { } #[derive(Debug, Serialize, Deserialize)] - pub struct Device { pub capabilities: Option<Capabilities>, @@ -128,7 +126,6 @@ pub struct Device { } #[derive(Debug, Serialize, Deserialize)] - pub struct Capabilities { pub authorization_modes: Option<Vec<AuthorizationMode>>, /// The number of lines that can be used to display information on the device. @@ -146,7 +143,6 @@ pub struct Capabilities { } #[derive(Debug, Serialize, Deserialize)] - pub struct Lodging { /// A reference that identifies the booking reference for a lodging stay. pub booking_reference: Option<String>, @@ -163,7 +159,6 @@ pub struct Lodging { } #[derive(Debug, Serialize, Deserialize)] - pub struct LodgingChargeItem { pub payment_method_program_codes: Option<Vec<PaymentMethodProgramCode>>, /// A reference that identifies the charge item, such as a lodging folio number. @@ -195,7 +190,6 @@ pub struct Notifications { } #[derive(Debug, Serialize, Deserialize)] - pub struct Order { /// Merchant defined field common to all transactions that are part of the same order. pub reference: Option<String>, @@ -239,7 +233,6 @@ pub struct PaymentMethod { } #[derive(Debug, Serialize, Deserialize)] - pub struct Apm { /// A string used to identify the payment method provider being used to execute this /// transaction. @@ -247,9 +240,7 @@ pub struct Apm { } /// Information outlining the degree of authentication executed related to a transaction. - #[derive(Debug, Serialize, Deserialize)] - pub struct Authentication { /// Information outlining the degree of 3D Secure authentication executed. pub three_ds: Option<ThreeDs>, @@ -259,9 +250,7 @@ pub struct Authentication { } /// Information outlining the degree of 3D Secure authentication executed. - #[derive(Debug, Serialize, Deserialize)] - pub struct ThreeDs { /// The reference created by the 3DSecure Directory Server to identify the specific /// authentication attempt. @@ -284,7 +273,6 @@ pub struct ThreeDs { } #[derive(Debug, Serialize, Deserialize)] - pub struct BankTransfer { /// The number or reference for the payer's bank account. pub account_number: Option<Secret<String>>, @@ -298,7 +286,6 @@ pub struct BankTransfer { pub sec_code: Option<SecCode>, } #[derive(Debug, Serialize, Deserialize)] - pub struct Bank { pub address: Option<Address>, /// The local identifier code for the bank. @@ -401,7 +388,6 @@ pub enum AuthorizationMode { /// requested amount. /// pub example: PARTIAL /// - /// /// Describes whether the device can process partial authorizations. Partial, } @@ -428,7 +414,6 @@ pub enum CaptureMode { /// Describes whether the transaction was processed in a face to face(CP) scenario or a /// Customer Not Present (CNP) scenario. - #[derive(Debug, Default, Serialize, Deserialize)] pub enum Channel { #[default] @@ -609,7 +594,6 @@ pub enum NumberType { } /// Indicates how the transaction was authorized by the merchant. - #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SecCode { @@ -766,7 +750,6 @@ pub enum CardStorageMode { /// Indicates the transaction processing model being executed when using stored /// credentials. - #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Model { diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 7f2d0d0e608..c350f151d72 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -2970,7 +2970,6 @@ pub struct PaypalSourceVerificationRequest { } #[derive(Deserialize, Serialize, Debug)] - pub struct PaypalSourceVerificationResponse { pub verification_status: PaypalSourceVerificationStatus, } diff --git a/crates/router/src/connector/riskified/transformers/api.rs b/crates/router/src/connector/riskified/transformers/api.rs index c2da0193f99..2d519b3caa8 100644 --- a/crates/router/src/connector/riskified/transformers/api.rs +++ b/crates/router/src/connector/riskified/transformers/api.rs @@ -657,7 +657,6 @@ fn get_fulfillment_status( } #[derive(Debug, Clone, Deserialize, Serialize)] - pub struct RiskifiedWebhookBody { pub id: String, pub status: RiskifiedWebhookStatus, diff --git a/crates/router/src/connector/signifyd/transformers/api.rs b/crates/router/src/connector/signifyd/transformers/api.rs index 348ca3d099a..028c0e82518 100644 --- a/crates/router/src/connector/signifyd/transformers/api.rs +++ b/crates/router/src/connector/signifyd/transformers/api.rs @@ -702,7 +702,6 @@ impl TryFrom<&frm_types::FrmRecordReturnRouterData> for SignifydPaymentsRecordRe #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] - pub struct SignifydWebhookBody { pub order_id: String, pub review_disposition: ReviewDisposition, diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index ed4b97e2a99..b5901f56d3b 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -54,7 +54,7 @@ use crate::{ pub fn missing_field_err( message: &'static str, -) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + '_> { +) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, diff --git a/crates/router/src/connector/wellsfargopayout.rs b/crates/router/src/connector/wellsfargopayout.rs index 51b303494bb..fe8f5dda25f 100644 --- a/crates/router/src/connector/wellsfargopayout.rs +++ b/crates/router/src/connector/wellsfargopayout.rs @@ -3,9 +3,9 @@ pub mod transformers; use common_utils::types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}; use error_stack::{report, ResultExt}; use masking::ExposeInterface; -use transformers as wellsfargopayout; -use super::utils::{self as connector_utils}; +use self::transformers as wellsfargopayout; +use super::utils as connector_utils; use crate::{ configs::settings, core::errors::{self, CustomResult}, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 6d4dde53082..055c428b1fb 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1199,7 +1199,7 @@ struct ConnectorAuthTypeAndMetadataValidation<'a> { connector_meta_data: &'a Option<pii::SecretSerdeValue>, } -impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> { +impl ConnectorAuthTypeAndMetadataValidation<'_> { pub fn validate_auth_and_metadata_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { @@ -1576,7 +1576,7 @@ struct ConnectorAuthTypeValidation<'a> { auth_type: &'a types::ConnectorAuthType, } -impl<'a> ConnectorAuthTypeValidation<'a> { +impl ConnectorAuthTypeValidation<'_> { fn validate_connector_auth_type( &self, ) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> { @@ -1666,7 +1666,7 @@ struct ConnectorStatusAndDisabledValidation<'a> { current_status: &'a api_enums::ConnectorStatus, } -impl<'a> ConnectorStatusAndDisabledValidation<'a> { +impl ConnectorStatusAndDisabledValidation<'_> { fn validate_status_and_disabled( &self, ) -> RouterResult<(api_enums::ConnectorStatus, Option<bool>)> { @@ -1709,7 +1709,7 @@ struct PaymentMethodsEnabled<'a> { payment_methods_enabled: &'a Option<Vec<api_models::admin::PaymentMethodsEnabled>>, } -impl<'a> PaymentMethodsEnabled<'a> { +impl PaymentMethodsEnabled<'_> { fn get_payment_methods_enabled(&self) -> RouterResult<Option<Vec<pii::SecretSerdeValue>>> { let mut vec = Vec::new(); let payment_methods_enabled = match self.payment_methods_enabled.clone() { @@ -1735,7 +1735,7 @@ struct ConnectorMetadata<'a> { connector_metadata: &'a Option<pii::SecretSerdeValue>, } -impl<'a> ConnectorMetadata<'a> { +impl ConnectorMetadata<'_> { fn validate_apple_pay_certificates_in_mca_metadata(&self) -> RouterResult<()> { self.connector_metadata .clone() @@ -1826,7 +1826,7 @@ struct ConnectorTypeAndConnectorName<'a> { connector_name: &'a api_enums::Connector, } -impl<'a> ConnectorTypeAndConnectorName<'a> { +impl ConnectorTypeAndConnectorName<'_> { fn get_routable_connector(&self) -> RouterResult<Option<api_enums::RoutableConnectors>> { let mut routable_connector = api_enums::RoutableConnectors::from_str(&self.connector_name.to_string()).ok(); diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 955cc37b0d9..345a3d4f490 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3149,7 +3149,7 @@ pub fn get_banks( .iter() .skip(1) .fold(first_element.to_owned(), |acc, hs| { - acc.intersection(hs).cloned().collect() + acc.intersection(hs).copied().collect() }); } @@ -3617,7 +3617,7 @@ pub async fn list_payment_methods( .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid PaymentRoutingInfo format found in payment attempt")? - .unwrap_or_else(|| storage::PaymentRoutingInfo { + .unwrap_or(storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }); diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs index 1afdaaab062..604e8c70626 100644 --- a/crates/router/src/core/payment_methods/utils.rs +++ b/crates/router/src/core/payment_methods/utils.rs @@ -737,7 +737,7 @@ fn compile_accepted_currency_for_mca( let config_currency: Vec<common_enums::Currency> = Vec::from_iter(config_currencies) .into_iter() - .cloned() + .copied() .collect(); let dir_currencies: Vec<dir::DirValue> = config_currency @@ -767,7 +767,7 @@ fn compile_accepted_currency_for_mca( let config_currency: Vec<common_enums::Currency> = Vec::from_iter(config_currencies) .into_iter() - .cloned() + .copied() .collect(); let dir_currencies: Vec<dir::DirValue> = config_currency diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 5eb97e6eebe..60a17aee9e2 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4312,7 +4312,7 @@ pub fn if_not_create_change_operation<'a, Op, F>( status: storage_enums::IntentStatus, confirm: Option<bool>, current: &'a Op, -) -> BoxedOperation<'_, F, api::PaymentsRequest, PaymentData<F>> +) -> BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>> where F: Send + Clone, Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>> + Send + Sync, @@ -4336,7 +4336,7 @@ where pub fn is_confirm<'a, F: Clone + Send, R, Op>( operation: &'a Op, confirm: Option<bool>, -) -> BoxedOperation<'_, F, R, PaymentData<F>> +) -> BoxedOperation<'a, F, R, PaymentData<F>> where PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, &'a PaymentConfirm: Operation<F, R, Data = PaymentData<F>>, @@ -5044,7 +5044,7 @@ where .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Invalid straight through algorithm format found in payment attempt")? - .unwrap_or_else(|| storage::PaymentRoutingInfo { + .unwrap_or(storage::PaymentRoutingInfo { algorithm: None, pre_routing_results: None, }), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 219a4d90519..e7de03804d1 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -19,7 +19,7 @@ use common_utils::{ MinorUnit, }, }; -use diesel_models::enums::{self}; +use diesel_models::enums; // TODO : Evaluate all the helper functions () use error_stack::{report, ResultExt}; use futures::future::Either; diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs index d516cab62fe..b8a855f5332 100644 --- a/crates/router/src/core/pm_auth/transformers.rs +++ b/crates/router/src/core/pm_auth/transformers.rs @@ -1,4 +1,4 @@ -use pm_auth::types::{self as pm_auth_types}; +use pm_auth::types as pm_auth_types; use crate::{core::errors, types, types::transformers::ForeignTryFrom}; diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index c706d8854af..ebc4c926599 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -914,7 +914,6 @@ pub async fn validate_and_create_refund( /// If payment-id is provided, lists all the refunds associated with that particular payment-id /// If payment-id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default - #[instrument(skip_all)] #[cfg(feature = "olap")] pub async fn refund_list( diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 264328796c8..c22a5021a26 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -356,7 +356,7 @@ impl MerchantConnectorAccounts { } #[cfg(feature = "v2")] -impl<'h> RoutingAlgorithmHelpers<'h> { +impl RoutingAlgorithmHelpers<'_> { fn connector_choice( &self, choice: &routing_types::RoutableConnectorChoice, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 1168ea87bf5..039e891e422 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -216,12 +216,12 @@ pub async fn connect_account( .await; logger::info!(?send_email_result); - return Ok(ApplicationResponse::Json( + Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { is_email_sent: send_email_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, - )); + )) } else if find_user .as_ref() .map_err(|e| e.current_context().is_db_not_found()) diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs index 0250415d4fd..c01d585feb7 100644 --- a/crates/router/src/core/user_role/role.rs +++ b/crates/router/src/core/user_role/role.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use api_models::user_role::role::{self as role_api}; +use api_models::user_role::role as role_api; use common_enums::{EntityType, ParentGroup, PermissionGroup, RoleScope}; use common_utils::generate_id_with_default_len; use diesel_models::role::{RoleNew, RoleUpdate}; diff --git a/crates/router/src/db/user_authentication_method.rs b/crates/router/src/db/user_authentication_method.rs index bcc2313d5db..a02e7bdb11f 100644 --- a/crates/router/src/db/user_authentication_method.rs +++ b/crates/router/src/db/user_authentication_method.rs @@ -1,4 +1,4 @@ -use diesel_models::user_authentication_method::{self as storage}; +use diesel_models::user_authentication_method as storage; use error_stack::report; use router_env::{instrument, tracing}; diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs index 783566335bc..71f10fe73e9 100644 --- a/crates/router/src/routes/payment_link.rs +++ b/crates/router/src/routes/payment_link.rs @@ -26,7 +26,6 @@ use crate::{ security(("api_key" = []), ("publishable_key" = [])) )] #[instrument(skip(state, req), fields(flow = ?Flow::PaymentLinkRetrieve))] - pub async fn payment_link_retrieve( state: web::Data<AppState>, req: actix_web::HttpRequest, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 93f50f3ed9a..27a5462c05e 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -1977,7 +1977,7 @@ impl GetLockingInput for payment_types::PaymentsCaptureRequest { struct FPaymentsApproveRequest<'a>(&'a payment_types::PaymentsApproveRequest); #[cfg(feature = "oltp")] -impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> { +impl GetLockingInput for FPaymentsApproveRequest<'_> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, @@ -1997,7 +1997,7 @@ impl<'a> GetLockingInput for FPaymentsApproveRequest<'a> { struct FPaymentsRejectRequest<'a>(&'a payment_types::PaymentsRejectRequest); #[cfg(feature = "oltp")] -impl<'a> GetLockingInput for FPaymentsRejectRequest<'a> { +impl GetLockingInput for FPaymentsRejectRequest<'_> { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction where F: types::FlowMetric, diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs index e1f113633a8..9a496c18d9a 100644 --- a/crates/router/src/services/api/client.rs +++ b/crates/router/src/services/api/client.rs @@ -403,9 +403,7 @@ impl ApiClient for ProxyClient { fn add_flow_name(&mut self, _flow_name: String) {} } -/// /// Api client for testing sending request -/// #[derive(Clone)] pub struct MockApiClient; diff --git a/crates/router/src/services/authentication/decision.rs b/crates/router/src/services/authentication/decision.rs index c31a4696bc9..4ff9f8401ba 100644 --- a/crates/router/src/services/authentication/decision.rs +++ b/crates/router/src/services/authentication/decision.rs @@ -179,10 +179,7 @@ pub async fn revoke_api_key( call_decision_service(state, decision_config, rule, RULE_DELETE_METHOD).await } -/// -/// /// Safety: i64::MAX < u64::MAX -/// #[allow(clippy::as_conversions)] pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 { let now = common_utils::date_time::now(); diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs index 51ae9456ecc..91968510a6b 100644 --- a/crates/router/src/services/kafka.rs +++ b/crates/router/src/services/kafka.rs @@ -94,7 +94,7 @@ impl<'a, T: KafkaMessage> KafkaEvent<'a, T> { } } -impl<'a, T: KafkaMessage> KafkaMessage for KafkaEvent<'a, T> { +impl<T: KafkaMessage> KafkaMessage for KafkaEvent<'_, T> { fn key(&self) -> String { self.event.key() } @@ -130,7 +130,7 @@ impl<'a, T: KafkaMessage> KafkaConsolidatedEvent<'a, T> { } } -impl<'a, T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'a, T> { +impl<T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'_, T> { fn key(&self) -> String { self.log.event.key() } diff --git a/crates/router/src/services/kafka/authentication.rs b/crates/router/src/services/kafka/authentication.rs index 67e488d6c8f..5cf2d066ee2 100644 --- a/crates/router/src/services/kafka/authentication.rs +++ b/crates/router/src/services/kafka/authentication.rs @@ -86,7 +86,7 @@ impl<'a> KafkaAuthentication<'a> { } } -impl<'a> super::KafkaMessage for KafkaAuthentication<'a> { +impl super::KafkaMessage for KafkaAuthentication<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/authentication_event.rs b/crates/router/src/services/kafka/authentication_event.rs index 7c8b77a3848..4169ff7b42a 100644 --- a/crates/router/src/services/kafka/authentication_event.rs +++ b/crates/router/src/services/kafka/authentication_event.rs @@ -87,7 +87,7 @@ impl<'a> KafkaAuthenticationEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaAuthenticationEvent<'a> { +impl super::KafkaMessage for KafkaAuthenticationEvent<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs index cc3a538851e..4414af494f2 100644 --- a/crates/router/src/services/kafka/dispute.rs +++ b/crates/router/src/services/kafka/dispute.rs @@ -71,7 +71,7 @@ impl<'a> KafkaDispute<'a> { } } -impl<'a> super::KafkaMessage for KafkaDispute<'a> { +impl super::KafkaMessage for KafkaDispute<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs index 64d91e8acaa..92327c044d7 100644 --- a/crates/router/src/services/kafka/dispute_event.rs +++ b/crates/router/src/services/kafka/dispute_event.rs @@ -72,7 +72,7 @@ impl<'a> KafkaDisputeEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaDisputeEvent<'a> { +impl super::KafkaMessage for KafkaDisputeEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/fraud_check.rs b/crates/router/src/services/kafka/fraud_check.rs index 26fa9e6b4e2..3010f85753b 100644 --- a/crates/router/src/services/kafka/fraud_check.rs +++ b/crates/router/src/services/kafka/fraud_check.rs @@ -53,7 +53,7 @@ impl<'a> KafkaFraudCheck<'a> { } } -impl<'a> super::KafkaMessage for KafkaFraudCheck<'a> { +impl super::KafkaMessage for KafkaFraudCheck<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/kafka/fraud_check_event.rs b/crates/router/src/services/kafka/fraud_check_event.rs index f35748cb1c8..4fd71174418 100644 --- a/crates/router/src/services/kafka/fraud_check_event.rs +++ b/crates/router/src/services/kafka/fraud_check_event.rs @@ -52,7 +52,7 @@ impl<'a> KafkaFraudCheckEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaFraudCheckEvent<'a> { +impl super::KafkaMessage for KafkaFraudCheckEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs index e585b21d4b2..adfff7450bc 100644 --- a/crates/router/src/services/kafka/payment_attempt.rs +++ b/crates/router/src/services/kafka/payment_attempt.rs @@ -180,7 +180,7 @@ impl<'a> KafkaPaymentAttempt<'a> { } } -impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> { +impl super::KafkaMessage for KafkaPaymentAttempt<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index cbce46ad9c7..177b211ae89 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -181,7 +181,7 @@ impl<'a> KafkaPaymentAttemptEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaPaymentAttemptEvent<'a> { +impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}", diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs index 82e33de8c60..378bddf193b 100644 --- a/crates/router/src/services/kafka/payment_intent.rs +++ b/crates/router/src/services/kafka/payment_intent.rs @@ -180,7 +180,7 @@ impl KafkaPaymentIntent<'_> { } } -impl<'a> super::KafkaMessage for KafkaPaymentIntent<'a> { +impl super::KafkaMessage for KafkaPaymentIntent<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index 5657846ca4c..7509f711620 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -182,7 +182,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaPaymentIntentEvent<'a> { +impl super::KafkaMessage for KafkaPaymentIntentEvent<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs index 7a6254bd527..babf7c1c568 100644 --- a/crates/router/src/services/kafka/payout.rs +++ b/crates/router/src/services/kafka/payout.rs @@ -77,7 +77,7 @@ impl<'a> KafkaPayout<'a> { } } -impl<'a> super::KafkaMessage for KafkaPayout<'a> { +impl super::KafkaMessage for KafkaPayout<'_> { fn key(&self) -> String { format!( "{}_{}", diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs index 7eff6f881ba..a7e37930cf2 100644 --- a/crates/router/src/services/kafka/refund.rs +++ b/crates/router/src/services/kafka/refund.rs @@ -66,7 +66,7 @@ impl<'a> KafkaRefund<'a> { } } -impl<'a> super::KafkaMessage for KafkaRefund<'a> { +impl super::KafkaMessage for KafkaRefund<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index 8f9f77878a1..74278944b04 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -67,7 +67,7 @@ impl<'a> KafkaRefundEvent<'a> { } } -impl<'a> super::KafkaMessage for KafkaRefundEvent<'a> { +impl super::KafkaMessage for KafkaRefundEvent<'_> { fn key(&self) -> String { format!( "{}_{}_{}_{}", diff --git a/crates/router/src/services/logger.rs b/crates/router/src/services/logger.rs index 7dfd7abb844..e88d4072f90 100644 --- a/crates/router/src/services/logger.rs +++ b/crates/router/src/services/logger.rs @@ -1,5 +1,3 @@ -//! //! Logger of the system. -//! pub use crate::logger::*; diff --git a/crates/router/src/types/storage/payment_link.rs b/crates/router/src/types/storage/payment_link.rs index 9a251d760bd..ae9aa417326 100644 --- a/crates/router/src/types/storage/payment_link.rs +++ b/crates/router/src/types/storage/payment_link.rs @@ -11,8 +11,8 @@ use crate::{ core::errors::{self, CustomResult}, logger, }; -#[async_trait::async_trait] +#[async_trait::async_trait] pub trait PaymentLinkDbExt: Sized { async fn filter_by_constraints( conn: &PgPooledConn, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 4ae02668957..210ae715202 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -701,7 +701,7 @@ impl ForeignFrom<storage::Config> for api_types::Config { } } -impl<'a> ForeignFrom<&'a api_types::ConfigUpdate> for storage::ConfigUpdate { +impl ForeignFrom<&api_types::ConfigUpdate> for storage::ConfigUpdate { fn foreign_from(config: &api_types::ConfigUpdate) -> Self { Self::Update { config: Some(config.value.clone()), @@ -709,7 +709,7 @@ impl<'a> ForeignFrom<&'a api_types::ConfigUpdate> for storage::ConfigUpdate { } } -impl<'a> From<&'a domain::Address> for api_types::Address { +impl From<&domain::Address> for api_types::Address { fn from(address: &domain::Address) -> Self { // If all the fields of address are none, then pass the address as None let address_details = if address.city.is_none() diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index 0bd0e81149f..8acab436491 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -25,7 +25,7 @@ pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { .attach_printable("Role groups cannot be empty"); } - let unique_groups: HashSet<_> = groups.iter().cloned().collect(); + let unique_groups: HashSet<_> = groups.iter().copied().collect(); if unique_groups.contains(&PermissionGroup::OrganizationManage) { return Err(report!(UserErrors::InvalidRoleOperation)) diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index b4fcf69241b..04fa1648492 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -243,7 +243,6 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow { /// `start_after`: The first psync should happen after 60 seconds /// /// `frequency` and `count`: The next 5 retries should have an interval of 300 seconds between them -/// pub async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 92cba2eec3f..751359c7763 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -205,7 +205,6 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> { } #[actix_web::test] - async fn payments_create_success() { let conf = Settings::new().unwrap(); let tx: oneshot::Sender<()> = oneshot::channel().0; @@ -314,7 +313,6 @@ async fn payments_create_failure() { } #[actix_web::test] - async fn refund_for_successful_payments() { let conf = Settings::new().unwrap(); use router::connector::Aci; diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index 33edd5e215e..d1fb543318f 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -166,7 +166,6 @@ pub fn diesel_enum( /// } /// ``` /// - /// # Panics /// /// Panics if a struct without named fields is provided as input to the macro @@ -505,7 +504,6 @@ pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStre /// payment_method: String, /// } /// ``` - #[proc_macro_derive( PolymorphicSchema, attributes(mandatory_in, generate_schemas, remove_in) @@ -620,6 +618,7 @@ pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::Token /// /// Example /// +/// ``` /// #[derive(Default, Serialize, FlatStruct)] /// pub struct User { /// name: String, @@ -644,7 +643,7 @@ pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::Token /// ("address.zip", "941222"), /// ("email", "[email protected]"), /// ] -/// +/// ``` #[proc_macro_derive(FlatStruct)] pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as syn::DeriveInput); diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index 407e910b29d..a096c236b2f 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -5,7 +5,7 @@ use quote::{quote, ToTokens}; use strum::IntoEnumIterator; use syn::{self, parse::Parse, DeriveInput}; -use crate::macros::helpers::{self}; +use crate::macros::helpers; #[derive(Debug, Clone, Copy, strum::EnumString, strum::EnumIter, strum::Display)] #[strum(serialize_all = "snake_case")] diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 0d46f8ac332..9b3aec4c949 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -1,8 +1,6 @@ #![warn(missing_debug_implementations)] -//! //! Environment of payment router: logger, basic config, its environment awareness. -//! #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] diff --git a/crates/router_env/src/logger/mod.rs b/crates/router_env/src/logger.rs similarity index 98% rename from crates/router_env/src/logger/mod.rs rename to crates/router_env/src/logger.rs index a7aa0610e9b..2b0ae49b1f6 100644 --- a/crates/router_env/src/logger/mod.rs +++ b/crates/router_env/src/logger.rs @@ -1,6 +1,4 @@ -//! //! Logger of the system. -//! pub use tracing::{debug, error, event as log, info, warn}; pub use tracing_attributes::instrument; diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs index 03cc9ac17bc..746c8ee9580 100644 --- a/crates/router_env/src/logger/config.rs +++ b/crates/router_env/src/logger/config.rs @@ -1,6 +1,4 @@ -//! //! Logger-specific config. -//! use std::path::PathBuf; diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index 6bcf669e73a..5c3341026c2 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -1,6 +1,4 @@ -//! //! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. -//! use std::{ collections::{HashMap, HashSet}, @@ -117,10 +115,8 @@ impl fmt::Display for RecordType { } } -/// /// Format log records. /// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries. -/// #[derive(Debug)] pub struct FormattingLayer<W, F> where @@ -145,7 +141,6 @@ where W: for<'a> MakeWriter<'a> + 'static, F: Formatter + Clone, { - /// /// Constructor of `FormattingLayer`. /// /// A `name` will be attached to all records during formatting. @@ -155,7 +150,6 @@ where /// ```rust /// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter); /// ``` - /// pub fn new( service: &str, dst_writer: W, @@ -296,11 +290,9 @@ where Ok(()) } - /// /// Flush memory buffer into an output stream trailing it with next line. /// /// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading. - /// fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> { buffer.write_all(b"\n")?; self.dst_writer.make_writer().write_all(&buffer) @@ -361,12 +353,9 @@ where Ok(buffer) } - /// /// Format message of a span. /// /// Example: "[FN_WITHOUT_COLON - START]" - /// - fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String where S: Subscriber + for<'a> LookupSpan<'a>, @@ -374,12 +363,9 @@ where format!("[{} - {}]", span.metadata().name().to_uppercase(), ty) } - /// /// Format message of an event. /// /// Examples: "[FN_WITHOUT_COLON - EVENT] Message" - /// - fn event_message<S>( span: &Option<&SpanRef<'_, S>>, event: &Event<'_>, diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index 428112fb37c..6433172edf4 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -181,9 +181,7 @@ struct TraceAssertion { } impl TraceAssertion { - /// /// Should the provided url be traced - /// fn should_trace_url(&self, url: &str) -> bool { match &self.clauses { Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)), @@ -192,9 +190,7 @@ impl TraceAssertion { } } -/// /// Conditional Sampler for providing control on url based tracing -/// #[derive(Clone, Debug)] struct ConditionalSampler<T: trace::ShouldSample + Clone + 'static>(TraceAssertion, T); diff --git a/crates/router_env/src/logger/storage.rs b/crates/router_env/src/logger/storage.rs index ce220680bb1..cdaf06ecf93 100644 --- a/crates/router_env/src/logger/storage.rs +++ b/crates/router_env/src/logger/storage.rs @@ -1,6 +1,4 @@ -//! //! Storing [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router. -//! use std::{collections::HashMap, fmt, time::Instant}; diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 5d59e7ddbac..b1488b904be 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -1,6 +1,4 @@ -//! //! Types. -//! use serde::Deserialize; use strum::{Display, EnumString}; @@ -9,12 +7,9 @@ pub use tracing::{ Level, Value, }; -/// /// Category and tag of log event. /// /// Don't hesitate to add your variant if it is missing here. -/// - #[derive(Debug, Default, Deserialize, Clone, Display, EnumString)] pub enum Tag { /// General. @@ -516,9 +511,7 @@ pub enum Flow { PaymentStartRedirection, } -/// /// Trait for providing generic behaviour to flow metric -/// pub trait FlowMetric: ToString + std::fmt::Debug + Clone {} impl FlowMetric for Flow {} diff --git a/crates/router_env/tests/logger.rs b/crates/router_env/tests/logger.rs index 46b5b9538cf..1070938a8a1 100644 --- a/crates/router_env/tests/logger.rs +++ b/crates/router_env/tests/logger.rs @@ -1,10 +1,11 @@ #![allow(clippy::unwrap_used)] mod test_module; + use ::config::ConfigError; use router_env::TelemetryGuard; -use self::test_module::some_module::*; +use self::test_module::fn_with_colon; fn logger() -> error_stack::Result<&'static TelemetryGuard, ConfigError> { use once_cell::sync::OnceCell; diff --git a/crates/router_env/tests/test_module/some_module.rs b/crates/router_env/tests/test_module.rs similarity index 90% rename from crates/router_env/tests/test_module/some_module.rs rename to crates/router_env/tests/test_module.rs index 8c9dda2c08e..f3c382706b4 100644 --- a/crates/router_env/tests/test_module/some_module.rs +++ b/crates/router_env/tests/test_module.rs @@ -1,7 +1,6 @@ -use logger::instrument; use router_env as logger; -#[instrument(skip_all)] +#[tracing::instrument(skip_all)] pub async fn fn_with_colon(val: i32) { let a = 13; let b = 31; @@ -23,7 +22,7 @@ pub async fn fn_with_colon(val: i32) { fn_without_colon(131).await; } -#[instrument(fields(val3 = "abc"), skip_all)] +#[tracing::instrument(fields(val3 = "abc"), skip_all)] pub async fn fn_without_colon(val: i32) { let a = 13; let b = 31; diff --git a/crates/router_env/tests/test_module/mod.rs b/crates/router_env/tests/test_module/mod.rs deleted file mode 100644 index 7699174549d..00000000000 --- a/crates/router_env/tests/test_module/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod some_module; diff --git a/crates/scheduler/src/db/mod.rs b/crates/scheduler/src/db.rs similarity index 100% rename from crates/scheduler/src/db/mod.rs rename to crates/scheduler/src/db.rs diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs index efcce567727..b81676a6cc4 100644 --- a/crates/storage_impl/src/mock_db.rs +++ b/crates/storage_impl/src/mock_db.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use diesel_models::{self as store}; +use diesel_models as store; use error_stack::ResultExt; use futures::lock::Mutex; use hyperswitch_domain_models::{ diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs index 69931057959..b32c3d22044 100644 --- a/crates/storage_impl/src/redis/cache.rs +++ b/crates/storage_impl/src/redis/cache.rs @@ -117,7 +117,7 @@ impl<'a> TryFrom<CacheRedact<'a>> for RedisValue { } } -impl<'a> TryFrom<RedisValue> for CacheRedact<'a> { +impl TryFrom<RedisValue> for CacheRedact<'_> { type Error = Report<errors::ValidationError>; fn try_from(v: RedisValue) -> Result<Self, Self::Error> { diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs index 2fde935b670..83d8de9c30a 100644 --- a/crates/storage_impl/src/redis/kv_store.rs +++ b/crates/storage_impl/src/redis/kv_store.rs @@ -57,7 +57,7 @@ pub enum PartitionKey<'a> { }, } // PartitionKey::MerchantIdPaymentId {merchant_id, payment_id} -impl<'a> std::fmt::Display for PartitionKey<'a> { +impl std::fmt::Display for PartitionKey<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { PartitionKey::MerchantIdPaymentId { @@ -279,7 +279,7 @@ pub enum Op<'a> { Find, } -impl<'a> std::fmt::Display for Op<'a> { +impl std::fmt::Display for Op<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Op::Insert => f.write_str("insert"),
2024-12-01T18:55:46Z
## 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 addresses clippy lints stabilized / enabled in Rust 1.83.0. The major warnings being thrown due to the version bump were [`empty_line_after_doc_comments`](https://rust-lang.github.io/rust-clippy/master/index.html#empty_line_after_doc_comments) and [`empty_line_after_outer_attr`](https://rust-lang.github.io/rust-clippy/master/index.html#empty_line_after_outer_attr), and very few were from [`needless_lifetimes`](https://rust-lang.github.io/rust-clippy/master/index.html#needless_lifetimes). Consequently, addressing these involved removing some blank lines after doc comments and attributes, and removing the unnecessary lifetime annotations. In addition, this PR enables and addresses the following lints: - [`cloned_instead_of_copied`](https://rust-lang.github.io/rust-clippy/master/index.html#cloned_instead_of_copied): Checks for usage of `cloned()` on an `Iterator` or `Option` where `copied()` could be used instead. - [`dbg_macro`](https://rust-lang.github.io/rust-clippy/master/index.html#dbg_macro): Checks for usage of the `dbg!` macro. - [`fn_params_excessive_bools`](https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools): Checks for excessive use of bools in function definitions, suggests two-variant enums instead. The maximum number of boolean params allowed by default is 3. - There's also [`struct_excessive_bools`](https://rust-lang.github.io/rust-clippy/master/index.html#struct_excessive_bools) which warns about excessive usage of bools in structs, which I did NOT enable, since some of the fields in say business profile are bools, which toggle specific features of behavior and may not be easily replaceable with enums. - [`mod_module_files`](https://rust-lang.github.io/rust-clippy/master/index.html#mod_module_files): Warns if `mod.rs` files are included in the module structure. - [`unnecessary_self_imports`](https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_self_imports): Checks for imports ending in `::{self}`. - [`wildcard_dependencies`](https://rust-lang.github.io/rust-clippy/master/index.html#wildcard_dependencies): Checks for wildcard dependencies in the `Cargo.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). --> Resolves #6704. As for the new lints enabled, they should help ensure better consistency throughout the codebase and help enforce certain practices. ## 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)? --> From what I'd expect, none of the existing behavior should be affected due to these changes. Our Postman and Cypress tests running on CI should pass, as before. ## 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
982b26a8c2851266b6e8615699479a05ab62e519
juspay/hyperswitch
juspay__hyperswitch-6709
Bug: [FEATURE] Add webhook support for network tokenization ### Feature Description Add webhook support to consume the webhooks from network token requestor. ### Possible Implementation New webhook wrapper should be introduced, since current implementation are specific to payments, but payment methods. ### 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/payment_methods.rs b/crates/api_models/src/payment_methods.rs index 25b583f5dc4..c681cf7edd0 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -1065,6 +1065,23 @@ pub struct Card { pub nick_name: Option<String>, } +#[cfg(feature = "v1")] +impl From<(Card, Option<common_enums::CardNetwork>)> for CardDetail { + fn from((card, card_network): (Card, Option<common_enums::CardNetwork>)) -> Self { + Self { + card_number: card.card_number.clone(), + card_exp_month: card.card_exp_month.clone(), + card_exp_year: card.card_exp_year.clone(), + card_holder_name: card.name_on_card.clone(), + nick_name: card.nick_name.map(masking::Secret::new), + card_issuing_country: None, + card_network, + card_issuer: None, + card_type: None, + } + } +} + #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs index 7895588e8e0..4667866073b 100644 --- a/crates/api_models/src/webhooks.rs +++ b/crates/api_models/src/webhooks.rs @@ -129,6 +129,11 @@ pub enum WebhookResponseTracker { mandate_id: String, status: common_enums::MandateStatus, }, + #[cfg(feature = "v1")] + PaymentMethod { + payment_method_id: String, + status: common_enums::PaymentMethodStatus, + }, NoEffect, Relay { relay_id: common_utils::id_type::RelayId, @@ -143,13 +148,30 @@ impl WebhookResponseTracker { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), - Self::NoEffect | Self::Mandate { .. } => None, + Self::NoEffect | Self::Mandate { .. } | Self::PaymentMethod { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } + #[cfg(feature = "v1")] + pub fn get_payment_method_id(&self) -> Option<String> { + match self { + Self::PaymentMethod { + payment_method_id, .. + } => Some(payment_method_id.to_owned()), + Self::Payment { .. } + | Self::Refund { .. } + | Self::Dispute { .. } + | Self::NoEffect + | Self::Mandate { .. } + | Self::Relay { .. } => None, + #[cfg(feature = "payouts")] + Self::Payout { .. } => None, + } + } + #[cfg(feature = "v2")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> { match self { diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index d7f4a1b2a20..d36b2d624f0 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -8535,3 +8535,23 @@ impl RoutingApproach { } } } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Serialize, + serde::Deserialize, + ToSchema, + strum::Display, + strum::EnumString, + Hash, +)] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +#[router_derive::diesel_enum(storage_type = "text")] +pub enum CallbackMapperIdType { + NetworkTokenRequestorRefernceID, +} diff --git a/crates/common_types/src/callback_mapper.rs b/crates/common_types/src/callback_mapper.rs new file mode 100644 index 00000000000..c7af35d1c79 --- /dev/null +++ b/crates/common_types/src/callback_mapper.rs @@ -0,0 +1,40 @@ +use common_utils::id_type; +use diesel::{AsExpression, FromSqlRow}; + +#[derive( + Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, AsExpression, FromSqlRow, +)] +#[diesel(sql_type = diesel::sql_types::Jsonb)] +/// Represents the data associated with a callback mapper. +pub enum CallbackMapperData { + /// data variant used while processing the network token webhook + NetworkTokenWebhook { + /// Merchant id assiociated with the network token requestor reference id + merchant_id: id_type::MerchantId, + /// Payment Method id assiociated with the network token requestor reference id + payment_method_id: String, + /// Customer id assiociated with the network token requestor reference id + customer_id: id_type::CustomerId, + }, +} + +impl CallbackMapperData { + /// Retrieves the details of the network token webhook type from callback mapper data. + pub fn get_network_token_webhook_details( + &self, + ) -> (id_type::MerchantId, String, id_type::CustomerId) { + match self { + Self::NetworkTokenWebhook { + merchant_id, + payment_method_id, + customer_id, + } => ( + merchant_id.clone(), + payment_method_id.clone(), + customer_id.clone(), + ), + } + } +} + +common_utils::impl_to_sql_from_sql_json!(CallbackMapperData); diff --git a/crates/common_types/src/lib.rs b/crates/common_types/src/lib.rs index 4913f1ebcc0..91ee876184a 100644 --- a/crates/common_types/src/lib.rs +++ b/crates/common_types/src/lib.rs @@ -12,3 +12,6 @@ pub mod primitive_wrappers; pub mod refunds; /// types for three ds decision rule engine pub mod three_ds_decision_rule_engine; + +///types for callback mapper +pub mod callback_mapper; diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs index 506211c4d7a..376b57fbb47 100644 --- a/crates/common_utils/src/events.rs +++ b/crates/common_utils/src/events.rs @@ -75,6 +75,10 @@ pub enum ApiEventsType { connector: String, payment_id: Option<id_type::PaymentId>, }, + #[cfg(feature = "v1")] + NetworkTokenWebhook { + payment_method_id: Option<String>, + }, #[cfg(feature = "v2")] Webhooks { connector: id_type::MerchantConnectorAccountId, diff --git a/crates/diesel_models/src/callback_mapper.rs b/crates/diesel_models/src/callback_mapper.rs index 3e031d483ac..f9a8fa47c87 100644 --- a/crates/diesel_models/src/callback_mapper.rs +++ b/crates/diesel_models/src/callback_mapper.rs @@ -1,4 +1,5 @@ -use common_utils::pii; +use common_enums::enums as common_enums; +use common_types::callback_mapper::CallbackMapperData; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::callback_mapper; @@ -7,8 +8,8 @@ use crate::schema::callback_mapper; #[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))] pub struct CallbackMapper { pub id: String, - pub type_: String, - pub data: pii::SecretSerdeValue, + pub type_: common_enums::CallbackMapperIdType, + pub data: CallbackMapperData, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, } diff --git a/crates/hyperswitch_domain_models/src/callback_mapper.rs b/crates/hyperswitch_domain_models/src/callback_mapper.rs index fffc33e572a..429f3f7ff95 100644 --- a/crates/hyperswitch_domain_models/src/callback_mapper.rs +++ b/crates/hyperswitch_domain_models/src/callback_mapper.rs @@ -1,12 +1,29 @@ -use common_utils::pii; -use serde::{self, Deserialize, Serialize}; +use common_enums::enums as common_enums; +use common_types::callback_mapper::CallbackMapperData; -#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Debug, Eq, PartialEq)] pub struct CallbackMapper { pub id: String, - #[serde(rename = "type")] - pub type_: String, - pub data: pii::SecretSerdeValue, + pub callback_mapper_id_type: common_enums::CallbackMapperIdType, + pub data: CallbackMapperData, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, } + +impl CallbackMapper { + pub fn new( + id: String, + callback_mapper_id_type: common_enums::CallbackMapperIdType, + data: CallbackMapperData, + created_at: time::PrimitiveDateTime, + last_modified_at: time::PrimitiveDateTime, + ) -> Self { + Self { + id, + callback_mapper_id_type, + data, + created_at, + last_modified_at, + } + } +} diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs index b4c579a07a8..9129a9a78f6 100644 --- a/crates/router/src/configs/secrets_transformers.rs +++ b/crates/router/src/configs/secrets_transformers.rs @@ -314,11 +314,15 @@ impl SecretsHandler for settings::NetworkTokenizationService { let private_key = secret_management_client .get_secret(network_tokenization.private_key.clone()) .await?; + let webhook_source_verification_key = secret_management_client + .get_secret(network_tokenization.webhook_source_verification_key.clone()) + .await?; Ok(value.transition_state(|network_tokenization| Self { public_key, private_key, token_service_api_key, + webhook_source_verification_key, ..network_tokenization })) } diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 9424b2572da..8a2132a7fe1 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -601,6 +601,7 @@ pub struct NetworkTokenizationService { pub key_id: String, pub delete_token_url: url::Url, pub check_token_status_url: url::Url, + pub webhook_source_verification_key: Secret<String>, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/configs/validations.rs b/crates/router/src/configs/validations.rs index 1b8adfaa8b8..ab5f2af4160 100644 --- a/crates/router/src/configs/validations.rs +++ b/crates/router/src/configs/validations.rs @@ -244,7 +244,16 @@ impl super::settings::NetworkTokenizationService { Err(ApplicationError::InvalidConfigurationValueError( "private_key must not be empty".into(), )) - }) + })?; + + when( + self.webhook_source_verification_key.is_default_or_empty(), + || { + Err(ApplicationError::InvalidConfigurationValueError( + "webhook_source_verification_key must not be empty".into(), + )) + }, + ) } } diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 59be79c66f6..2034119fa21 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -20,16 +20,16 @@ use api_models::payment_methods; #[cfg(feature = "payouts")] pub use api_models::{enums::PayoutConnectors, payouts as payout_types}; #[cfg(feature = "v1")] -use common_utils::ext_traits::{Encode, OptionExt}; -use common_utils::{consts::DEFAULT_LOCALE, id_type}; +use common_utils::{consts::DEFAULT_LOCALE, ext_traits::OptionExt}; #[cfg(feature = "v2")] use common_utils::{ crypto::Encryptable, errors::CustomResult, - ext_traits::{AsyncExt, Encode, ValueExt}, + ext_traits::{AsyncExt, ValueExt}, fp_utils::when, generate_id, types as util_types, }; +use common_utils::{ext_traits::Encode, id_type}; use diesel_models::{ enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData, }; diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index b88476e19d8..ef9e8b580dd 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -7,6 +7,7 @@ use api_models::{ payment_methods::PaymentMethodDataWalletInfo, payments::ConnectorMandateReferenceId, }; use common_enums::{ConnectorMandateStatus, PaymentMethod}; +use common_types::callback_mapper::CallbackMapperData; use common_utils::{ crypto::Encryptable, ext_traits::{AsyncExt, Encode, ValueExt}, @@ -17,6 +18,7 @@ use common_utils::{ use error_stack::{report, ResultExt}; #[cfg(feature = "v1")] use hyperswitch_domain_models::{ + callback_mapper::CallbackMapper, mandates::{CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord}, payment_method_data, }; @@ -754,11 +756,45 @@ where card.card_network .map(|card_network| card_network.to_string()) }), - network_token_requestor_ref_id, + network_token_requestor_ref_id.clone(), network_token_locker_id, pm_network_token_data_encrypted, ) .await?; + + match network_token_requestor_ref_id { + Some(network_token_requestor_ref_id) => { + //Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks + let callback_mapper_data = + CallbackMapperData::NetworkTokenWebhook { + merchant_id: merchant_context + .get_merchant_account() + .get_id() + .clone(), + customer_id, + payment_method_id: resp.payment_method_id.clone(), + }; + let callback_mapper = CallbackMapper::new( + network_token_requestor_ref_id, + common_enums::CallbackMapperIdType::NetworkTokenRequestorRefernceID, + callback_mapper_data, + common_utils::date_time::now(), + common_utils::date_time::now(), + ); + + db.insert_call_back_mapper(callback_mapper) + .await + .change_context( + errors::ApiErrorResponse::InternalServerError, + ) + .attach_printable( + "Failed to insert in Callback Mapper table", + )?; + } + None => { + logger::info!("Network token requestor reference ID is not available, skipping callback mapper insertion"); + } + }; }; } } diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 298cf936132..88a3361ec01 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -3,6 +3,8 @@ mod incoming; #[cfg(feature = "v2")] mod incoming_v2; #[cfg(feature = "v1")] +mod network_tokenization_incoming; +#[cfg(feature = "v1")] mod outgoing; #[cfg(feature = "v2")] mod outgoing_v2; @@ -15,7 +17,7 @@ pub mod webhook_events; #[cfg(feature = "v1")] pub(crate) use self::{ - incoming::incoming_webhooks_wrapper, + incoming::{incoming_webhooks_wrapper, network_token_incoming_webhooks_wrapper}, outgoing::{ create_event_and_trigger_outgoing_webhook, get_outgoing_webhook_request, trigger_webhook_and_raise_event, diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs index 9763e63f179..e9c95576469 100644 --- a/crates/router/src/core/webhooks/incoming.rs +++ b/crates/router/src/core/webhooks/incoming.rs @@ -7,7 +7,7 @@ use api_models::webhooks::{self, WebhookResponseTracker}; use common_utils::{ errors::ReportSwitchExt, events::ApiEventsType, - ext_traits::AsyncExt, + ext_traits::{AsyncExt, ByteSliceExt}, types::{AmountConvertor, StringMinorUnitForConnector}, }; use diesel_models::ConnectorMandateReferenceId; @@ -28,10 +28,10 @@ use crate::{ core::{ api_locking, errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt}, - metrics, + metrics, payment_methods, payments::{self, tokenization}, refunds, relay, utils as core_utils, - webhooks::utils::construct_webhook_router_data, + webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data}, }, db::StorageInterface, events::api_logs::ApiEvent, @@ -125,6 +125,68 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( Ok(application_response) } +#[cfg(feature = "v1")] +pub async fn network_token_incoming_webhooks_wrapper<W: types::OutgoingWebhookType>( + flow: &impl router_env::types::FlowMetric, + state: SessionState, + req: &actix_web::HttpRequest, + body: actix_web::web::Bytes, +) -> RouterResponse<serde_json::Value> { + let start_instant = Instant::now(); + + let request_details: IncomingWebhookRequestDetails<'_> = IncomingWebhookRequestDetails { + method: req.method().clone(), + uri: req.uri().clone(), + headers: req.headers(), + query_params: req.query_string().to_string(), + body: &body, + }; + + let (application_response, webhooks_response_tracker, serialized_req, merchant_id) = Box::pin( + network_token_incoming_webhooks_core::<W>(&state, request_details), + ) + .await?; + + logger::info!(incoming_webhook_payload = ?serialized_req); + + let request_duration = Instant::now() + .saturating_duration_since(start_instant) + .as_millis(); + + let request_id = RequestId::extract(req) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to extract request id from request")?; + let auth_type = auth::AuthenticationType::NoAuth; + let status_code = 200; + let api_event = ApiEventsType::NetworkTokenWebhook { + payment_method_id: webhooks_response_tracker.get_payment_method_id(), + }; + let response_value = serde_json::to_value(&webhooks_response_tracker) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not convert webhook effect to string")?; + let infra = state.infra_components.clone(); + let api_event = ApiEvent::new( + state.tenant.tenant_id.clone(), + Some(merchant_id), + flow, + &request_id, + request_duration, + status_code, + serialized_req, + Some(response_value), + None, + auth_type, + None, + api_event, + req, + req.method(), + infra, + ); + state.event_handler().log_event(&api_event); + Ok(application_response) +} + #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn incoming_webhooks_core<W: types::OutgoingWebhookType>( @@ -598,6 +660,81 @@ fn handle_incoming_webhook_error( } } +#[instrument(skip_all)] +#[cfg(feature = "v1")] +async fn network_token_incoming_webhooks_core<W: types::OutgoingWebhookType>( + state: &SessionState, + request_details: IncomingWebhookRequestDetails<'_>, +) -> errors::RouterResult<( + services::ApplicationResponse<serde_json::Value>, + WebhookResponseTracker, + serde_json::Value, + common_utils::id_type::MerchantId, +)> { + let serialized_request = + network_tokenization_incoming::get_network_token_resource_object(&request_details) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Network Token Requestor Webhook deserialization failed")? + .masked_serialize() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Could not convert webhook effect to string")?; + + let network_tokenization_service = &state + .conf + .network_tokenization_service + .as_ref() + .ok_or(errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Network Tokenization Service not configured")?; + + //source verification + network_tokenization_incoming::Authorization::new(request_details.headers.get("Authorization")) + .verify_webhook_source(network_tokenization_service.get_inner()) + .await?; + + let response: network_tokenization_incoming::NetworkTokenWebhookResponse = request_details + .body + .parse_struct("NetworkTokenWebhookResponse") + .change_context(errors::ApiErrorResponse::WebhookUnprocessableEntity)?; + + let (merchant_id, payment_method_id, _customer_id) = response + .fetch_merchant_id_payment_method_id_customer_id_from_callback_mapper(state) + .await?; + + metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add( + 1, + router_env::metric_attributes!((MERCHANT_ID, merchant_id.clone())), + ); + + let merchant_context = + network_tokenization_incoming::fetch_merchant_account_for_network_token_webhooks( + state, + &merchant_id, + ) + .await?; + let payment_method = + network_tokenization_incoming::fetch_payment_method_for_network_token_webhooks( + state, + merchant_context.get_merchant_account(), + merchant_context.get_merchant_key_store(), + &payment_method_id, + ) + .await?; + + let response_data = response.get_response_data(); + + let webhook_resp_tracker = response_data + .update_payment_method(state, &payment_method, &merchant_context) + .await?; + + Ok(( + services::ApplicationResponse::StatusOk, + webhook_resp_tracker, + serialized_request, + merchant_id.clone(), + )) +} + #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] async fn payments_incoming_webhook_flow( @@ -1316,7 +1453,7 @@ async fn external_authentication_incoming_webhook_flow( authentication_details .authentication_value .async_map(|auth_val| { - crate::core::payment_methods::vault::create_tokenize( + payment_methods::vault::create_tokenize( &state, auth_val.expose(), None, diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rs new file mode 100644 index 00000000000..a49ec40cbaa --- /dev/null +++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs @@ -0,0 +1,463 @@ +use std::str::FromStr; + +use ::payment_methods::controller::PaymentMethodsController; +use api_models::webhooks::WebhookResponseTracker; +use async_trait::async_trait; +use common_utils::{ + crypto::Encryptable, + ext_traits::{AsyncExt, ByteSliceExt, ValueExt}, + id_type, +}; +use error_stack::{report, ResultExt}; +use http::HeaderValue; +use masking::{ExposeInterface, Secret}; +use serde::{Deserialize, Serialize}; + +use crate::{ + configs::settings, + core::{ + errors::{self, CustomResult, RouterResult, StorageErrorExt}, + payment_methods::cards, + }, + logger, + routes::{app::SessionStateInfo, SessionState}, + types::{ + api, domain, payment_methods as pm_types, + storage::{self, enums}, + }, + utils::{self as helper_utils, ext_traits::OptionExt}, +}; + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(untagged)] +pub enum NetworkTokenWebhookResponse { + PanMetadataUpdate(pm_types::PanMetadataUpdateBody), + NetworkTokenMetadataUpdate(pm_types::NetworkTokenMetaDataUpdateBody), +} + +impl NetworkTokenWebhookResponse { + fn get_network_token_requestor_ref_id(&self) -> String { + match self { + Self::PanMetadataUpdate(data) => data.card.card_reference.clone(), + Self::NetworkTokenMetadataUpdate(data) => data.token.card_reference.clone(), + } + } + + pub fn get_response_data(self) -> Box<dyn NetworkTokenWebhookResponseExt> { + match self { + Self::PanMetadataUpdate(data) => Box::new(data), + Self::NetworkTokenMetadataUpdate(data) => Box::new(data), + } + } + + pub async fn fetch_merchant_id_payment_method_id_customer_id_from_callback_mapper( + &self, + state: &SessionState, + ) -> RouterResult<(id_type::MerchantId, String, id_type::CustomerId)> { + let network_token_requestor_ref_id = &self.get_network_token_requestor_ref_id(); + + let db = &*state.store; + let callback_mapper_data = db + .find_call_back_mapper_by_id(network_token_requestor_ref_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch callback mapper data")?; + + Ok(callback_mapper_data + .data + .get_network_token_webhook_details()) + } +} + +pub fn get_network_token_resource_object( + request_details: &api::IncomingWebhookRequestDetails<'_>, +) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::NetworkTokenizationError> { + let response: NetworkTokenWebhookResponse = request_details + .body + .parse_struct("NetworkTokenWebhookResponse") + .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?; + Ok(Box::new(response)) +} + +#[async_trait] +pub trait NetworkTokenWebhookResponseExt { + fn decrypt_payment_method_data( + &self, + payment_method: &domain::PaymentMethod, + ) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse>; + + async fn update_payment_method( + &self, + state: &SessionState, + payment_method: &domain::PaymentMethod, + merchant_context: &domain::MerchantContext, + ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse>; +} + +#[async_trait] +impl NetworkTokenWebhookResponseExt for pm_types::PanMetadataUpdateBody { + fn decrypt_payment_method_data( + &self, + payment_method: &domain::PaymentMethod, + ) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse> { + let decrypted_data = payment_method + .payment_method_data + .clone() + .map(|payment_method_data| payment_method_data.into_inner().expose()) + .and_then(|val| { + val.parse_value::<api::payment_methods::PaymentMethodsData>("PaymentMethodsData") + .map_err(|err| logger::error!(?err, "Failed to parse PaymentMethodsData")) + .ok() + }) + .and_then(|pmd| match pmd { + api::payment_methods::PaymentMethodsData::Card(token) => { + Some(api::payment_methods::CardDetailFromLocker::from(token)) + } + _ => None, + }) + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to obtain decrypted token object from db")?; + Ok(decrypted_data) + } + + async fn update_payment_method( + &self, + state: &SessionState, + payment_method: &domain::PaymentMethod, + merchant_context: &domain::MerchantContext, + ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + let decrypted_data = self.decrypt_payment_method_data(payment_method)?; + handle_metadata_update( + state, + &self.card, + payment_method + .locker_id + .clone() + .get_required_value("locker_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Locker id is not found for the payment method")?, + payment_method, + merchant_context, + decrypted_data, + true, + ) + .await + } +} + +#[async_trait] +impl NetworkTokenWebhookResponseExt for pm_types::NetworkTokenMetaDataUpdateBody { + fn decrypt_payment_method_data( + &self, + payment_method: &domain::PaymentMethod, + ) -> CustomResult<api::payment_methods::CardDetailFromLocker, errors::ApiErrorResponse> { + let decrypted_data = payment_method + .network_token_payment_method_data + .clone() + .map(|x| x.into_inner().expose()) + .and_then(|val| { + val.parse_value::<api::payment_methods::PaymentMethodsData>("PaymentMethodsData") + .map_err(|err| logger::error!(?err, "Failed to parse PaymentMethodsData")) + .ok() + }) + .and_then(|pmd| match pmd { + api::payment_methods::PaymentMethodsData::Card(token) => { + Some(api::payment_methods::CardDetailFromLocker::from(token)) + } + _ => None, + }) + .ok_or(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to obtain decrypted token object from db")?; + Ok(decrypted_data) + } + + async fn update_payment_method( + &self, + state: &SessionState, + payment_method: &domain::PaymentMethod, + merchant_context: &domain::MerchantContext, + ) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> { + let decrypted_data = self.decrypt_payment_method_data(payment_method)?; + handle_metadata_update( + state, + &self.token, + payment_method + .network_token_locker_id + .clone() + .get_required_value("locker_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Locker id is not found for the payment method")?, + payment_method, + merchant_context, + decrypted_data, + true, + ) + .await + } +} + +pub struct Authorization { + header: Option<HeaderValue>, +} + +impl Authorization { + pub fn new(header: Option<&HeaderValue>) -> Self { + Self { + header: header.cloned(), + } + } + + pub async fn verify_webhook_source( + self, + nt_service: &settings::NetworkTokenizationService, + ) -> CustomResult<(), errors::ApiErrorResponse> { + let secret = nt_service.webhook_source_verification_key.clone(); + + let source_verified = match self.header { + Some(authorization_header) => match authorization_header.to_str() { + Ok(header_value) => Ok(header_value == secret.expose()), + Err(err) => { + logger::error!(?err, "Failed to parse authorization header"); + Err(errors::ApiErrorResponse::WebhookAuthenticationFailed) + } + }, + None => Ok(false), + }?; + logger::info!(source_verified=?source_verified); + + helper_utils::when(!source_verified, || { + Err(report!( + errors::ApiErrorResponse::WebhookAuthenticationFailed + )) + })?; + + Ok(()) + } +} + +#[allow(clippy::too_many_arguments)] +pub async fn handle_metadata_update( + state: &SessionState, + metadata: &pm_types::NetworkTokenRequestorData, + locker_id: String, + payment_method: &domain::PaymentMethod, + merchant_context: &domain::MerchantContext, + decrypted_data: api::payment_methods::CardDetailFromLocker, + is_pan_update: bool, +) -> RouterResult<WebhookResponseTracker> { + let merchant_id = merchant_context.get_merchant_account().get_id(); + let customer_id = &payment_method.customer_id; + let payment_method_id = payment_method.get_id().clone(); + let status = payment_method.status; + + match metadata.is_update_required(decrypted_data) { + false => { + logger::info!( + "No update required for payment method {} for locker_id {}", + payment_method.get_id(), + locker_id + ); + Ok(WebhookResponseTracker::PaymentMethod { + payment_method_id, + status, + }) + } + true => { + let mut card = cards::get_card_from_locker(state, customer_id, merchant_id, &locker_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch token information from the locker")?; + + card.card_exp_year = metadata.expiry_year.clone(); + card.card_exp_month = metadata.expiry_month.clone(); + + let card_network = card + .card_brand + .clone() + .map(|card_brand| enums::CardNetwork::from_str(&card_brand)) + .transpose() + .change_context(errors::ApiErrorResponse::InvalidDataValue { + field_name: "card network", + }) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Invalid Card Network stored in vault")?; + + let card_data = api::payment_methods::CardDetail::from((card, card_network)); + + let payment_method_request: api::payment_methods::PaymentMethodCreate = + PaymentMethodCreateWrapper::from((&card_data, payment_method)).get_inner(); + + let pm_cards = cards::PmCards { + state, + merchant_context, + }; + + pm_cards + .delete_card_from_locker(customer_id, merchant_id, &locker_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to delete network token")?; + + let (res, _) = pm_cards + .add_card_to_locker(payment_method_request, &card_data, customer_id, None) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to add network token")?; + + let pm_details = res.card.as_ref().map(|card| { + api::payment_methods::PaymentMethodsData::Card( + api::payment_methods::CardDetailsPaymentMethod::from((card.clone(), None)), + ) + }); + let key_manager_state = state.into(); + + let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_details + .async_map(|pm_card| { + cards::create_encrypted_data( + &key_manager_state, + merchant_context.get_merchant_key_store(), + pm_card, + ) + }) + .await + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to encrypt payment method data")?; + + let pm_update = if is_pan_update { + storage::PaymentMethodUpdate::AdditionalDataUpdate { + locker_id: Some(res.payment_method_id), + payment_method_data: pm_data_encrypted.map(Into::into), + status: None, + payment_method: None, + payment_method_type: None, + payment_method_issuer: None, + network_token_requestor_reference_id: None, + network_token_locker_id: None, + network_token_payment_method_data: None, + } + } else { + storage::PaymentMethodUpdate::AdditionalDataUpdate { + locker_id: None, + payment_method_data: None, + status: None, + payment_method: None, + payment_method_type: None, + payment_method_issuer: None, + network_token_requestor_reference_id: None, + network_token_locker_id: Some(res.payment_method_id), + network_token_payment_method_data: pm_data_encrypted.map(Into::into), + } + }; + let db = &*state.store; + + db.update_payment_method( + &key_manager_state, + merchant_context.get_merchant_key_store(), + payment_method.clone(), + pm_update, + merchant_context.get_merchant_account().storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update the payment method")?; + + Ok(WebhookResponseTracker::PaymentMethod { + payment_method_id, + status, + }) + } + } +} + +pub struct PaymentMethodCreateWrapper(pub api::payment_methods::PaymentMethodCreate); + +impl From<(&api::payment_methods::CardDetail, &domain::PaymentMethod)> + for PaymentMethodCreateWrapper +{ + fn from( + (data, payment_method): (&api::payment_methods::CardDetail, &domain::PaymentMethod), + ) -> Self { + Self(api::payment_methods::PaymentMethodCreate { + customer_id: Some(payment_method.customer_id.clone()), + payment_method: payment_method.payment_method, + payment_method_type: payment_method.payment_method_type, + payment_method_issuer: payment_method.payment_method_issuer.clone(), + payment_method_issuer_code: payment_method.payment_method_issuer_code, + metadata: payment_method.metadata.clone(), + payment_method_data: None, + connector_mandate_details: None, + client_secret: None, + billing: None, + card: Some(data.clone()), + card_network: data + .card_network + .clone() + .map(|card_network| card_network.to_string()), + bank_transfer: None, + wallet: None, + network_transaction_id: payment_method.network_transaction_id.clone(), + }) + } +} + +impl PaymentMethodCreateWrapper { + fn get_inner(self) -> api::payment_methods::PaymentMethodCreate { + self.0 + } +} + +pub async fn fetch_merchant_account_for_network_token_webhooks( + state: &SessionState, + merchant_id: &id_type::MerchantId, +) -> RouterResult<domain::MerchantContext> { + let db = &*state.store; + let key_manager_state = &(state).into(); + + let key_store = state + .store() + .get_merchant_key_store_by_merchant_id( + key_manager_state, + merchant_id, + &state.store().get_master_key().to_vec().into(), + ) + .await + .change_context(errors::ApiErrorResponse::Unauthorized) + .attach_printable("Failed to fetch merchant key store for the merchant id")?; + + let merchant_account = db + .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to fetch merchant account for the merchant id")?; + + let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( + merchant_account.clone(), + key_store, + ))); + + Ok(merchant_context) +} + +pub async fn fetch_payment_method_for_network_token_webhooks( + state: &SessionState, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + payment_method_id: &str, +) -> RouterResult<domain::PaymentMethod> { + let db = &*state.store; + let key_manager_state = &(state).into(); + + let payment_method = db + .find_payment_method( + key_manager_state, + key_store, + payment_method_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound) + .attach_printable("Failed to fetch the payment method")?; + + Ok(payment_method) +} diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index d77e1926260..59c31d4b2b8 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -142,6 +142,7 @@ pub trait StorageInterface: + user::theme::ThemeInterface + payment_method_session::PaymentMethodsSessionInterface + tokenization::TokenizationInterface + + callback_mapper::CallbackMapperInterface + 'static { fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>; diff --git a/crates/router/src/db/callback_mapper.rs b/crates/router/src/db/callback_mapper.rs index 0697f41bdac..70e9bd30ccc 100644 --- a/crates/router/src/db/callback_mapper.rs +++ b/crates/router/src/db/callback_mapper.rs @@ -1,7 +1,7 @@ use error_stack::report; use hyperswitch_domain_models::callback_mapper as domain; use router_env::{instrument, tracing}; -use storage_impl::DataModelExt; +use storage_impl::{DataModelExt, MockDb}; use super::Store; use crate::{ @@ -51,3 +51,22 @@ impl CallbackMapperInterface for Store { .map(domain::CallbackMapper::from_storage_model) } } + +#[async_trait::async_trait] +impl CallbackMapperInterface for MockDb { + #[instrument(skip_all)] + async fn insert_call_back_mapper( + &self, + _call_back_mapper: domain::CallbackMapper, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } + + #[instrument(skip_all)] + async fn find_call_back_mapper_by_id( + &self, + _id: &str, + ) -> CustomResult<domain::CallbackMapper, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index f1c2def317b..53e31ae1e49 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1714,6 +1714,24 @@ impl Webhooks { #[allow(unused_mut)] let mut route = web::scope("/webhooks") .app_data(web::Data::new(config)) + .service( + web::resource("/network_token_requestor/ref") + .route( + web::post().to(receive_network_token_requestor_incoming_webhook::< + webhook_type::OutgoingWebhook, + >), + ) + .route( + web::get().to(receive_network_token_requestor_incoming_webhook::< + webhook_type::OutgoingWebhook, + >), + ) + .route( + web::put().to(receive_network_token_requestor_incoming_webhook::< + webhook_type::OutgoingWebhook, + >), + ), + ) .service( web::resource("/{merchant_id}/{connector_id_or_name}") .route( diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index c1f3533ef1f..fa616a3da3e 100644 --- a/crates/router/src/routes/lock_utils.rs +++ b/crates/router/src/routes/lock_utils.rs @@ -192,7 +192,8 @@ impl From<Flow> for ApiIdentifier { | Flow::WebhookEventInitialDeliveryAttemptList | Flow::WebhookEventDeliveryAttemptList | Flow::WebhookEventDeliveryRetry - | Flow::RecoveryIncomingWebhookReceive => Self::Webhooks, + | Flow::RecoveryIncomingWebhookReceive + | Flow::IncomingNetworkTokenWebhookReceive => Self::Webhooks, Flow::ApiKeyCreate | Flow::ApiKeyRetrieve diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs index d19f48b62f0..41188288eab 100644 --- a/crates/router/src/routes/webhooks.rs +++ b/crates/router/src/routes/webhooks.rs @@ -179,3 +179,32 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( )) .await } + +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow = ?Flow::IncomingNetworkTokenWebhookReceive))] +pub async fn receive_network_token_requestor_incoming_webhook<W: types::OutgoingWebhookType>( + state: web::Data<AppState>, + req: HttpRequest, + body: web::Bytes, + _path: web::Path<String>, +) -> impl Responder { + let flow = Flow::IncomingNetworkTokenWebhookReceive; + + Box::pin(api::server_wrap( + flow.clone(), + state, + &req, + (), + |state, _: (), _, _| { + webhooks::network_token_incoming_webhooks_wrapper::<W>( + &flow, + state.to_owned(), + &req, + body.clone(), + ) + }, + &auth::NoAuth, + api_locking::LockAction::NotApplicable, + )) + .await +} diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs index 3e94375b5e6..63c27e43008 100644 --- a/crates/router/src/types/domain.rs +++ b/crates/router/src/types/domain.rs @@ -19,7 +19,7 @@ mod customers { pub use hyperswitch_domain_models::customer::*; } -mod callback_mapper { +pub mod callback_mapper { pub use hyperswitch_domain_models::callback_mapper::CallbackMapper; } diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index 29814ddcef4..0d205f33e8f 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -15,10 +15,11 @@ use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails; use masking::Secret; use serde::{Deserialize, Serialize}; +use crate::types::api; #[cfg(feature = "v2")] use crate::{ consts, - types::{api, domain, storage}, + types::{domain, storage}, }; #[cfg(feature = "v2")] @@ -357,3 +358,33 @@ pub struct CheckTokenStatusResponsePayload { pub struct CheckTokenStatusResponse { pub payload: CheckTokenStatusResponsePayload, } + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct NetworkTokenRequestorData { + pub card_reference: String, + pub customer_id: String, + pub expiry_year: Secret<String>, + pub expiry_month: Secret<String>, +} + +impl NetworkTokenRequestorData { + pub fn is_update_required( + &self, + data_stored_in_vault: api::payment_methods::CardDetailFromLocker, + ) -> bool { + //if the expiry year and month in the vault are not the same as the ones in the requestor data, + //then we need to update the vault data with the updated expiry year and month. + !((data_stored_in_vault.expiry_year.unwrap_or_default() == self.expiry_year) + && (data_stored_in_vault.expiry_month.unwrap_or_default() == self.expiry_month)) + } +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct NetworkTokenMetaDataUpdateBody { + pub token: NetworkTokenRequestorData, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct PanMetadataUpdateBody { + pub card: NetworkTokenRequestorData, +} diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 4e0bdab3ce6..d395cd1f6da 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -606,6 +606,8 @@ pub enum Flow { ProfileAcquirerUpdate, /// ThreeDs Decision Rule Execute flow ThreeDsDecisionRuleExecute, + /// Incoming Network Token Webhook Receive + IncomingNetworkTokenWebhookReceive, } /// Trait for providing generic behaviour to flow metric diff --git a/crates/storage_impl/src/callback_mapper.rs b/crates/storage_impl/src/callback_mapper.rs index 186f2b7f927..4f22dd079e9 100644 --- a/crates/storage_impl/src/callback_mapper.rs +++ b/crates/storage_impl/src/callback_mapper.rs @@ -9,7 +9,7 @@ impl DataModelExt for CallbackMapper { fn to_storage_model(self) -> Self::StorageModel { DieselCallbackMapper { id: self.id, - type_: self.type_, + type_: self.callback_mapper_id_type, data: self.data, created_at: self.created_at, last_modified_at: self.last_modified_at, @@ -19,7 +19,7 @@ impl DataModelExt for CallbackMapper { fn from_storage_model(storage_model: Self::StorageModel) -> Self { Self { id: storage_model.id, - type_: storage_model.type_, + callback_mapper_id_type: storage_model.type_, data: storage_model.data, created_at: storage_model.created_at, last_modified_at: storage_model.last_modified_at,
2024-11-28T13:10:26Z
## 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 webhooks for network tokenization - added support to process webhooks from token service. - verify webhooks updates the pan and network token metadata ### 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 cannot be tested unless we get real-time webhooks from CardNetwork. ## 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 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced support for network tokenization webhooks, including a new dedicated endpoint for network token requestor reference webhooks. - Added new webhook event types and metadata update flows for payment methods linked to network tokens. - Enhanced validation and configuration options for network tokenization services, including webhook source verification. - Exposed new data structures and API responses for handling network token and card metadata updates. - Added callback mapper integration to link webhook callbacks with merchant, payment method, and customer data. - **Bug Fixes** - Improved validation to ensure all required secrets, including webhook verification keys, are present for network tokenization services. - **Documentation** - Expanded public API surface and type exports to support new webhook and callback mapping features. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
46709ae3695eb1a6601c356397545f86de9f0f64
juspay/hyperswitch
juspay__hyperswitch-6693
Bug: bug(users): Mark users as verified if user comes from SSO - Currently we are not marking users as verified if they use SSO to login. - But if there is only SSO to login, then they won't be able to verify their email unless they come from the accept invite email. - Instead, we will mark users coming from SSO as verified.
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index aad2537c3d9..5595d72850c 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -2318,13 +2318,24 @@ pub async fn sso_sign( .await?; // TODO: Use config to handle not found error - let user_from_db = state + let user_from_db: domain::UserFromStorage = state .global_store .find_user_by_email(&email.into_inner()) .await .map(Into::into) .to_not_found_response(UserErrors::UserNotFound)?; + if !user_from_db.is_verified() { + state + .global_store + .update_user_by_user_id( + user_from_db.get_user_id(), + storage_user::UserUpdate::VerifyUser, + ) + .await + .change_context(UserErrors::InternalServerError)?; + } + let next_flow = if let Some(user_from_single_purpose_token) = user_from_single_purpose_token { let current_flow = domain::CurrentFlow::new(user_from_single_purpose_token, domain::SPTFlow::SSO.into())?;
2024-11-28T10:33:46Z
## 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 we are not marking users as verified if the user comes from SSO and there is no other way to verify if SSO is the only login method that is available. ### 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 #6693. ## 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:9000/api/user/oidc' \ -H 'Content-Type: application/json' \ --data-raw '{"code":"okta oidc code","state":"okta oidc state"}' ``` - The above curl when hit correctly should verify the user if the user was unverified. ## 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
707f48ceda789185187d23e35f483e117c67b81b
juspay/hyperswitch
juspay__hyperswitch-6696
Bug: bug(authn): Throw 401 if cookies are not found Currently BE is throwing 400 if cookies are not found and this is breaking FE if token is present in local storage but not in cookies. If 401 is thrown, FE will remove the token from the local storage automatically.
diff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs index b02da396075..850cc470316 100644 --- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs +++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs @@ -274,6 +274,11 @@ pub enum ApiErrorResponse { LinkConfigurationError { message: String }, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")] PayoutFailed { data: Option<serde_json::Value> }, + #[error( + error_type = ErrorType::InvalidRequestError, code = "IR_42", + message = "Cookies are not found in the request" + )] + CookieNotFound, #[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")] WebhookAuthenticationFailed, @@ -627,6 +632,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::PayoutFailed { data } => { AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()}))) }, + Self::CookieNotFound => { + AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None)) + }, Self::WebhookAuthenticationFailed => { AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None)) diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index efe0ac157e0..6cf078b5f81 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -444,7 +444,8 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } | errors::ApiErrorResponse::InvalidCookie - | errors::ApiErrorResponse::InvalidEphemeralKey => Self::Unauthorized, + | errors::ApiErrorResponse::InvalidEphemeralKey + | errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod | errors::ApiErrorResponse::InvalidCardIin diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 2087d01dbb4..20fea3ac362 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -166,7 +166,7 @@ pub async fn signin_token_only_flow( ) -> UserResponse<user_api::TokenResponse> { let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email(&request.email) + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .to_not_found_response(UserErrors::InvalidCredentials)? .into(); @@ -191,7 +191,10 @@ pub async fn connect_account( request: user_api::ConnectAccountRequest, auth_id: Option<String>, ) -> UserResponse<user_api::ConnectAccountResponse> { - let find_user = state.global_store.find_user_by_email(&request.email).await; + let find_user = state + .global_store + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email.clone())?) + .await; if let Ok(found_user) = find_user { let user_from_db: domain::UserFromStorage = found_user.into(); @@ -369,7 +372,7 @@ pub async fn forgot_password( let user_from_db = state .global_store - .find_user_by_email(&user_email.into_inner()) + .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -453,11 +456,7 @@ pub async fn reset_password_token_only_flow( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -564,10 +563,7 @@ async fn handle_invitation( } let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?; - let invitee_user = state - .global_store - .find_user_by_email(&invitee_email.into_inner()) - .await; + let invitee_user = state.global_store.find_user_by_email(&invitee_email).await; if let Ok(invitee_user) = invitee_user { handle_existing_user_invitation( @@ -946,7 +942,7 @@ pub async fn resend_invite( let invitee_email = domain::UserEmail::from_pii_email(request.email)?; let user: domain::UserFromStorage = state .global_store - .find_user_by_email(&invitee_email.clone().into_inner()) + .find_user_by_email(&invitee_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1045,11 +1041,7 @@ pub async fn accept_invite_from_email_token_only_flow( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -1493,11 +1485,7 @@ pub async fn verify_email_token_only_flow( let user_from_email = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)?; @@ -1540,7 +1528,7 @@ pub async fn send_verification_mail( let user_email = domain::UserEmail::try_from(req.email)?; let user = state .global_store - .find_user_by_email(&user_email.into_inner()) + .find_user_by_email(&user_email) .await .map_err(|e| { if e.current_context().is_db_not_found() { @@ -1637,11 +1625,7 @@ pub async fn user_from_email( let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email( - &email_token - .get_email() - .change_context(UserErrors::InternalServerError)?, - ) + .find_user_by_email(&email_token.get_email()?) .await .change_context(UserErrors::InternalServerError)? .into(); @@ -2347,7 +2331,7 @@ pub async fn sso_sign( // TODO: Use config to handle not found error let user_from_db = state .global_store - .find_user_by_email(&email.into_inner()) + .find_user_by_email(&email) .await .map(Into::into) .to_not_found_response(UserErrors::UserNotFound)?; diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 6641e553fd8..df4771dbe70 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -440,7 +440,7 @@ pub async fn delete_user_role( ) -> UserResponse<()> { let user_from_db: domain::UserFromStorage = state .global_store - .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?.into_inner()) + .find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?) .await .map_err(|e| { if e.current_context().is_db_not_found() { diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index a9df1abbc08..5d6fac3b130 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use common_enums::enums::MerchantStorageScheme; use common_utils::{ errors::CustomResult, - id_type, pii, + id_type, types::{keymanager::KeyManagerState, theme::ThemeLineage}, }; use diesel_models::{ @@ -2983,7 +2983,7 @@ impl UserInterface for KafkaStore { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store.find_user_by_email(user_email).await } @@ -3007,7 +3007,7 @@ impl UserInterface for KafkaStore { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { self.diesel_store diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index 14bed15fa45..089c9fc6eb7 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -3,11 +3,10 @@ use error_stack::report; use masking::Secret; use router_env::{instrument, tracing}; -use super::MockDb; +use super::{domain, MockDb}; use crate::{ connection, core::errors::{self, CustomResult}, - pii, services::Store, }; pub mod sample_data; @@ -22,7 +21,7 @@ pub trait UserInterface { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError>; async fn find_user_by_id( @@ -38,7 +37,7 @@ pub trait UserInterface { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError>; @@ -70,10 +69,10 @@ impl UserInterface for Store { #[instrument(skip_all)] async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::User::find_by_user_email(&conn, user_email) + storage::User::find_by_user_email(&conn, user_email.get_inner()) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -104,11 +103,11 @@ impl UserInterface for Store { #[instrument(skip_all)] async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::User::update_by_user_email(&conn, user_email, user) + storage::User::update_by_user_email(&conn, user_email.get_inner(), user) .await .map_err(|error| report!(errors::StorageError::from(error))) } @@ -171,12 +170,12 @@ impl UserInterface for MockDb { async fn find_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, ) -> CustomResult<storage::User, errors::StorageError> { let users = self.users.lock().await; users .iter() - .find(|user| user.email.eq(user_email)) + .find(|user| user.email.eq(user_email.get_inner())) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( @@ -253,13 +252,13 @@ impl UserInterface for MockDb { async fn update_user_by_email( &self, - user_email: &pii::Email, + user_email: &domain::UserEmail, update_user: storage::UserUpdate, ) -> CustomResult<storage::User, errors::StorageError> { let mut users = self.users.lock().await; users .iter_mut() - .find(|user| user.email.eq(user_email)) + .find(|user| user.email.eq(user_email.get_inner())) .map(|user| { *user = match &update_user { storage::UserUpdate::VerifyUser => storage::User { diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index c05e4514aaa..2d5f81e980c 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -2545,7 +2545,8 @@ where T: serde::de::DeserializeOwned, A: SessionStateInfo + Sync, { - let cookie_token_result = get_cookie_from_header(headers).and_then(cookies::parse_cookie); + let cookie_token_result = + get_cookie_from_header(headers).and_then(cookies::get_jwt_from_cookies); let auth_header_token_result = get_jwt_from_authorization_header(headers); let force_cookie = state.conf().user.force_cookies; @@ -3112,7 +3113,7 @@ pub fn is_ephemeral_auth<A: SessionStateInfo + Sync + Send>( pub fn is_jwt_auth(headers: &HeaderMap) -> bool { headers.get(headers::AUTHORIZATION).is_some() || get_cookie_from_header(headers) - .and_then(cookies::parse_cookie) + .and_then(cookies::get_jwt_from_cookies) .is_ok() } @@ -3174,10 +3175,13 @@ pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&s } pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> { - headers + let cookie = headers .get(cookies::get_cookie_header()) - .and_then(|header_value| header_value.to_str().ok()) - .ok_or(errors::ApiErrorResponse::InvalidCookie.into()) + .ok_or(report!(errors::ApiErrorResponse::CookieNotFound))?; + + cookie + .to_str() + .change_context(errors::ApiErrorResponse::InvalidCookie) } pub fn strip_jwt_token(token: &str) -> RouterResult<&str> { diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rs index 96518840800..4a297c0f0eb 100644 --- a/crates/router/src/services/authentication/cookies.rs +++ b/crates/router/src/services/authentication/cookies.rs @@ -49,7 +49,7 @@ pub fn remove_cookie_response() -> UserResponse<()> { Ok(ApplicationResponse::JsonWithHeaders(((), header))) } -pub fn parse_cookie(cookies: &str) -> RouterResult<String> { +pub fn get_jwt_from_cookies(cookies: &str) -> RouterResult<String> { Cookie::split_parse(cookies) .find_map(|cookie| { cookie @@ -57,8 +57,8 @@ pub fn parse_cookie(cookies: &str) -> RouterResult<String> { .filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME) .map(|parsed_cookie| parsed_cookie.value().to_owned()) }) - .ok_or(report!(ApiErrorResponse::InvalidCookie)) - .attach_printable("Cookie Parsing Failed") + .ok_or(report!(ApiErrorResponse::InvalidJwtToken)) + .attach_printable("Unable to find JWT token in cookies") } #[cfg(feature = "olap")] diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 87ff9f6abd5..8f48ef068ce 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -40,10 +40,12 @@ where i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?; let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp(); - set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) - .await - .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) - .ok(); + if cache_ttl > 0 { + set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl) + .await + .map_err(|e| logger::error!("Failed to set role info in cache {e:?}")) + .ok(); + } Ok(role_info) } diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index d092afdc5de..8c966d79d80 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,9 +1,6 @@ use api_models::user::dashboard_metadata::ProdIntent; use common_enums::EntityType; -use common_utils::{ - errors::{self, CustomResult}, - pii, -}; +use common_utils::{errors::CustomResult, pii}; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; use masking::{ExposeInterface, Secret}; @@ -183,7 +180,7 @@ impl EmailToken { entity: Option<Entity>, flow: domain::Origin, settings: &configs::Settings, - ) -> CustomResult<String, UserErrors> { + ) -> UserResult<String> { let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(expiration_duration)?.as_secs(); let token_payload = Self { @@ -195,8 +192,10 @@ impl EmailToken { jwt::generate_jwt(&token_payload, settings).await } - pub fn get_email(&self) -> CustomResult<pii::Email, errors::ParsingError> { + pub fn get_email(&self) -> UserResult<domain::UserEmail> { pii::Email::try_from(self.email.clone()) + .change_context(UserErrors::InternalServerError) + .and_then(domain::UserEmail::from_pii_email) } pub fn get_entity(&self) -> Option<&Entity> { diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 6d0d2a4ea07..21212bf6b62 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -131,6 +131,10 @@ impl UserEmail { self.0 } + pub fn get_inner(&self) -> &pii::Email { + &self.0 + } + pub fn get_secret(self) -> Secret<String, pii::EmailStrategy> { (*self.0).clone() } @@ -617,7 +621,7 @@ impl NewUser { pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> { if state .global_store - .find_user_by_email(&self.get_email().into_inner()) + .find_user_by_email(&self.get_email()) .await .is_ok() { diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index f115a16c062..443db741ae3 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -124,7 +124,7 @@ pub async fn get_user_from_db_by_email( ) -> CustomResult<UserFromStorage, StorageError> { state .global_store - .find_user_by_email(&email.into_inner()) + .find_user_by_email(&email) .await .map(UserFromStorage::from) }
2024-11-28T13:49:22Z
## 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 does 3 things. 1. Throw 401 if cookies are not found in request or if JWT is not found in cookies. 2. Cache role info only if the ttl is greater than or equal to 0. 3. Use `UserEmail` type in DB functions. ### 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` 4. `crates/router/src/configs` 5. `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 #6696. Closes #6697. Closes #6698. ## 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)? --> todo!() ## 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
707f48ceda789185187d23e35f483e117c67b81b
juspay/hyperswitch
juspay__hyperswitch-6692
Bug: Refactor(router): [ZSL] remove partially capture status ### Feature Description Currently, in case of underpayment we are mapping the payment status as partially captured. ### Possible Implementation We will map the underpayment status as succeeded and provide information about the amount actually captured ### 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/zsl/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs index 81019325113..b2ba05b7cde 100644 --- a/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zsl/transformers.rs @@ -414,20 +414,10 @@ impl<F> TryFrom<ResponseRouterData<F, ZslWebhookResponse, PaymentsSyncData, Paym .consr_paid_amt .parse::<i64>() .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let txn_amount = item - .response - .txn_amt - .parse::<i64>() - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let status = if txn_amount > paid_amount { - enums::AttemptStatus::PartialCharged - } else { - enums::AttemptStatus::Charged - }; if item.response.status == "0" { Ok(Self { - status, + status: enums::AttemptStatus::Charged, amount_captured: Some(paid_amount), response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.txn_id.clone()),
2024-11-28T07:54: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 --> Currently, in case of underpayment we are mapping the payment status as `partially captured` with the changes of this PR. We will map the underpayment status as `succeeded` and provide information about the amount actually captured ## 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)? --> Webhooks cannot be tested in ZSL sandbox. ## 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
9be012826abe87ffa2d0cea5423aed3e50449de2
juspay/hyperswitch
juspay__hyperswitch-6731
Bug: feat(analytics): Analytics Request Validator and config driven forex feature ## Current behaviour - Forex api calls are occuring on every analytics api call - There is no analytics request validator. ## Proposed Changes - Enable/Disable forex functionality based on a config flag. - `request_validator()` to validate requests on various grounds and throw contextual and comprehensive `4xx` errors. - `request_validator()` should also be able to discern whether metrics passed in a request, require `forex_api` call.
diff --git a/config/config.example.toml b/config/config.example.toml index 54a3ab3827b..fbeea44774b 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -660,6 +660,7 @@ pm_auth_key = "Some_pm_auth_key" # Analytics configuration. [analytics] source = "sqlx" # The Analytics source/strategy to be used +forex_enabled = false # Enable or disable forex conversion for analytics [analytics.clickhouse] username = "" # Clickhouse username diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 5cadc66ddfc..9db2474989e 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -9,6 +9,7 @@ database_name = "clickhouse_db_name" # Clickhouse database name # Analytics configuration. [analytics] source = "sqlx" # The Analytics source/strategy to be used +forex_enabled = false # Boolean to enable or disable forex conversion [analytics.sqlx] username = "db_user" # Analytics DB Username diff --git a/config/development.toml b/config/development.toml index 4e3a9b09993..c4920b2c029 100644 --- a/config/development.toml +++ b/config/development.toml @@ -717,6 +717,7 @@ authentication_analytics_topic = "hyperswitch-authentication-events" [analytics] source = "sqlx" +forex_enabled = false [analytics.clickhouse] username = "default" diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md index eb5c26a6ba3..e24dc6c5af7 100644 --- a/crates/analytics/docs/README.md +++ b/crates/analytics/docs/README.md @@ -104,6 +104,12 @@ To use Forex services, you need to sign up and get your API keys from the follow - It will be in dashboard, labeled as `access key`. ### Configuring Forex APIs +To enable Forex functionality, update the `config/development.toml` or `config/docker_compose.toml` file: + +```toml +[analytics] +forex_enabled = true # default set to false +``` To configure the Forex APIs, update the `config/development.toml` or `config/docker_compose.toml` file with your API keys: diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 6d694caadf5..0ad8886b820 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -969,21 +969,25 @@ impl AnalyticsProvider { tenant: &dyn storage_impl::config::TenantConfig, ) -> Self { match config { - AnalyticsConfig::Sqlx { sqlx } => { + AnalyticsConfig::Sqlx { sqlx, .. } => { Self::Sqlx(SqlxClient::from_conf(sqlx, tenant.get_schema()).await) } - AnalyticsConfig::Clickhouse { clickhouse } => Self::Clickhouse(ClickhouseClient { + AnalyticsConfig::Clickhouse { clickhouse, .. } => Self::Clickhouse(ClickhouseClient { config: Arc::new(clickhouse.clone()), database: tenant.get_clickhouse_database().to_string(), }), - AnalyticsConfig::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh( + AnalyticsConfig::CombinedCkh { + sqlx, clickhouse, .. + } => Self::CombinedCkh( SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), database: tenant.get_clickhouse_database().to_string(), }, ), - AnalyticsConfig::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx( + AnalyticsConfig::CombinedSqlx { + sqlx, clickhouse, .. + } => Self::CombinedSqlx( SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), @@ -1000,20 +1004,35 @@ impl AnalyticsProvider { pub enum AnalyticsConfig { Sqlx { sqlx: Database, + forex_enabled: bool, }, Clickhouse { clickhouse: ClickhouseConfig, + forex_enabled: bool, }, CombinedCkh { sqlx: Database, clickhouse: ClickhouseConfig, + forex_enabled: bool, }, CombinedSqlx { sqlx: Database, clickhouse: ClickhouseConfig, + forex_enabled: bool, }, } +impl AnalyticsConfig { + pub fn get_forex_enabled(&self) -> bool { + match self { + Self::Sqlx { forex_enabled, .. } + | Self::Clickhouse { forex_enabled, .. } + | Self::CombinedCkh { forex_enabled, .. } + | Self::CombinedSqlx { forex_enabled, .. } => *forex_enabled, + } + } +} + #[async_trait::async_trait] impl SecretsHandler for AnalyticsConfig { async fn convert_to_raw_secret( @@ -1024,7 +1043,7 @@ impl SecretsHandler for AnalyticsConfig { let decrypted_password = match analytics_config { // Todo: Perform kms decryption of clickhouse password Self::Clickhouse { .. } => masking::Secret::new(String::default()), - Self::Sqlx { sqlx } + Self::Sqlx { sqlx, .. } | Self::CombinedCkh { sqlx, .. } | Self::CombinedSqlx { sqlx, .. } => { secret_management_client @@ -1034,26 +1053,46 @@ impl SecretsHandler for AnalyticsConfig { }; Ok(value.transition_state(|conf| match conf { - Self::Sqlx { sqlx } => Self::Sqlx { + Self::Sqlx { + sqlx, + forex_enabled, + } => Self::Sqlx { sqlx: Database { password: decrypted_password, ..sqlx }, + forex_enabled, }, - Self::Clickhouse { clickhouse } => Self::Clickhouse { clickhouse }, - Self::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh { + Self::Clickhouse { + clickhouse, + forex_enabled, + } => Self::Clickhouse { + clickhouse, + forex_enabled, + }, + Self::CombinedCkh { + sqlx, + clickhouse, + forex_enabled, + } => Self::CombinedCkh { sqlx: Database { password: decrypted_password, ..sqlx }, clickhouse, + forex_enabled, }, - Self::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx { + Self::CombinedSqlx { + sqlx, + clickhouse, + forex_enabled, + } => Self::CombinedSqlx { sqlx: Database { password: decrypted_password, ..sqlx }, clickhouse, + forex_enabled, }, })) } @@ -1063,6 +1102,7 @@ impl Default for AnalyticsConfig { fn default() -> Self { Self::Sqlx { sqlx: Database::default(), + forex_enabled: false, } } } diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index 80cfc563071..b5761cd8779 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -69,7 +69,7 @@ pub async fn get_sankey( #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, - ex_rates: &ExchangeRates, + ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetPaymentIntentMetricRequest, ) -> AnalyticsResult<PaymentIntentsMetricsResponse<MetricsBucketResponse>> { @@ -202,22 +202,25 @@ pub async fn get_metrics( total += total_count; } if let Some(retried_amount) = collected_values.smart_retried_amount { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(retried_amount) - .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) - .ok() - .and_then(|amount_i64| { - convert(ex_rates, currency, Currency::USD, amount_i64) - .inspect_err(|e| { - logger::error!("Currency conversion error: {:?}", e) - }) - .ok() - }) - }) - .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) - .unwrap_or_default(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(retried_amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default() + } else { + None + }; collected_values.smart_retried_amount_in_usd = amount_in_usd; total_smart_retried_amount += retried_amount; total_smart_retried_amount_in_usd += amount_in_usd.unwrap_or(0); @@ -225,44 +228,50 @@ pub async fn get_metrics( if let Some(retried_amount) = collected_values.smart_retried_amount_without_smart_retries { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(retried_amount) - .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) - .ok() - .and_then(|amount_i64| { - convert(ex_rates, currency, Currency::USD, amount_i64) - .inspect_err(|e| { - logger::error!("Currency conversion error: {:?}", e) - }) - .ok() - }) - }) - .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) - .unwrap_or_default(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(retried_amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default() + } else { + None + }; collected_values.smart_retried_amount_without_smart_retries_in_usd = amount_in_usd; total_smart_retried_amount_without_smart_retries += retried_amount; total_smart_retried_amount_without_smart_retries_in_usd += amount_in_usd.unwrap_or(0); } if let Some(amount) = collected_values.payment_processed_amount { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(amount) - .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) - .ok() - .and_then(|amount_i64| { - convert(ex_rates, currency, Currency::USD, amount_i64) - .inspect_err(|e| { - logger::error!("Currency conversion error: {:?}", e) - }) - .ok() - }) - }) - .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) - .unwrap_or_default(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default() + } else { + None + }; collected_values.payment_processed_amount_in_usd = amount_in_usd; total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0); total_payment_processed_amount += amount; @@ -271,22 +280,25 @@ pub async fn get_metrics( total_payment_processed_count += count; } if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(amount) - .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) - .ok() - .and_then(|amount_i64| { - convert(ex_rates, currency, Currency::USD, amount_i64) - .inspect_err(|e| { - logger::error!("Currency conversion error: {:?}", e) - }) - .ok() - }) - }) - .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) - .unwrap_or_default(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default() + } else { + None + }; collected_values.payment_processed_amount_without_smart_retries_in_usd = amount_in_usd; total_payment_processed_amount_without_smart_retries_in_usd += @@ -323,14 +335,26 @@ pub async fn get_metrics( total_payment_processed_amount_without_smart_retries: Some( total_payment_processed_amount_without_smart_retries, ), - total_smart_retried_amount_in_usd: Some(total_smart_retried_amount_in_usd), - total_smart_retried_amount_without_smart_retries_in_usd: Some( - total_smart_retried_amount_without_smart_retries_in_usd, - ), - total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd), - total_payment_processed_amount_without_smart_retries_in_usd: Some( - total_payment_processed_amount_without_smart_retries_in_usd, - ), + total_smart_retried_amount_in_usd: if ex_rates.is_some() { + Some(total_smart_retried_amount_in_usd) + } else { + None + }, + total_smart_retried_amount_without_smart_retries_in_usd: if ex_rates.is_some() { + Some(total_smart_retried_amount_without_smart_retries_in_usd) + } else { + None + }, + total_payment_processed_amount_in_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_in_usd) + } else { + None + }, + total_payment_processed_amount_without_smart_retries_in_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_without_smart_retries_in_usd) + } else { + None + }, total_payment_processed_count: Some(total_payment_processed_count), total_payment_processed_count_without_smart_retries: Some( total_payment_processed_count_without_smart_retries, diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index c6f0276c47f..5cb32cbec37 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -49,7 +49,7 @@ pub enum TaskType { #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, - ex_rates: &ExchangeRates, + ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetPaymentMetricRequest, ) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> { @@ -235,22 +235,25 @@ pub async fn get_metrics( .map(|(id, val)| { let mut collected_values = val.collect(); if let Some(amount) = collected_values.payment_processed_amount { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(amount) - .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) - .ok() - .and_then(|amount_i64| { - convert(ex_rates, currency, Currency::USD, amount_i64) - .inspect_err(|e| { - logger::error!("Currency conversion error: {:?}", e) - }) - .ok() - }) - }) - .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) - .unwrap_or_default(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default() + } else { + None + }; collected_values.payment_processed_amount_in_usd = amount_in_usd; total_payment_processed_amount += amount; total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0); @@ -259,22 +262,25 @@ pub async fn get_metrics( total_payment_processed_count += count; } if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(amount) - .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) - .ok() - .and_then(|amount_i64| { - convert(ex_rates, currency, Currency::USD, amount_i64) - .inspect_err(|e| { - logger::error!("Currency conversion error: {:?}", e) - }) - .ok() - }) - }) - .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) - .unwrap_or_default(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default() + } else { + None + }; collected_values.payment_processed_amount_without_smart_retries_usd = amount_in_usd; total_payment_processed_amount_without_smart_retries += amount; total_payment_processed_amount_without_smart_retries_usd += @@ -299,13 +305,19 @@ pub async fn get_metrics( query_data, meta_data: [PaymentsAnalyticsMetadata { total_payment_processed_amount: Some(total_payment_processed_amount), - total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd), + total_payment_processed_amount_in_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_in_usd) + } else { + None + }, total_payment_processed_amount_without_smart_retries: Some( total_payment_processed_amount_without_smart_retries, ), - total_payment_processed_amount_without_smart_retries_usd: Some( - total_payment_processed_amount_without_smart_retries_usd, - ), + total_payment_processed_amount_without_smart_retries_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_without_smart_retries_usd) + } else { + None + }, total_payment_processed_count: Some(total_payment_processed_count), total_payment_processed_count_without_smart_retries: Some( total_payment_processed_count_without_smart_retries, diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs index ca72c9003a6..f0ad21de080 100644 --- a/crates/analytics/src/refunds/core.rs +++ b/crates/analytics/src/refunds/core.rs @@ -48,7 +48,7 @@ pub enum TaskType { pub async fn get_metrics( pool: &AnalyticsProvider, - ex_rates: &ExchangeRates, + ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetRefundMetricRequest, ) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> { @@ -218,22 +218,25 @@ pub async fn get_metrics( total += total_count; } if let Some(amount) = collected_values.refund_processed_amount { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(amount) - .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) - .ok() - .and_then(|amount_i64| { - convert(ex_rates, currency, Currency::USD, amount_i64) - .inspect_err(|e| { - logger::error!("Currency conversion error: {:?}", e) - }) - .ok() - }) - }) - .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) - .unwrap_or_default(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(amount) + .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) + .ok() + .and_then(|amount_i64| { + convert(ex_rates, currency, Currency::USD, amount_i64) + .inspect_err(|e| { + logger::error!("Currency conversion error: {:?}", e) + }) + .ok() + }) + }) + .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) + .unwrap_or_default() + } else { + None + }; collected_values.refund_processed_amount_in_usd = amount_in_usd; total_refund_processed_amount += amount; total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0); @@ -262,7 +265,11 @@ pub async fn get_metrics( meta_data: [RefundsAnalyticsMetadata { total_refund_success_rate, total_refund_processed_amount: Some(total_refund_processed_amount), - total_refund_processed_amount_in_usd: Some(total_refund_processed_amount_in_usd), + total_refund_processed_amount_in_usd: if ex_rates.is_some() { + Some(total_refund_processed_amount_in_usd) + } else { + None + }, total_refund_processed_count: Some(total_refund_processed_count), total_refund_reason_count: Some(total_refund_reason_count), total_refund_error_message_count: Some(total_refund_error_message_count), diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 806eb4b6e0e..a8db3a3cb0c 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -62,7 +62,42 @@ pub enum Granularity { #[serde(rename = "G_ONEDAY")] OneDay, } - +pub trait ForexMetric { + fn is_forex_metric(&self) -> bool; +} + +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AnalyticsRequest { + pub payment_intent: Option<GetPaymentIntentMetricRequest>, + pub payment_attempt: Option<GetPaymentMetricRequest>, + pub refund: Option<GetRefundMetricRequest>, + pub dispute: Option<GetDisputeMetricRequest>, +} + +impl AnalyticsRequest { + pub fn requires_forex_functionality(&self) -> bool { + self.payment_attempt + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + || self + .payment_intent + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + || self + .refund + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + || self + .dispute + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + } +} #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentMetricRequest { diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs index 2509d83e132..e373704b87c 100644 --- a/crates/api_models/src/analytics/disputes.rs +++ b/crates/api_models/src/analytics/disputes.rs @@ -3,7 +3,7 @@ use std::{ hash::{Hash, Hasher}, }; -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::DisputeStage; #[derive( @@ -28,6 +28,14 @@ pub enum DisputeMetrics { SessionizedTotalAmountDisputed, SessionizedTotalDisputeLostAmount, } +impl ForexMetric for DisputeMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::TotalAmountDisputed | Self::TotalDisputeLostAmount + ) + } +} #[derive( Debug, diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index 365abd71edc..15c107dfb66 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -5,7 +5,7 @@ use std::{ use common_utils::id_type; -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, }; @@ -106,6 +106,17 @@ pub enum PaymentIntentMetrics { SessionizedPaymentProcessedAmount, SessionizedPaymentsDistribution, } +impl ForexMetric for PaymentIntentMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::PaymentProcessedAmount + | Self::SmartRetriedAmount + | Self::SessionizedPaymentProcessedAmount + | Self::SessionizedSmartRetriedAmount + ) + } +} #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index 8fd24f15124..691e827043f 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -5,7 +5,7 @@ use std::{ use common_utils::id_type; -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod, PaymentMethodType, @@ -119,6 +119,17 @@ pub enum PaymentMetrics { FailureReasons, } +impl ForexMetric for PaymentMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::PaymentProcessedAmount + | Self::AvgTicketSize + | Self::SessionizedPaymentProcessedAmount + | Self::SessionizedAvgTicketSize + ) + } +} #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { pub reason: String, diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs index 0afca6c1ef6..84954e70910 100644 --- a/crates/api_models/src/analytics/refunds.rs +++ b/crates/api_models/src/analytics/refunds.rs @@ -30,7 +30,7 @@ pub enum RefundType { RetryRefund, } -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct RefundFilters { #[serde(default)] @@ -137,6 +137,14 @@ pub enum RefundDistributions { #[strum(serialize = "refund_error_message")] SessionizedRefundErrorMessage, } +impl ForexMetric for RefundMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::RefundProcessedAmount | Self::SessionizedRefundProcessedAmount + ) + } +} pub mod metric_behaviour { pub struct RefundSuccessRate; diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index d957c3071ff..62af479b23a 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -18,12 +18,12 @@ pub mod routes { search::{ GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex, }, - GenerateReportRequest, GetActivePaymentsMetricRequest, GetApiEventFiltersRequest, - GetApiEventMetricRequest, GetAuthEventMetricRequest, GetDisputeMetricRequest, - GetFrmFilterRequest, GetFrmMetricRequest, GetPaymentFiltersRequest, - GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, GetPaymentMetricRequest, - GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest, - GetSdkEventMetricRequest, ReportRequest, + AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest, + GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventMetricRequest, + GetDisputeMetricRequest, GetFrmFilterRequest, GetFrmMetricRequest, + GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, + GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, + GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, }; use common_enums::EntityType; use common_utils::types::TimeRange; @@ -31,11 +31,9 @@ pub mod routes { use futures::{stream::FuturesUnordered, StreamExt}; use crate::{ + analytics_validator::request_validator, consts::opensearch::SEARCH_INDEXES, - core::{ - api_locking, currency::get_forex_exchange_rates, errors::user::UserErrors, - verification::utils, - }, + core::{api_locking, errors::user::UserErrors, verification::utils}, db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload}, routes::AppState, services::{ @@ -405,7 +403,15 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + let validator_response = request_validator( + AnalyticsRequest { + payment_attempt: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -444,7 +450,16 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_attempt: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -491,7 +506,16 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_attempt: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -532,7 +556,16 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_intent: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -571,7 +604,16 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_intent: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -618,7 +660,16 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_intent: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -659,7 +710,16 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + refund: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -698,7 +758,16 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + refund: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -745,7 +814,16 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + refund: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) diff --git a/crates/router/src/analytics_validator.rs b/crates/router/src/analytics_validator.rs new file mode 100644 index 00000000000..d50308cc848 --- /dev/null +++ b/crates/router/src/analytics_validator.rs @@ -0,0 +1,24 @@ +use analytics::errors::AnalyticsError; +use api_models::analytics::AnalyticsRequest; +use common_utils::errors::CustomResult; +use currency_conversion::types::ExchangeRates; +use router_env::logger; + +use crate::core::currency::get_forex_exchange_rates; + +pub async fn request_validator( + req_type: AnalyticsRequest, + state: &crate::routes::SessionState, +) -> CustomResult<Option<ExchangeRates>, AnalyticsError> { + let forex_enabled = state.conf.analytics.get_inner().get_forex_enabled(); + let require_forex_functionality = req_type.requires_forex_functionality(); + + let ex_rates = if forex_enabled && require_forex_functionality { + logger::info!("Fetching forex exchange rates"); + Some(get_forex_exchange_rates(state.clone()).await?) + } else { + None + }; + + Ok(ex_rates) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 839dd472423..d43fa054313 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -16,6 +16,7 @@ pub mod workflows; #[cfg(feature = "olap")] pub mod analytics; +pub mod analytics_validator; pub mod events; pub mod middleware; pub mod services;
2024-12-03T13:03:26Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Fixes #6731 ## Description <!-- Describe your changes in detail --> ### Config driven forex functionality - Created a `forex_enabled` flag in config settings under analytics config. - Instead of passing `ExchangeRates` data structure now we are passing `Option<ExchangeRates>` - In amount related fields of response of any metric, we now get `null` if `forex_enabled = false` ### Request Validator - Created an encapsulating `AnalyticsRequest` for all analytics request types - implemented method `requires_forex_functionality` to give additional check, as to whether forex api call is required for the given set of metrics or not. - Most importantly, it will serve as an extensible validator and provide contextual and comprehensive `4xx` errors in future. ### 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` --> ## 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). --> ### Config Driven Forex Functionality The introduction of the `forex_enabled` flag allows greater flexibility in analytics operations by enabling or disabling forex functionality dynamically. This change minimizes unnecessary computations and API calls when forex functionality is not required, optimizing performance. By transitioning to passing `Option<ExchangeRates>`, the implementation better represents cases where forex data may not be applicable, (for e.g merchants that operate with single currency) aligning the API's behavior with user expectations. Setting `null` for amount-related fields in responses when forex is disabled ensures consistent and clear communication to the user about the absence of forex adjustments. ### Request Validator The encapsulating `AnalyticsRequest` structure improves the overall request validation framework by providing a unified approach to handling diverse analytics request types. The `requires_forex_functionality` method enhances efficiency by explicitly determining when forex operations are necessary, further reducing redundant forex API calls. Additionally, the extensibility of this validator sets the foundation for robust error handling, allowing the system to provide detailed and actionable `4xx` error responses in the future. ## 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)? --> ### Prerequisites ```toml [analytics] source = "sqlx" forex_enabled = false # update this to enable or disable ``` ### Testing config driven forex api call ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMzI5Njk3MSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.fuAh7MTL96PeEizddbU3fOjOyHaXli5CXPrXMFjc-wU' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T18:30:00Z", "endTime": "2024-11-11T08:24:00Z" }, "source": "BATCH", "metrics": [ "payment_processed_amount" ], "delta": true } ]' ``` #### when `forex_enabled=true` ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 371940, "payment_processed_amount_in_usd": 4392, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "INR", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-01T18:30:00.000Z", "end_time": "2024-11-11T08:24:00.000Z" }, "time_bucket": "2024-11-01 18:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 200000, "payment_processed_amount_in_usd": 200000, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": 0, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "USD", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-01T18:30:00.000Z", "end_time": "2024-11-11T08:24:00.000Z" }, "time_bucket": "2024-11-01 18:30:00" } ], "metaData": [ { "total_payment_processed_amount": 571940, "total_payment_processed_amount_in_usd": 204392, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` #### When `forex_enabled=false` ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 371940, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "INR", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-01T18:30:00.000Z", "end_time": "2024-11-11T08:24:00.000Z" }, "time_bucket": "2024-11-01 18:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 200000, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": "USD", "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-01T18:30:00.000Z", "end_time": "2024-11-11T08:24:00.000Z" }, "time_bucket": "2024-11-01 18:30:00" } ], "metaData": [ { "total_payment_processed_amount": 571940, "total_payment_processed_amount_in_usd": null, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": null, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` ### Testing `request_validator()` ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/payments' \ --header 'Accept: */*' \ --header 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' \ --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/130.0.0.0 Safari/537.36' \ --header 'api-key: dev_r3kVZ4URj3fMiHhJJuhHOVqteaXwKyEMGCaFo6PiCS6S9vZsb0ErV4kCVqogM60H' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDZlOGRmZWYtMzI0Zi00Yjc0LTg2MTItYzdkZjNhOGZmZTcyIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI3NDM0NTkzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMzI5Njk3MSwib3JnX2lkIjoib3JnXzl3Y0kxQ2hTOGVEdnRRQmRXak9IIiwicHJvZmlsZV9pZCI6InByb19FNW5lek43YjZUbVB1WlUzbEU1VSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.fuAh7MTL96PeEizddbU3fOjOyHaXli5CXPrXMFjc-wU' \ --header 'sec-ch-ua: "Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'sec-ch-ua-platform: "macOS"' \ --data '[ { "timeRange": { "startTime": "2024-11-01T18:30:00Z", "endTime": "2024-11-11T08:24:00Z" }, "source": "BATCH", "metrics": [ "payment_success_rate" ], "delta": true } ]' ``` #### Check the logs, there won't be forex api call, and the response time also is lesser ## 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
d75625f11d4611c688593d5730efc8c6f2c59afd
juspay/hyperswitch
juspay__hyperswitch-6691
Bug: populate card network in the network transaction id based MIT flow In the PG agnostic MIT flow (card details with network transaction id) the card network is being passed a null in the response. As the card network fetched form the card info lookup is not being used. Additionally add changes to include the `network_transaction_id_supported_connectors` in `production.toml`. And pass internet as the commerce_indicator for discover cards in cybersource.
diff --git a/config/config.example.toml b/config/config.example.toml index ba14ed881cf..76a38192909 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -787,6 +787,9 @@ 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 +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" # Supported connectors for network transaction id + [grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration host = "localhost" # Client Host port = 7000 # Client Port diff --git a/config/deployments/production.toml b/config/deployments/production.toml index a859d08ac4a..c266b94bba6 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -176,6 +176,8 @@ bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # M card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card +[network_transaction_id_supported_connectors] +connector_list = "stripe,adyen,cybersource" [payouts] payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 22fa8965b7a..2ea36e3e35e 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -620,7 +620,7 @@ impl .as_ref() .map(|card_network| match card_network.to_lowercase().as_str() { "amex" => "internet", - "discover" => "dipb", + "discover" => "internet", "mastercard" => "spa", "visa" => "internet", _ => "internet", diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 8435f09e8f3..219a4d90519 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -4674,7 +4674,7 @@ pub async fn get_additional_payment_data( api_models::payments::AdditionalPaymentData::Card(Box::new( api_models::payments::AdditionalCardInfo { card_issuer: card_info.card_issuer, - card_network, + card_network: card_info.card_network, bank_code: card_info.bank_code, card_type: card_info.card_type, card_issuing_country: card_info.card_issuing_country,
2024-11-28T08:03:58Z
## 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 --> In the PG agnostic MIT flow (card details with network transaction id) the card network is being passed a null in the response. As the card network fetched form the card info lookup is not being used. Additionally this pr also contains the changes to include the `network_transaction_id_supported_connectors` in `production.toml`. And pass internet as the commerce_indicator for discover cards in cybersource. ### 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 merchant account and merchant connector account -> enable `is_connector_agnostic_mit_enabled` flag ``` curl --location 'http://localhost:8080/account/merchant_1732783890/business_profile/pro_lNl3x8up5RJTzGLgq0cC' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "is_connector_agnostic_mit_enabled": true }' ``` ``` { "merchant_id": "merchant_1732783890", "profile_id": "pro_lNl3x8up5RJTzGLgq0cC", "profile_name": "US_default", "return_url": "https://google.com/success", "enable_payment_response_hash": true, "payment_response_hash_key": "EHpgSu6g2VWesxu9L3tPGXVI7XuL1lqZ4CAwjYH3PUHr6VTiO1gyVuPsLSQoCGCO", "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, "is_network_tokenization_enabled": false, "is_auto_retries_enabled": false, "max_auto_retries_enabled": null } ``` -> Create a payment with `"setup_future_usage": "off_session",` ``` { "amount": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_{{$timestamp}}", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "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_fnfBuSFwvwVMzmk0OZM3", "merchant_id": "merchant_1732784068", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "cybersource", "client_secret": "pay_fnfBuSFwvwVMzmk0OZM3_secret_VoTLxuhAVA1mYPyTQyN4", "created": "2024-11-28T08:55:25.492Z", "currency": "USD", "customer_id": "cu_1732784125", "customer": { "id": "cu_1732784125", "name": "John Doe", "email": "[email protected]", "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": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "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_hrw68v72wmWkd6uDjNCl", "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, "product_tax_code": null, "requires_shipping": null } ], "email": "[email protected]", "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": "cu_1732784125", "created_at": 1732784125, "expires": 1732787725, "secret": "epk_06284b9a905f4c3aa196b00ad8112174" }, "manual_retry_allowed": false, "connector_transaction_id": "7327841265636354504951", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_fnfBuSFwvwVMzmk0OZM3_1", "payment_link": null, "profile_id": "pro_ENrgK0m9AXuOtOMzxFju", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_N3lWoDG7yvB9rbvJFyrb", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-28T09:10:25.492Z", "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_qUyvJqDRB16ItLjiBATM", "payment_method_status": "active", "updated": "2024-11-28T08:55:27.234Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "27F62F9C4E44ACD0E063AF598E0A7075" } ``` ![image](https://github.com/user-attachments/assets/6c5ed3d5-0430-4db6-a252-cf7af0213c3f) -> Create a payment for the same customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_JZ5SfN6HmdFyVadqiq6iO6cZD9JDnWNT0bVhEEbOFLbw9NXkYNNr3MaXXTpVjFEY' \ --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_1732784125" }' ``` ``` { "payment_id": "pay_Nxx6173Q7F2ES49eeMYr", "merchant_id": "merchant_1732784068", "status": "requires_payment_method", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_Nxx6173Q7F2ES49eeMYr_secret_2qPhrFGrz8F4ODupztNl", "created": "2024-11-28T08:58:33.763Z", "currency": "USD", "customer_id": "cu_1732784125", "customer": { "id": "cu_1732784125", "name": "John Doe", "email": "[email protected]", "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": "[email protected]", "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_1732784125", "created_at": 1732784313, "expires": 1732787913, "secret": "epk_9ed01dde281f46a0966f1c0d779f6099" }, "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_ENrgK0m9AXuOtOMzxFju", "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-11-28T09:13:33.763Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-28T08:58:33.784Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> List customer pml with the client_secret ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_Nxx6173Q7F2ES49eeMYr_secret_2qPhrFGrz8F4ODupztNl' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_2cbdf84777ed4b15827d8bc8e6b19622' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_GN84Zv1iv1sbEpE9Fupv", "payment_method_id": "pm_qUyvJqDRB16ItLjiBATM", "customer_id": "cu_1732784125", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "STRIPE PAYMENTS UK LIMITED", "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": "Visa", "issuer_country": "UNITEDKINGDOM", "last4_digits": "4242", "expiry_month": "03", "expiry_year": "2030", "card_token": null, "card_holder_name": "name name", "card_fingerprint": null, "nick_name": null, "card_network": "Visa", "card_isin": "424242", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_type": "CREDIT", "saved_to_locker": true }, "metadata": null, "created": "2024-11-28T08:55:27.197Z", "bank": null, "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-11-28T08:55:27.197Z", "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 ``` curl --location 'http://localhost:8080/payments/pay_Nxx6173Q7F2ES49eeMYr/confirm' \ --header 'api-key: pk_dev_2cbdf84777ed4b15827d8bc8e6b19622' \ --header 'Content-Type: application/json' \ --data-raw '{ "payment_token": "token_GN84Zv1iv1sbEpE9Fupv", "payment_method_type": "credit", "payment_method": "card", "client_secret": "pay_Nxx6173Q7F2ES49eeMYr_secret_2qPhrFGrz8F4ODupztNl", "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": "[email protected]" } }' ``` ``` { "payment_id": "pay_Nxx6173Q7F2ES49eeMYr", "merchant_id": "merchant_1732784068", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_Nxx6173Q7F2ES49eeMYr_secret_2qPhrFGrz8F4ODupztNl", "created": "2024-11-28T08:58:33.763Z", "currency": "USD", "customer_id": "cu_1732784125", "customer": { "id": "cu_1732784125", "name": "John Doe", "email": "[email protected]", "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": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_GN84Zv1iv1sbEpE9Fupv", "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": "[email protected]" }, "order_details": null, "email": "[email protected]", "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": "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": "7327843962556379004951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_Nxx6173Q7F2ES49eeMYr_1", "payment_link": null, "profile_id": "pro_ENrgK0m9AXuOtOMzxFju", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_N3lWoDG7yvB9rbvJFyrb", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-28T09:13:33.763Z", "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_qUyvJqDRB16ItLjiBATM", "payment_method_status": "active", "updated": "2024-11-28T08:59:56.654Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Create a cit with stripe and perform the recurring with cybersource ``` { "amount": 100, "currency": "USD", "confirm": true, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "customer_id": "cu_{{$timestamp}}", "email": "[email protected]", "name": "John Doe", "phone": "999999999", "phone_country_code": "+65", "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": "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_mKYKX3ChuavzS7atiqrC", "merchant_id": "merchant_1732786757", "status": "succeeded", "amount": 100, "net_amount": 100, "shipping_cost": null, "amount_capturable": 0, "amount_received": 100, "connector": "stripe", "client_secret": "pay_mKYKX3ChuavzS7atiqrC_secret_aI23DBV8qxTNg2WPESAt", "created": "2024-11-28T09:41:01.957Z", "currency": "USD", "customer_id": "cu_1732786862", "customer": { "id": "cu_1732786862", "name": "John Doe", "email": "[email protected]", "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": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "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": { "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, "product_tax_code": null, "requires_shipping": null } ], "email": "[email protected]", "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": "cu_1732786862", "created_at": 1732786861, "expires": 1732790461, "secret": "epk_2ee23c3779a54e56b9c15816e56d47af" }, "manual_retry_allowed": false, "connector_transaction_id": "pi_3QQ4DaEOqOywnAIx00EgTOEA", "frm_message": null, "metadata": {}, "connector_metadata": null, "feature_metadata": null, "reference_id": "pi_3QQ4DaEOqOywnAIx00EgTOEA", "payment_link": null, "profile_id": "pro_LHl9xKTts4FUwsDgPIAA", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_PohIcY4T0yRYB4FRQpsG", "incremental_authorization_allowed": null, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-28T09:56:01.957Z", "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_GuFw64hE9GdwBaAdu60R", "payment_method_status": "active", "updated": "2024-11-28T09:41:04.190Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": "pm_1QQ4DaEOqOywnAIxeM9Q73Pt" } ``` -> Create payment for same customer ``` curl --location 'http://localhost:8080/payments' \ --header 'Accept: application/json' \ --header 'api-key: dev_vEvPY8nOxGDtjC1IfIgOVDVouV4bfDK1MPyTB2vqPCDjf3QTSaW4lP0UkjDORWi1' \ --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_1732786862" }' ``` ``` { "payment_id": "pay_PiKxSAcgYv1SCRuTgbNW", "merchant_id": "merchant_1732786757", "status": "requires_payment_method", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": null, "client_secret": "pay_PiKxSAcgYv1SCRuTgbNW_secret_6PMdd9eOqqYm0XyBvRCs", "created": "2024-11-28T09:41:24.895Z", "currency": "USD", "customer_id": "cu_1732786862", "customer": { "id": "cu_1732786862", "name": "John Doe", "email": "[email protected]", "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": "[email protected]", "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_1732786862", "created_at": 1732786884, "expires": 1732790484, "secret": "epk_89b1364c0b6048d9aba374bfee2c68e6" }, "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_LHl9xKTts4FUwsDgPIAA", "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-11-28T09:56:24.895Z", "fingerprint": null, "browser_info": null, "payment_method_id": null, "payment_method_status": null, "updated": "2024-11-28T09:41:24.934Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Customer pml ``` curl --location 'http://localhost:8080/customers/payment_methods?client_secret=pay_PiKxSAcgYv1SCRuTgbNW_secret_6PMdd9eOqqYm0XyBvRCs' \ --header 'Accept: application/json' \ --header 'api-key: pk_dev_c7c7295d08b54d589459ec0e8de731aa' ``` ``` { "customer_payment_methods": [ { "payment_token": "token_WTkWv5zRyilJVfcZFZB4", "payment_method_id": "pm_GuFw64hE9GdwBaAdu60R", "customer_id": "cu_1732786862", "payment_method": "card", "payment_method_type": "credit", "payment_method_issuer": "STRIPE PAYMENTS UK LIMITED", "payment_method_issuer_code": null, "recurring_enabled": true, "installment_payment_enabled": false, "payment_experience": [ "redirect_to_url" ], "card": { "scheme": "Visa", "issuer_country": "UNITEDKINGDOM", "last4_digits": "4242", "expiry_month": "03", "expiry_year": "2030", "card_token": null, "card_holder_name": "name name", "card_fingerprint": null, "nick_name": null, "card_network": "Visa", "card_isin": "424242", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_type": "CREDIT", "saved_to_locker": true }, "metadata": null, "created": "2024-11-28T09:41:04.160Z", "bank": null, "surcharge_details": null, "requires_cvv": false, "last_used_at": "2024-11-28T09:41:04.160Z", "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 with cybersource ``` curl --location 'http://localhost:8080/payments/pay_PiKxSAcgYv1SCRuTgbNW/confirm' \ --header 'api-key: pk_dev_c7c7295d08b54d589459ec0e8de731aa' \ --header 'Content-Type: application/json' \ --data-raw '{ "payment_token": "token_WTkWv5zRyilJVfcZFZB4", "payment_method_type": "credit", "payment_method": "card", "client_secret": "pay_PiKxSAcgYv1SCRuTgbNW_secret_6PMdd9eOqqYm0XyBvRCs", "routing": { "type": "single", "data": { "connector": "cybersource", "merchant_connector_id": "mca_XcYZAcIAg28iKuSfTVOm" } }, "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": "[email protected]" } }' ``` ``` { "payment_id": "pay_PiKxSAcgYv1SCRuTgbNW", "merchant_id": "merchant_1732786757", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_PiKxSAcgYv1SCRuTgbNW_secret_6PMdd9eOqqYm0XyBvRCs", "created": "2024-11-28T09:41:24.895Z", "currency": "USD", "customer_id": "cu_1732786862", "customer": { "id": "cu_1732786862", "name": "John Doe", "email": "[email protected]", "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": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_WTkWv5zRyilJVfcZFZB4", "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": "[email protected]" }, "order_details": null, "email": "[email protected]", "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": "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": "7327869509776879404951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_PiKxSAcgYv1SCRuTgbNW_1", "payment_link": null, "profile_id": "pro_LHl9xKTts4FUwsDgPIAA", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_XcYZAcIAg28iKuSfTVOm", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-28T09:56:24.895Z", "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_GuFw64hE9GdwBaAdu60R", "payment_method_status": "active", "updated": "2024-11-28T09:42:31.429Z", "charges": null, "frm_metadata": null, "merchant_order_reference_id": null, "order_tax_amount": null, "connector_mandate_id": null } ``` -> Psync ``` curl --location 'http://localhost:8080/payments/pay_PiKxSAcgYv1SCRuTgbNW?force_sync=true' \ --header 'Accept: application/json' \ --header 'api-key: dev_vEvPY8nOxGDtjC1IfIgOVDVouV4bfDK1MPyTB2vqPCDjf3QTSaW4lP0UkjDORWi1' ``` ``` { "payment_id": "pay_PiKxSAcgYv1SCRuTgbNW", "merchant_id": "merchant_1732786757", "status": "succeeded", "amount": 10000, "net_amount": 10000, "shipping_cost": null, "amount_capturable": 0, "amount_received": 10000, "connector": "cybersource", "client_secret": "pay_PiKxSAcgYv1SCRuTgbNW_secret_6PMdd9eOqqYm0XyBvRCs", "created": "2024-11-28T09:41:24.895Z", "currency": "USD", "customer_id": "cu_1732786862", "customer": { "id": "cu_1732786862", "name": "John Doe", "email": "[email protected]", "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": "4242", "card_type": "CREDIT", "card_network": "Visa", "card_issuer": "STRIPE PAYMENTS UK LIMITED", "card_issuing_country": "UNITEDKINGDOM", "card_isin": "424242", "card_extended_bin": null, "card_exp_month": "03", "card_exp_year": "2030", "card_holder_name": null, "payment_checks": null, "authentication_data": null }, "billing": null }, "payment_token": "token_WTkWv5zRyilJVfcZFZB4", "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": "[email protected]" }, "order_details": null, "email": "[email protected]", "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": "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": "7327869509776879404951", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": "pay_PiKxSAcgYv1SCRuTgbNW_1", "payment_link": null, "profile_id": "pro_LHl9xKTts4FUwsDgPIAA", "surcharge_details": null, "attempt_count": 1, "merchant_decision": null, "merchant_connector_id": "mca_XcYZAcIAg28iKuSfTVOm", "incremental_authorization_allowed": false, "authorization_count": null, "incremental_authorizations": null, "external_authentication_details": null, "external_3ds_authentication_attempted": false, "expires_on": "2024-11-28T09:56:24.895Z", "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_GuFw64hE9GdwBaAdu60R", "payment_method_status": "active", "updated": "2024-11-28T09:42:31.429Z", "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
9be012826abe87ffa2d0cea5423aed3e50449de2
juspay/hyperswitch
juspay__hyperswitch-6684
Bug: fix(opensearch): handle empty free-text query search in global search Previously, there was no support to add filters in global-search, hence only free-search queries were supported. Because of this, the following query object was being mandatorily added. ```bash { "multi_match": { "type": "phrase", "query": "merchant_1726046328", "lenient": true } }, ``` Now, since adding filters is provided as a feature, it is no longer compulsary to have a free-search query in addition to the filters applied. So if no free-search query is being applied, the query object will have the following: ```bash { "multi_match": { "type": "phrase", "query": "", "lenient": true } }, ``` This empty string in the query is resulting in wrong data being fetched when we hit opensearch/elasticsearch using the `/search` API. Should make changes to incorporate free-search query into the opensearch query only when free-search query is non-empty. Search should happen only based on filters as expected, when filters are provided and free-search query is empty.
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs index 84a2b9db3d4..e8726840a2e 100644 --- a/crates/analytics/src/opensearch.rs +++ b/crates/analytics/src/opensearch.rs @@ -510,14 +510,15 @@ impl OpenSearchQueryBuilder { case_sensitive_filters: Vec<&(String, Vec<String>)>, ) -> Vec<Value> { let mut filter_array = Vec::new(); - - filter_array.push(json!({ - "multi_match": { - "type": "phrase", - "query": self.query, - "lenient": true - } - })); + if !self.query.is_empty() { + filter_array.push(json!({ + "multi_match": { + "type": "phrase", + "query": self.query, + "lenient": true + } + })); + } let case_sensitive_json_filters = case_sensitive_filters .into_iter()
2024-11-27T14:28:36Z
## 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, there was no support to add filters in global-search, hence only free-text search queries were supported. Because of this, the following query object was being mandatorily added. ```bash { "multi_match": { "type": "phrase", "query": "merchant_1726046328", "lenient": true } }, ``` Now, since adding filters is provided as a feature, it is no longer compulsary to have a free-text search query in addition to the filters applied. So if no free-text search query is being applied, the query object will have the following: ```bash { "multi_match": { "type": "phrase", "query": "", "lenient": true } }, ``` This empty string in the query is resulting in wrong data being fetched when we hit opensearch/elasticsearch using the `/search` API. Made changes to incorporate free-text search query into the opensearch query only when free-text search query is non-empty. Now, search will happen only based on filters as expected, when filters are provided and free-text search query is empty. ### 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). --> Extract correct results when using global search. ## 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)? --> Hit the curl: ```bash curl --location 'http://localhost:8080/analytics/v1/search' \ --header 'sec-ch-ua-platform: "macOS"' \ --header 'authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --header 'Referer: http://localhost:9000/' \ --header 'sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"' \ --header 'sec-ch-ua-mobile: ?0' \ --header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \ --header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36' \ --header 'Content-Type: application/json' \ --data '{ "query": "", "filters": { "status": [ "CharGed" ] }, "timeRange": { "startTime": "2024-09-13T00:30:00Z", "endTime": "2024-11-27T21:45:00Z" } }' ``` Should get the expected results. Sample query which will be made: - when free-text search query is empty and filters are non-empty: ```bash Index: SessionizerPaymentIntents Payload: { "query": { "bool": { "filter": [ { "range": { "@timestamp": { "gte": "2024-09-13T00:30:00.000Z", "lte": "2024-11-27T21:45:00.000Z" } } } ], "must": [ { "bool": { "must": [ { "bool": { "should": [ { "term": { "status.keyword": { "value": "CharGed", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "bool": { "must": [ { "term": { "organization_id.keyword": { "value": "org_VpSHOjsYfDvabVYJgCAJ" } } } ] } } ], "minimum_should_match": 1 } } ] } } ] } }, "sort": [ { "@timestamp": { "order": "desc" } } ] } ``` - when free-text search query and filters both are non-empty: ```bash Index: SessionizerPaymentIntents Payload: { "query": { "bool": { "filter": [ { "multi_match": { "type": "phrase", "query": "merchant_1726046328", "lenient": true } }, { "range": { "@timestamp": { "gte": "2024-09-13T00:30:00.000Z", "lte": "2024-11-27T21:45:00.000Z" } } } ], "must": [ { "bool": { "must": [ { "bool": { "should": [ { "term": { "status.keyword": { "value": "CharGed", "case_insensitive": true } } } ], "minimum_should_match": 1 } } ] } }, { "bool": { "must": [ { "bool": { "should": [ { "bool": { "must": [ { "term": { "organization_id.keyword": { "value": "org_VpSHOjsYfDvabVYJgCAJ" } } } ] } } ], "minimum_should_match": 1 } } ] } } ] } }, "sort": [ { "@timestamp": { "order": "desc" } } ] } ``` - when free-text search query is non-empty and no filters are applied: ```bash Index: SessionizerPaymentIntents Payload: { "query": { "bool": { "filter": [ { "multi_match": { "type": "phrase", "query": "merchant_1726046328", "lenient": true } }, { "range": { "@timestamp": { "gte": "2024-09-13T00:30:00.000Z", "lte": "2024-11-27T21:45:00.000Z" } } } ], "must": [ { "bool": { "must": [ { "bool": { "should": [ { "bool": { "must": [ { "term": { "organization_id.keyword": { "value": "org_VpSHOjsYfDvabVYJgCAJ" } } } ] } } ], "minimum_should_match": 1 } } ] } } ] } }, "sort": [ { "@timestamp": { "order": "desc" } } ] } ``` - when free-text search query is empty and no filters are applied: ```json { "error": { "type": "invalid_request", "message": "Both query and filters are empty", "code": "IR_01" } } ``` ## 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
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
juspay/hyperswitch
juspay__hyperswitch-6688
Bug: refactor(dynamic_fields): rename fields like ach, bacs and becs for bank debit payment method ## Type of Change - Refactoring ## Description - The fields ach, becs, and bacs in the payment method data (particularly in bank_debit) should be renamed to improve clarity. ## Changes to be made: - Rename ach to ach_bank_debit. - Rename becs to becs_bank_debit. - Rename bacs to bacs_bank_debit. ## Rationale - These changes aim to make the field names more descriptive and self-explanatory, aligning with best practices for data clarity.
diff --git a/crates/router/src/configs/defaults/payment_connector_required_fields.rs b/crates/router/src/configs/defaults/payment_connector_required_fields.rs index 4e80ccf027e..1cb41827be3 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -11521,18 +11521,18 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.bank_debit.ach.account_number".to_string(), + "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.ach.account_number".to_string(), + required_field: "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( - "payment_method_data.bank_debit.ach.routing_number".to_string(), + "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.ach.routing_number".to_string(), + required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), display_name: "bank_routing_number".to_string(), field_type: enums::FieldType::Text, value: None, @@ -11563,18 +11563,18 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.bank_debit.ach.account_number".to_string(), + "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.ach.account_number".to_string(), + required_field: "payment_method_data.bank_debit.ach_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( - "payment_method_data.bank_debit.ach.routing_number".to_string(), + "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.ach.routing_number".to_string(), + required_field: "payment_method_data.bank_debit.ach_bank_debit.routing_number".to_string(), display_name: "bank_routing_number".to_string(), field_type: enums::FieldType::Text, value: None, @@ -11732,18 +11732,18 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.bank_debit.bacs.account_number".to_string(), + "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.account_number".to_string(), + required_field: "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( - "payment_method_data.bank_debit.bacs.sort_code".to_string(), + "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.sort_code".to_string(), + required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: enums::FieldType::Text, value: None, @@ -11804,18 +11804,18 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.bank_debit.bacs.account_number".to_string(), + "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.account_number".to_string(), + required_field: "payment_method_data.bank_debit.bacs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( - "payment_method_data.bank_debit.bacs.sort_code".to_string(), + "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.sort_code".to_string(), + required_field: "payment_method_data.bank_debit.bacs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: enums::FieldType::Text, value: None, @@ -11854,18 +11854,18 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.bank_debit.becs.account_number".to_string(), + "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.becs.account_number".to_string(), + required_field: "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( - "payment_method_data.bank_debit.becs.bsb_number".to_string(), + "payment_method_data.bank_debit.becs_bank_debit.bsb_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.becs.bsb_number".to_string(), + required_field: "payment_method_data.bank_debit.becs_bank_debit.bsb_number".to_string(), display_name: "bsb_number".to_string(), field_type: enums::FieldType::Text, value: None, @@ -11906,18 +11906,18 @@ impl Default for settings::RequiredFields { } ), ( - "payment_method_data.bank_debit.bacs.account_number".to_string(), + "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.account_number".to_string(), + required_field: "payment_method_data.bank_debit.becs_bank_debit.account_number".to_string(), display_name: "bank_account_number".to_string(), field_type: enums::FieldType::UserBankAccountNumber, value: None, } ), ( - "payment_method_data.bank_debit.bacs.sort_code".to_string(), + "payment_method_data.bank_debit.becs_bank_debit.sort_code".to_string(), RequiredFieldInfo { - required_field: "payment_method_data.bank_debit.bacs.sort_code".to_string(), + required_field: "payment_method_data.bank_debit.becs_bank_debit.sort_code".to_string(), display_name: "bank_sort_code".to_string(), field_type: enums::FieldType::Text, value: None,
2024-11-27T13:05:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description ach, becs and bacs in payment method data is renamed to ach_bank_debit, becs_bank_debit, bacs_bank_debit ### 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` --> ## 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? Tested it through Postman. - Create Connector (Stripe): ``` { "connector_type": "payment_processor", "connector_name": "stripe", "business_country": "US", "business_label": "default", "connector_account_details": { "auth_type": "HeaderKey", "api_key": "some key here" }, "test_mode": false, "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": "redirect_to_url", "payment_method_type": "affirm" } ] }, { "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": "afterpay_clearpay" } ] }, { "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": "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": "bank_redirect", "payment_method_types": [ { "payment_method_type": "ideal", "payment_experience": null, "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": "giropay", "payment_experience": null, "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": "sofort", "payment_experience": null, "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": "eps", "payment_experience": null, "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_debit", "payment_method_types": [ { "payment_method_type": "ach", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "becs", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "bacs", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sepa", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "bank_transfer", "payment_method_types": [ { "payment_method_type": "ach", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "bacs", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "sepa", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "credit", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "card_networks": [ "AmericanExpress", "Discover", "Interac", "JCB", "Mastercard", "Visa", "DinersClub", "UnionPay", "RuPay" ] } ] }, { "payment_method": "card", "payment_method_types": [ { "payment_method_type": "debit", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true, "card_networks": [ "AmericanExpress", "Discover", "Interac", "JCB", "Mastercard", "Visa", "DinersClub", "UnionPay", "RuPay" ] } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "apple_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] }, { "payment_method": "wallet", "payment_method_types": [ { "payment_method_type": "google_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true }, { "payment_method_type": "we_chat_pay", "payment_experience": "invoke_sdk_client", "minimum_amount": 1, "maximum_amount": 68607706, "recurring_enabled": true, "installment_payment_enabled": true } ] } ], "metadata": { "google_pay": { "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": "example", "gateway_merchant_id": "{{gateway_merchant_id}}" } } } ], "merchant_info": { "merchant_name": "Narayan Bhat" } } } } ``` - Create Payment (Confirm set to false): ``` { "amount": 100, "currency": "USD", "confirm": false, "capture_method": "automatic", "capture_on": "2022-09-10T10:11:12Z", "amount_to_capture": 100, "customer_id": "StripeCustomer", "email": "[email protected]", "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_debit", "payment_method_type": "ach", "payment_method_data": { "bank_debit": { "ach_bank_debit":{ "account_number" : "40308669", "routing_number" : "121000358", "sort_code" : "560036", "shopper_email" : "[email protected]", "card_holder_name": "joseph Doe", "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" : "[email protected]" }, "reference": "daslvcgbaieh" } } }, "billing": { "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": "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": "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" } } ``` - Do a list calll to get the ach, becs and bacs details from dynamic fields: ``` curl --location 'http://localhost:8080/account/payment_methods?client_secret={{client_secret}}' \ --header 'Accept: application/json' \ --header 'api-key: {{publishable_key}}' ``` - The response should contain the following: ``` { "payment_method": "bank_debit", "payment_method_types": [ { "payment_method_type": "sepa", "payment_experience": null, "card_networks": null, "bank_names": null, "bank_debits": { "eligible_connectors": [ "stripe" ] }, "bank_transfers": null, "required_fields": { "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": "[email protected]" }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "owner_name", "field_type": "user_billing_name", "value": "Doe" }, "payment_method_data.bank_debit.sepa_bank_debit.iban": { "required_field": "payment_method_data.bank_debit.sepa_bank_debit.iban", "display_name": "iban", "field_type": "user_iban", "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": "joseph" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "becs", "payment_experience": null, "card_networks": null, "bank_names": null, "bank_debits": { "eligible_connectors": [ "stripe" ] }, "bank_transfers": null, "required_fields": { "payment_method_data.bank_debit.becs_bank_debit.account_number": { "required_field": "payment_method_data.bank_debit.becs_bank_debit.account_number", "display_name": "bank_account_number", "field_type": "user_bank_account_number", "value": null }, "payment_method_data.bank_debit.becs_bank_debit.bsb_number": { "required_field": "payment_method_data.bank_debit.becs_bank_debit.bsb_number", "display_name": "bsb_number", "field_type": "text", "value": null }, "billing.email": { "required_field": "payment_method_data.billing.email", "display_name": "email", "field_type": "user_email_address", "value": "[email protected]" }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "owner_name", "field_type": "user_billing_name", "value": "Doe" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "bacs", "payment_experience": null, "card_networks": null, "bank_names": null, "bank_debits": { "eligible_connectors": [ "stripe" ] }, "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": "1467" }, "billing.address.first_name": { "required_field": "payment_method_data.billing.address.first_name", "display_name": "billing_first_name", "field_type": "user_billing_name", "value": "joseph" }, "billing.address.zip": { "required_field": "payment_method_data.billing.address.zip", "display_name": "zip", "field_type": "user_address_pincode", "value": "94122" }, "payment_method_data.bank_debit.bacs_bank_debit.account_number": { "required_field": "payment_method_data.bank_debit.bacs_bank_debit.account_number", "display_name": "bank_account_number", "field_type": "user_bank_account_number", "value": null }, "payment_method_data.bank_debit.bacs_bank_debit.sort_code": { "required_field": "payment_method_data.bank_debit.bacs_bank_debit.sort_code", "display_name": "bank_sort_code", "field_type": "text", "value": null }, "billing.address.country": { "required_field": "payment_method_data.billing.address.country", "display_name": "country", "field_type": { "user_address_country": { "options": [ "UK" ] } }, "value": "GB" } }, "surcharge_details": null, "pm_auth_connector": null }, { "payment_method_type": "ach", "payment_experience": null, "card_networks": null, "bank_names": null, "bank_debits": { "eligible_connectors": [ "stripe" ] }, "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": "joseph" }, "billing.address.last_name": { "required_field": "payment_method_data.billing.address.last_name", "display_name": "owner_name", "field_type": "user_billing_name", "value": "Doe" }, "payment_method_data.bank_debit.ach_bank_debit.account_number": { "required_field": "payment_method_data.bank_debit.ach_bank_debit.account_number", "display_name": "bank_account_number", "field_type": "user_bank_account_number", "value": null }, "payment_method_data.bank_debit.ach_bank_debit.routing_number": { "required_field": "payment_method_data.bank_debit.ach_bank_debit.routing_number", "display_name": "bank_routing_number", "field_type": "text", "value": null } }, "surcharge_details": null, "pm_auth_connector": 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
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
juspay/hyperswitch
juspay__hyperswitch-6679
Bug: bug(users): Check lineage across entities in invite Currently in invites we don't check if user exists across entities. This will be a problem when inviting a user with higher entity from different lineage. We should check if user exists across lineage before allowing invite in this case.
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index c6501dac3bd..2087d01dbb4 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -642,6 +642,38 @@ async fn handle_existing_user_invitation( return Err(UserErrors::UserExists.into()); } + let (org_id, merchant_id, profile_id) = match role_info.get_entity_type() { + EntityType::Organization => (Some(&user_from_token.org_id), None, None), + EntityType::Merchant => ( + Some(&user_from_token.org_id), + Some(&user_from_token.merchant_id), + None, + ), + EntityType::Profile => ( + Some(&user_from_token.org_id), + Some(&user_from_token.merchant_id), + Some(&user_from_token.profile_id), + ), + }; + + if state + .global_store + .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { + user_id: invitee_user_from_db.get_user_id(), + org_id, + merchant_id, + profile_id, + entity_id: None, + version: None, + status: None, + limit: Some(1), + }) + .await + .is_ok_and(|data| data.is_empty().not()) + { + return Err(UserErrors::UserExists.into()); + } + let user_role = domain::NewUserRole { user_id: invitee_user_from_db.get_user_id().to_owned(), role_id: request.role_id.clone(),
2024-11-27T13:02:47Z
## 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 invites we don't check if user exists across entities. This will be a problem when inviting a user with higher entity from different lineage. 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 #6679. ## 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. Invite a user in a specific (org, merchant, profile) combination. 2. Create a new profile in the same merchant account and switch to it. 3. Invite the same user as merchant level user. This should be stopped by API. ## 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
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
juspay/hyperswitch
juspay__hyperswitch-6681
Bug: refactor(currency_conversion): release redis lock if api call fails ### Description Refactor currency conversion: -> For Better error propagation -> For Redis lock realease, if data isn't fetched from api, so that the other subsequent calls donot fail.
diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 2173478ab67..9ab2780da73 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -7,6 +7,7 @@ use error_stack::ResultExt; use masking::PeekInterface; use once_cell::sync::Lazy; use redis_interface::DelReply; +use router_env::{instrument, tracing}; use rust_decimal::Decimal; use strum::IntoEnumIterator; use tokio::{sync::RwLock, time::sleep}; @@ -150,11 +151,13 @@ impl TryFrom<DefaultExchangeRates> for ExchangeRates { let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for (curr, conversion) in value.conversion { let enum_curr = enums::Currency::from_str(curr.as_str()) - .change_context(ForexCacheError::ConversionError)?; + .change_context(ForexCacheError::ConversionError) + .attach_printable("Unable to Convert currency received")?; conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion)); } let base_curr = enums::Currency::from_str(value.base_currency.as_str()) - .change_context(ForexCacheError::ConversionError)?; + .change_context(ForexCacheError::ConversionError) + .attach_printable("Unable to convert base currency")?; Ok(Self { base_currency: base_curr, conversion: conversion_usable, @@ -170,6 +173,8 @@ impl From<Conversion> for CurrencyFactors { } } } + +#[instrument(skip_all)] pub async fn get_forex_rates( state: &SessionState, call_delay: i64, @@ -235,6 +240,7 @@ async fn successive_fetch_and_save_forex( Ok(rates) => Ok(successive_save_data_to_redis_local(state, rates).await?), Err(error) => stale_redis_data.ok_or({ logger::error!(?error); + release_redis_lock(state).await?; ForexCacheError::ApiUnresponsive.into() }), } @@ -254,9 +260,9 @@ async fn successive_save_data_to_redis_local( ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { Ok(save_forex_to_redis(state, &forex) .await - .async_and_then(|_rates| async { release_redis_lock(state).await }) + .async_and_then(|_rates| release_redis_lock(state)) .await - .async_and_then(|_val| async { Ok(save_forex_to_local(forex.clone()).await) }) + .async_and_then(|_val| save_forex_to_local(forex.clone())) .await .map_or_else( |error| { @@ -336,11 +342,15 @@ async fn fetch_forex_rates( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive)?; + .change_context(ForexCacheError::ApiUnresponsive) + .attach_printable("Primary forex fetch api unresponsive")?; let forex_response = response .json::<ForexResponse>() .await - .change_context(ForexCacheError::ParsingError)?; + .change_context(ForexCacheError::ParsingError) + .attach_printable( + "Unable to parse response received from primary api into ForexResponse", + )?; logger::info!("{:?}", forex_response); @@ -392,11 +402,16 @@ pub async fn fallback_fetch_forex_rates( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive)?; + .change_context(ForexCacheError::ApiUnresponsive) + .attach_printable("Fallback forex fetch api unresponsive")?; + let fallback_forex_response = response .json::<FallbackForexResponse>() .await - .change_context(ForexCacheError::ParsingError)?; + .change_context(ForexCacheError::ParsingError) + .attach_printable( + "Unable to parse response received from falback api into ForexResponse", + )?; logger::info!("{:?}", fallback_forex_response); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); @@ -453,6 +468,7 @@ async fn release_redis_lock( .delete_key(REDIX_FOREX_CACHE_KEY) .await .change_context(ForexCacheError::RedisLockReleaseFailed) + .attach_printable("Unable to release redis lock") } async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCacheError> { @@ -475,6 +491,7 @@ async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCac .await .map(|val| matches!(val, redis_interface::SetnxReply::KeySet)) .change_context(ForexCacheError::CouldNotAcquireLock) + .attach_printable("Unable to acquire redis lock") } async fn save_forex_to_redis( @@ -488,6 +505,7 @@ async fn save_forex_to_redis( .serialize_and_set_key(REDIX_FOREX_CACHE_DATA, forex_exchange_cache_entry) .await .change_context(ForexCacheError::RedisWriteError) + .attach_printable("Unable to save forex data to redis") } async fn retrieve_forex_from_redis( @@ -500,6 +518,7 @@ async fn retrieve_forex_from_redis( .get_and_deserialize_key(REDIX_FOREX_CACHE_DATA, "FxExchangeRatesCache") .await .change_context(ForexCacheError::EntryNotFound) + .attach_printable("Forex entry not found in redis") } async fn is_redis_expired( @@ -515,6 +534,7 @@ async fn is_redis_expired( }) } +#[instrument(skip_all)] pub async fn convert_currency( state: SessionState, amount: i64, @@ -532,14 +552,17 @@ pub async fn convert_currency( .change_context(ForexCacheError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable)?; + .change_context(ForexCacheError::CurrencyNotAcceptable) + .attach_printable("The provided currency is not acceptable")?; let from_currency = enums::Currency::from_str(from_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable)?; + .change_context(ForexCacheError::CurrencyNotAcceptable) + .attach_printable("The provided currency is not acceptable")?; let converted_amount = currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount) - .change_context(ForexCacheError::ConversionError)?; + .change_context(ForexCacheError::ConversionError) + .attach_printable("Unable to perform currency conversion")?; Ok(api_models::currency::CurrencyConversionResponse { converted_amount: converted_amount.to_string(),
2024-11-27T07:12: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 --> Refactors for currency conversion which invlolves: -> Better error propagation -> Redis lock realease, if data isn't fetched from api, so that the other subsequent calls donot fail. ### 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). --> Reqired for analytics ## 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)? --> Scenarios tested: 1. No api_keys provided: call returned error and redis key was deleted after being set. 2. fallback api_key provided: call returned forex rates and lock was also released. 3. primary api_key provided: call returned forex rates and lock was also released. ## 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
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
juspay/hyperswitch
juspay__hyperswitch-6666
Bug: fix(analytics): fix first_attempt filter value parsing for Payments - `first_attempt` filter takes in `true` or `false` as variants. - But while it is getting applied in the query, it is being converted into a string: `'true'` or `'false'` This works on latest clickhouse versions, but fails on the older clickhouse versions, with the error: ```error DB::Exception: Cannot convert string false to type Bool: While processing (first_attempt IN ('false')) ``` Should fix the issue by converting the way these values are parsed.
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs index e80f762c41b..caa112ec175 100644 --- a/crates/analytics/src/query.rs +++ b/crates/analytics/src/query.rs @@ -459,7 +459,8 @@ impl<T: AnalyticsDataSource> ToSql<T> for common_utils::id_type::CustomerId { impl<T: AnalyticsDataSource> ToSql<T> for bool { fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> { - Ok(self.to_string().to_owned()) + let flag = *self; + Ok(i8::from(flag).to_string()) } }
2024-11-26T13:05:27Z
## 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 this issue: [https://github.com/juspay/hyperswitch-cloud/issues/7580](https://github.com/juspay/hyperswitch-cloud/issues/7580) - `first_attempt` filter takes in `true` or `false` as variants. - But while it is getting applied in the query, it is being converted into a string: `'true'` or `'false'` This works on latest clickhouse versions, but fails on the older clickhouse versions, with the error: ```error DB::Exception: Cannot convert string false to type Bool: While processing (first_attempt IN ('false')) ``` Now, internally converting `'true'` to `'1'` and `'false'` to `'0'` to fix the issue, and this gets accepted in both the versions. The query which was previously running was: ```bash SELECT connector, status, sum(sign_flag) as count, first_attempt, min(created_at) as start_bucket, max(created_at) as end_bucket FROM sessionizer_payment_attempts WHERE ( first_attempt IN ('false') AND organization_id = 'org_id' AND created_at >= '1731803400' AND created_at <= '1732577400' ) GROUP BY connector, status, first_attempt HAVING sum(sign_flag) >= '1' ``` Now the query which will run is: ```bash SELECT connector, status, sum(sign_flag) as count, first_attempt, min(created_at) as start_bucket, max(created_at) as end_bucket FROM sessionizer_payment_attempts WHERE ( first_attempt IN ('0') AND organization_id = 'org_id' AND created_at >= '1731803400' AND created_at <= '1732577400' ) GROUP BY connector, status, first_attempt HAVING sum(sign_flag) >= '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). --> Fix the issue: [https://github.com/juspay/hyperswitch/issues/6666](https://github.com/juspay/hyperswitch/issues/6666) ## 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)? --> Hit the curl with first_attempt filter containing either `true` or `false`: ```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjc5Mjk0OCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.Q5ruAj8DwAp5XDj1ktFhma4aZXAHSZBmRSw_EnPk4HE' \ --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-11-17T00:30:00Z", "endTime": "2024-11-25T23:30:00Z" }, "groupByNames": [ "connector" ], "filters":{ "first_attempt": [false] }, "source": "BATCH", "metrics": [ "payments_distribution" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": 100.0, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution": 0.0, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": 0.0, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": null, "status": null, "connector": "stripe_test", "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-17T00:30:00.000Z", "end_time": "2024-11-25T23:30:00.000Z" }, "time_bucket": "2024-11-17 00:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_in_usd": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 0 } ] } ``` If smart retries are made, then these fields will show null: ```json "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, ``` And these fields will have some value: ```json "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution_with_only_retries": 0.0, ``` <img width="1728" alt="image" src="https://github.com/user-attachments/assets/591a1b3f-ced4-4fb4-a16d-1ddc246ad5c1"> <img width="1726" alt="image" src="https://github.com/user-attachments/assets/eea88a15-41c6-4998-b2a5-7485c3aebf75"> ## 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
d4b482c21cf57b022c7bbadc1a3a9c9d9e5d4f03
juspay/hyperswitch
juspay__hyperswitch-6656
Bug: ci: use ubuntu runner
2024-11-25T11:34:38Z
## 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 --> Use ubuntu runners instead. closes https://github.com/juspay/hyperswitch/issues/6656 ### 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). --> NA ## 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)? --> See if CI checks pass. ## 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
83e8bc0775c20e9d055e65bd13a2e8b1148092e1
juspay/hyperswitch
juspay__hyperswitch-6653
Bug: fix(analytics): fix bugs in payments page metrics in Analytics V2 dashboard Fix bugs in metrics calculations for Payments page - Analytics V2 dashboard: - `Successful Payments Distribution` and `Failure Payments Distribution`: Exclude the dropoffs from the denominator while calculating the rates - `Failure reasons`: Remove limit by clause and extract data for all error_reasons - `Payments lifecycle`: Update the sankey response structure to look like this: ```bash { "count":"25", "first_attempt":0, "status":"requires_payment_method", "refunds_status":null, "dispute_status":null } ```
diff --git a/crates/analytics/src/payment_intents/accumulator.rs b/crates/analytics/src/payment_intents/accumulator.rs index ef3cd3129c4..d8f27501b56 100644 --- a/crates/analytics/src/payment_intents/accumulator.rs +++ b/crates/analytics/src/payment_intents/accumulator.rs @@ -273,8 +273,14 @@ impl PaymentIntentMetricAccumulator for PaymentsDistributionAccumulator { } } - if let Some(total) = metrics.count.and_then(|total| u32::try_from(total).ok()) { - self.total += total; + 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; + } } } } diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index 3654cad8c09..0b66dfda58c 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -8,10 +8,9 @@ use api_models::analytics::{ }, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, PaymentIntentFilterValue, PaymentIntentFiltersResponse, PaymentIntentsAnalyticsMetadata, PaymentIntentsMetricsResponse, - SankeyResponse, }; use bigdecimal::ToPrimitive; -use common_enums::{Currency, IntentStatus}; +use common_enums::Currency; use common_utils::{errors::CustomResult, types::TimeRange}; use currency_conversion::{conversion::convert, types::ExchangeRates}; use error_stack::ResultExt; @@ -24,7 +23,7 @@ use router_env::{ use super::{ filters::{get_payment_intent_filter_for_dimension, PaymentIntentFilterRow}, metrics::PaymentIntentMetricRow, - sankey::{get_sankey_data, SessionizerRefundStatus}, + sankey::{get_sankey_data, SankeyRow}, PaymentIntentMetricsAccumulator, }; use crate::{ @@ -51,7 +50,7 @@ pub async fn get_sankey( pool: &AnalyticsProvider, auth: &AuthInfo, req: TimeRange, -) -> AnalyticsResult<SankeyResponse> { +) -> AnalyticsResult<Vec<SankeyRow>> { match pool { AnalyticsProvider::Sqlx(_) => Err(AnalyticsError::NotImplemented( "Sankey not implemented for sqlx", @@ -62,69 +61,7 @@ pub async fn get_sankey( 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, 1) => { - sankey_response.refunded += i.count; - sankey_response.normal_success += i.count - } - (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, 1) => { - sankey_response.partial_refunded += i.count; - sankey_response.normal_success += i.count - } - (IntentStatus::Succeeded, SessionizerRefundStatus::FullRefunded, _) => { - sankey_response.refunded += i.count; - sankey_response.smart_retried_success += i.count - } - (IntentStatus::Succeeded, SessionizerRefundStatus::PartialRefunded, _) => { - sankey_response.partial_refunded += i.count; - sankey_response.smart_retried_success += 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) + Ok(sankey_rows) } } } diff --git a/crates/analytics/src/payment_intents/sankey.rs b/crates/analytics/src/payment_intents/sankey.rs index 53fd03562f1..626dcef2744 100644 --- a/crates/analytics/src/payment_intents/sankey.rs +++ b/crates/analytics/src/payment_intents/sankey.rs @@ -5,7 +5,6 @@ use common_utils::{ }; use error_stack::ResultExt; use router_env::logger; -use time::PrimitiveDateTime; use crate::{ clickhouse::ClickhouseClient, @@ -13,29 +12,19 @@ use crate::{ 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, + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, )] #[serde(rename_all = "snake_case")] pub enum SessionizerRefundStatus { @@ -45,13 +34,36 @@ pub enum SessionizerRefundStatus { PartialRefunded, } -#[derive(Debug, serde::Deserialize)] +#[derive( + Clone, + Copy, + Debug, + Default, + Eq, + Hash, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumIter, + strum::EnumString, +)] +#[serde(rename_all = "snake_case")] +pub enum SessionizerDisputeStatus { + DisputePresent, + #[default] + NotDisputed, +} + +#[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SankeyRow { + pub count: i64, pub status: DBEnumWrapper<enums::IntentStatus>, #[serde(default)] pub refunds_status: Option<DBEnumWrapper<SessionizerRefundStatus>>, - pub attempt_count: i64, - pub count: i64, + #[serde(default)] + pub dispute_status: Option<DBEnumWrapper<SessionizerDisputeStatus>>, + pub first_attempt: i64, } impl TryInto<SankeyRow> for serde_json::Value { @@ -90,7 +102,12 @@ pub async fn get_sankey_data( .change_context(MetricsError::QueryBuildingError)?; query_builder - .add_select_column("attempt_count") + .add_select_column("dispute_status") + .attach_printable("Error adding select clause") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_select_column("(attempt_count = 1) as first_attempt") .attach_printable("Error adding select clause") .change_context(MetricsError::QueryBuildingError)?; @@ -112,7 +129,12 @@ pub async fn get_sankey_data( .change_context(MetricsError::QueryBuildingError)?; query_builder - .add_group_by_clause("attempt_count") + .add_group_by_clause("dispute_status") + .attach_printable("Error adding group by clause") + .change_context(MetricsError::QueryBuildingError)?; + + query_builder + .add_group_by_clause("first_attempt") .attach_printable("Error adding group by clause") .change_context(MetricsError::QueryBuildingError)?; diff --git a/crates/analytics/src/payments/accumulator.rs b/crates/analytics/src/payments/accumulator.rs index 291d7364071..20ccc634068 100644 --- a/crates/analytics/src/payments/accumulator.rs +++ b/crates/analytics/src/payments/accumulator.rs @@ -218,12 +218,19 @@ impl PaymentMetricAccumulator for PaymentsDistributionAccumulator { } } } - 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; - } else { - self.total_with_only_retries += total; + if status.as_ref() != &storage_enums::AttemptStatus::AuthenticationFailed + && status.as_ref() != &storage_enums::AttemptStatus::PaymentMethodAwaited + && status.as_ref() != &storage_enums::AttemptStatus::DeviceDataCollectionPending + && status.as_ref() != &storage_enums::AttemptStatus::ConfirmationAwaited + && status.as_ref() != &storage_enums::AttemptStatus::Unresolved + { + 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; + } else { + self.total_with_only_retries += total; + } } } } diff --git a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs index bcbce0502d2..c472c12795f 100644 --- a/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs +++ b/crates/analytics/src/payments/metrics/sessionized_metrics/failure_reasons.rs @@ -160,11 +160,6 @@ where .switch()?; } - outer_query_builder - .set_limit_by(5, &filtered_dimensions) - .attach_printable("Error adding limit clause") - .switch()?; - outer_query_builder .execute_query::<PaymentMetricRow, _>(pool) .await diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index ee904652154..d25f35589b6 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -458,17 +458,9 @@ pub struct GetDisputeMetricRequest { #[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, + pub count: i64, + pub status: String, + pub refunds_status: Option<String>, + pub dispute_status: Option<String>, + pub first_attempt: i64, }
2024-11-25T08:40:46Z
## 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 --> Fixing some bugs in metrics calculations for Payments page - Analytics V2 dashboard: - `Successful Payments Distribution` and `Failure Payments Distribution`: Excluded the following dropoffs from the denominator while calculating the rates - Without smart retries - From Payment Intents - RequiresCustomerAction - RequiresPaymentMethod - RequiresMerchantAction - RequiresConfirmation - With smart retries - AuthenticationFailed - PaymentMethodAwaited - DeviceDataCollectionPending - ConfirmationAwaited - Unresolved - `Failure reasons`: Removed limit by clause and extracting data for all error_reasons - `Payments lifecycle`: Updated the sankey response structure, now it will look like this: ```bash { "count":"25", "first_attempt":0, "status":"requires_payment_method", "refunds_status":null, "dispute_status":null } ``` ### 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 bugs and send correct data to be displayed in the analytics v2 dashboard. ## 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)? --> Sankey: ```bash curl --location 'http://localhost:8080/analytics/v1/org/metrics/sankey' \ --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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjYwODUzNCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.tQYvWyhWQInhAymh0c4itE1CWVwhOG3L4_yHMY4RLkQ' \ --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 '{ "startTime": "2024-05-11T00:30:00Z", "endTime": "2024-11-25T23:30:00Z" }' ``` Response: ```json [ { "count": 2, "status": "succeeded", "refunds_status": null, "dispute_status": null, "first_attempt": 0 }, { "count": 40, "status": "succeeded", "refunds_status": null, "dispute_status": null, "first_attempt": 1 }, { "count": 1, "status": "failed", "refunds_status": null, "dispute_status": null, "first_attempt": 0 }, { "count": 2, "status": "requires_confirmation", "refunds_status": null, "dispute_status": null, "first_attempt": 1 }, { "count": 3, "status": "failed", "refunds_status": null, "dispute_status": null, "first_attempt": 1 }, { "count": 2, "status": "requires_payment_method", "refunds_status": null, "dispute_status": null, "first_attempt": 1 }, { "count": 7, "status": "succeeded", "refunds_status": "partial_refunded", "dispute_status": null, "first_attempt": 1 } ] ``` 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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjYwODUzNCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.tQYvWyhWQInhAymh0c4itE1CWVwhOG3L4_yHMY4RLkQ' \ --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-11-19T00:30:00Z", "endTime": "2024-11-19T23:30:00Z" }, "groupByNames": [ "connector" ], "source": "BATCH", "metrics": [ "payments_distribution" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": null, "status": null, "connector": null, "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-19T00:30:00.000Z", "end_time": "2024-11-19T23:30:00.000Z" }, "time_bucket": "2024-11-19 00:30:00" }, { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": 88.88888888888889, "payments_success_rate_distribution_without_smart_retries": 87.5, "payments_success_rate_distribution_with_only_retries": 100.0, "payments_failure_rate_distribution": 11.11111111111111, "payments_failure_rate_distribution_without_smart_retries": 12.5, "payments_failure_rate_distribution_with_only_retries": 0.0, "failure_reason_count": 0, "failure_reason_count_without_smart_retries": 0, "currency": null, "status": null, "connector": "stripe_test", "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-19T00:30:00.000Z", "end_time": "2024-11-19T23:30:00.000Z" }, "time_bucket": "2024-11-19 00:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_in_usd": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 0, "total_failure_reasons_count_without_smart_retries": 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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjYwODUzNCwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.tQYvWyhWQInhAymh0c4itE1CWVwhOG3L4_yHMY4RLkQ' \ --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-11-17T00:30:00Z", "endTime": "2024-11-25T23:30:00Z" }, "groupByNames": [ "connector", "error_reason" ], "source": "BATCH", "metrics": [ "failure_reasons" ], "delta": true } ]' ``` Response: ```json { "queryData": [ { "payment_success_rate": null, "payment_count": null, "payment_success_count": null, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_usd": null, "payment_processed_count_without_smart_retries": null, "avg_ticket_size": null, "payment_error_message": null, "retries_count": null, "retries_amount_processed": 0, "connector_success_rate": null, "payments_success_rate_distribution": null, "payments_success_rate_distribution_without_smart_retries": null, "payments_success_rate_distribution_with_only_retries": null, "payments_failure_rate_distribution": null, "payments_failure_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_with_only_retries": null, "failure_reason_count": 1, "failure_reason_count_without_smart_retries": 1, "currency": null, "status": null, "connector": "stripe_test", "authentication_type": null, "payment_method": null, "payment_method_type": null, "client_source": null, "client_version": null, "profile_id": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": "TEST ERROR - 1", "time_range": { "start_time": "2024-11-17T00:30:00.000Z", "end_time": "2024-11-25T23:30:00.000Z" }, "time_bucket": "2024-11-17 00:30:00" } ], "metaData": [ { "total_payment_processed_amount": 0, "total_payment_processed_amount_in_usd": 0, "total_payment_processed_amount_without_smart_retries": 0, "total_payment_processed_amount_without_smart_retries_usd": 0, "total_payment_processed_count": 0, "total_payment_processed_count_without_smart_retries": 0, "total_failure_reasons_count": 1, "total_failure_reasons_count_without_smart_retries": 1 } ] } ``` ## 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
31204941ee24fe7b23344ba9b4a2615c46f33bb0
juspay/hyperswitch
juspay__hyperswitch-6647
Bug: [REFACTOR] add `error_category` column to gsm table Add `error_category` column to gsm table which is an enum in application. These could be used to take multiple decisions but currently these are required for elimination routing in which these categories will serve as bucket name.
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index e3f54813a43..ae9265aa41d 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -7776,6 +7776,16 @@ } } }, + "ErrorCategory": { + "type": "string", + "enum": [ + "frm_decline", + "processor_downtime", + "processor_decline_unauthorized", + "issue_with_payment_method", + "processor_decline_incorrect_data" + ] + }, "ErrorDetails": { "type": "object", "description": "Error details for the payment", @@ -9162,6 +9172,14 @@ "type": "string", "description": "error message unified across the connectors", "nullable": true + }, + "error_category": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorCategory" + } + ], + "nullable": true } } }, @@ -9295,6 +9313,14 @@ "type": "string", "description": "error message unified across the connectors", "nullable": true + }, + "error_category": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorCategory" + } + ], + "nullable": true } } }, @@ -9391,6 +9417,14 @@ "type": "string", "description": "error message unified across the connectors", "nullable": true + }, + "error_category": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorCategory" + } + ], + "nullable": true } } }, diff --git a/crates/api_models/src/gsm.rs b/crates/api_models/src/gsm.rs index 30e49062439..b95794ef707 100644 --- a/crates/api_models/src/gsm.rs +++ b/crates/api_models/src/gsm.rs @@ -1,3 +1,4 @@ +use common_enums::ErrorCategory; use utoipa::ToSchema; use crate::enums::Connector; @@ -26,6 +27,8 @@ pub struct GsmCreateRequest { pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, + /// category in which error belongs to + pub error_category: Option<ErrorCategory>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -88,6 +91,8 @@ pub struct GsmUpdateRequest { pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, + /// category in which error belongs to + pub error_category: Option<ErrorCategory>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] @@ -141,4 +146,6 @@ pub struct GsmResponse { pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, + /// category in which error belongs to + pub error_category: Option<ErrorCategory>, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 781b5e3710a..1c7eaf8878b 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3357,3 +3357,28 @@ pub enum ConnectorMandateStatus { /// Indicates that the connector mandate is not active and hence cannot be used for payments. Inactive, } + +#[derive( + Clone, + Copy, + Debug, + strum::Display, + PartialEq, + Eq, + serde::Serialize, + serde::Deserialize, + strum::EnumString, + ToSchema, + PartialOrd, + Ord, +)] +#[router_derive::diesel_enum(storage_type = "text")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum ErrorCategory { + FrmDecline, + ProcessorDowntime, + ProcessorDeclineUnauthorized, + IssueWithPaymentMethod, + ProcessorDeclineIncorrectData, +} diff --git a/crates/diesel_models/src/gsm.rs b/crates/diesel_models/src/gsm.rs index 6a444410fa8..aba8d75a6eb 100644 --- a/crates/diesel_models/src/gsm.rs +++ b/crates/diesel_models/src/gsm.rs @@ -1,5 +1,6 @@ //! Gateway status mapping +use common_enums::ErrorCategory; use common_utils::{ custom_serde, events::{ApiEventMetric, ApiEventsType}, @@ -39,6 +40,7 @@ pub struct GatewayStatusMap { pub step_up_possible: bool, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub error_category: Option<ErrorCategory>, } #[derive(Clone, Debug, Eq, PartialEq, Insertable)] @@ -55,17 +57,11 @@ pub struct GatewayStatusMappingNew { pub step_up_possible: bool, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub error_category: Option<ErrorCategory>, } #[derive( - Clone, - Debug, - PartialEq, - Eq, - AsChangeset, - router_derive::DebugAsDisplay, - Default, - serde::Deserialize, + Clone, Debug, PartialEq, Eq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, )] #[diesel(table_name = gateway_status_map)] pub struct GatewayStatusMapperUpdateInternal { @@ -80,6 +76,8 @@ pub struct GatewayStatusMapperUpdateInternal { pub step_up_possible: Option<bool>, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub error_category: Option<ErrorCategory>, + pub last_modified: PrimitiveDateTime, } #[derive(Debug)] @@ -90,6 +88,7 @@ pub struct GatewayStatusMappingUpdate { pub step_up_possible: Option<bool>, pub unified_code: Option<String>, pub unified_message: Option<String>, + pub error_category: Option<ErrorCategory>, } impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { @@ -101,6 +100,7 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { step_up_possible, unified_code, unified_message, + error_category, } = value; Self { status, @@ -109,7 +109,13 @@ impl From<GatewayStatusMappingUpdate> for GatewayStatusMapperUpdateInternal { step_up_possible, unified_code, unified_message, - ..Default::default() + error_category, + last_modified: common_utils::date_time::now(), + connector: None, + flow: None, + sub_flow: None, + code: None, + message: None, } } } diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index d3e560fc048..b6f1a4f8d05 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -508,6 +508,8 @@ diesel::table! { unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, + #[max_length = 64] + error_category -> Nullable<Varchar>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index f6bab9071cd..470868ed82d 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -520,6 +520,8 @@ diesel::table! { unified_code -> Nullable<Varchar>, #[max_length = 1024] unified_message -> Nullable<Varchar>, + #[max_length = 64] + error_category -> Nullable<Varchar>, } } diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index ed6efea27f8..8b5940ebf61 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -605,6 +605,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::blocklist::ToggleBlocklistResponse, api_models::blocklist::ListBlocklistQuery, api_models::enums::BlocklistDataKind, + api_models::enums::ErrorCategory, api_models::webhook_events::EventListItemResponse, api_models::webhook_events::EventRetrieveResponse, api_models::webhook_events::OutgoingWebhookRequestContent, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index a756d9fb1b1..2221055be5a 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -569,6 +569,7 @@ Never share your secret api keys. Keep them guarded and secure. api_models::blocklist::ToggleBlocklistResponse, api_models::blocklist::ListBlocklistQuery, api_models::enums::BlocklistDataKind, + api_models::enums::ErrorCategory, api_models::webhook_events::EventListItemResponse, api_models::webhook_events::EventRetrieveResponse, api_models::webhook_events::OutgoingWebhookRequestContent, diff --git a/crates/router/src/core/gsm.rs b/crates/router/src/core/gsm.rs index 4a678a5c408..c7daee111a9 100644 --- a/crates/router/src/core/gsm.rs +++ b/crates/router/src/core/gsm.rs @@ -67,6 +67,7 @@ pub async fn update_gsm_rule( step_up_possible, unified_code, unified_message, + error_category, } = gsm_request; GsmInterface::update_gsm_rule( db, @@ -82,6 +83,7 @@ pub async fn update_gsm_rule( step_up_possible, unified_code, unified_message, + error_category, }, ) .await diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 4ae02668957..ef21dba9e4b 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1686,6 +1686,7 @@ impl ForeignFrom<gsm_api_types::GsmCreateRequest> for storage::GatewayStatusMapp step_up_possible: value.step_up_possible, unified_code: value.unified_code, unified_message: value.unified_message, + error_category: value.error_category, } } } @@ -1704,6 +1705,7 @@ impl ForeignFrom<storage::GatewayStatusMap> for gsm_api_types::GsmResponse { step_up_possible: value.step_up_possible, unified_code: value.unified_code, unified_message: value.unified_message, + error_category: value.error_category, } } } diff --git a/migrations/2024-11-24-104438_add_error_category_col_to_gsm/down.sql b/migrations/2024-11-24-104438_add_error_category_col_to_gsm/down.sql new file mode 100644 index 00000000000..609afbdfd75 --- /dev/null +++ b/migrations/2024-11-24-104438_add_error_category_col_to_gsm/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE gateway_status_map DROP COLUMN error_category; diff --git a/migrations/2024-11-24-104438_add_error_category_col_to_gsm/up.sql b/migrations/2024-11-24-104438_add_error_category_col_to_gsm/up.sql new file mode 100644 index 00000000000..298f6d263aa --- /dev/null +++ b/migrations/2024-11-24-104438_add_error_category_col_to_gsm/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE gateway_status_map ADD COLUMN error_category VARCHAR(64);
2024-11-24T12:45:50Z
## 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 --> This PR adds `error_category` column to gsm table which is an enum in application. These could be used to take multiple decisions in future but currently these are required for elimination routing in which these categories will serve as bucket name. Additionally the pr fixes the `last_modified` column not being updated in gsm table during `/update` ### 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)? --> Added new column to GSM table. (`error_category`) ``` curl --location 'http://localhost:8080/gsm' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'api-key: test_admin' \ --data '{ "connector": "stripe", "flow" : "flow1", "sub_flow": "sub_flow", "code": "incorrect_cvc", "status": "status1", "decision": "retry", "message": "xyz", "step_up_possible": false, "error_category": "issue_with_payment_method" }' ``` ## 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
797a0db7733c5b387564fb1bbc106d054c8dffa6
juspay/hyperswitch
juspay__hyperswitch-6673
Bug: [FEATURE] [REDSYS] add Connector Template Code ### Feature Description Add Connector Template Code for Redsys ### Possible Implementation Add Connector Template Code for Redsys ### 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 191f2ba7f8b..c0a7f8ad8d1 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -252,6 +252,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 00a544dc565..46be8699930 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -93,6 +93,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" riskified.base_url = "https://sandbox.riskified.com/api" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 0fe9095d280..3f89e755cfb 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -97,6 +97,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://api.juspay.in" +redsys.base_url = "https://sis.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://wh.riskified.com/api/" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 82c347ae389..aa77e9b9fe7 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -97,6 +97,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" diff --git a/config/development.toml b/config/development.toml index ee6ea5dab0b..76519ce809e 100644 --- a/config/development.toml +++ b/config/development.toml @@ -155,6 +155,7 @@ cards = [ "plaid", "powertranz", "prophetpay", + "redsys", "shift4", "square", "stax", @@ -268,6 +269,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index ed0ede98d94..1b56d83a81d 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -182,6 +182,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" @@ -275,6 +276,7 @@ cards = [ "plaid", "powertranz", "prophetpay", + "redsys", "shift4", "square", "stax", diff --git a/crates/api_models/src/connector_enums.rs b/crates/api_models/src/connector_enums.rs index 783ecb12b48..3b672cea009 100644 --- a/crates/api_models/src/connector_enums.rs +++ b/crates/api_models/src/connector_enums.rs @@ -113,6 +113,7 @@ pub enum Connector { Prophetpay, Rapyd, Razorpay, + // Redsys, Shift4, Square, Stax, @@ -251,6 +252,7 @@ impl Connector { | Self::Powertranz | Self::Prophetpay | Self::Rapyd + // | Self::Redsys | Self::Shift4 | Self::Square | Self::Stax diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index c3bbf6e078f..421a51205de 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -108,6 +108,7 @@ pub enum RoutableConnectors { Prophetpay, Rapyd, Razorpay, + // Redsys, Riskified, Shift4, Signifyd, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index d1cdb85e57f..fdd87a25e8a 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -28,6 +28,7 @@ pub mod payeezy; pub mod payu; pub mod powertranz; pub mod razorpay; +pub mod redsys; pub mod shift4; pub mod square; pub mod stax; @@ -49,6 +50,7 @@ pub use self::{ helcim::Helcim, inespay::Inespay, jpmorgan::Jpmorgan, mollie::Mollie, multisafepay::Multisafepay, nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, payeezy::Payeezy, payu::Payu, powertranz::Powertranz, razorpay::Razorpay, - shift4::Shift4, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, tsys::Tsys, - volt::Volt, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl, + redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, + tsys::Tsys, volt::Volt, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, + zsl::Zsl, }; diff --git a/crates/hyperswitch_connectors/src/connectors/redsys.rs b/crates/hyperswitch_connectors/src/connectors/redsys.rs new file mode 100644 index 00000000000..760ce148b40 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/redsys.rs @@ -0,0 +1,563 @@ +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 redsys; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Redsys { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Redsys { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Redsys {} +impl api::PaymentSession for Redsys {} +impl api::ConnectorAccessToken for Redsys {} +impl api::MandateSetup for Redsys {} +impl api::PaymentAuthorize for Redsys {} +impl api::PaymentSync for Redsys {} +impl api::PaymentCapture for Redsys {} +impl api::PaymentVoid for Redsys {} +impl api::Refund for Redsys {} +impl api::RefundExecute for Redsys {} +impl api::RefundSync for Redsys {} +impl api::PaymentToken for Redsys {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Redsys +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Redsys +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 Redsys { + fn id(&self) -> &'static str { + "redsys" + } + + 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.redsys.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = redsys::RedsysAuthType::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: redsys::RedsysErrorResponse = res + .response + .parse_struct("RedsysErrorResponse") + .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 Redsys { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Redsys { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Redsys {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Redsys {} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Redsys { + 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 = redsys::RedsysRouterData::from((amount, req)); + let connector_req = redsys::RedsysPaymentsRequest::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: redsys::RedsysPaymentsResponse = res + .response + .parse_struct("Redsys 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 Redsys { + 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: redsys::RedsysPaymentsResponse = res + .response + .parse_struct("redsys 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 Redsys { + 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: redsys::RedsysPaymentsResponse = res + .response + .parse_struct("Redsys 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 Redsys {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Redsys { + 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 = redsys::RedsysRouterData::from((refund_amount, req)); + let connector_req = redsys::RedsysRefundRequest::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: redsys::RefundResponse = + res.response + .parse_struct("redsys 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 Redsys { + 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: redsys::RefundResponse = res + .response + .parse_struct("redsys 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 Redsys { + 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/redsys/transformers.rs b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs new file mode 100644 index 00000000000..78329b5719d --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs @@ -0,0 +1,228 @@ +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 RedsysRouterData<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 RedsysRouterData<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 RedsysPaymentsRequest { + amount: StringMinorUnit, + card: RedsysCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct RedsysCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&RedsysRouterData<&PaymentsAuthorizeRouterData>> for RedsysPaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &RedsysRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = RedsysCard { + number: req_card.card_number, + expiry_month: req_card.card_exp_month, + expiry_year: req_card.card_exp_year, + cvc: req_card.card_cvc, + complete: item.router_data.request.is_auto_capture()?, + }; + Ok(Self { + amount: item.amount.clone(), + card, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct RedsysAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for RedsysAuthType { + 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 RedsysPaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RedsysPaymentStatus> for common_enums::AttemptStatus { + fn from(item: RedsysPaymentStatus) -> Self { + match item { + RedsysPaymentStatus::Succeeded => Self::Charged, + RedsysPaymentStatus::Failed => Self::Failure, + RedsysPaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct RedsysPaymentsResponse { + status: RedsysPaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, RedsysPaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, RedsysPaymentsResponse, T, PaymentsResponseData>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: common_enums::AttemptStatus::from(item.response.status), + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } +} + +//TODO: Fill the struct with respective fields +// REFUND : +// Type definition for RefundRequest +#[derive(Default, Debug, Serialize)] +pub struct RedsysRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&RedsysRouterData<&RefundsRouterData<F>>> for RedsysRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &RedsysRouterData<&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 RedsysErrorResponse { + 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 50b28be2b0b..25306458e8f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -119,6 +119,7 @@ default_imp_for_authorize_session_token!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Taxjar, @@ -177,6 +178,7 @@ default_imp_for_calculate_tax!( connectors::Payu, connectors::Powertranz, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -223,6 +225,7 @@ default_imp_for_session_update!( connectors::Inespay, connectors::Jpmorgan, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -283,6 +286,7 @@ default_imp_for_post_session_tokens!( connectors::Inespay, connectors::Jpmorgan, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Taxjar, @@ -348,6 +352,7 @@ default_imp_for_complete_authorize!( connectors::Payeezy, connectors::Payu, connectors::Razorpay, + connectors::Redsys, connectors::Stax, connectors::Square, connectors::Taxjar, @@ -406,6 +411,7 @@ default_imp_for_incremental_authorization!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -466,6 +472,7 @@ default_imp_for_create_customer!( connectors::Payu, connectors::Powertranz, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Square, connectors::Taxjar, @@ -522,6 +529,7 @@ default_imp_for_connector_redirect_response!( connectors::Payu, connectors::Powertranz, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -578,6 +586,7 @@ default_imp_for_pre_processing_steps!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Stax, connectors::Square, connectors::Taxjar, @@ -637,6 +646,7 @@ default_imp_for_post_processing_steps!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -697,6 +707,7 @@ default_imp_for_approve!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -757,6 +768,7 @@ default_imp_for_reject!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -817,6 +829,7 @@ default_imp_for_webhook_source_verification!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -878,6 +891,7 @@ default_imp_for_accept_dispute!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -938,6 +952,7 @@ default_imp_for_submit_evidence!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -998,6 +1013,7 @@ default_imp_for_defend_dispute!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1067,6 +1083,7 @@ default_imp_for_file_upload!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1120,6 +1137,7 @@ default_imp_for_payouts!( connectors::Payu, connectors::Powertranz, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Square, connectors::Stax, @@ -1181,6 +1199,7 @@ default_imp_for_payouts_create!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1243,6 +1262,7 @@ default_imp_for_payouts_retrieve!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1305,6 +1325,7 @@ default_imp_for_payouts_eligibility!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1367,6 +1388,7 @@ default_imp_for_payouts_fulfill!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1429,6 +1451,7 @@ default_imp_for_payouts_cancel!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1491,6 +1514,7 @@ default_imp_for_payouts_quote!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1553,6 +1577,7 @@ default_imp_for_payouts_recipient!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1615,6 +1640,7 @@ default_imp_for_payouts_recipient_account!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1677,6 +1703,7 @@ default_imp_for_frm_sale!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1739,6 +1766,7 @@ default_imp_for_frm_checkout!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1801,6 +1829,7 @@ default_imp_for_frm_transaction!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1863,6 +1892,7 @@ default_imp_for_frm_fulfillment!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1925,6 +1955,7 @@ default_imp_for_frm_record_return!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1984,6 +2015,7 @@ default_imp_for_revoking_mandates!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 7b19ca68365..6a30a180fe7 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -235,6 +235,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -296,6 +297,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -352,6 +354,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -414,6 +417,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -475,6 +479,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -536,6 +541,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -607,6 +613,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -670,6 +677,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -733,6 +741,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -796,6 +805,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -859,6 +869,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -922,6 +933,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -985,6 +997,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1048,6 +1061,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1111,6 +1125,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1172,6 +1187,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1235,6 +1251,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1298,6 +1315,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1361,6 +1379,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1424,6 +1443,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1487,6 +1507,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, @@ -1547,6 +1568,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Mollie, connectors::Multisafepay, connectors::Razorpay, + connectors::Redsys, connectors::Shift4, connectors::Stax, connectors::Square, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index 539b87c4808..d6e195bbec4 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -76,6 +76,7 @@ pub struct Connectors { pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, + pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub shift4: ConnectorParams, pub signifyd: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index b6668323ba9..5874f4ba463 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -54,10 +54,11 @@ pub use hyperswitch_connectors::connectors::{ inespay::Inespay, jpmorgan, jpmorgan::Jpmorgan, mollie, mollie::Mollie, multisafepay, multisafepay::Multisafepay, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, novalnet, novalnet::Novalnet, payeezy, payeezy::Payeezy, payu, - payu::Payu, powertranz, powertranz::Powertranz, razorpay, razorpay::Razorpay, shift4, - shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, - thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, worldline, worldline::Worldline, worldpay, - worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, + payu::Payu, powertranz, powertranz::Powertranz, razorpay, razorpay::Razorpay, redsys, + redsys::Redsys, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar, + taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, volt, volt::Volt, worldline, + worldline::Worldline, worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, + zsl::Zsl, }; #[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 44e8c25d67b..8afd019d080 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -1170,6 +1170,7 @@ default_imp_for_new_connector_integration_payouts!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Redsys, connector::Riskified, connector::Signifyd, connector::Square, @@ -1818,6 +1819,7 @@ default_imp_for_new_connector_integration_frm!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Redsys, connector::Riskified, connector::Signifyd, connector::Square, @@ -2314,6 +2316,7 @@ default_imp_for_new_connector_integration_connector_authentication!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Redsys, connector::Riskified, connector::Signifyd, connector::Square, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 9ba260f554f..df319724bc4 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -511,6 +511,7 @@ default_imp_for_connector_request_id!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Redsys, connector::Riskified, connector::Shift4, connector::Signifyd, @@ -1799,6 +1800,7 @@ default_imp_for_fraud_check!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Redsys, connector::Shift4, connector::Square, connector::Stax, @@ -2462,6 +2464,7 @@ default_imp_for_connector_authentication!( connector::Prophetpay, connector::Rapyd, connector::Razorpay, + connector::Redsys, connector::Riskified, connector::Shift4, connector::Signifyd, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index d550c1978b2..f5fa2d9a37e 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -486,6 +486,7 @@ impl ConnectorData { enums::Connector::Rapyd => { Ok(ConnectorEnum::Old(Box::new(connector::Rapyd::new()))) } + // enums::Connector::Redsys => Ok(ConnectorEnum::Old(Box::new(connector::Redsys))), enums::Connector::Shift4 => { Ok(ConnectorEnum::Old(Box::new(connector::Shift4::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 78138757493..2ff243ec4b9 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -280,6 +280,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { api_enums::Connector::Prophetpay => Self::Prophetpay, api_enums::Connector::Rapyd => Self::Rapyd, api_enums::Connector::Razorpay => Self::Razorpay, + // api_enums::Connector::Redsys => Self::Redsys, api_enums::Connector::Shift4 => Self::Shift4, api_enums::Connector::Signifyd => { Err(common_utils::errors::ValidationError::InvalidValue { diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index ef3ae2d14db..dcedb171675 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -74,6 +74,7 @@ mod powertranz; mod prophetpay; mod rapyd; mod razorpay; +mod redsys; mod shift4; mod square; mod stax; diff --git a/crates/router/tests/connectors/redsys.rs b/crates/router/tests/connectors/redsys.rs new file mode 100644 index 00000000000..532bbb6f550 --- /dev/null +++ b/crates/router/tests/connectors/redsys.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 RedsysTest; +impl ConnectorActions for RedsysTest {} +impl utils::Connector for RedsysTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Redsys; + utils::construct_connector_data_old( + Box::new(Redsys::new()), + types::Connector::Plaid, + api::GetToken::Connector, + None, + ) + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .redsys + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "redsys".to_string() + } +} + +static CONNECTOR: RedsysTest = RedsysTest {}; + +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/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml index 120ce5e9d26..d099c16254b 100644 --- a/crates/router/tests/connectors/sample_auth.toml +++ b/crates/router/tests/connectors/sample_auth.toml @@ -268,6 +268,9 @@ api_key="API Key" [nexixpay] api_key="API Key" +[redsys] +api_key="API Key" + [wellsfargopayout] api_key = "Consumer Key" key1 = "Gateway Entity Id" diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 4bb348d6679..3fab02e64d1 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -77,6 +77,7 @@ pub struct ConnectorAuthentication { pub prophetpay: Option<HeaderKey>, pub rapyd: Option<BodyKey>, pub razorpay: Option<BodyKey>, + pub redsys: Option<HeaderKey>, pub shift4: Option<HeaderKey>, pub square: Option<BodyKey>, pub stax: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index dab85eb3cdd..7f93d50d462 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -148,6 +148,7 @@ powertranz.base_url = "https://staging.ptranz.com/api/" prophetpay.base_url = "https://ccm-thirdparty.cps.golf/" rapyd.base_url = "https://sandboxapi.rapyd.net" razorpay.base_url = "https://sandbox.juspay.in/" +redsys.base_url = "https://sis-t.redsys.es:25443/sis/realizarPago" riskified.base_url = "https://sandbox.riskified.com/api" shift4.base_url = "https://api.shift4.com/" signifyd.base_url = "https://api.signifyd.com/" diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index e5a65128319..fd555a41613 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -6,7 +6,7 @@ function find_prev_connector() { git checkout $self cp $self $self.tmp # Add new connector to existing list and sort it - connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
2024-11-26T09:11:29Z
## 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 --> Template code added for new connector Inespay This PR is related to issue: https://github.com/juspay/hyperswitch-cloud/issues/7572 ### 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. This PR is related to issue: https://github.com/juspay/hyperswitch/issues/6673 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). --> This PR is related to issue: https://github.com/juspay/hyperswitch/issues/6673 ## 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 PR, 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
108b1603fa44b2a56c278196edb5a1f76f5d3d03
juspay/hyperswitch
juspay__hyperswitch-6633
Bug: [FEATURE] [AIRWALLEX] Update production endpoint ### Feature Description Update production endpoint for connector Airwallex (https://api.airwallex.com/) ### Possible Implementation Update production endpoint for connector Airwallex (https://api.airwallex.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/config/deployments/production.toml b/config/deployments/production.toml index 76f42085f92..ebd9e49d86b 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -28,7 +28,7 @@ adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpaymen adyen.payout_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/" adyen.dispute_base_url = "https://{{merchant_endpoint_prefix}}-ca-live.adyen.com/" adyenplatform.base_url = "https://balanceplatform-api-live.adyen.com/" -airwallex.base_url = "https://api-demo.airwallex.com/" +airwallex.base_url = "https://api.airwallex.com/" amazonpay.base_url = "https://pay-api.amazon.com/v2" applepay.base_url = "https://apple-pay-gateway.apple.com/" authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api"
2024-11-21T12:24:28Z
## 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 --> Update production endpoint for connector Airwallex (https://api.airwallex.com/) ### 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/6633 ## 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 config changes 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
f24578310f44adf75c993ba42225554377399961
juspay/hyperswitch
juspay__hyperswitch-6638
Bug: feat(users): Send welcome to community email in magic link signup Send [this](https://www.figma.com/design/lhmTvW2vuc2p5B4ZvsEOTw/Email-Tempalte-Design?node-id=0-1&t=OKWmXqVOsidKUk7y-1) email when user signs up with magic link.
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index aa427992082..32ca4ad31d7 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -41,3 +41,5 @@ pub const EMAIL_SUBJECT_INVITATION: &str = "You have been invited to join Hypers 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"; +pub const EMAIL_SUBJECT_WELCOME_TO_COMMUNITY: &str = + "Thank you for signing up on Hyperswitch Dashboard!"; diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index bff6205f5db..eedd9ac5672 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -246,26 +246,41 @@ pub async fn connect_account( ) .await?; - let email_contents = email_types::VerifyEmail { + let magic_link_email = email_types::VerifyEmail { recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, settings: state.conf.clone(), subject: consts::user::EMAIL_SUBJECT_SIGNUP, auth_id, }; - let send_email_result = state + let magic_link_result = state .email_client .compose_and_send_email( - Box::new(email_contents), + Box::new(magic_link_email), state.conf.proxy.https_url.as_ref(), ) .await; - logger::info!(?send_email_result); + logger::info!(?magic_link_result); + + let welcome_to_community_email = email_types::WelcomeToCommunity { + recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?, + subject: consts::user::EMAIL_SUBJECT_WELCOME_TO_COMMUNITY, + }; + + let welcome_email_result = state + .email_client + .compose_and_send_email( + Box::new(welcome_to_community_email), + state.conf.proxy.https_url.as_ref(), + ) + .await; + + logger::info!(?welcome_email_result); return Ok(ApplicationResponse::Json( user_api::ConnectAccountResponse { - is_email_sent: send_email_result.is_ok(), + is_email_sent: magic_link_result.is_ok(), user_id: user_from_db.get_user_id().to_string(), }, )); diff --git a/crates/router/src/services/email/assets/welcome_to_community.html b/crates/router/src/services/email/assets/welcome_to_community.html new file mode 100644 index 00000000000..05f7fac1d55 --- /dev/null +++ b/crates/router/src/services/email/assets/welcome_to_community.html @@ -0,0 +1,306 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Email Template</title> + <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet"> + <style> + @media only screen and (max-width: 600px) { + .card-container { + display: block !important; + width: 100% !important; + padding: 0 !important; + } + + .card { + width: 100% !important; + max-width: 100% !important; + margin-bottom: 15px !important; + display: block !important; + box-sizing: border-box; + } + + .repocard, + .communitycard, + .devdocs-card { + width: 100% !important; + padding: 0 !important; + margin-bottom: 10px !important; + } + + .card-content { + width: 100% !important; + max-width: 100% !important; + height: auto !important; + min-height: 100px !important; + padding: 20px 0 0 20px !important; + box-sizing: border-box; + } + + + .docscard-content { + width: 100% !important; + max-width: 100% !important; + height: auto !important; + min-height: 100px !important; + padding: 0 20px 0 20px !important; + box-sizing: border-box; + } + + .divider { + width: 100% !important; + padding: 0 !important; + } + + .footer-section { + text-align: center !important; + margin: 0 auto; + width: 100%; + } + + td.card-container, + td.card { + width: 100% !important; + padding: 0 !important; + display: block !important; + } + + .logo-section { + text-align: center !important; + width: 100% !important; + } + + .logo-section img { + display: block; + margin: 0 auto; + } + } + + a.card-link { + text-decoration: none !important; + color: inherit !important; + } + + .card-content td { + color: #151A1F !important; + } + + .card-content td img { + display: block !important; + } + </style> +</head> + +<body style="margin: 0; padding: 0; background-color: #f6f6f8; font-family: 'Inter', Arial, sans-serif;"> + <center> + <table width="100%" cellspacing="0" cellpadding="0" + style="border-spacing: 0; margin: 0; padding: 0; background-color: #f6f6f8;"> + <tr> + <td align="center"> + <table role="presentation" width="600" cellspacing="0" cellpadding="0" class="container" + style="max-width: 600px; background-color: #ffffff; border-radius: 10px; border-collapse: collapse;"> + + <!-- Header Section --> + <tr> + <td align="center" bgcolor="#283652" + style="padding: 40px 30px; color: white; border-top-left-radius: 20px; border-top-right-radius: 20px;"> + <table width="100%" role="presentation" cellspacing="0" cellpadding="0"> + <tr> + <td align="left"> + <img src="https://app.hyperswitch.io/assets/welcome-email/logotext.png" + alt="Hyperswitch Logo" width="150" + style="display: block; margin-bottom: 20px;"> + </td> + </tr> + <tr> + <td align="left" + style="font-size: 36px; line-height: 40px; font-weight: 500; color: white;"> + Welcome to + <span style="font-weight: 700;">Hyperswitch</span> + <img src="https://app.hyperswitch.io/assets/welcome-email/star.png" + alt="Star Icon" width="30" + style="display: inline-block; vertical-align: middle; position: relative; top: -3px; margin-left: -2px;"> + </td> + </tr> + </table> + </td> + </tr> + + <!-- Body Section --> + <tr> + <td align="left" + style="padding: 30px; background-color: #FFFFFF; color: #151A1F; font-size: 16px; font-family: 'Inter', Arial, sans-serif; font-weight: 400; line-height: 23.68px; text-align: left;"> + <p style="margin-bottom: 20px; font-weight: 500;">Hello,</p> + <p style="margin-bottom: 20px;">I wanted to reach out and introduce our community to + you.</p> + <p style="margin-bottom: 20px;">I’m Neeraj. I work in Community Growth here at + Hyperswitch. We are a bunch of passionate people solving for payment diversity, + complexity, and innovation. Juspay, our parent organization, processes 125 Mn + transactions every day and has been providing payment platform solutions to large + digital enterprises for the past 12 years. We wish to empower global businesses to + expand their reach and enhance customer experiences through diverse payment + solutions.</p> + <p style="margin-bottom: 20px;">Our mission is to provide a Fast, Reliable, Affordable & + Transparent payments platform, allowing businesses the flexibility to choose between + open-source and SaaS solution.</p> + </td> + </tr> + + <!-- CTA Cards Section (GitHub & Slack) --> + <tr> + <td align="center" style="padding: 0 30px;"> + <table width="100%" cellspacing="0" cellpadding="0"> + <tr> + <!-- GitHub Repo Card --> + <td width="50%" class="card" valign="top" style="padding-right: 10px;"> + <a href="https://github.com/juspay/hyperswitch" target="_blank" + class="card-link"> + <table class="card-content" width="100%" cellspacing="0" cellpadding="0" + style="background-color: #F6F6F6; border-radius: 16px; padding: 20px 0 0 20px;"> + <tr> + <td align="left" + style="vertical-align: top; font-size: 22px; font-weight: 600; padding-right: 20px;"> + Star <br /> our repo + </td> + <td align="right" + style="vertical-align: top; padding: 0 20px 0 0;"> + <img src="https://app.hyperswitch.io/assets/welcome-email/repoArrow.png" + alt="Arrow Icon" width="24" height="24" + style="border-radius: 50%; padding: 7px; background-color: #fff;"> + </td> + </tr> + <tr> + <td colspan="2" align="right"> + <img src="https://app.hyperswitch.io/assets/welcome-email/github-logo1.png" + alt="GitHub Icon" width="98" height="98" + style="display: block;"> + </td> + </tr> + </table> + </a> + </td> + + <!-- Slack Community Card --> + <td width="50%" class="card" valign="top" style="padding-left: 10px;"> + <a href="https://hyperswitch-io.slack.com/join/shared_invite/zt-2jqxmpsbm-WXUENx022HjNEy~Ark7Orw#/shared-invite/email" + target="_blank" class="card-link"> + <table class="card-content" width="100%" cellspacing="0" cellpadding="0" + style="background-color: #F6F6F6; border-radius: 16px; padding: 20px 0 0 20px;"> + <tr> + <td align="left" + style="vertical-align: top; font-size: 22px; font-weight: 600; padding-right: 20px;"> + Join our <br /> Community + </td> + <td align="right" + style="vertical-align: top; padding: 0 20px 0 0;"> + <img src="https://app.hyperswitch.io/assets/welcome-email/communityArrow.png" + alt="Arrow Icon" width="24" height="24" + style="border-radius: 50%; padding: 7px; background-color: #fff;"> + </td> + </tr> + <tr> + <td colspan="2" align="right"> + <img src="https://app.hyperswitch.io/assets/welcome-email/slack.png" + alt="Slack Icon" width="98" height="98" + style="display: block;"> + </td> + </tr> + </table> + </a> + </td> + </tr> + </table> + </td> + </tr> + + <!-- Read Dev Docs Section --> + <tr> + <td style="padding: 10px 30px 0 30px ;"> + <a href="https://api-reference.hyperswitch.io/introduction" target="_blank" + class="card-link"> + <table class="docscard-content" width="100%" cellspacing="0" cellpadding="0" + style="background-color: #FFEFEF; border-radius: 16px; padding: 20px;"> + <tr> + <td style="vertical-align: middle;"> + <table> + <tr> + <td style="vertical-align: middle;"> + <img src="https://app.hyperswitch.io/assets/welcome-email/docs.png" + alt="docs icon" width="24" height="29" + style="margin-right: 10px;"> + </td> + <td style="vertical-align: middle;"> + <span style="font-size: 22px; font-weight: 600;">Read dev + docs</span> + </td> + </tr> + </table> + </td> + <td align="right" style="vertical-align: middle;"> + <img src="https://app.hyperswitch.io/assets/welcome-email/docsArrow.png" + alt="Arrow Icon" width="24" height="24" + style="border-radius: 50%; padding: 7px; background-color: #fff;"> + </td> + </tr> + </table> + </a> + </td> + </tr> + + <!-- Divider and Footer Section --> + <tr> + <td style="padding: 40px 0 0 0;"> + <!-- Divider (Top Border) --> + <table width="100%" class="divider" cellpadding="0" cellspacing="0" + style="border-top: 1px solid #F2F2F2;"> + <tr> + <td align="center"> + <table cellspacing="0" cellpadding="0" + style="margin: 0 auto; padding: 30px 0; max-width: 378px; width: 100%;"> + <tr> + <td align="center" style="padding: 0;" class="logo-section"> + <img src="https://app.hyperswitch.io/assets/welcome-email/logo.png" + alt="Icon" width="82" height="40" style="display: block;"> + </td> + </tr> + </table> + </td> + </tr> + </table> + </td> + </tr> + + </table> + </td> + </tr> + + <!-- Footer Section with max-width 600px --> + <tr> + <td align="center" style="padding: 16px 4px 0 4px; background-color: #f6f6f8;"> + <table width="100%" cellspacing="0" cellpadding="0" style="max-width: 601px;"> + <tr> + <!-- Follow us on and Social Media Icons --> + <td align="left" + style="font-family: 'Inter', Arial, sans-serif; font-size: 12px; font-weight: 500; line-height: 16px; color: #63605F;"> + Follow us on + <a href="https://x.com/hyperswitchio" + style="margin-right: 10px; text-decoration: none;"> + <img src="https://app.hyperswitch.io/assets/welcome-email/twitter.png" alt="Twitter" + width="14" height="14" style="vertical-align: -3px;"> + </a> + <a href="https://www.linkedin.com/company/hyperswitch/" style="text-decoration: none;"> + <img src="https://app.hyperswitch.io/assets/welcome-email/linkedin.png" + alt="LinkedIn" width="13.33" height="13.33" style="vertical-align: -3px;"> + </a> + </td> + </tr> + </table> + </td> + </tr> + </table> + </center> +</body> + +</html> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index cedd17828f1..d092afdc5de 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -57,6 +57,7 @@ pub enum EmailBody { api_key_name: String, prefix: String, }, + WelcomeToCommunity, } pub mod html { @@ -145,6 +146,9 @@ Email : {user_email} prefix = prefix, expires_in = expires_in, ), + EmailBody::WelcomeToCommunity => { + include_str!("assets/welcome_to_community.html").to_string() + } } } } @@ -505,3 +509,21 @@ impl EmailData for ApiKeyExpiryReminder { }) } } + +pub struct WelcomeToCommunity { + pub recipient_email: domain::UserEmail, + pub subject: &'static str, +} + +#[async_trait::async_trait] +impl EmailData for WelcomeToCommunity { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let body = html::get_html_body(EmailBody::WelcomeToCommunity); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient: self.recipient_email.clone().into_inner(), + }) + } +}
2024-11-22T08:42: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 --> Magic link will send one more email along with magic link email if user is signing up. ### 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 #6638. ## 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)? --> Local SES ![image](https://github.com/user-attachments/assets/f4e15419-31c7-452e-ba77-4a8815944ca0) ``` curl --location 'http://localhost:8080/user/connect_account' \ --header 'Content-Type: application/json' \ --data-raw '{ "email": "new user email" }' ``` The above email should be sent. ## 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
83e8bc0775c20e9d055e65bd13a2e8b1148092e1
juspay/hyperswitch
juspay__hyperswitch-6660
Bug: feat(user_roles): support tenant_id reads For tenancy support tenant_id in user roles queries - Adding tenant id to reads, deletes and updates queries.
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs index ed018cc2381..bb07f671824 100644 --- a/crates/diesel_models/src/query/user_role.rs +++ b/crates/diesel_models/src/query/user_role.rs @@ -1,7 +1,11 @@ use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::id_type; use diesel::{ - associations::HasTable, debug_query, pg::Pg, result::Error as DieselError, + associations::HasTable, + debug_query, + pg::Pg, + result::Error as DieselError, + sql_types::{Bool, Nullable}, BoolExpressionMethods, ExpressionMethods, QueryDsl, }; use error_stack::{report, ResultExt}; @@ -22,89 +26,70 @@ impl UserRoleNew { } impl UserRole { - pub async fn find_by_user_id( - conn: &PgPooledConn, - user_id: String, - version: UserRoleVersion, - ) -> StorageResult<Self> { - generics::generic_find_one::<<Self as HasTable>::Table, _, _>( - conn, - dsl::user_id.eq(user_id).and(dsl::version.eq(version)), - ) - .await - } - - pub async fn find_by_user_id_merchant_id( - conn: &PgPooledConn, - user_id: String, - merchant_id: id_type::MerchantId, - version: UserRoleVersion, - ) -> StorageResult<Self> { - generics::generic_find_one::<<Self as HasTable>::Table, _, _>( - conn, - dsl::user_id - .eq(user_id) - .and(dsl::merchant_id.eq(merchant_id)) - .and(dsl::version.eq(version)), - ) - .await - } - - pub async fn list_by_user_id( - conn: &PgPooledConn, - user_id: String, - version: UserRoleVersion, - ) -> StorageResult<Vec<Self>> { - generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( - conn, - dsl::user_id.eq(user_id).and(dsl::version.eq(version)), - None, - None, - Some(dsl::created_at.asc()), - ) - .await - } - - pub async fn list_by_merchant_id( - conn: &PgPooledConn, - merchant_id: id_type::MerchantId, - version: UserRoleVersion, - ) -> StorageResult<Vec<Self>> { - generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( - conn, - dsl::merchant_id - .eq(merchant_id) - .and(dsl::version.eq(version)), - None, - None, - Some(dsl::created_at.asc()), + fn check_user_in_lineage( + tenant_id: id_type::TenantId, + org_id: Option<id_type::OrganizationId>, + merchant_id: Option<id_type::MerchantId>, + profile_id: Option<id_type::ProfileId>, + ) -> Box< + dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>> + + 'static, + > { + // Checking in user roles, for a user in token hierarchy, only one of the relations will be true: + // either tenant level, org level, merchant level, or profile level + // Tenant-level: (tenant_id = ? && org_id = null && merchant_id = null && profile_id = null) + // Org-level: (org_id = ? && merchant_id = null && profile_id = null) + // Merchant-level: (org_id = ? && merchant_id = ? && profile_id = null) + // Profile-level: (org_id = ? && merchant_id = ? && profile_id = ?) + Box::new( + // Tenant-level condition + dsl::tenant_id + .eq(tenant_id.clone()) + .and(dsl::org_id.is_null()) + .and(dsl::merchant_id.is_null()) + .and(dsl::profile_id.is_null()) + .or( + // Org-level condition + dsl::tenant_id + .eq(tenant_id.clone()) + .and(dsl::org_id.eq(org_id.clone())) + .and(dsl::merchant_id.is_null()) + .and(dsl::profile_id.is_null()), + ) + .or( + // Merchant-level condition + dsl::tenant_id + .eq(tenant_id.clone()) + .and(dsl::org_id.eq(org_id.clone())) + .and(dsl::merchant_id.eq(merchant_id.clone())) + .and(dsl::profile_id.is_null()), + ) + .or( + // Profile-level condition + dsl::tenant_id + .eq(tenant_id) + .and(dsl::org_id.eq(org_id)) + .and(dsl::merchant_id.eq(merchant_id)) + .and(dsl::profile_id.eq(profile_id)), + ), ) - .await } - pub async fn find_by_user_id_org_id_merchant_id_profile_id( + pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, + tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { - // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level - // (org_id = ? && merchant_id = null && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = ?) - let check_lineage = dsl::org_id - .eq(org_id.clone()) - .and(dsl::merchant_id.is_null().and(dsl::profile_id.is_null())) - .or(dsl::org_id.eq(org_id.clone()).and( - dsl::merchant_id - .eq(merchant_id.clone()) - .and(dsl::profile_id.is_null()), - )) - .or(dsl::org_id.eq(org_id).and( - dsl::merchant_id - .eq(merchant_id) - .and(dsl::profile_id.eq(profile_id)), - )); + let check_lineage = Self::check_user_in_lineage( + tenant_id, + Some(org_id), + Some(merchant_id), + Some(profile_id), + ); let predicate = dsl::user_id .eq(user_id) @@ -114,30 +99,46 @@ impl UserRole { generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await } - pub async fn update_by_user_id_org_id_merchant_id_profile_id( + #[allow(clippy::too_many_arguments)] + pub async fn update_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, + tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, update: UserRoleUpdate, version: UserRoleVersion, ) -> StorageResult<Self> { - // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level - // (org_id = ? && merchant_id = null && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = ?) - let check_lineage = dsl::org_id - .eq(org_id.clone()) - .and(dsl::merchant_id.is_null().and(dsl::profile_id.is_null())) - .or(dsl::org_id.eq(org_id.clone()).and( - dsl::merchant_id - .eq(merchant_id.clone()) + let check_lineage = dsl::tenant_id + .eq(tenant_id.clone()) + .and(dsl::org_id.is_null()) + .and(dsl::merchant_id.is_null()) + .and(dsl::profile_id.is_null()) + .or( + // Org-level condition + dsl::tenant_id + .eq(tenant_id.clone()) + .and(dsl::org_id.eq(org_id.clone())) + .and(dsl::merchant_id.is_null()) + .and(dsl::profile_id.is_null()), + ) + .or( + // Merchant-level condition + dsl::tenant_id + .eq(tenant_id.clone()) + .and(dsl::org_id.eq(org_id.clone())) + .and(dsl::merchant_id.eq(merchant_id.clone())) .and(dsl::profile_id.is_null()), - )) - .or(dsl::org_id.eq(org_id).and( - dsl::merchant_id - .eq(merchant_id) + ) + .or( + // Profile-level condition + dsl::tenant_id + .eq(tenant_id) + .and(dsl::org_id.eq(org_id)) + .and(dsl::merchant_id.eq(merchant_id)) .and(dsl::profile_id.eq(profile_id)), - )); + ); let predicate = dsl::user_id .eq(user_id) @@ -153,29 +154,21 @@ impl UserRole { .await } - pub async fn delete_by_user_id_org_id_merchant_id_profile_id( + pub async fn delete_by_user_id_tenant_id_org_id_merchant_id_profile_id( conn: &PgPooledConn, user_id: String, + tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: id_type::MerchantId, profile_id: id_type::ProfileId, version: UserRoleVersion, ) -> StorageResult<Self> { - // Checking in user roles, for a user in token hierarchy, only one of the relation will be true, either org level, merchant level or profile level - // (org_id = ? && merchant_id = null && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = null) || (org_id = ? && merchant_id = ? && profile_id = ?) - let check_lineage = dsl::org_id - .eq(org_id.clone()) - .and(dsl::merchant_id.is_null().and(dsl::profile_id.is_null())) - .or(dsl::org_id.eq(org_id.clone()).and( - dsl::merchant_id - .eq(merchant_id.clone()) - .and(dsl::profile_id.is_null()), - )) - .or(dsl::org_id.eq(org_id).and( - dsl::merchant_id - .eq(merchant_id) - .and(dsl::profile_id.eq(profile_id)), - )); + let check_lineage = Self::check_user_in_lineage( + tenant_id, + Some(org_id), + Some(merchant_id), + Some(profile_id), + ); let predicate = dsl::user_id .eq(user_id) @@ -190,6 +183,7 @@ impl UserRole { pub async fn generic_user_roles_list_for_user( conn: &PgPooledConn, user_id: String, + tenant_id: id_type::TenantId, org_id: Option<id_type::OrganizationId>, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, @@ -199,7 +193,7 @@ impl UserRole { limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() - .filter(dsl::user_id.eq(user_id)) + .filter(dsl::user_id.eq(user_id).and(dsl::tenant_id.eq(tenant_id))) .into_boxed(); if let Some(org_id) = org_id { @@ -248,9 +242,11 @@ impl UserRole { } } + #[allow(clippy::too_many_arguments)] pub async fn generic_user_roles_list_for_org_and_extra( conn: &PgPooledConn, user_id: Option<String>, + tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, @@ -258,7 +254,7 @@ impl UserRole { limit: Option<u32>, ) -> StorageResult<Vec<Self>> { let mut query = <Self as HasTable>::table() - .filter(dsl::org_id.eq(org_id)) + .filter(dsl::org_id.eq(org_id).and(dsl::tenant_id.eq(tenant_id))) .into_boxed(); if let Some(user_id) = user_id { diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index 96f41f75ee0..d957c3071ff 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -1864,6 +1864,7 @@ pub mod routes { .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, + tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: Some(&auth.org_id), merchant_id: None, profile_id: None, @@ -1987,6 +1988,7 @@ pub mod routes { .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &auth.user_id, + tenant_id: auth.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: Some(&auth.org_id), merchant_id: None, profile_id: None, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index 2087d01dbb4..53db3cf07e1 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -614,6 +614,10 @@ async fn handle_existing_user_invitation( .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -630,6 +634,10 @@ async fn handle_existing_user_invitation( .global_store .find_user_role_by_user_id_and_lineage( invitee_user_from_db.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -660,6 +668,10 @@ async fn handle_existing_user_invitation( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: invitee_user_from_db.get_user_id(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id, profile_id, @@ -962,6 +974,10 @@ pub async fn resend_invite( .global_store .find_user_role_by_user_id_and_lineage( user.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -985,6 +1001,10 @@ pub async fn resend_invite( .global_store .find_user_role_by_user_id_and_lineage( user.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -1064,6 +1084,10 @@ pub async fn accept_invite_from_email_token_only_flow( utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_token.user_id, + user_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), entity.entity_id.clone(), entity.entity_type, ) @@ -1074,6 +1098,10 @@ pub async fn accept_invite_from_email_token_only_flow( let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_from_db.get_user_id(), + user_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &org_id, merchant_id.as_ref(), profile_id.as_ref(), @@ -1260,6 +1288,10 @@ pub async fn list_user_roles_details( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: required_user.get_user_id(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_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), @@ -2435,6 +2467,10 @@ pub async fn list_orgs_for_user( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, @@ -2500,6 +2536,10 @@ pub async fn list_merchants_for_user_in_org( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: None, profile_id: None, @@ -2579,6 +2619,10 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_token.user_id.as_str(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&user_from_token.merchant_id), profile_id: None, @@ -2655,6 +2699,10 @@ pub async fn switch_org_for_user( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: Some(&request.org_id), merchant_id: None, profile_id: None, @@ -2828,6 +2876,10 @@ pub async fn switch_merchant_for_user_in_org( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&request.merchant_id), profile_id: None, @@ -2944,6 +2996,10 @@ pub async fn switch_profile_for_user_in_org_and_merchant( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload{ user_id:&user_from_token.user_id, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: Some(&user_from_token.org_id), merchant_id: Some(&user_from_token.merchant_id), profile_id:Some(&request.profile_id), diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs index 6641e553fd8..eaa655a07f3 100644 --- a/crates/router/src/core/user_role.rs +++ b/crates/router/src/core/user_role.rs @@ -159,6 +159,10 @@ pub async fn update_user_role( .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -213,6 +217,10 @@ pub async fn update_user_role( .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), @@ -232,6 +240,10 @@ pub async fn update_user_role( .global_store .find_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -286,6 +298,10 @@ pub async fn update_user_role( .global_store .update_user_role_by_user_id_and_lineage( user_to_be_updated.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, Some(&user_from_token.merchant_id), Some(&user_from_token.profile_id), @@ -320,6 +336,10 @@ pub async fn accept_invitations_v2( utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_from_token.user_id, + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), entity.entity_id, entity.entity_type, ) @@ -335,6 +355,10 @@ pub async fn accept_invitations_v2( utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_from_token.user_id.as_str(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id.as_ref(), profile_id.as_ref(), @@ -372,6 +396,10 @@ pub async fn accept_invitations_pre_auth( utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite( &state, &user_token.user_id, + user_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), entity.entity_id, entity.entity_type, ) @@ -387,6 +415,10 @@ pub async fn accept_invitations_pre_auth( utils::user_role::update_v1_and_v2_user_roles_in_db( &state, user_token.user_id.as_str(), + user_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id, merchant_id.as_ref(), profile_id.as_ref(), @@ -473,6 +505,10 @@ pub async fn delete_user_role( .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -520,6 +556,10 @@ pub async fn delete_user_role( .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -535,6 +575,10 @@ pub async fn delete_user_role( .global_store .find_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -582,6 +626,10 @@ pub async fn delete_user_role( .global_store .delete_user_role_by_user_id_and_lineage( user_from_db.get_user_id(), + user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), &user_from_token.org_id, &user_from_token.merchant_id, &user_from_token.profile_id, @@ -602,6 +650,11 @@ pub async fn delete_user_role( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user_from_db.get_user_id(), + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), + org_id: None, merchant_id: None, profile_id: None, @@ -650,6 +703,10 @@ pub async fn list_users_in_lineage( &state, ListUserRolesByOrgIdPayload { user_id: None, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: None, profile_id: None, @@ -665,6 +722,10 @@ pub async fn list_users_in_lineage( &state, ListUserRolesByOrgIdPayload { user_id: None, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: None, @@ -680,6 +741,10 @@ pub async fn list_users_in_lineage( &state, ListUserRolesByOrgIdPayload { user_id: None, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: &user_from_token.org_id, merchant_id: Some(&user_from_token.merchant_id), profile_id: Some(&user_from_token.profile_id), @@ -779,6 +844,10 @@ pub async fn list_invitations_for_user( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: &user_from_token.user_id, + tenant_id: user_from_token + .tenant_id + .as_ref() + .unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs index a9df1abbc08..8b7e7dc0306 100644 --- a/crates/router/src/db/kafka_store.rs +++ b/crates/router/src/db/kafka_store.rs @@ -3048,6 +3048,7 @@ impl UserRoleInterface for KafkaStore { async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, @@ -3056,6 +3057,7 @@ impl UserRoleInterface for KafkaStore { self.diesel_store .find_user_role_by_user_id_and_lineage( user_id, + tenant_id, org_id, merchant_id, profile_id, @@ -3067,6 +3069,7 @@ impl UserRoleInterface for KafkaStore { async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, @@ -3076,6 +3079,7 @@ impl UserRoleInterface for KafkaStore { self.diesel_store .update_user_role_by_user_id_and_lineage( user_id, + tenant_id, org_id, merchant_id, profile_id, @@ -3088,6 +3092,7 @@ impl UserRoleInterface for KafkaStore { async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, @@ -3096,6 +3101,7 @@ impl UserRoleInterface for KafkaStore { self.diesel_store .delete_user_role_by_user_id_and_lineage( user_id, + tenant_id, org_id, merchant_id, profile_id, diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs index e4e564dc9a4..0da51898326 100644 --- a/crates/router/src/db/user_role.rs +++ b/crates/router/src/db/user_role.rs @@ -15,6 +15,7 @@ use crate::{ pub struct ListUserRolesByOrgIdPayload<'a> { pub user_id: Option<&'a String>, + pub tenant_id: &'a id_type::TenantId, pub org_id: &'a id_type::OrganizationId, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, @@ -24,6 +25,7 @@ pub struct ListUserRolesByOrgIdPayload<'a> { pub struct ListUserRolesByUserIdPayload<'a> { pub user_id: &'a str, + pub tenant_id: &'a id_type::TenantId, pub org_id: Option<&'a id_type::OrganizationId>, pub merchant_id: Option<&'a id_type::MerchantId>, pub profile_id: Option<&'a id_type::ProfileId>, @@ -43,15 +45,18 @@ pub trait UserRoleInterface { async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError>; + #[allow(clippy::too_many_arguments)] async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, @@ -62,6 +67,7 @@ pub trait UserRoleInterface { async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, @@ -98,15 +104,17 @@ impl UserRoleInterface for Store { async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; - storage::UserRole::find_by_user_id_org_id_merchant_id_profile_id( + storage::UserRole::find_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), + tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), @@ -120,6 +128,7 @@ impl UserRoleInterface for Store { async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, @@ -127,9 +136,10 @@ impl UserRoleInterface for Store { version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::update_by_user_id_org_id_merchant_id_profile_id( + storage::UserRole::update_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), + tenant_id.to_owned(), org_id.to_owned(), merchant_id.cloned(), profile_id.cloned(), @@ -144,15 +154,17 @@ impl UserRoleInterface for Store { async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, version: enums::UserRoleVersion, ) -> CustomResult<storage::UserRole, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; - storage::UserRole::delete_by_user_id_org_id_merchant_id_profile_id( + storage::UserRole::delete_by_user_id_tenant_id_org_id_merchant_id_profile_id( &conn, user_id.to_owned(), + tenant_id.to_owned(), org_id.to_owned(), merchant_id.to_owned(), profile_id.to_owned(), @@ -170,6 +182,7 @@ impl UserRoleInterface for Store { storage::UserRole::generic_user_roles_list_for_user( &conn, payload.user_id.to_owned(), + payload.tenant_id.to_owned(), payload.org_id.cloned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), @@ -190,6 +203,7 @@ impl UserRoleInterface for Store { storage::UserRole::generic_user_roles_list_for_org_and_extra( &conn, payload.user_id.cloned(), + payload.tenant_id.to_owned(), payload.org_id.to_owned(), payload.merchant_id.cloned(), payload.profile_id.cloned(), @@ -243,6 +257,7 @@ impl UserRoleInterface for MockDb { async fn find_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, @@ -251,21 +266,32 @@ impl UserRoleInterface for MockDb { let user_roles = self.user_roles.lock().await; for user_role in user_roles.iter() { - let org_level_check = user_role.org_id.as_ref() == Some(org_id) + let tenant_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.is_none() && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); - let merchant_level_check = user_role.org_id.as_ref() == Some(org_id) + let org_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.as_ref() == Some(org_id) + && user_role.merchant_id.is_none() + && user_role.profile_id.is_none(); + + let merchant_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.is_none(); - let profile_level_check = user_role.org_id.as_ref() == Some(org_id) + let profile_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == Some(merchant_id) && user_role.profile_id.as_ref() == Some(profile_id); // Check if any condition matches and the version matches if user_role.user_id == user_id - && (org_level_check || merchant_level_check || profile_level_check) + && (tenant_level_check + || org_level_check + || merchant_level_check + || profile_level_check) && user_role.version == version { return Ok(user_role.clone()); @@ -282,6 +308,7 @@ impl UserRoleInterface for MockDb { async fn update_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, @@ -291,21 +318,32 @@ impl UserRoleInterface for MockDb { let mut user_roles = self.user_roles.lock().await; for user_role in user_roles.iter_mut() { - let org_level_check = user_role.org_id.as_ref() == Some(org_id) + let tenant_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.is_none() + && user_role.merchant_id.is_none() + && user_role.profile_id.is_none(); + + let org_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.is_none() && user_role.profile_id.is_none(); - let merchant_level_check = user_role.org_id.as_ref() == Some(org_id) + let merchant_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.is_none(); - let profile_level_check = user_role.org_id.as_ref() == Some(org_id) + let profile_level_check = user_role.tenant_id == *tenant_id + && user_role.org_id.as_ref() == Some(org_id) && user_role.merchant_id.as_ref() == merchant_id && user_role.profile_id.as_ref() == profile_id; - // Check if the user role matches the conditions and the version matches + // Check if any condition matches and the version matches if user_role.user_id == user_id - && (org_level_check || merchant_level_check || profile_level_check) + && (tenant_level_check + || org_level_check + || merchant_level_check + || profile_level_check) && user_role.version == version { match &update { @@ -336,6 +374,7 @@ impl UserRoleInterface for MockDb { async fn delete_user_role_by_user_id_and_lineage( &self, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, profile_id: &id_type::ProfileId, @@ -345,21 +384,32 @@ impl UserRoleInterface for MockDb { // Find the position of the user role to delete let index = user_roles.iter().position(|role| { - let org_level_check = role.org_id.as_ref() == Some(org_id) + let tenant_level_check = role.tenant_id == *tenant_id + && role.org_id.is_none() + && role.merchant_id.is_none() + && role.profile_id.is_none(); + + let org_level_check = role.tenant_id == *tenant_id + && role.org_id.as_ref() == Some(org_id) && role.merchant_id.is_none() && role.profile_id.is_none(); - let merchant_level_check = role.org_id.as_ref() == Some(org_id) + let merchant_level_check = role.tenant_id == *tenant_id + && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.is_none(); - let profile_level_check = role.org_id.as_ref() == Some(org_id) + let profile_level_check = role.tenant_id == *tenant_id + && role.org_id.as_ref() == Some(org_id) && role.merchant_id.as_ref() == Some(merchant_id) && role.profile_id.as_ref() == Some(profile_id); // Check if the user role matches the conditions and the version matches role.user_id == user_id - && (org_level_check || merchant_level_check || profile_level_check) + && (tenant_level_check + || org_level_check + || merchant_level_check + || profile_level_check) && role.version == version }); diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index c05e4514aaa..d50933b708d 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -273,6 +273,7 @@ pub struct UserFromToken { pub struct UserIdFromAuth { pub user_id: String, + pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] @@ -858,6 +859,7 @@ where Ok(( UserIdFromAuth { user_id: payload.user_id.clone(), + tenant_id: payload.tenant_id, }, AuthenticationType::SinglePurposeOrLoginJwt { user_id: payload.user_id, @@ -899,6 +901,7 @@ where Ok(( UserIdFromAuth { user_id: payload.user_id.clone(), + tenant_id: payload.tenant_id, }, AuthenticationType::SinglePurposeOrLoginJwt { user_id: payload.user_id, diff --git a/crates/router/src/types/domain/user/decision_manager.rs b/crates/router/src/types/domain/user/decision_manager.rs index 634c781da7f..10990da6ccb 100644 --- a/crates/router/src/types/domain/user/decision_manager.rs +++ b/crates/router/src/types/domain/user/decision_manager.rs @@ -1,4 +1,5 @@ use common_enums::TokenPurpose; +use common_utils::id_type; use diesel_models::{enums::UserStatus, user_role::UserRole}; use error_stack::{report, ResultExt}; use masking::Secret; @@ -24,9 +25,10 @@ impl UserFlow { user: &UserFromStorage, path: &[TokenPurpose], state: &SessionState, + user_tenant_id: &id_type::TenantId, ) -> UserResult<bool> { match self { - Self::SPTFlow(flow) => flow.is_required(user, path, state).await, + Self::SPTFlow(flow) => flow.is_required(user, path, state, user_tenant_id).await, Self::JWTFlow(flow) => flow.is_required(user, state).await, } } @@ -50,6 +52,7 @@ impl SPTFlow { user: &UserFromStorage, path: &[TokenPurpose], state: &SessionState, + user_tenant_id: &id_type::TenantId, ) -> UserResult<bool> { match self { // Auth @@ -68,6 +71,7 @@ impl SPTFlow { .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: user.get_user_id(), + tenant_id: user_tenant_id, org_id: None, merchant_id: None, profile_id: None, @@ -220,6 +224,7 @@ pub struct CurrentFlow { origin: Origin, current_flow_index: usize, path: Vec<TokenPurpose>, + tenant_id: Option<id_type::TenantId>, } impl CurrentFlow { @@ -239,6 +244,7 @@ impl CurrentFlow { origin: token.origin, current_flow_index: index, path, + tenant_id: token.tenant_id, }) } @@ -247,12 +253,21 @@ impl CurrentFlow { let remaining_flows = flows.iter().skip(self.current_flow_index + 1); for flow in remaining_flows { - if flow.is_required(&user, &self.path, state).await? { + if flow + .is_required( + &user, + &self.path, + state, + self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), + ) + .await? + { return Ok(NextFlow { origin: self.origin.clone(), next_flow: *flow, user, path: self.path, + tenant_id: self.tenant_id, }); } } @@ -265,6 +280,7 @@ pub struct NextFlow { next_flow: UserFlow, user: UserFromStorage, path: Vec<TokenPurpose>, + tenant_id: Option<id_type::TenantId>, } impl NextFlow { @@ -276,12 +292,16 @@ impl NextFlow { let flows = origin.get_flows(); let path = vec![]; for flow in flows { - if flow.is_required(&user, &path, state).await? { + if flow + .is_required(&user, &path, state, &state.tenant.tenant_id) + .await? + { return Ok(Self { origin, next_flow: *flow, user, path, + tenant_id: Some(state.tenant.tenant_id.clone()), }); } } @@ -304,6 +324,7 @@ impl NextFlow { .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id: self.user.get_user_id(), + tenant_id: self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), org_id: None, merchant_id: None, profile_id: None, @@ -352,12 +373,16 @@ impl NextFlow { .ok_or(UserErrors::InternalServerError)?; let remaining_flows = flows.iter().skip(index + 1); for flow in remaining_flows { - if flow.is_required(&user, &self.path, state).await? { + if flow + .is_required(&user, &self.path, state, &state.tenant.tenant_id) + .await? + { return Ok(Self { origin: self.origin.clone(), next_flow: *flow, user, path: self.path, + tenant_id: Some(state.tenant.tenant_id.clone()), }); } } diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index aaf313a196e..0bd0e81149f 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -133,6 +133,7 @@ pub async fn set_role_permissions_in_cache_if_required( pub async fn update_v1_and_v2_user_roles_in_db( state: &SessionState, user_id: &str, + tenant_id: &id_type::TenantId, org_id: &id_type::OrganizationId, merchant_id: Option<&id_type::MerchantId>, profile_id: Option<&id_type::ProfileId>, @@ -145,6 +146,7 @@ pub async fn update_v1_and_v2_user_roles_in_db( .global_store .update_user_role_by_user_id_and_lineage( user_id, + tenant_id, org_id, merchant_id, profile_id, @@ -161,6 +163,7 @@ pub async fn update_v1_and_v2_user_roles_in_db( .global_store .update_user_role_by_user_id_and_lineage( user_id, + tenant_id, org_id, merchant_id, profile_id, @@ -210,6 +213,7 @@ pub async fn get_single_merchant_id( pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( state: &SessionState, user_id: &str, + tenant_id: &id_type::TenantId, entity_id: String, entity_type: EntityType, ) -> UserResult< @@ -231,6 +235,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, + tenant_id, org_id: Some(&org_id), merchant_id: None, profile_id: None, @@ -275,6 +280,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, + tenant_id, org_id: None, merchant_id: Some(&merchant_id), profile_id: None, @@ -320,6 +326,7 @@ pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, + tenant_id: &state.tenant.tenant_id, org_id: None, merchant_id: None, profile_id: Some(&profile_id),
2024-11-26T09:27:22Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [x] New feature - [x] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Support tenant id in user roles queries. ### 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 [#6660](https://github.com/juspay/hyperswitch/issues/6660) ## How did you test it? With tenancy feature flag enabled these changes will be tested when upcoming tenant related PRs from dashboard gets merged. The current behaviour of user apis should not change. Since hyperswitch has its own tenant id and we don't have tenant_id feature flag enabled for now. Tested the sanity flows for users. Working as expected. ## 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
b1c4e30e929fb8d31d854765d5f1ddad5e77f065
juspay/hyperswitch
juspay__hyperswitch-6629
Bug: fix: merchant order ref id filter and refund_id filter - Add merchant_order reference id filter for payments list - Fix refunds list filter, search by refund id. (It is construction a totally new filter ignoring the merchant id when searching)
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 98bc7b754a4..a5fc687ef28 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -4923,6 +4923,8 @@ pub struct PaymentListFilterConstraints { pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, + /// The identifier for merchant order reference id + pub merchant_order_reference_id: Option<String>, } impl PaymentListFilterConstraints { diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs index 4f2053ec6f9..e706c4ae45a 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs @@ -1002,6 +1002,7 @@ pub struct PaymentIntentListParams { pub limit: Option<u32>, pub order: api_models::payments::Order, pub card_network: Option<Vec<storage_enums::CardNetwork>>, + pub merchant_order_reference_id: Option<String>, } impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints { @@ -1036,6 +1037,7 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)), order: Default::default(), card_network: None, + merchant_order_reference_id: None, })) } } @@ -1061,6 +1063,7 @@ impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints { limit: None, order: Default::default(), card_network: None, + merchant_order_reference_id: None, })) } } @@ -1084,6 +1087,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF merchant_connector_id, order, card_network, + merchant_order_reference_id, } = value; if let Some(payment_intent_id) = payment_id { Self::Single { payment_intent_id } @@ -1107,6 +1111,7 @@ impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentF limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)), order, card_network, + merchant_order_reference_id, })) } } diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs index 2d42aaa0a8a..cf1ff52960f 100644 --- a/crates/router/src/types/storage/dispute.rs +++ b/crates/router/src/types/storage/dispute.rs @@ -1,6 +1,6 @@ use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; -use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; pub use diesel_models::dispute::{Dispute, DisputeNew, DisputeUpdate}; use diesel_models::{errors, query::generics::db_metrics, schema::dispute::dsl}; use error_stack::ResultExt; @@ -43,9 +43,11 @@ impl DisputeDbExt for Dispute { &dispute_list_constraints.dispute_id, ) { search_by_payment_or_dispute_id = true; - filter = filter - .filter(dsl::payment_id.eq(payment_id.to_owned())) - .or_filter(dsl::dispute_id.eq(dispute_id.to_owned())); + filter = filter.filter( + dsl::payment_id + .eq(payment_id.to_owned()) + .or(dsl::dispute_id.eq(dispute_id.to_owned())), + ); }; if !search_by_payment_or_dispute_id { diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs index 8076c2c7a6e..e46fc1a3f47 100644 --- a/crates/router/src/types/storage/refund.rs +++ b/crates/router/src/types/storage/refund.rs @@ -1,7 +1,7 @@ use api_models::payments::AmountFilter; use async_bb8_diesel::AsyncRunQueryDsl; use common_utils::errors::CustomResult; -use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; +use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl}; pub use diesel_models::refund::{ Refund, RefundCoreWorkflow, RefundNew, RefundUpdate, RefundUpdateInternal, }; @@ -67,8 +67,11 @@ impl RefundDbExt for Refund { ) { search_by_pay_or_ref_id = true; filter = filter - .filter(dsl::payment_id.eq(pid.to_owned())) - .or_filter(dsl::refund_id.eq(ref_id.to_owned())) + .filter( + dsl::payment_id + .eq(pid.to_owned()) + .or(dsl::refund_id.eq(ref_id.to_owned())), + ) .limit(limit) .offset(offset); }; @@ -228,9 +231,11 @@ impl RefundDbExt for Refund { &refund_list_details.refund_id, ) { search_by_pay_or_ref_id = true; - filter = filter - .filter(dsl::payment_id.eq(pid.to_owned())) - .or_filter(dsl::refund_id.eq(ref_id.to_owned())); + filter = filter.filter( + dsl::payment_id + .eq(pid.to_owned()) + .or(dsl::refund_id.eq(ref_id.to_owned())), + ); }; if !search_by_pay_or_ref_id { diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index f26cf876ade..15f1aa24370 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -871,6 +871,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } + if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { + query = query.filter( + pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), + ) + } + if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } @@ -1041,6 +1047,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> { if let Some(customer_id) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } + if let Some(merchant_order_reference_id) = &params.merchant_order_reference_id { + query = query.filter( + pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()), + ) + } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); }
2024-11-21T10:51:13Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [x] Bugfix - [x] New feature - [ ] Enhancement - [ ] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description The PR - Add merchant order reference id filter for payments list - Fix bug for search by refund id (or payment_id), using `or` instead of `or_filter`. Earlier we were searching in whole list, ignoring the filter previously applied in the query. However this was the only case for when we were searching dynamically for ids, it can be payment or refund id. It was producing correct result when searching for only payment id or only refund 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 Closes [#6629](https://github.com/juspay/hyperswitch/issues/6629) ## How did you test it? Merchant Order filter is working as expected Request ``` curl --location 'http://localhost:8080/payments/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "merchant_order_reference_id": "test" }' ``` Response: ``` { "count": 1, "total_count": 1, "data": [ { "payment_id": "test_rkAjUPAeyOVH0V1JPBcg", "merchant_id": "merchant_1732182386", "status": "succeeded", "amount": 19900, "net_amount": 19900, "shipping_cost": null, "amount_capturable": 0, "amount_received": null, "connector": "stripe_test", "client_secret": "test_rkAjUPAeyOVH0V1JPBcg_secret_s8xZQVITYn3CT5RKTiUj", "created": "2024-11-20T22:30:10.000Z", "currency": "USD", "customer_id": "hs-dashboard-user", "customer": null, "description": "This is a sample payment", "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": "card", "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": "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": "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": null, "connector_transaction_id": "test_rkAjUPAeyOVH0V1JPBcg_1", "frm_message": null, "metadata": null, "connector_metadata": null, "feature_metadata": null, "reference_id": null, "payment_link": null, "profile_id": "pro_7J9fiPceBUM7IMdb045X", "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": "test", "order_tax_amount": null, "connector_mandate_id": null } ] } ``` In refunds list when dynamically searching for both payment_id and refund_id, we are getting correct result now ``` curl --location 'http://localhost:8080/refunds/list' \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ --header 'Authorization: Bearer JWT' \ --data '{ "refund_id": "test_LlBBfgQbHHJfQxsoLiyT", "payment_id": "test_LlBBfgQbHHJfQxsoLiyT" }' ``` 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
f24578310f44adf75c993ba42225554377399961
juspay/hyperswitch
juspay__hyperswitch-6642
Bug: refactor(tenant): use tenant id type Refactor: Use tenant_id type instead of string for better type safety
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 3d57a72376e..a8085564145 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -12,6 +12,7 @@ mod payment; mod profile; mod refunds; mod routing; +mod tenant; #[cfg(feature = "v2")] mod global_id; @@ -40,6 +41,7 @@ pub use profile::ProfileId; pub use refunds::RefundReferenceId; pub use routing::RoutingId; use serde::{Deserialize, Serialize}; +pub use tenant::TenantId; use thiserror::Error; use crate::{fp_utils::when, generate_id_with_default_len}; diff --git a/crates/common_utils/src/id_type/organization.rs b/crates/common_utils/src/id_type/organization.rs index a83f35db1d8..2097fbb2450 100644 --- a/crates/common_utils/src/id_type/organization.rs +++ b/crates/common_utils/src/id_type/organization.rs @@ -18,7 +18,7 @@ crate::impl_to_sql_from_sql_id_type!(OrganizationId); impl OrganizationId { /// Get an organization id from String - pub fn wrap(org_id: String) -> CustomResult<Self, ValidationError> { + pub fn try_from_string(org_id: String) -> CustomResult<Self, ValidationError> { Self::try_from(std::borrow::Cow::from(org_id)) } } diff --git a/crates/common_utils/src/id_type/tenant.rs b/crates/common_utils/src/id_type/tenant.rs new file mode 100644 index 00000000000..953bf82287a --- /dev/null +++ b/crates/common_utils/src/id_type/tenant.rs @@ -0,0 +1,22 @@ +use crate::errors::{CustomResult, ValidationError}; + +crate::id_type!( + TenantId, + "A type for tenant_id that can be used for unique identifier for a tenant" +); +crate::impl_id_type_methods!(TenantId, "tenant_id"); + +// This is to display the `TenantId` as TenantId(abcd) +crate::impl_debug_id_type!(TenantId); +crate::impl_try_from_cow_str_id_type!(TenantId, "tenant_id"); + +crate::impl_serializable_secret_id_type!(TenantId); +crate::impl_queryable_id_type!(TenantId); +crate::impl_to_sql_from_sql_id_type!(TenantId); + +impl TenantId { + /// Get tenant id from String + pub fn try_from_string(tenant_id: String) -> CustomResult<Self, ValidationError> { + Self::try_from(std::borrow::Cow::from(tenant_id)) + } +} diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs index 03b4cf23a6c..9ad9206acce 100644 --- a/crates/common_utils/src/types/theme.rs +++ b/crates/common_utils/src/types/theme.rs @@ -12,15 +12,15 @@ pub enum ThemeLineage { // }, /// Org lineage variant Organization { - /// tenant_id: String - tenant_id: String, + /// tenant_id: TenantId + tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, }, /// Merchant lineage variant Merchant { - /// tenant_id: String - tenant_id: String, + /// tenant_id: TenantId + tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId @@ -28,8 +28,8 @@ pub enum ThemeLineage { }, /// Profile lineage variant Profile { - /// tenant_id: String - tenant_id: String, + /// tenant_id: TenantId + tenant_id: id_type::TenantId, /// org_id: OrganizationId org_id: id_type::OrganizationId, /// merchant_id: MerchantId diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs index 2f8152e419c..9841e21443c 100644 --- a/crates/diesel_models/src/user/theme.rs +++ b/crates/diesel_models/src/user/theme.rs @@ -9,7 +9,7 @@ use crate::schema::themes; #[diesel(table_name = themes, primary_key(theme_id), check_for_backend(diesel::pg::Pg))] pub struct Theme { pub theme_id: String, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, @@ -23,7 +23,7 @@ pub struct Theme { #[diesel(table_name = themes)] pub struct ThemeNew { pub theme_id: String, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: Option<id_type::OrganizationId>, pub merchant_id: Option<id_type::MerchantId>, pub profile_id: Option<id_type::ProfileId>, diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs index ceddbfd61e4..04f3264b45e 100644 --- a/crates/diesel_models/src/user_role.rs +++ b/crates/diesel_models/src/user_role.rs @@ -24,7 +24,7 @@ pub struct UserRole { pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, } impl UserRole { @@ -88,7 +88,7 @@ pub struct UserRoleNew { pub entity_id: Option<String>, pub entity_type: Option<EntityType>, pub version: enums::UserRoleVersion, - pub tenant_id: String, + pub tenant_id: id_type::TenantId, } #[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs index d8a8bff5afc..d0c26195453 100644 --- a/crates/drainer/src/handler.rs +++ b/crates/drainer/src/handler.rs @@ -3,6 +3,7 @@ use std::{ sync::{atomic, Arc}, }; +use common_utils::id_type; use router_env::tracing::Instrument; use tokio::{ sync::{mpsc, oneshot}, @@ -34,12 +35,15 @@ pub struct HandlerInner { loop_interval: Duration, active_tasks: Arc<atomic::AtomicU64>, conf: DrainerSettings, - stores: HashMap<String, Arc<Store>>, + stores: HashMap<id_type::TenantId, Arc<Store>>, running: Arc<atomic::AtomicBool>, } impl Handler { - pub fn from_conf(conf: DrainerSettings, stores: HashMap<String, Arc<Store>>) -> Self { + pub fn from_conf( + conf: DrainerSettings, + stores: HashMap<id_type::TenantId, Arc<Store>>, + ) -> Self { let shutdown_interval = Duration::from_millis(conf.shutdown_interval.into()); let loop_interval = Duration::from_millis(conf.loop_interval.into()); diff --git a/crates/drainer/src/health_check.rs b/crates/drainer/src/health_check.rs index 48d5f311905..2ca2c1cc79c 100644 --- a/crates/drainer/src/health_check.rs +++ b/crates/drainer/src/health_check.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, sync::Arc}; use actix_web::{web, Scope}; use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl}; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, id_type}; use diesel_models::{Config, ConfigNew}; use error_stack::ResultExt; use router_env::{instrument, logger, tracing}; @@ -20,7 +20,7 @@ pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")]; pub struct Health; impl Health { - pub fn server(conf: Settings, stores: HashMap<String, Arc<Store>>) -> Scope { + pub fn server(conf: Settings, stores: HashMap<id_type::TenantId, Arc<Store>>) -> Scope { web::scope("health") .app_data(web::Data::new(conf)) .app_data(web::Data::new(stores)) diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index 5b67640663c..6eb8c505e15 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -14,7 +14,7 @@ use std::{collections::HashMap, sync::Arc}; mod secrets_transformers; use actix_web::dev::Server; -use common_utils::signals::get_allowed_signals; +use common_utils::{id_type, signals::get_allowed_signals}; use diesel_models::kv; use error_stack::ResultExt; use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret; @@ -31,7 +31,7 @@ use crate::{ }; pub async fn start_drainer( - stores: HashMap<String, Arc<Store>>, + stores: HashMap<id_type::TenantId, Arc<Store>>, conf: DrainerSettings, ) -> errors::DrainerResult<()> { let drainer_handler = handler::Handler::from_conf(conf, stores); @@ -62,7 +62,7 @@ pub async fn start_drainer( pub async fn start_web_server( conf: Settings, - stores: HashMap<String, Arc<Store>>, + stores: HashMap<id_type::TenantId, Arc<Store>>, ) -> Result<Server, errors::DrainerError> { let server = conf.server.clone(); let web_server = actix_web::HttpServer::new(move || { diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs index 5b391b492e0..9b6c88b3466 100644 --- a/crates/drainer/src/settings.rs +++ b/crates/drainer/src/settings.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, path::PathBuf, sync::Arc}; -use common_utils::{ext_traits::ConfigExt, DbConnectionParams}; +use common_utils::{ext_traits::ConfigExt, id_type, DbConnectionParams}; use config::{Environment, File}; use external_services::managers::{ encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig, @@ -122,23 +122,23 @@ pub struct Multitenancy { pub tenants: TenantConfig, } impl Multitenancy { - pub fn get_tenants(&self) -> &HashMap<String, Tenant> { + pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } - pub fn get_tenant_ids(&self) -> Vec<String> { + pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } - pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> { + pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } #[derive(Debug, Clone, Default)] -pub struct TenantConfig(pub HashMap<String, Tenant>); +pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); impl<'de> Deserialize<'de> for TenantConfig { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { @@ -150,7 +150,7 @@ impl<'de> Deserialize<'de> for TenantConfig { clickhouse_database: String, } - let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?; + let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap @@ -172,9 +172,9 @@ impl<'de> Deserialize<'de> for TenantConfig { } } -#[derive(Debug, Deserialize, Clone, Default)] +#[derive(Debug, Deserialize, Clone)] pub struct Tenant { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub redis_key_prefix: String, diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 76b58f5b67b..7b212ec6d1d 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; +use common_utils::{ext_traits::ConfigExt, id_type}; use config::{Environment, File}; use error_stack::ResultExt; #[cfg(feature = "email")] @@ -138,17 +138,17 @@ pub struct Multitenancy { } impl Multitenancy { - pub fn get_tenants(&self) -> &HashMap<String, Tenant> { + pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> { &self.tenants.0 } - pub fn get_tenant_ids(&self) -> Vec<String> { + pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> { self.tenants .0 .values() .map(|tenant| tenant.tenant_id.clone()) .collect() } - pub fn get_tenant(&self, tenant_id: &str) -> Option<&Tenant> { + pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> { self.tenants.0.get(tenant_id) } } @@ -159,11 +159,11 @@ pub struct DecisionConfig { } #[derive(Debug, Clone, Default)] -pub struct TenantConfig(pub HashMap<String, Tenant>); +pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>); -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct Tenant { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub base_url: String, pub schema: String, pub redis_key_prefix: String, @@ -743,8 +743,7 @@ pub struct LockerBasedRecipientConnectorList { #[derive(Debug, Deserialize, Clone, Default)] pub struct ConnectorRequestReferenceIdConfig { - pub merchant_ids_send_payment_id_as_connector_request_id: - HashSet<common_utils::id_type::MerchantId>, + pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<id_type::MerchantId>, } #[derive(Debug, Deserialize, Clone, Default)] @@ -970,7 +969,7 @@ pub struct ServerTls { #[cfg(feature = "v2")] #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct CellInformation { - pub id: common_utils::id_type::CellId, + pub id: id_type::CellId, } #[cfg(feature = "v2")] @@ -981,8 +980,8 @@ impl Default for CellInformation { // 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_string("defid") - .expect("Failed to create a default for Cell Id"); + let cell_id = + id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id"); Self { id: cell_id } } } @@ -1120,7 +1119,7 @@ impl<'de> Deserialize<'de> for TenantConfig { clickhouse_database: String, } - let hashmap = <HashMap<String, Inner>>::deserialize(deserializer)?; + let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index c0f54a30f3f..c3fbfd8afbf 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -389,7 +389,7 @@ pub async fn mk_add_locker_request_hs( locker: &settings::Locker, payload: &StoreLockerReq, locker_choice: api_enums::LockerChoice, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let payload = payload @@ -409,7 +409,10 @@ 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()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -584,7 +587,7 @@ 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, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = customer_id.to_owned(); @@ -612,7 +615,10 @@ 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()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -665,7 +671,7 @@ pub async fn mk_delete_card_request_hs( customer_id: &id_type::CustomerId, merchant_id: &id_type::MerchantId, card_reference: &str, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = customer_id.to_owned(); @@ -691,7 +697,10 @@ 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()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -711,7 +720,7 @@ pub async fn mk_delete_card_request_hs_by_id( id: &String, merchant_id: &id_type::MerchantId, card_reference: &str, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let merchant_customer_id = id.to_owned(); @@ -737,7 +746,10 @@ 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()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, @@ -832,7 +844,7 @@ pub fn mk_crud_locker_request( locker: &settings::Locker, path: &str, req: api::TokenizePayloadEncrypted, - tenant_id: String, + tenant_id: id_type::TenantId, request_id: Option<RequestId>, ) -> CustomResult<services::Request, errors::VaultError> { let mut url = locker.basilisk_host.to_owned(); @@ -840,7 +852,10 @@ pub fn mk_crud_locker_request( 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()); + request.add_header( + headers::X_TENANT_ID, + tenant_id.get_string_repr().to_owned().into(), + ); if let Some(req_id) = request_id { request.add_header( headers::X_REQUEST_ID, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index aef89ea8ed9..264328796c8 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -751,7 +751,10 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( &metrics::CONTEXT, 1, &add_attributes([ - ("tenant", state.tenant.tenant_id.clone()), + ( + "tenant", + state.tenant.tenant_id.get_string_repr().to_owned(), + ), ( "merchant_profile_id", format!( diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index bff6205f5db..78f5682fd7f 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -1105,11 +1105,15 @@ pub async fn create_internal_user( } })?; - let default_tenant_id = common_utils::consts::DEFAULT_TENANT.to_string(); + let default_tenant_id = common_utils::id_type::TenantId::try_from_string( + common_utils::consts::DEFAULT_TENANT.to_owned(), + ) + .change_context(UserErrors::InternalServerError) + .attach_printable("Unable to parse default tenant id")?; if state.tenant.tenant_id != default_tenant_id { return Err(UserErrors::ForbiddenTenantId) - .attach_printable("Operation allowed only for the default tenant."); + .attach_printable("Operation allowed only for the default tenant"); } let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id( diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs index 651c2ece610..6bb7de1b7d9 100644 --- a/crates/router/src/db/events.rs +++ b/crates/router/src/db/events.rs @@ -732,7 +732,10 @@ mod tests { )) .await; let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let merchant_id = common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1")) diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index be2c25d4767..687f6e8fea2 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -1502,8 +1502,12 @@ mod merchant_connector_account_cache_tests { Box::new(services::MockApiClient), )) .await; + let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) @@ -1685,7 +1689,10 @@ mod merchant_connector_account_cache_tests { )) .await; let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); #[allow(clippy::expect_used)] let db = MockDb::new(&redis_interface::RedisSettings::default()) diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs index 65a5515a391..9f12ec8e8fd 100644 --- a/crates/router/src/db/merchant_key_store.rs +++ b/crates/router/src/db/merchant_key_store.rs @@ -348,7 +348,10 @@ mod tests { )) .await; let state = &Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); #[allow(clippy::expect_used)] let mock_db = MockDb::new(&redis_interface::RedisSettings::default()) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index baa2ba4ae15..1584cfae2b9 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -7,6 +7,7 @@ use api_models::routing::RoutingRetrieveQuery; use common_enums::TransactionType; #[cfg(feature = "partial-auth")] use common_utils::crypto::Blake3; +use common_utils::id_type; #[cfg(feature = "email")] use external_services::email::{ no_email::NoEmailClient, ses::AwsSes, smtp::SmtpServer, EmailClientConfigs, EmailService, @@ -193,14 +194,14 @@ impl SessionStateInfo for SessionState { pub struct AppState { pub flow_name: String, pub global_store: Box<dyn GlobalStorageInterface>, - pub stores: HashMap<String, Box<dyn StorageInterface>>, + pub stores: HashMap<id_type::TenantId, Box<dyn StorageInterface>>, pub conf: Arc<settings::Settings<RawSecret>>, pub event_handler: EventsHandler, #[cfg(feature = "email")] pub email_client: Arc<Box<dyn EmailService>>, pub api_client: Box<dyn crate::services::ApiClient>, #[cfg(feature = "olap")] - pub pools: HashMap<String, AnalyticsProvider>, + pub pools: HashMap<id_type::TenantId, AnalyticsProvider>, #[cfg(feature = "olap")] pub opensearch_client: Arc<OpenSearchClient>, pub request_id: Option<RequestId>, @@ -209,7 +210,7 @@ pub struct AppState { pub grpc_client: Arc<GrpcClients>, } impl scheduler::SchedulerAppState for AppState { - fn get_tenants(&self) -> Vec<String> { + fn get_tenants(&self) -> Vec<id_type::TenantId> { self.conf.multitenancy.get_tenant_ids() } } @@ -328,7 +329,7 @@ impl AppState { ); #[cfg(feature = "olap")] - let mut pools: HashMap<String, AnalyticsProvider> = HashMap::new(); + let mut pools: HashMap<id_type::TenantId, AnalyticsProvider> = HashMap::new(); let mut stores = HashMap::new(); #[allow(clippy::expect_used)] let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable) @@ -443,7 +444,11 @@ impl AppState { .await } - pub fn get_session_state<E, F>(self: Arc<Self>, tenant: &str, err: F) -> Result<SessionState, E> + pub fn get_session_state<E, F>( + self: Arc<Self>, + tenant: &id_type::TenantId, + err: F, + ) -> Result<SessionState, E> where F: FnOnce() -> E + Copy, { diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index bdd650389a7..9416ff175a8 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -68,7 +68,7 @@ use crate::{ api_logs::{ApiEvent, ApiEventMetric, ApiEventsType}, connector_api_logs::ConnectorEvent, }, - logger, + headers, logger, routes::{ app::{AppStateInfo, ReqState, SessionStateInfo}, metrics, AppState, SessionState, @@ -722,33 +722,44 @@ where let mut event_type = payload.get_api_event_type(); let tenant_id = if !state.conf.multitenancy.enabled { - DEFAULT_TENANT.to_string() + common_utils::id_type::TenantId::try_from_string(DEFAULT_TENANT.to_owned()) + .attach_printable("Unable to get default tenant id") + .change_context(errors::ApiErrorResponse::InternalServerError.switch())? } else { let request_tenant_id = incoming_request_header .get(TENANT_HEADER) .and_then(|value| value.to_str().ok()) - .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())?; + .ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch()) + .and_then(|header_value| { + common_utils::id_type::TenantId::try_from_string(header_value.to_string()).map_err( + |_| { + errors::ApiErrorResponse::InvalidRequestData { + message: format!("`{}` header is invalid", headers::X_TENANT_ID), + } + .switch() + }, + ) + })?; state .conf .multitenancy - .get_tenant(request_tenant_id) + .get_tenant(&request_tenant_id) .map(|tenant| tenant.tenant_id.clone()) .ok_or( errors::ApiErrorResponse::InvalidTenant { - tenant_id: request_tenant_id.to_string(), + tenant_id: request_tenant_id.get_string_repr().to_string(), } .switch(), )? }; - let mut session_state = - Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || { - errors::ApiErrorResponse::InvalidTenant { - tenant_id: tenant_id.clone(), - } - .switch() - })?; + let mut session_state = Arc::new(app_state.clone()).get_session_state(&tenant_id, || { + errors::ApiErrorResponse::InvalidTenant { + tenant_id: tenant_id.get_string_repr().to_string(), + } + .switch() + })?; session_state.add_request_id(request_id); let mut request_state = session_state.get_req_state(); @@ -757,9 +768,10 @@ where .event_context .record_info(("flow".to_string(), flow.to_string())); - request_state - .event_context - .record_info(("tenant_id".to_string(), tenant_id.to_string())); + request_state.event_context.record_info(( + "tenant_id".to_string(), + tenant_id.get_string_repr().to_string(), + )); // Currently auth failures are not recorded as API events let (auth_out, auth_type) = api_auth diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 2541a5dc7d4..2f5f55b8434 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -185,7 +185,7 @@ pub struct UserFromSinglePurposeToken { pub user_id: String, pub origin: domain::Origin, pub path: Vec<TokenPurpose>, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] @@ -196,7 +196,7 @@ pub struct SinglePurposeToken { pub origin: domain::Origin, pub path: Vec<TokenPurpose>, pub exp: u64, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] @@ -207,7 +207,7 @@ impl SinglePurposeToken { origin: domain::Origin, settings: &Settings, path: Vec<TokenPurpose>, - tenant_id: Option<String>, + tenant_id: Option<id_type::TenantId>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS); @@ -232,7 +232,7 @@ pub struct AuthToken { pub exp: u64, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } #[cfg(feature = "olap")] @@ -244,7 +244,7 @@ impl AuthToken { settings: &Settings, org_id: id_type::OrganizationId, profile_id: id_type::ProfileId, - tenant_id: Option<String>, + tenant_id: Option<id_type::TenantId>, ) -> UserResult<String> { let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS); let exp = jwt::generate_exp(exp_duration)?.as_secs(); @@ -268,7 +268,7 @@ pub struct UserFromToken { pub role_id: String, pub org_id: id_type::OrganizationId, pub profile_id: id_type::ProfileId, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } pub struct UserIdFromAuth { @@ -282,7 +282,7 @@ pub struct SinglePurposeOrLoginToken { pub role_id: Option<String>, pub purpose: Option<TokenPurpose>, pub exp: u64, - pub tenant_id: Option<String>, + pub tenant_id: Option<id_type::TenantId>, } pub trait AuthInfo { @@ -1110,7 +1110,7 @@ impl<'a> HeaderMapStruct<'a> { self.get_mandatory_header_value_by_key(headers::X_ORGANIZATION_ID) .map(|val| val.to_owned()) .and_then(|organization_id| { - id_type::OrganizationId::wrap(organization_id).change_context( + id_type::OrganizationId::try_from_string(organization_id).change_context( errors::ApiErrorResponse::InvalidRequestData { message: format!("`{}` header is invalid", headers::X_ORGANIZATION_ID), }, diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs index 35a0b159ab2..87ff9f6abd5 100644 --- a/crates/router/src/services/authorization.rs +++ b/crates/router/src/services/authorization.rs @@ -112,12 +112,16 @@ pub fn check_permission( ) } -pub fn check_tenant(token_tenant_id: Option<String>, header_tenant_id: &str) -> RouterResult<()> { +pub fn check_tenant( + token_tenant_id: Option<id_type::TenantId>, + header_tenant_id: &id_type::TenantId, +) -> RouterResult<()> { if let Some(tenant_id) = token_tenant_id { - if tenant_id != header_tenant_id { + if tenant_id != *header_tenant_id { return Err(ApiErrorResponse::InvalidJwtToken).attach_printable(format!( "Token tenant ID: '{}' does not match Header tenant ID: '{}'", - tenant_id, header_tenant_id + tenant_id.get_string_repr().to_owned(), + header_tenant_id.get_string_repr().to_owned() )); } } diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 4cb69e68ed8..6d0d2a4ea07 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1106,20 +1106,20 @@ pub struct NoLevel; #[derive(Clone)] pub struct OrganizationLevel { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, } #[derive(Clone)] pub struct MerchantLevel { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, } #[derive(Clone)] pub struct ProfileLevel { - pub tenant_id: String, + pub tenant_id: id_type::TenantId, pub org_id: id_type::OrganizationId, pub merchant_id: id_type::MerchantId, pub profile_id: id_type::ProfileId, @@ -1156,7 +1156,7 @@ impl NewUserRole<NoLevel> { } pub struct EntityInfo { - tenant_id: String, + tenant_id: id_type::TenantId, org_id: id_type::OrganizationId, merchant_id: Option<id_type::MerchantId>, profile_id: Option<id_type::ProfileId>, diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs index 8a9daefb287..f115a16c062 100644 --- a/crates/router/src/utils/user.rs +++ b/crates/router/src/utils/user.rs @@ -92,7 +92,7 @@ pub async fn generate_jwt_auth_token_with_attributes( org_id: id_type::OrganizationId, role_id: String, profile_id: id_type::ProfileId, - tenant_id: Option<String>, + tenant_id: Option<id_type::TenantId>, ) -> UserResult<Secret<String>> { let token = AuthToken::new_token( user_id, diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs index 8c3f34cd1e1..55b92b4aace 100644 --- a/crates/router/tests/cache.rs +++ b/crates/router/tests/cache.rs @@ -18,7 +18,10 @@ async fn invalidate_existing_cache_success() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let cache_key = "cacheKey".to_string(); let cache_key_value = "val".to_string(); diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 6f4855d1e22..9dfd331b72a 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -216,7 +216,10 @@ async fn payments_create_success() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); use router::connector::Aci; @@ -263,7 +266,10 @@ async fn payments_create_failure() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let connector = utils::construct_connector_data_old( Box::new(Aci::new()), @@ -326,7 +332,10 @@ async fn refund_for_successful_payments() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< types::api::Authorize, @@ -396,7 +405,10 @@ async fn refunds_create_failure() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let connector_integration: services::BoxedRefundConnectorIntegrationInterface< types::api::Execute, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 52218b211ac..383b4db358c 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -599,7 +599,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -639,7 +642,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -680,7 +686,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -720,7 +729,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -811,7 +823,10 @@ pub trait ConnectorActions: Connector { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let res = services::api::execute_connector_processing_step( &state, @@ -848,7 +863,10 @@ async fn call_connector< )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); services::api::execute_connector_processing_step( &state, diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs index df4340a353e..68ca08c8bd3 100644 --- a/crates/router/tests/payments.rs +++ b/crates/router/tests/payments.rs @@ -295,7 +295,10 @@ async fn payments_create_core() { let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap(); let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let key_manager_state = &(&state).into(); let key_store = state @@ -552,7 +555,10 @@ async fn payments_create_core_adyen_no_redirect() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let payment_id = diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs index b5962d454fa..90fe3a1f847 100644 --- a/crates/router/tests/payments2.rs +++ b/crates/router/tests/payments2.rs @@ -56,7 +56,10 @@ async fn payments_create_core() { let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap(); let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let key_manager_state = &(&state).into(); let key_store = state @@ -321,7 +324,10 @@ async fn payments_create_core_adyen_no_redirect() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let customer_id = format!("cust_{}", Uuid::new_v4()); diff --git a/crates/router/tests/services.rs b/crates/router/tests/services.rs index d907000cccd..c014370b24f 100644 --- a/crates/router/tests/services.rs +++ b/crates/router/tests/services.rs @@ -18,7 +18,10 @@ async fn get_redis_conn_failure() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); let _ = state.store.get_redis_conn().map(|conn| { @@ -46,7 +49,10 @@ async fn get_redis_conn_success() { )) .await; let state = Arc::new(app_state) - .get_session_state("public", || {}) + .get_session_state( + &common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(), + || {}, + ) .unwrap(); // Act diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs index 5791edd31b0..846f1137b12 100644 --- a/crates/scheduler/src/consumer.rs +++ b/crates/scheduler/src/consumer.rs @@ -7,7 +7,7 @@ use std::{ pub mod types; pub mod workflows; -use common_utils::{errors::CustomResult, signals::get_allowed_signals}; +use common_utils::{errors::CustomResult, id_type, signals::get_allowed_signals}; use diesel_models::enums; pub use diesel_models::{self, process_tracker as storage}; use error_stack::ResultExt; @@ -42,7 +42,7 @@ pub async fn start_consumer<T: SchedulerAppState + 'static, U: SchedulerSessionS app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where - F: Fn(&T, &str) -> CustomResult<U, errors::ProcessTrackerError>, + F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, { use std::time::Duration; @@ -88,7 +88,7 @@ where let start_time = std_time::Instant::now(); let tenants = state.get_tenants(); for tenant in tenants { - let session_state = app_state_to_session_state(state, tenant.as_str())?; + let session_state = app_state_to_session_state(state, &tenant)?; pt_utils::consumer_operation_handler( session_state.clone(), settings.clone(), diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rs index 6f710f55a34..b91434fcbb0 100644 --- a/crates/scheduler/src/producer.rs +++ b/crates/scheduler/src/producer.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, id_type}; use diesel_models::enums::ProcessTrackerStatus; use error_stack::{report, ResultExt}; use router_env::{ @@ -27,7 +27,7 @@ pub async fn start_producer<T, U, F>( app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where - F: Fn(&T, &str) -> CustomResult<U, errors::ProcessTrackerError>, + F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, T: SchedulerAppState, U: SchedulerSessionState, { @@ -69,7 +69,7 @@ where interval.tick().await; let tenants = state.get_tenants(); for tenant in tenants { - let session_state = app_state_to_session_state(state, tenant.as_str())?; + let session_state = app_state_to_session_state(state, &tenant)?; match run_producer_flow(&session_state, &scheduler_settings).await { Ok(_) => (), Err(error) => { diff --git a/crates/scheduler/src/scheduler.rs b/crates/scheduler/src/scheduler.rs index 39a45d02ba9..2685c6311ea 100644 --- a/crates/scheduler/src/scheduler.rs +++ b/crates/scheduler/src/scheduler.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use common_utils::errors::CustomResult; +use common_utils::{errors::CustomResult, id_type}; use storage_impl::mock_db::MockDb; #[cfg(feature = "kv_store")] use storage_impl::KVRouterStore; @@ -52,7 +52,7 @@ impl SchedulerInterface for MockDb {} #[async_trait::async_trait] pub trait SchedulerAppState: Send + Sync + Clone { - fn get_tenants(&self) -> Vec<String>; + fn get_tenants(&self) -> Vec<id_type::TenantId>; } #[async_trait::async_trait] pub trait SchedulerSessionState: Send + Sync + Clone { @@ -71,7 +71,7 @@ pub async fn start_process_tracker< app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where - F: Fn(&T, &str) -> CustomResult<U, errors::ProcessTrackerError>, + F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, { match scheduler_flow { SchedulerFlow::Producer => {
2024-11-22T12:01:12Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [x] Refactoring - [ ] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description Use tenant_id type for better type safety ### 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 [#6642](https://github.com/juspay/hyperswitch/issues/6642) ## How did you test it? It refactoring PR, its compiling and checks are passing Tested flows like signup/signin with tenancy featue flag enabled and disabled in local ## 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
8d0639ea6f22227253a44e6bd8272d9e55d17f92
juspay/hyperswitch
juspay__hyperswitch-6626
Bug: fix(analytics): remove `first_attempt` group by in Payment Intent old metrics `first_attempt` as a group by is getting added internally in the queries as it is required by the new PaymentIntent based metrics for Analytics V2 Dashboard. The logic was added for the existing older metrics as well for PaymentIntents on the older dashboard, and is failing when using sqlx as the Pool. Need to remove the logic for adding `first_attempt` as a group_by in the older metrics, and also tweak the manner in which this is getting added as a group_by in the new metrics.
diff --git a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs index cf733b0c3da..696dd6a584b 100644 --- a/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/payment_processed_amount.rs @@ -59,10 +59,6 @@ where }) .switch()?; - query_builder - .add_select_column("attempt_count == 1 as first_attempt") - .switch()?; - query_builder.add_select_column("currency").switch()?; query_builder @@ -102,11 +98,6 @@ where .switch()?; } - query_builder - .add_group_by_clause("attempt_count") - .attach_printable("Error grouping by attempt_count") - .switch()?; - query_builder .add_group_by_clause("currency") .attach_printable("Error grouping by currency") diff --git a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs index 07b1bfcf69f..4bb9dc36b07 100644 --- a/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs +++ b/crates/analytics/src/payment_intents/metrics/payments_success_rate.rs @@ -57,10 +57,6 @@ where }) .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", @@ -90,11 +86,6 @@ 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) 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 index 2ba75ca8519..0f13ff39af7 100644 --- 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 @@ -59,7 +59,7 @@ where .switch()?; query_builder - .add_select_column("attempt_count == 1 as first_attempt") + .add_select_column("(attempt_count = 1) as first_attempt") .switch()?; query_builder.add_select_column("currency").switch()?; query_builder @@ -98,8 +98,8 @@ where } query_builder - .add_group_by_clause("attempt_count") - .attach_printable("Error grouping by attempt_count") + .add_group_by_clause("first_attempt") + .attach_printable("Error grouping by first_attempt") .switch()?; query_builder .add_group_by_clause("currency") 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 index 0b55c101a7c..437b22aac71 100644 --- a/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs +++ b/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_distribution.rs @@ -59,7 +59,7 @@ where .switch()?; query_builder - .add_select_column("attempt_count == 1 as first_attempt") + .add_select_column("(attempt_count = 1) as first_attempt") .switch()?; query_builder 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 index 8c340d0b2d6..9716c7ce4de 100644 --- 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 @@ -58,7 +58,7 @@ where .switch()?; query_builder - .add_select_column("(attempt_count == 1) as first_attempt".to_string()) + .add_select_column("(attempt_count = 1) as first_attempt".to_string()) .switch()?; query_builder 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 index b92b7356924..c6d7c59f240 100644 --- 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 @@ -60,7 +60,7 @@ where .switch()?; query_builder - .add_select_column("attempt_count == 1 as first_attempt") + .add_select_column("(attempt_count = 1) as first_attempt") .switch()?; query_builder.add_select_column("currency").switch()?; @@ -105,7 +105,7 @@ where .switch()?; query_builder .add_group_by_clause("currency") - .attach_printable("Error grouping by first_attempt") + .attach_printable("Error grouping by currency") .switch()?; if let Some(granularity) = granularity.as_ref() { granularity 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 ac08f59f358..f8acb2e6e9a 100644 --- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs +++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs @@ -59,9 +59,6 @@ where }) .switch()?; - query_builder - .add_select_column("attempt_count == 1 as first_attempt") - .switch()?; query_builder.add_select_column("currency").switch()?; query_builder .add_select_column(Aggregate::Min { @@ -98,10 +95,6 @@ where .switch()?; } - query_builder - .add_group_by_clause("first_attempt") - .attach_printable("Error grouping by first_attempt") - .switch()?; query_builder .add_group_by_clause("currency") .attach_printable("Error grouping by currency")
2024-11-21T08:35:38Z
## 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 --> `first_attempt` as a group by is getting added internally in the queries as it is required by the new PaymentIntent based metrics for Analytics V2 Dashboard. The logic was added for the existing older metrics as well for PaymentIntents on the older dashboard, and is failing when using sqlx as the Pool. Need to remove the logic for adding `first_attempt` as a group_by in the older metrics, and also tweak the manner in which this is getting added as a group_by in the new metrics. ### 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 error when using older metrics on the old dashboard (PaymentIntent based metrics) ## 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)? --> Hit the curls to test the various metrics. Sessionized_metrics should be tested only on clickhouse. Older metricss can be tested on both sqlx and clickhouse. ```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.eyJ1c2VyX2lkIjoiNTQ5ZTNkMmItMTY5Yi00NzUzLWJmNTQtZDcxMTM2YjRiN2JkIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzI2MDQ2MzI4Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTczMjI3OTExOSwib3JnX2lkIjoib3JnX1ZwU0hPanNZZkR2YWJWWUpnQ0FKIiwicHJvZmlsZV9pZCI6InByb192NXNGb0hlODBPZWlVbElvbm9jTSIsInRlbmFudF9pZCI6InB1YmxpYyJ9.c3u-icFmoDrNwBzR5Av3IiK-tNktGLZarVxSqg3-LgY' \ --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-11-14T18:30:00Z", "endTime": "2024-11-22T15:24:00Z" }, "mode": "ORDER", "source": "BATCH", "metrics": [ "smart_retried_amount", "payments_success_rate", "payment_processed_amount", "sessionized_smart_retried_amount", "sessionized_payments_success_rate", "sessionized_payment_processed_amount", "sessionized_payments_distribution" ] } ]' ``` API should not fail, and should give out response as expected. ```json { "queryData": [ { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": null, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": null, "payment_intent_count": null, "successful_payments": 15, "successful_payments_without_smart_retries": 7, "total_payments": 15, "payments_success_rate": 100.0, "payments_success_rate_without_smart_retries": 46.666666666666664, "payment_processed_amount": 0, "payment_processed_amount_in_usd": null, "payment_processed_count": null, "payment_processed_amount_without_smart_retries": 0, "payment_processed_amount_without_smart_retries_in_usd": null, "payment_processed_count_without_smart_retries": null, "payments_success_rate_distribution_without_smart_retries": 87.5, "payments_failure_rate_distribution_without_smart_retries": 0.0, "status": null, "currency": null, "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" }, { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": 0, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 40000, "payment_processed_amount_in_usd": 40000, "payment_processed_count": 4, "payment_processed_amount_without_smart_retries": 20000, "payment_processed_amount_without_smart_retries_in_usd": 20000, "payment_processed_count_without_smart_retries": 2, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "USD", "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" }, { "successful_smart_retries": null, "total_smart_retries": null, "smart_retried_amount": 0, "smart_retried_amount_in_usd": 0, "smart_retried_amount_without_smart_retries": 0, "smart_retried_amount_without_smart_retries_in_usd": 0, "payment_intent_count": null, "successful_payments": null, "successful_payments_without_smart_retries": null, "total_payments": null, "payments_success_rate": null, "payments_success_rate_without_smart_retries": null, "payment_processed_amount": 110000, "payment_processed_amount_in_usd": 1302, "payment_processed_count": 11, "payment_processed_amount_without_smart_retries": 50000, "payment_processed_amount_without_smart_retries_in_usd": 591, "payment_processed_count_without_smart_retries": 5, "payments_success_rate_distribution_without_smart_retries": null, "payments_failure_rate_distribution_without_smart_retries": null, "status": null, "currency": "INR", "profile_id": null, "connector": null, "auth_type": null, "payment_method": null, "payment_method_type": null, "card_network": null, "merchant_id": null, "card_last_4": null, "card_issuer": null, "error_reason": null, "time_range": { "start_time": "2024-11-14T18:30:00.000Z", "end_time": "2024-11-22T15:24:00.000Z" }, "time_bucket": "2024-11-14 18:30:00" } ], "metaData": [ { "total_success_rate": 100.0, "total_success_rate_without_smart_retries": 46.666666666666664, "total_smart_retried_amount": 0, "total_smart_retried_amount_without_smart_retries": 0, "total_payment_processed_amount": 150000, "total_payment_processed_amount_without_smart_retries": 70000, "total_smart_retried_amount_in_usd": 0, "total_smart_retried_amount_without_smart_retries_in_usd": 0, "total_payment_processed_amount_in_usd": 41302, "total_payment_processed_amount_without_smart_retries_in_usd": 20591, "total_payment_processed_count": 15, "total_payment_processed_count_without_smart_retries": 7 } ] } ``` ## 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
f24578310f44adf75c993ba42225554377399961
juspay/hyperswitch
juspay__hyperswitch-6623
Bug: Address `CVE-2024-21538` in Cypress https://vulert.com/vuln-db/CVE-2024-21538
diff --git a/cypress-tests-v2/package-lock.json b/cypress-tests-v2/package-lock.json index 36f801468a9..cac88cab055 100644 --- a/cypress-tests-v2/package-lock.json +++ b/cypress-tests-v2/package-lock.json @@ -10,7 +10,7 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.15.2", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", "nanoid": "^5.0.8", @@ -727,8 +727,8 @@ "license": "MIT" }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "license": "MIT", @@ -742,9 +742,9 @@ } }, "node_modules/cypress": { - "version": "13.15.2", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.15.2.tgz", - "integrity": "sha512-ARbnUorjcCM3XiPwgHKuqsyr5W9Qn+pIIBPaoilnoBkLdSC2oLQjV1BUpnmc7KR+b7Avah3Ly2RMFnfxr96E/A==", + "version": "13.16.0", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.16.0.tgz", + "integrity": "sha512-g6XcwqnvzXrqiBQR/5gN+QsyRmKRhls1y5E42fyOvsmU7JuY+wM6uHJWj4ZPttjabzbnRvxcik2WemR8+xT6FA==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -1057,7 +1057,7 @@ "dev": true, "license": "MIT", "dependencies": { - "cross-spawn": "^7.0.0", + "cross-spawn": "^7.0.6", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", diff --git a/cypress-tests-v2/package.json b/cypress-tests-v2/package.json index 20403f9e777..37a51db93cb 100644 --- a/cypress-tests-v2/package.json +++ b/cypress-tests-v2/package.json @@ -15,7 +15,7 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.15.2", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", "prettier": "^3.3.2",
2024-11-21T07:17:18Z
## Type of Change <!-- Put an `x` in the boxes that apply --> - [ ] Bugfix - [ ] New feature - [ ] Enhancement - [ ] Refactoring - [x] Dependency updates - [ ] Documentation - [ ] CI/CD ## Description <!-- Describe your changes in detail --> This PR update Cypress packages to address [CVE-2024-21538](https://vulert.com/vuln-db/CVE-2024-21538). Closes https://github.com/juspay/hyperswitch/issues/6623 ### 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). --> CVE. ## 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)? --> No tests needed as it is just a dependency update. CI passing should be enough. ## 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
f24578310f44adf75c993ba42225554377399961
juspay/hyperswitch
juspay__hyperswitch-6620
Bug: feat(themes): Support naming themes Currently themes don't have names, and it's better to have a way to attach a name to a theme. So that we can know about theme without having to look at the theme data.
diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs index a2e6fe4b19c..03b4cf23a6c 100644 --- a/crates/common_utils/src/types/theme.rs +++ b/crates/common_utils/src/types/theme.rs @@ -4,11 +4,12 @@ use crate::id_type; /// Currently being used for theme related APIs and queries. #[derive(Debug)] pub enum ThemeLineage { - /// Tenant lineage variant - Tenant { - /// tenant_id: String - tenant_id: String, - }, + // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType + // /// Tenant lineage variant + // Tenant { + // /// tenant_id: String + // tenant_id: String, + // }, /// Org lineage variant Organization { /// tenant_id: String diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs index c021edca325..78fd5025ef9 100644 --- a/crates/diesel_models/src/query/user/theme.rs +++ b/crates/diesel_models/src/query/user/theme.rs @@ -3,7 +3,7 @@ use diesel::{ associations::HasTable, pg::Pg, sql_types::{Bool, Nullable}, - BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, + BoolExpressionMethods, ExpressionMethods, }; use crate::{ @@ -27,14 +27,15 @@ impl Theme { + 'static, > { match lineage { - ThemeLineage::Tenant { tenant_id } => Box::new( - dsl::tenant_id - .eq(tenant_id) - .and(dsl::org_id.is_null()) - .and(dsl::merchant_id.is_null()) - .and(dsl::profile_id.is_null()) - .nullable(), - ), + // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType + // ThemeLineage::Tenant { tenant_id } => Box::new( + // dsl::tenant_id + // .eq(tenant_id) + // .and(dsl::org_id.is_null()) + // .and(dsl::merchant_id.is_null()) + // .and(dsl::profile_id.is_null()) + // .nullable(), + // ), ThemeLineage::Organization { tenant_id, org_id } => Box::new( dsl::tenant_id .eq(tenant_id) diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 19a0763d770..4b3a374090e 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1279,6 +1279,10 @@ diesel::table! { profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + entity_type -> Varchar, + #[max_length = 64] + theme_name -> Varchar, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index e3097f80db9..21f112ea37c 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -1225,6 +1225,10 @@ diesel::table! { profile_id -> Nullable<Varchar>, created_at -> Timestamp, last_modified_at -> Timestamp, + #[max_length = 64] + entity_type -> Varchar, + #[max_length = 64] + theme_name -> Varchar, } } diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs index 0824ae71919..2f8152e419c 100644 --- a/crates/diesel_models/src/user/theme.rs +++ b/crates/diesel_models/src/user/theme.rs @@ -1,3 +1,4 @@ +use common_enums::EntityType; use common_utils::id_type; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use time::PrimitiveDateTime; @@ -14,6 +15,8 @@ pub struct Theme { pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub entity_type: EntityType, + pub theme_name: String, } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] @@ -26,4 +29,6 @@ pub struct ThemeNew { pub profile_id: Option<id_type::ProfileId>, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, + pub entity_type: EntityType, + pub theme_name: String, } diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs index d71b82cdea4..f1e4f4f794e 100644 --- a/crates/router/src/db/user/theme.rs +++ b/crates/router/src/db/user/theme.rs @@ -65,12 +65,13 @@ impl ThemeInterface for Store { fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool { match lineage { - ThemeLineage::Tenant { tenant_id } => { - &theme.tenant_id == tenant_id - && theme.org_id.is_none() - && theme.merchant_id.is_none() - && theme.profile_id.is_none() - } + // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType + // ThemeLineage::Tenant { tenant_id } => { + // &theme.tenant_id == tenant_id + // && theme.org_id.is_none() + // && theme.merchant_id.is_none() + // && theme.profile_id.is_none() + // } ThemeLineage::Organization { tenant_id, org_id } => { &theme.tenant_id == tenant_id && theme @@ -156,6 +157,8 @@ impl ThemeInterface for MockDb { profile_id: new_theme.profile_id, created_at: new_theme.created_at, last_modified_at: new_theme.last_modified_at, + entity_type: new_theme.entity_type, + theme_name: new_theme.theme_name, }; themes.push(theme.clone()); diff --git a/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/down.sql b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/down.sql new file mode 100644 index 00000000000..a56426b60c0 --- /dev/null +++ b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE themes DROP COLUMN IF EXISTS entity_type; +ALTER TABLE themes DROP COLUMN IF EXISTS theme_name; diff --git a/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql new file mode 100644 index 00000000000..924385d45d6 --- /dev/null +++ b/migrations/2024-11-20-110014_add-entity-type-and-theme-name-in-themes/up.sql @@ -0,0 +1,3 @@ +-- Your SQL goes here +ALTER TABLE themes ADD COLUMN IF NOT EXISTS entity_type VARCHAR(64) NOT NULL; +ALTER TABLE themes ADD COLUMN IF NOT EXISTS theme_name VARCHAR(64) NOT NULL;
2024-11-20T12:13:51Z
## 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 --> This PR adds `theme_name` and `entity_type` in the themes table. This will help us in 1. Having a name for the theme. 2. EntityType identifier to help us identity the lineage type instead of guessing it. ### Additional Changes - [ ] 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` 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 #6620. ## 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 is an internal change and doesn't affect any APIs. ## 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
43d87913ab3d177a6d193b3e475c96609cc09a28
juspay/hyperswitch
juspay__hyperswitch-6625
Bug: Feature(routing): Stats table for dynamic_routing ## Description Creation of new table for storing required fields for dynamic_routing for list and point queries.
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs index c4c2f072b1e..eeb67d679ee 100644 --- a/crates/api_models/src/routing.rs +++ b/crates/api_models/src/routing.rs @@ -740,7 +740,6 @@ pub struct ToggleDynamicRoutingPath { #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct EliminationRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, - // pub labels: Option<Vec<String>>, pub elimination_analyser_config: Option<EliminationAnalyserConfig>, } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index d966902af89..adb1f453aae 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -20,7 +20,9 @@ pub mod diesel_exports { DbMandateStatus as MandateStatus, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType, DbRefundStatus as RefundStatus, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, - DbScaExemptionType as ScaExemptionType, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbScaExemptionType as ScaExemptionType, + DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, + DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } @@ -3280,10 +3282,20 @@ pub enum DeleteStatus { } #[derive( - Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, Hash, + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + Hash, + strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] +#[router_derive::diesel_enum(storage_type = "db_enum")] pub enum SuccessBasedRoutingConclusiveState { // pc: payment connector // sc: success based routing outcome/first connector diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rs new file mode 100644 index 00000000000..168699d7f56 --- /dev/null +++ b/crates/diesel_models/src/dynamic_routing_stats.rs @@ -0,0 +1,41 @@ +use diesel::{Insertable, Queryable, Selectable}; + +use crate::schema::dynamic_routing_stats; + +#[derive(Clone, Debug, Eq, Insertable, PartialEq)] +#[diesel(table_name = dynamic_routing_stats)] +pub struct DynamicRoutingStatsNew { + pub payment_id: common_utils::id_type::PaymentId, + pub attempt_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub amount: common_utils::types::MinorUnit, + pub success_based_routing_connector: String, + pub payment_connector: String, + pub currency: Option<common_enums::Currency>, + pub payment_method: Option<common_enums::PaymentMethod>, + pub capture_method: Option<common_enums::CaptureMethod>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub payment_status: common_enums::AttemptStatus, + pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, + pub created_at: time::PrimitiveDateTime, +} + +#[derive(Clone, Debug, Eq, PartialEq, Queryable, Selectable, Insertable)] +#[diesel(table_name = dynamic_routing_stats, primary_key(payment_id), check_for_backend(diesel::pg::Pg))] +pub struct DynamicRoutingStats { + pub payment_id: common_utils::id_type::PaymentId, + pub attempt_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_id: common_utils::id_type::ProfileId, + pub amount: common_utils::types::MinorUnit, + pub success_based_routing_connector: String, + pub payment_connector: String, + pub currency: Option<common_enums::Currency>, + pub payment_method: Option<common_enums::PaymentMethod>, + pub capture_method: Option<common_enums::CaptureMethod>, + pub authentication_type: Option<common_enums::AuthenticationType>, + pub payment_status: common_enums::AttemptStatus, + pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState, + pub created_at: time::PrimitiveDateTime, +} diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index 5de048e32ef..19f3bf0a382 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -20,9 +20,11 @@ pub mod diesel_exports { DbRefundStatus as RefundStatus, DbRefundType as RefundType, DbRequestIncrementalAuthorization as RequestIncrementalAuthorization, DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind, - DbScaExemptionType as ScaExemptionType, DbTotpStatus as TotpStatus, - DbTransactionType as TransactionType, DbUserRoleVersion as UserRoleVersion, - DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, + DbScaExemptionType as ScaExemptionType, + DbSuccessBasedRoutingConclusiveState as SuccessBasedRoutingConclusiveState, + DbTotpStatus as TotpStatus, DbTransactionType as TransactionType, + DbUserRoleVersion as UserRoleVersion, DbUserStatus as UserStatus, + DbWebhookDeliveryAttempt as WebhookDeliveryAttempt, }; } pub use common_enums::*; diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs index 7e476662ea7..d07f84aa65e 100644 --- a/crates/diesel_models/src/lib.rs +++ b/crates/diesel_models/src/lib.rs @@ -12,6 +12,7 @@ pub mod blocklist; pub mod blocklist_fingerprint; pub mod customers; pub mod dispute; +pub mod dynamic_routing_stats; pub mod enums; pub mod ephemeral_key; pub mod errors; diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs index f966e90acba..ab044b5c6e6 100644 --- a/crates/diesel_models/src/query.rs +++ b/crates/diesel_models/src/query.rs @@ -13,6 +13,7 @@ pub mod blocklist_fingerprint; pub mod customers; pub mod dashboard_metadata; pub mod dispute; +pub mod dynamic_routing_stats; pub mod events; pub mod file; pub mod fraud_check; diff --git a/crates/diesel_models/src/query/dynamic_routing_stats.rs b/crates/diesel_models/src/query/dynamic_routing_stats.rs new file mode 100644 index 00000000000..f6771cd103d --- /dev/null +++ b/crates/diesel_models/src/query/dynamic_routing_stats.rs @@ -0,0 +1,11 @@ +use super::generics; +use crate::{ + dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew}, + PgPooledConn, StorageResult, +}; + +impl DynamicRoutingStatsNew { + pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DynamicRoutingStats> { + generics::generic_insert(conn, self).await + } +} diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index b6f1a4f8d05..6b41398aa86 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -388,6 +388,35 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + dynamic_routing_stats (attempt_id, merchant_id) { + #[max_length = 64] + payment_id -> Varchar, + #[max_length = 64] + attempt_id -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + profile_id -> Varchar, + amount -> Int8, + #[max_length = 64] + success_based_routing_connector -> Varchar, + #[max_length = 64] + payment_connector -> Varchar, + currency -> Nullable<Currency>, + #[max_length = 64] + payment_method -> Nullable<Varchar>, + capture_method -> Nullable<CaptureMethod>, + authentication_type -> Nullable<AuthenticationType>, + payment_status -> AttemptStatus, + conclusive_classification -> SuccessBasedRoutingConclusiveState, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1413,6 +1442,7 @@ diesel::allow_tables_to_appear_in_same_query!( customers, dashboard_metadata, dispute, + dynamic_routing_stats, events, file_metadata, fraud_check, diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 470868ed82d..a6bc51e74f2 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -400,6 +400,35 @@ diesel::table! { } } +diesel::table! { + use diesel::sql_types::*; + use crate::enums::diesel_exports::*; + + dynamic_routing_stats (attempt_id, merchant_id) { + #[max_length = 64] + payment_id -> Varchar, + #[max_length = 64] + attempt_id -> Varchar, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] + profile_id -> Varchar, + amount -> Int8, + #[max_length = 64] + success_based_routing_connector -> Varchar, + #[max_length = 64] + payment_connector -> Varchar, + currency -> Nullable<Currency>, + #[max_length = 64] + payment_method -> Nullable<Varchar>, + capture_method -> Nullable<CaptureMethod>, + authentication_type -> Nullable<AuthenticationType>, + payment_status -> AttemptStatus, + conclusive_classification -> SuccessBasedRoutingConclusiveState, + created_at -> Timestamp, + } +} + diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; @@ -1361,6 +1390,7 @@ diesel::allow_tables_to_appear_in_same_query!( customers, dashboard_metadata, dispute, + dynamic_routing_stats, events, file_metadata, fraud_check, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 196db63ff1b..af3e00494cf 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -12,6 +12,8 @@ use api_models::routing as routing_types; use common_utils::ext_traits::ValueExt; use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState}; use diesel_models::configs; +#[cfg(all(feature = "v1", feature = "dynamic_routing"))] +use diesel_models::dynamic_routing_stats::DynamicRoutingStatsNew; #[cfg(feature = "v1")] use diesel_models::routing_algorithm; use error_stack::ResultExt; @@ -751,6 +753,23 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( first_success_based_connector.to_string(), ); + let dynamic_routing_stats = DynamicRoutingStatsNew { + payment_id: payment_attempt.payment_id.to_owned(), + attempt_id: payment_attempt.attempt_id.clone(), + merchant_id: payment_attempt.merchant_id.to_owned(), + profile_id: payment_attempt.profile_id.to_owned(), + amount: payment_attempt.get_total_amount(), + success_based_routing_connector: first_success_based_connector.to_string(), + payment_connector: payment_connector.to_string(), + currency: payment_attempt.currency, + payment_method: payment_attempt.payment_method, + capture_method: payment_attempt.capture_method, + authentication_type: payment_attempt.authentication_type, + payment_status: payment_attempt.status, + conclusive_classification: outcome, + created_at: common_utils::date_time::now(), + }; + core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add( &metrics::CONTEXT, 1, @@ -812,6 +831,13 @@ pub async fn push_metrics_with_update_window_for_success_based_routing( ); logger::debug!("successfully pushed success_based_routing metrics"); + state + .store + .insert_dynamic_routing_stat_entry(dynamic_routing_stats) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to push dynamic routing stats to db")?; + client .update_success_rate( tenant_business_profile_id, diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs index 1ed83be4283..cc9a1e2f436 100644 --- a/crates/router/src/db.rs +++ b/crates/router/src/db.rs @@ -12,6 +12,7 @@ pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; +pub mod dynamic_routing_stats; pub mod ephemeral_key; pub mod events; pub mod file; @@ -107,6 +108,7 @@ pub trait StorageInterface: + payment_method::PaymentMethodInterface + blocklist::BlocklistInterface + blocklist_fingerprint::BlocklistFingerprintInterface + + dynamic_routing_stats::DynamicRoutingStatsInterface + scheduler::SchedulerInterface + PayoutAttemptInterface + PayoutsInterface diff --git a/crates/router/src/db/dynamic_routing_stats.rs b/crates/router/src/db/dynamic_routing_stats.rs new file mode 100644 index 00000000000..d22f4fdd40b --- /dev/null +++ b/crates/router/src/db/dynamic_routing_stats.rs @@ -0,0 +1,58 @@ +use error_stack::report; +use router_env::{instrument, tracing}; +use storage_impl::MockDb; + +use super::Store; +use crate::{ + connection, + core::errors::{self, CustomResult}, + db::kafka_store::KafkaStore, + types::storage, +}; + +#[async_trait::async_trait] +pub trait DynamicRoutingStatsInterface { + async fn insert_dynamic_routing_stat_entry( + &self, + dynamic_routing_stat_new: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>; +} + +#[async_trait::async_trait] +impl DynamicRoutingStatsInterface for Store { + #[instrument(skip_all)] + async fn insert_dynamic_routing_stat_entry( + &self, + dynamic_routing_stat: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + let conn = connection::pg_connection_write(self).await?; + dynamic_routing_stat + .insert(&conn) + .await + .map_err(|error| report!(errors::StorageError::from(error))) + } +} + +#[async_trait::async_trait] +impl DynamicRoutingStatsInterface for MockDb { + #[instrument(skip_all)] + async fn insert_dynamic_routing_stat_entry( + &self, + _dynamic_routing_stat: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + Err(errors::StorageError::MockDbError)? + } +} + +#[async_trait::async_trait] +impl DynamicRoutingStatsInterface for KafkaStore { + #[instrument(skip_all)] + async fn insert_dynamic_routing_stat_entry( + &self, + dynamic_routing_stat: storage::DynamicRoutingStatsNew, + ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { + self.diesel_store + .insert_dynamic_routing_stat_entry(dynamic_routing_stat) + .await + } +} diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs index 41ece363b4f..24573548d79 100644 --- a/crates/router/src/types/storage.rs +++ b/crates/router/src/types/storage.rs @@ -12,6 +12,7 @@ pub mod configs; pub mod customers; pub mod dashboard_metadata; pub mod dispute; +pub mod dynamic_routing_stats; pub mod enums; pub mod ephemeral_key; pub mod events; @@ -63,12 +64,12 @@ pub use scheduler::db::process_tracker; pub use self::{ address::*, api_keys::*, authentication::*, authorization::*, blocklist::*, blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, capture::*, cards_info::*, - configs::*, customers::*, dashboard_metadata::*, dispute::*, ephemeral_key::*, events::*, - file::*, fraud_check::*, generic_link::*, gsm::*, locker_mock_up::*, mandate::*, - merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*, - payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*, - routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*, - user_role::*, + configs::*, customers::*, dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, + ephemeral_key::*, events::*, file::*, fraud_check::*, generic_link::*, gsm::*, + locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*, + merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*, + reverse_lookup::*, role::*, routing_algorithm::*, unified_translations::*, user::*, + user_authentication_method::*, user_role::*, }; use crate::types::api::routing; diff --git a/crates/router/src/types/storage/dynamic_routing_stats.rs b/crates/router/src/types/storage/dynamic_routing_stats.rs new file mode 100644 index 00000000000..ba692a25255 --- /dev/null +++ b/crates/router/src/types/storage/dynamic_routing_stats.rs @@ -0,0 +1 @@ +pub use diesel_models::dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew}; diff --git a/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/down.sql b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/down.sql new file mode 100644 index 00000000000..993a082c234 --- /dev/null +++ b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/down.sql @@ -0,0 +1,3 @@ +-- This file should undo anything in `up.sql` +DROP TABLE IF EXISTS dynamic_routing_stats; +DROP TYPE IF EXISTS "SuccessBasedRoutingConclusiveState"; diff --git a/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/up.sql b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/up.sql new file mode 100644 index 00000000000..6b37787d722 --- /dev/null +++ b/migrations/2024-12-02-095127_add_new_table_dynamic_routing_stats/up.sql @@ -0,0 +1,26 @@ +--- Your SQL goes here +CREATE TYPE "SuccessBasedRoutingConclusiveState" AS ENUM( + 'true_positive', + 'false_positive', + 'true_negative', + 'false_negative' +); + +CREATE TABLE IF NOT EXISTS dynamic_routing_stats ( + payment_id VARCHAR(64) NOT NULL, + attempt_id VARCHAR(64) NOT NULL, + merchant_id VARCHAR(64) NOT NULL, + profile_id VARCHAR(64) NOT NULL, + amount BIGINT NOT NULL, + success_based_routing_connector VARCHAR(64) NOT NULL, + payment_connector VARCHAR(64) NOT NULL, + currency "Currency", + payment_method VARCHAR(64), + capture_method "CaptureMethod", + authentication_type "AuthenticationType", + payment_status "AttemptStatus" NOT NULL, + conclusive_classification "SuccessBasedRoutingConclusiveState" NOT NULL, + created_at TIMESTAMP NOT NULL, + PRIMARY KEY(attempt_id, merchant_id) +); +CREATE INDEX profile_id_index ON dynamic_routing_stats (profile_id);
2024-12-02T17:06:01Z
## 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 --> Previously we were pushing the Dynamic routing metrics to Prometheus, but due to high cardinality of some values(payment_id) we were not able to add that in our attributes, hence we are pushing this after creating a new table in our Database (dynamic_routing_stats). The further enhancement will be done in this track: https://github.com/juspay/hyperswitch/issues/6756 ### Additional Changes - [ ] 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). --> Required to get the payment_id for our metrics purpose. ## 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)? --> Can be tested in the following ways: 1. enable success_based_routing(feature = metrics) for merchant. ``` curl --location --request POST 'http://localhost:8080/account/m_id/business_profile/pro_id/dynamic_routing/success_based/toggle?enable=metrics' \ --header 'api-key:api_key' ``` 2. Make a payment afterwards. 3. Check the `dynamic_routing_stats` table for the specific value associated with the `payment_id`. <img width="645" alt="Screenshot 2024-12-06 at 6 31 56 PM" src="https://github.com/user-attachments/assets/8317e26b-347d-489a-a8fa-661ab692b157"> ## Migration ``` CREATE TYPE "SuccessBasedRoutingConclusiveState" AS ENUM( 'true_positive', 'false_positive', 'true_negative', 'false_negative' ); CREATE TABLE IF NOT EXISTS dynamic_routing_stats ( payment_id VARCHAR(64) NOT NULL, attempt_id VARCHAR(64) NOT NULL, merchant_id VARCHAR(64) NOT NULL, profile_id VARCHAR(64) NOT NULL, amount BIGINT NOT NULL, success_based_routing_connector VARCHAR(64) NOT NULL, payment_connector VARCHAR(64) NOT NULL, currency "Currency", payment_method VARCHAR(64), capture_method "CaptureMethod", authentication_type "AuthenticationType", payment_status "AttemptStatus" NOT NULL, conclusive_classification "SuccessBasedRoutingConclusiveState" NOT NULL, created_at TIMESTAMP NOT NULL, PRIMARY KEY(attempt_id, merchant_id) ); CREATE INDEX profile_id_index ON dynamic_routing_stats (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
03b936a117ae0931fab800cb82038ba45aa6f9a3