Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
refactor(core): structure of split payments (#6706)
Swangi Kumari5a85213e2170
diff --git a/Cargo.lock b/Cargo.lockindex 1347599445..581480f435 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -459,6 +459,7 @@ dependencies = ["actix-web","cards","common_enums",+ "common_types","common_utils","error-stack","euclid",@@ -2025,6 +2026,18 @@ dependencies = ["utoipa",]+[[package]]+name = "common_types"+version = "0.1.0"+dependencies = [+ "common_enums",+ "common_utils",+ "diesel",+ "serde",+ "serde_json",+ "utoipa",+]+[[package]]name = "common_utils"version = "0.1.0"@@ -2735,6 +2748,7 @@ version = "0.1.0"dependencies = ["async-bb8-diesel","common_enums",+ "common_types","common_utils","diesel","error-stack",@@ -4033,6 +4047,7 @@ dependencies = ["async-trait","cards","common_enums",+ "common_types","common_utils","diesel_models","error-stack",@@ -5254,6 +5269,7 @@ name = "openapi"version = "0.1.0"dependencies = ["api_models",+ "common_types","common_utils","router_env","serde_json",@@ -6545,6 +6561,7 @@ dependencies = ["cards","clap","common_enums",+ "common_types","common_utils","config","cookie 0.18.1",diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.jsonindex 0f62f11127..899b307837 100644--- a/api-reference-v2/openapi_spec.json+++ b/api-reference-v2/openapi_spec.json@@ -12475,59 +12475,6 @@}}},- "PaymentChargeRequest": {- "type": "object",- "description": "Fee information to be charged on the payment being collected",- "required": [- "charge_type",- "fees",- "transfer_account_id"- ],- "properties": {- "charge_type": {- "$ref": "#/components/schemas/PaymentChargeType"- },- "fees": {- "type": "integer",- "format": "int64",- "description": "Platform fees to be collected on the payment",- "example": 6540- },- "transfer_account_id": {- "type": "string",- "description": "Identifier for the reseller's account to send the funds to"- }- }- },- "PaymentChargeResponse": {- "type": "object",- "description": "Fee information to be charged on the payment being collected",- "required": [- "charge_type",- "application_fees",- "transfer_account_id"- ],- "properties": {- "charge_id": {- "type": "string",- "description": "Identifier for charge created for the payment",- "nullable": true- },- "charge_type": {- "$ref": "#/components/schemas/PaymentChargeType"- },- "application_fees": {- "type": "integer",- "format": "int64",- "description": "Platform fees collected on the payment",- "example": 6540- },- "transfer_account_id": {- "type": "string",- "description": "Identifier for the reseller's account where the funds were transferred"- }- }- },"PaymentChargeType": {"oneOf": [{@@ -15128,10 +15075,10 @@"example": "2022-09-10T10:11:12Z","nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeResponse"+ "$ref": "#/components/schemas/SplitPaymentsResponse"}],"nullable": true@@ -16028,10 +15975,10 @@"example": "2022-09-10T10:11:12Z","nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeResponse"+ "$ref": "#/components/schemas/SplitPaymentsResponse"}],"nullable": true@@ -18529,10 +18476,10 @@],"nullable": true},- "charges": {+ "split_refunds": {"allOf": [{- "$ref": "#/components/schemas/ChargeRefunds"+ "$ref": "#/components/schemas/SplitRefund"}],"nullable": true@@ -20156,6 +20103,53 @@"contain"]},+ "SplitPaymentsRequest": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "stripe_split_payment"+ ],+ "properties": {+ "stripe_split_payment": {+ "$ref": "#/components/schemas/StripeSplitPaymentRequest"+ }+ }+ }+ ],+ "description": "Fee information for Split Payments to be charged on the payment being collected"+ },+ "SplitPaymentsResponse": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "stripe_split_payment"+ ],+ "properties": {+ "stripe_split_payment": {+ "$ref": "#/components/schemas/StripeSplitPaymentsResponse"+ }+ }+ }+ ]+ },+ "SplitRefund": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "stripe_split_refund"+ ],+ "properties": {+ "stripe_split_refund": {+ "$ref": "#/components/schemas/StripeSplitRefundRequest"+ }+ }+ }+ ],+ "description": "Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details."+ },"StraightThroughAlgorithm": {"oneOf": [{@@ -20233,6 +20227,77 @@"destination"]},+ "StripeSplitPaymentRequest": {+ "type": "object",+ "description": "Fee information for Split Payments to be charged on the payment being collected for Stripe",+ "required": [+ "charge_type",+ "application_fees",+ "transfer_account_id"+ ],+ "properties": {+ "charge_type": {+ "$ref": "#/components/schemas/PaymentChargeType"+ },+ "application_fees": {+ "type": "integer",+ "format": "int64",+ "description": "Platform fees to be collected on the payment",+ "example": 6540+ },+ "transfer_account_id": {+ "type": "string",+ "description": "Identifier for the reseller's account to send the funds to"+ }+ },+ "additionalProperties": false+ },+ "StripeSplitPaymentsResponse": {+ "type": "object",+ "description": "Fee information to be charged on the payment being collected",+ "required": [+ "charge_type",+ "application_fees",+ "transfer_account_id"+ ],+ "properties": {+ "charge_id": {+ "type": "string",+ "description": "Identifier for charge created for the payment",+ "nullable": true+ },+ "charge_type": {+ "$ref": "#/components/schemas/PaymentChargeType"+ },+ "application_fees": {+ "type": "integer",+ "format": "int64",+ "description": "Platform fees collected on the payment",+ "example": 6540+ },+ "transfer_account_id": {+ "type": "string",+ "description": "Identifier for the reseller's account where the funds were transferred"+ }+ }+ },+ "StripeSplitRefundRequest": {+ "type": "object",+ "description": "Charge specific fields for controlling the revert of funds from either platform or connected account for Stripe. Check sub-fields for more details.",+ "properties": {+ "revert_platform_fee": {+ "type": "boolean",+ "description": "Toggle for reverting the application fee that was collected for the payment.\nIf set to false, the funds are pulled from the destination account.",+ "nullable": true+ },+ "revert_transfer": {+ "type": "boolean",+ "description": "Toggle for reverting the transfer that was made during the charge.\nIf set to false, the funds are pulled from the main platform's account.",+ "nullable": true+ }+ },+ "additionalProperties": false+ },"SurchargeCalculationOverride": {"type": "string","enum": [diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.jsonindex 8b06e167e2..81c8544b54 100644--- a/api-reference/openapi_spec.json+++ b/api-reference/openapi_spec.json@@ -15190,59 +15190,6 @@}}},- "PaymentChargeRequest": {- "type": "object",- "description": "Fee information to be charged on the payment being collected",- "required": [- "charge_type",- "fees",- "transfer_account_id"- ],- "properties": {- "charge_type": {- "$ref": "#/components/schemas/PaymentChargeType"- },- "fees": {- "type": "integer",- "format": "int64",- "description": "Platform fees to be collected on the payment",- "example": 6540- },- "transfer_account_id": {- "type": "string",- "description": "Identifier for the reseller's account to send the funds to"- }- }- },- "PaymentChargeResponse": {- "type": "object",- "description": "Fee information to be charged on the payment being collected",- "required": [- "charge_type",- "application_fees",- "transfer_account_id"- ],- "properties": {- "charge_id": {- "type": "string",- "description": "Identifier for charge created for the payment",- "nullable": true- },- "charge_type": {- "$ref": "#/components/schemas/PaymentChargeType"- },- "application_fees": {- "type": "integer",- "format": "int64",- "description": "Platform fees collected on the payment",- "example": 6540- },- "transfer_account_id": {- "type": "string",- "description": "Identifier for the reseller's account where the funds were transferred"- }- }- },"PaymentChargeType": {"oneOf": [{@@ -17240,10 +17187,10 @@],"nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeRequest"+ "$ref": "#/components/schemas/SplitPaymentsRequest"}],"nullable": true@@ -17626,10 +17573,10 @@],"nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeRequest"+ "$ref": "#/components/schemas/SplitPaymentsRequest"}],"nullable": true@@ -18168,10 +18115,10 @@"example": "2022-09-10T10:11:12Z","nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeResponse"+ "$ref": "#/components/schemas/SplitPaymentsResponse"}],"nullable": true@@ -18836,10 +18783,10 @@],"nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeRequest"+ "$ref": "#/components/schemas/SplitPaymentsRequest"}],"nullable": true@@ -19404,10 +19351,10 @@"example": "2022-09-10T10:11:12Z","nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeResponse"+ "$ref": "#/components/schemas/SplitPaymentsResponse"}],"nullable": true@@ -19885,10 +19832,10 @@],"nullable": true},- "charges": {+ "split_payments": {"allOf": [{- "$ref": "#/components/schemas/PaymentChargeRequest"+ "$ref": "#/components/schemas/SplitPaymentsRequest"}],"nullable": true@@ -22517,10 +22464,10 @@],"nullable": true},- "charges": {+ "split_refunds": {"allOf": [{- "$ref": "#/components/schemas/ChargeRefunds"+ "$ref": "#/components/schemas/SplitRefund"}],"nullable": true@@ -22608,10 +22555,10 @@"description": "The merchant_connector_id of the processor through which this payment went through","nullable": true},- "charges": {+ "split_refunds": {"allOf": [{- "$ref": "#/components/schemas/ChargeRefunds"+ "$ref": "#/components/schemas/SplitRefund"}],"nullable": true@@ -24074,6 +24021,53 @@"contain"]},+ "SplitPaymentsRequest": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "stripe_split_payment"+ ],+ "properties": {+ "stripe_split_payment": {+ "$ref": "#/components/schemas/StripeSplitPaymentRequest"+ }+ }+ }+ ],+ "description": "Fee information for Split Payments to be charged on the payment being collected"+ },+ "SplitPaymentsResponse": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "stripe_split_payment"+ ],+ "properties": {+ "stripe_split_payment": {+ "$ref": "#/components/schemas/StripeSplitPaymentsResponse"+ }+ }+ }+ ]+ },+ "SplitRefund": {+ "oneOf": [+ {+ "type": "object",+ "required": [+ "stripe_split_refund"+ ],+ "properties": {+ "stripe_split_refund": {+ "$ref": "#/components/schemas/StripeSplitRefundRequest"+ }+ }+ }+ ],+ "description": "Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details."+ },"StraightThroughAlgorithm": {"oneOf": [{@@ -24151,6 +24145,77 @@"destination"]},+ "StripeSplitPaymentRequest": {+ "type": "object",+ "description": "Fee information for Split Payments to be charged on the payment being collected for Stripe",+ "required": [+ "charge_type",+ "application_fees",+ "transfer_account_id"+ ],+ "properties": {+ "charge_type": {+ "$ref": "#/components/schemas/PaymentChargeType"+ },+ "application_fees": {+ "type": "integer",+ "format": "int64",+ "description": "Platform fees to be collected on the payment",+ "example": 6540+ },+ "transfer_account_id": {+ "type": "string",+ "description": "Identifier for the reseller's account to send the funds to"+ }+ },+ "additionalProperties": false+ },+ "StripeSplitPaymentsResponse": {+ "type": "object",+ "description": "Fee information to be charged on the payment being collected",+ "required": [+ "charge_type",+ "application_fees",+ "transfer_account_id"+ ],+ "properties": {+ "charge_id": {+ "type": "string",+ "description": "Identifier for charge created for the payment",+ "nullable": true+ },+ "charge_type": {+ "$ref": "#/components/schemas/PaymentChargeType"+ },+ "application_fees": {+ "type": "integer",+ "format": "int64",+ "description": "Platform fees collected on the payment",+ "example": 6540+ },+ "transfer_account_id": {+ "type": "string",+ "description": "Identifier for the reseller's account where the funds were transferred"+ }+ }+ },+ "StripeSplitRefundRequest": {+ "type": "object",+ "description": "Charge specific fields for controlling the revert of funds from either platform or connected account for Stripe. Check sub-fields for more details.",+ "properties": {+ "revert_platform_fee": {+ "type": "boolean",+ "description": "Toggle for reverting the application fee that was collected for the payment.\nIf set to false, the funds are pulled from the destination account.",+ "nullable": true+ },+ "revert_transfer": {+ "type": "boolean",+ "description": "Toggle for reverting the transfer that was made during the charge.\nIf set to false, the funds are pulled from the main platform's account.",+ "nullable": true+ }+ },+ "additionalProperties": false+ },"SurchargeDetailsResponse": {"type": "object","required": [diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.tomlindex e5bf74c20c..c159af9724 100644--- a/crates/api_models/Cargo.toml+++ b/crates/api_models/Cargo.toml@@ -42,6 +42,7 @@ nutype = { version = "0.4.2", features = ["serde"] }# First party cratescards = { version = "0.1.0", path = "../cards" }common_enums = { version = "0.1.0", path = "../common_enums" }+common_types = { version = "0.1.0", path = "../common_types" }common_utils = { version = "0.1.0", path = "../common_utils" }euclid = { version = "0.1.0", path = "../euclid" }masking = { version = "0.1.0", path = "../masking", default-features = false, features = ["alloc", "serde"] }diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex 4275b10fd8..f3c3f24245 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -401,50 +401,6 @@ pub fn convert_tax_connector(connector_name: &str) -> Option<TaxConnectors> {TaxConnectors::from_str(connector_name).ok()}-#[derive(- Clone,- Debug,- Eq,- PartialEq,- serde::Deserialize,- serde::Serialize,- strum::Display,- strum::EnumString,- ToSchema,- Hash,-)]-pub enum PaymentChargeType {- #[serde(untagged)]- Stripe(StripeChargeType),-}--impl Default for PaymentChargeType {- fn default() -> Self {- Self::Stripe(StripeChargeType::default())- }-}--#[derive(- Clone,- Debug,- Default,- Hash,- Eq,- PartialEq,- ToSchema,- serde::Serialize,- serde::Deserialize,- strum::Display,- strum::EnumString,-)]-#[serde(rename_all = "lowercase")]-#[strum(serialize_all = "lowercase")]-pub enum StripeChargeType {- #[default]- Direct,- Destination,-}-#[cfg(feature = "frm")]pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> {FrmConnectors::from_str(connector_name).ok()diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 83246d944a..9379bc77b2 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -995,7 +995,8 @@ pub struct PaymentsRequest {pub recurring_details: Option<RecurringDetails>,/// Fee information to be charged on the payment being collected- pub charges: Option<PaymentChargeRequest>,+ #[schema(value_type = Option<SplitPaymentsRequest>)]+ pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,/// Merchant's identifier for the payment/invoice. This will be sent to the connector/// if the connector provides support to accept multiple reference ids.@@ -1219,22 +1220,6 @@ mod payments_request_test {}}-/// Fee information to be charged on the payment being collected-#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]-#[serde(rename_all = "snake_case")]-pub struct PaymentChargeRequest {- /// Stripe's charge type- #[schema(value_type = PaymentChargeType, example = "direct")]- pub charge_type: api_enums::PaymentChargeType,-- /// Platform fees to be collected on the payment- #[schema(value_type = i64, example = 6540)]- pub fees: MinorUnit,-- /// Identifier for the reseller's account to send the funds to- pub transfer_account_id: String,-}-/// Details of surcharge applied on this payment, if applicable#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq,@@ -4687,7 +4672,7 @@ pub struct PaymentsResponse {pub updated: Option<PrimitiveDateTime>,/// Fee information to be charged on the payment being collected- pub charges: Option<PaymentChargeResponse>,+ pub split_payments: Option<SplitPaymentsResponse>,/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM.#[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)]@@ -4935,8 +4920,8 @@ pub struct PaymentStartRedirectionParams {}/// Fee information to be charged on the payment being collected-#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)]-pub struct PaymentChargeResponse {+#[derive(Setter, Clone, Debug, PartialEq, serde::Serialize, ToSchema)]+pub struct StripeSplitPaymentsResponse {/// Identifier for charge created for the paymentpub charge_id: Option<String>,@@ -4952,6 +4937,13 @@ pub struct PaymentChargeResponse {pub transfer_account_id: String,}+#[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum SplitPaymentsResponse {+ /// StripeSplitPaymentsResponse+ StripeSplitPayment(StripeSplitPaymentsResponse),+}+/// Details of external authentication#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)]pub struct ExternalAuthenticationDetailsResponse {diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rsindex ac5e5cb461..36a92e3ab0 100644--- a/crates/api_models/src/refunds.rs+++ b/crates/api_models/src/refunds.rs@@ -1,6 +1,6 @@use std::collections::HashMap;-pub use common_utils::types::{ChargeRefunds, MinorUnit};+pub use common_utils::types::MinorUnit;use common_utils::{pii, types::TimeRange};use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;@@ -57,8 +57,8 @@ pub struct RefundRequest {pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,/// Charge specific fields for controlling the revert of funds from either platform or connected account- #[schema(value_type = Option<ChargeRefunds>)]- pub charges: Option<ChargeRefunds>,+ #[schema(value_type = Option<SplitRefund>)]+ pub split_refunds: Option<common_types::refunds::SplitRefund>,}#[cfg(feature = "v2")]@@ -204,8 +204,8 @@ pub struct RefundResponse {#[schema(value_type = Option<String>)]pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,/// Charge specific fields for controlling the revert of funds from either platform or connected account- #[schema(value_type = Option<ChargeRefunds>)]- pub charges: Option<ChargeRefunds>,+ #[schema(value_type = Option<SplitRefund>,)]+ pub split_refunds: Option<common_types::refunds::SplitRefund>,}#[cfg(feature = "v1")]diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 2a74983f25..e3b11ffaa9 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -3464,3 +3464,41 @@ pub enum ErrorCategory {IssueWithPaymentMethod,ProcessorDeclineIncorrectData,}++#[derive(+ Clone,+ Debug,+ Eq,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+ Hash,+)]+pub enum PaymentChargeType {+ #[serde(untagged)]+ Stripe(StripeChargeType),+}++#[derive(+ Clone,+ Debug,+ Default,+ Hash,+ Eq,+ PartialEq,+ ToSchema,+ serde::Serialize,+ serde::Deserialize,+ strum::Display,+ strum::EnumString,+)]+#[serde(rename_all = "lowercase")]+#[strum(serialize_all = "lowercase")]+pub enum StripeChargeType {+ #[default]+ Direct,+ Destination,+}diff --git a/crates/common_types/Cargo.toml b/crates/common_types/Cargo.tomlnew file mode 100644index 0000000000..b21d7211a3--- /dev/null+++ b/crates/common_types/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "common_types"+description = "Types shared across the request/response types and database types"+version = "0.1.0"+edition.workspace = true+rust-version.workspace = true+license.workspace = true++[dependencies]+diesel = "2.2.3"+serde = { version = "1.0.197", features = ["derive"] }+serde_json = "1.0.115"+utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }++common_enums = { version = "0.1.0", path = "../common_enums" }+common_utils = { version = "0.1.0", path = "../common_utils"}++[lints]+workspace = truediff --git a/crates/common_types/src/lib.rs b/crates/common_types/src/lib.rsnew file mode 100644index 0000000000..30b46d98ae--- /dev/null+++ b/crates/common_types/src/lib.rs@@ -0,0 +1,6 @@+//! Types shared across the request/response types and database types++#![warn(missing_docs, missing_debug_implementations)]++pub mod payments;+pub mod refunds;diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsnew file mode 100644index 0000000000..0eef7ecaf2--- /dev/null+++ b/crates/common_types/src/payments.rs@@ -0,0 +1,40 @@+//! Payment related types++use common_enums::enums;+use common_utils::{impl_to_sql_from_sql_json, types::MinorUnit};+use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++#[derive(+ Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,+)]+#[diesel(sql_type = Jsonb)]+#[serde(rename_all = "snake_case")]+#[serde(deny_unknown_fields)]+/// Fee information for Split Payments to be charged on the payment being collected+pub enum SplitPaymentsRequest {+ /// StripeSplitPayment+ StripeSplitPayment(StripeSplitPaymentRequest),+}+impl_to_sql_from_sql_json!(SplitPaymentsRequest);++#[derive(+ Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,+)]+#[diesel(sql_type = Jsonb)]+#[serde(deny_unknown_fields)]+/// Fee information for Split Payments to be charged on the payment being collected for Stripe+pub struct StripeSplitPaymentRequest {+ /// Stripe's charge type+ #[schema(value_type = PaymentChargeType, example = "direct")]+ pub charge_type: enums::PaymentChargeType,++ /// Platform fees to be collected on the payment+ #[schema(value_type = i64, example = 6540)]+ pub application_fees: MinorUnit,++ /// Identifier for the reseller's account to send the funds to+ pub transfer_account_id: String,+}+impl_to_sql_from_sql_json!(StripeSplitPaymentRequest);diff --git a/crates/common_types/src/refunds.rs b/crates/common_types/src/refunds.rsnew file mode 100644index 0000000000..e4b7c5a336--- /dev/null+++ b/crates/common_types/src/refunds.rs@@ -0,0 +1,36 @@+//! Refund related types++use common_utils::impl_to_sql_from_sql_json;+use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++#[derive(+ Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,+)]+#[diesel(sql_type = Jsonb)]+#[serde(rename_all = "snake_case")]+#[serde(deny_unknown_fields)]+/// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details.+pub enum SplitRefund {+ /// StripeSplitRefundRequest+ StripeSplitRefund(StripeSplitRefundRequest),+}+impl_to_sql_from_sql_json!(SplitRefund);++#[derive(+ Serialize, Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,+)]+#[diesel(sql_type = Jsonb)]+#[serde(deny_unknown_fields)]+/// Charge specific fields for controlling the revert of funds from either platform or connected account for Stripe. Check sub-fields for more details.+pub struct StripeSplitRefundRequest {+ /// Toggle for reverting the application fee that was collected for the payment.+ /// If set to false, the funds are pulled from the destination account.+ pub revert_platform_fee: Option<bool>,++ /// Toggle for reverting the transfer that was made during the charge.+ /// If set to false, the funds are pulled from the main platform's account.+ pub revert_transfer: Option<bool>,+}+impl_to_sql_from_sql_json!(StripeSplitRefundRequest);diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.tomlindex 120a606d58..5da67eb307 100644--- a/crates/diesel_models/Cargo.toml+++ b/crates/diesel_models/Cargo.toml@@ -30,6 +30,7 @@ time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }# First party cratescommon_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils" }+common_types = { version = "0.1.0", path = "../common_types" }masking = { version = "0.1.0", path = "../masking" }router_derive = { version = "0.1.0", path = "../router_derive" }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rsindex 8d037c5356..69743dbf1c 100644--- a/crates/diesel_models/src/payment_intent.rs+++ b/crates/diesel_models/src/payment_intent.rs@@ -73,6 +73,7 @@ pub struct PaymentIntent {pub payment_link_config: Option<PaymentLinkConfigRequestForPayments>,pub id: common_utils::id_type::GlobalPaymentId,pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,+ pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,}#[cfg(feature = "v1")]@@ -138,6 +139,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 split_payments: Option<common_types::payments::SplitPaymentsRequest>,}#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)]@@ -362,6 +364,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 split_payments: Option<common_types::payments::SplitPaymentsRequest>,}#[cfg(feature = "v1")]diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rsindex 42a22b9139..758eba7255 100644--- a/crates/diesel_models/src/refund.rs+++ b/crates/diesel_models/src/refund.rs@@ -53,6 +53,7 @@ pub struct Refund {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>,}#[derive(@@ -98,6 +99,7 @@ pub struct RefundNew {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>,}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex bb2aea0701..782bdb1b9d 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -967,6 +967,7 @@ diesel::table! {tax_details -> Nullable<Jsonb>,skip_external_tax_calculation -> Nullable<Bool>,psd2_sca_exemption_type -> Nullable<ScaExemptionType>,+ split_payments -> Nullable<Jsonb>,}}@@ -1228,6 +1229,7 @@ diesel::table! {connector_refund_data -> Nullable<Varchar>,#[max_length = 512]connector_transaction_data -> Nullable<Varchar>,+ split_refunds -> Nullable<Jsonb>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 9960b136e7..cb1eaad64f 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -930,6 +930,7 @@ diesel::table! {#[max_length = 64]id -> Varchar,psd2_sca_exemption_type -> Nullable<ScaExemptionType>,+ split_payments -> Nullable<Jsonb>,}}@@ -1174,6 +1175,7 @@ diesel::table! {connector_refund_data -> Nullable<Varchar>,#[max_length = 512]connector_transaction_data -> Nullable<Varchar>,+ split_refunds -> Nullable<Jsonb>,}}diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.tomlindex 8fa6d2cc4e..ced2151e52 100644--- a/crates/hyperswitch_domain_models/Cargo.toml+++ b/crates/hyperswitch_domain_models/Cargo.toml@@ -24,6 +24,7 @@ api_models = { version = "0.1.0", path = "../api_models", features = ["errors"]cards = { version = "0.1.0", path = "../cards" }common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext", "metrics", "encryption_service", "keymanager"] }+common_types = { version = "0.1.0", path = "../common_types" }diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }masking = { version = "0.1.0", path = "../masking" }router_derive = { version = "0.1.0", path = "../router_derive" }diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex 9e6477fa26..d22b9eb182 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -92,7 +92,7 @@ pub struct PaymentIntent {#[serde(with = "common_utils::custom_serde::iso8601::option")]pub session_expiry: Option<PrimitiveDateTime>,pub request_external_three_ds_authentication: Option<bool>,- pub charges: Option<pii::SecretSerdeValue>,+ pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,pub frm_metadata: Option<pii::SecretSerdeValue>,#[encrypt]pub customer_details: Option<Encryptable<Secret<Value>>>,diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex 9b6b6fe557..4fd861acb6 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -1338,6 +1338,7 @@ impl behaviour::Conversion for PaymentIntent {payment_link_config,routing_algorithm_id,psd2_sca_exemption_type: None,+ split_payments: None,})}async fn convert_back(@@ -1588,7 +1589,8 @@ impl behaviour::Conversion for PaymentIntent {fingerprint_id: self.fingerprint_id,session_expiry: self.session_expiry,request_external_three_ds_authentication: self.request_external_three_ds_authentication,- charges: self.charges,+ charges: None,+ split_payments: self.split_payments,frm_metadata: self.frm_metadata,customer_details: self.customer_details.map(Encryption::from),billing_details: self.billing_details.map(Encryption::from),@@ -1676,7 +1678,7 @@ impl behaviour::Conversion for PaymentIntent {session_expiry: storage_model.session_expiry,request_external_three_ds_authentication: storage_model.request_external_three_ds_authentication,- charges: storage_model.charges,+ split_payments: storage_model.split_payments,frm_metadata: storage_model.frm_metadata,shipping_cost: storage_model.shipping_cost,tax_details: storage_model.tax_details,@@ -1739,7 +1741,8 @@ impl behaviour::Conversion for PaymentIntent {fingerprint_id: self.fingerprint_id,session_expiry: self.session_expiry,request_external_three_ds_authentication: self.request_external_three_ds_authentication,- charges: self.charges,+ charges: None,+ split_payments: self.split_payments,frm_metadata: self.frm_metadata,customer_details: self.customer_details.map(Encryption::from),billing_details: self.billing_details.map(Encryption::from),diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex 7a45faf026..2f68b481d8 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -2,12 +2,7 @@ pub mod authentication;pub mod fraud_check;pub mod unified_authentication_service;use api_models::payments::{AdditionalPaymentData, RequestSurchargeDetails};-use common_utils::{- consts, errors,- ext_traits::OptionExt,- id_type, pii,- types::{self as common_types, MinorUnit},-};+use common_utils::{consts, errors, ext_traits::OptionExt, id_type, pii, types::MinorUnit};use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount};use error_stack::ResultExt;use masking::Secret;@@ -63,7 +58,7 @@ pub struct PaymentsAuthorizeData {pub request_incremental_authorization: bool,pub metadata: Option<serde_json::Value>,pub authentication_data: Option<AuthenticationData>,- pub charges: Option<PaymentCharges>,+ pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,// New amount for amount frame workpub minor_amount: MinorUnit,@@ -110,13 +105,6 @@ pub struct SyncIntegrityObject {pub currency: Option<storage_enums::Currency>,}-#[derive(Debug, serde::Deserialize, Clone)]-pub struct PaymentCharges {- pub charge_type: api_models::enums::PaymentChargeType,- pub fees: MinorUnit,- pub transfer_account_id: String,-}-#[derive(Debug, Clone, Default)]pub struct PaymentsCaptureData {pub amount_to_capture: i64,@@ -446,8 +434,7 @@ pub struct PaymentsSyncData {pub payment_method_type: Option<storage_enums::PaymentMethodType>,pub currency: storage_enums::Currency,pub payment_experience: Option<common_enums::PaymentExperience>,- pub charges: Option<PaymentCharges>,-+ pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,pub amount: MinorUnit,pub integrity_object: Option<SyncIntegrityObject>,}@@ -591,7 +578,7 @@ pub struct AuthenticationData {pub eci: Option<String>,pub cavv: String,pub threeds_server_transaction_id: String,- pub message_version: common_types::SemanticVersion,+ pub message_version: common_utils::types::SemanticVersion,pub ds_trans_id: Option<String>,}@@ -613,7 +600,7 @@ pub struct RefundsData {pub connector_metadata: Option<serde_json::Value>,pub browser_info: Option<BrowserInformation>,/// Charges associated with the payment- pub charges: Option<ChargeRefunds>,+ pub split_refunds: Option<SplitRefundsRequest>,// New amount for amount frame workpub minor_payment_amount: MinorUnit,@@ -630,6 +617,19 @@ pub struct RefundIntegrityObject {pub refund_amount: MinorUnit,}+#[derive(Debug, serde::Deserialize, Clone)]+pub enum SplitRefundsRequest {+ StripeSplitRefund(StripeSplitRefund),+}++#[derive(Debug, serde::Deserialize, Clone)]+pub struct StripeSplitRefund {+ pub charge_id: String,+ pub transfer_account_id: String,+ pub charge_type: api_models::enums::PaymentChargeType,+ pub options: ChargeRefundsOptions,+}+#[derive(Debug, serde::Deserialize, Clone)]pub struct ChargeRefunds {pub charge_id: String,diff --git a/crates/openapi/Cargo.toml b/crates/openapi/Cargo.tomlindex 930f9739e6..7e7e5a6fb3 100644--- a/crates/openapi/Cargo.toml+++ b/crates/openapi/Cargo.toml@@ -13,6 +13,7 @@ utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order# First party cratesapi_models = { version = "0.1.0", path = "../api_models", features = ["frm", "payouts", "openapi"] }common_utils = { version = "0.1.0", path = "../common_utils", features = ["logs"] }+common_types = { version = "0.1.0", path = "../common_types" }router_env = { version = "0.1.0", path = "../router_env" }[features]diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 68b0893bcc..f68199d69f 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -208,6 +208,13 @@ Never share your secret api keys. Keep them guarded and secure.common_utils::payout_method_utils::PixBankTransferAdditionalData,common_utils::payout_method_utils::PaypalAdditionalData,common_utils::payout_method_utils::VenmoAdditionalData,+ common_types::payments::SplitPaymentsRequest,+ common_types::payments::StripeSplitPaymentRequest,+ common_utils::types::ChargeRefunds,+ common_types::refunds::SplitRefund,+ common_types::refunds::StripeSplitRefundRequest,+ api_models::payments::SplitPaymentsResponse,+ api_models::payments::StripeSplitPaymentsResponse,api_models::refunds::RefundRequest,api_models::refunds::RefundType,api_models::refunds::RefundResponse,@@ -618,9 +625,6 @@ Never share your secret api keys. Keep them guarded and secure.api_models::enums::WebhookDeliveryAttempt,api_models::enums::PaymentChargeType,api_models::enums::StripeChargeType,- api_models::payments::PaymentChargeRequest,- api_models::payments::PaymentChargeResponse,- api_models::refunds::ChargeRefunds,api_models::payments::CustomerDetailsResponse,api_models::payments::OpenBankingData,api_models::payments::OpenBankingSessionToken,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex e3c9ef0b01..af156c89eb 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -158,6 +158,13 @@ Never share your secret api keys. Keep them guarded and secure.common_utils::payout_method_utils::PixBankTransferAdditionalData,common_utils::payout_method_utils::PaypalAdditionalData,common_utils::payout_method_utils::VenmoAdditionalData,+ common_types::payments::SplitPaymentsRequest,+ common_types::payments::StripeSplitPaymentRequest,+ common_types::refunds::StripeSplitRefundRequest,+ common_utils::types::ChargeRefunds,+ common_types::refunds::SplitRefund,+ api_models::payments::SplitPaymentsResponse,+ api_models::payments::StripeSplitPaymentsResponse,api_models::refunds::RefundRequest,api_models::refunds::RefundsCreateRequest,api_models::refunds::RefundErrorDetails,@@ -585,9 +592,6 @@ Never share your secret api keys. Keep them guarded and secure.api_models::enums::WebhookDeliveryAttempt,api_models::enums::PaymentChargeType,api_models::enums::StripeChargeType,- api_models::payments::PaymentChargeRequest,- api_models::payments::PaymentChargeResponse,- api_models::refunds::ChargeRefunds,api_models::payments::CustomerDetailsResponse,api_models::payments::OpenBankingData,api_models::payments::OpenBankingSessionToken,diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 58815ad924..619d2fb193 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -127,6 +127,7 @@ api_models = { version = "0.1.0", path = "../api_models", features = ["errors",cards = { version = "0.1.0", path = "../cards" }common_enums = { version = "0.1.0", path = "../common_enums" }common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] }+common_types = { version = "0.1.0", path = "../common_types" }currency_conversion = { version = "0.1.0", path = "../currency_conversion" }diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] }diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rsindex cb2eba4d0e..31cc0a713a 100644--- a/crates/router/src/connector/stripe.rs+++ b/crates/router/src/connector/stripe.rs@@ -8,6 +8,7 @@ use common_utils::{};use diesel_models::enums;use error_stack::ResultExt;+use hyperswitch_domain_models::router_request_types::SplitRefundsRequest;use masking::PeekInterface;use router_env::{instrument, tracing};use stripe::auth_headers;@@ -763,13 +764,20 @@ impl)];let mut api_key = self.get_auth_header(&req.connector_auth_type)?;header.append(&mut api_key);- req.request.charges.as_ref().map(|charges| {- transformers::transform_headers_for_connect_platform(- charges.charge_type.clone(),- charges.transfer_account_id.clone(),- &mut header,- )- });++ if let Some(split_payments) = &req.request.split_payments {+ match split_payments {+ common_types::payments::SplitPaymentsRequest::StripeSplitPayment(+ stripe_split_payment,+ ) => {+ transformers::transform_headers_for_connect_platform(+ stripe_split_payment.charge_type.clone(),+ stripe_split_payment.transfer_account_id.clone(),+ &mut header,+ );+ }+ }+ }Ok(header)}@@ -934,20 +942,28 @@ impllet mut api_key = self.get_auth_header(&req.connector_auth_type)?;header.append(&mut api_key);- req.request- .charges- .as_ref()- .map(|charge| match &charge.charge_type {- api::enums::PaymentChargeType::Stripe(stripe_charge) => {- if stripe_charge == &api::enums::StripeChargeType::Direct {+ if let Some(split_payments) = &req.request.split_payments {+ match split_payments {+ common_types::payments::SplitPaymentsRequest::StripeSplitPayment(+ stripe_split_payment,+ ) => {+ if stripe_split_payment.charge_type+ == api::enums::PaymentChargeType::Stripe(+ api::enums::StripeChargeType::Direct,+ )+ {let mut customer_account_header = vec![(headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),- charge.transfer_account_id.clone().into_masked(),+ stripe_split_payment+ .transfer_account_id+ .clone()+ .into_masked(),)];header.append(&mut customer_account_header);}}- });+ }+ }Ok(header)}@@ -1467,20 +1483,26 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Reflet mut api_key = self.get_auth_header(&req.connector_auth_type)?;header.append(&mut api_key);- req.request- .charges- .as_ref()- .map(|charge| match &charge.charge_type {- api::enums::PaymentChargeType::Stripe(stripe_charge) => {- if stripe_charge == &api::enums::StripeChargeType::Direct {- let mut customer_account_header = vec![(- headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),- charge.transfer_account_id.clone().into_masked(),- )];- header.append(&mut customer_account_header);+ if let Some(split_refunds) = req.request.split_refunds.as_ref() {+ match split_refunds {+ SplitRefundsRequest::StripeSplitRefund(ref stripe_split_refund) => {+ match &stripe_split_refund.charge_type {+ api::enums::PaymentChargeType::Stripe(stripe_charge) => {+ if stripe_charge == &api::enums::StripeChargeType::Direct {+ let mut customer_account_header = vec![(+ headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),+ stripe_split_refund+ .transfer_account_id+ .clone()+ .into_masked(),+ )];+ header.append(&mut customer_account_header);+ }+ }}}- });+ }+ }Ok(header)}@@ -1506,14 +1528,16 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Refreq.request.minor_refund_amount,req.request.currency,)?;- let request_body = match req.request.charges.as_ref() {+ let request_body = match req.request.split_refunds.as_ref() {None => RequestContent::FormUrlEncoded(Box::new(stripe::RefundRequest::try_from((req,refund_amount,))?)),- Some(_) => RequestContent::FormUrlEncoded(Box::new(- stripe::ChargeRefundRequest::try_from(req)?,- )),+ Some(split_refunds) => match split_refunds {+ SplitRefundsRequest::StripeSplitRefund(_) => RequestContent::FormUrlEncoded(+ Box::new(stripe::ChargeRefundRequest::try_from(req)?),+ ),+ },};Ok(request_body)}@@ -1627,13 +1651,18 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun)];let mut api_key = self.get_auth_header(&req.connector_auth_type)?;header.append(&mut api_key);- req.request.charges.as_ref().map(|charges| {- transformers::transform_headers_for_connect_platform(- charges.charge_type.clone(),- charges.transfer_account_id.clone(),- &mut header,- )- });++ if let Some(split_refunds) = req.request.split_refunds.as_ref() {+ match split_refunds {+ SplitRefundsRequest::StripeSplitRefund(ref stripe_refund) => {+ transformers::transform_headers_for_connect_platform(+ stripe_refund.charge_type.clone(),+ stripe_refund.transfer_account_id.clone(),+ &mut header,+ );+ }+ }+ }Ok(header)}diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rsindex 8114569c0d..2f0b0e0316 100644--- a/crates/router/src/connector/stripe/transformers.rs+++ b/crates/router/src/connector/stripe/transformers.rs@@ -1919,19 +1919,27 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, MinorUnit)> for PaymentIntentNone};- let (charges, customer) = match &item.request.charges {- Some(charges) => {- let charges = match &charges.charge_type {- api_enums::PaymentChargeType::Stripe(charge_type) => match charge_type {- api_enums::StripeChargeType::Direct => Some(IntentCharges {- application_fee_amount: charges.fees,- destination_account_id: None,- }),- api_enums::StripeChargeType::Destination => Some(IntentCharges {- application_fee_amount: charges.fees,- destination_account_id: Some(charges.transfer_account_id.clone()),- }),- },+ let (charges, customer) = match &item.request.split_payments {+ Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(+ stripe_split_payment,+ )) => {+ let charges = match &stripe_split_payment.charge_type {+ api_models::enums::PaymentChargeType::Stripe(charge_type) => {+ match charge_type {+ api_models::enums::StripeChargeType::Direct => Some(IntentCharges {+ application_fee_amount: stripe_split_payment.application_fees,+ destination_account_id: None,+ }),+ api_models::enums::StripeChargeType::Destination => {+ Some(IntentCharges {+ application_fee_amount: stripe_split_payment.application_fees,+ destination_account_id: Some(+ stripe_split_payment.transfer_account_id.clone(),+ ),+ })+ }+ }+ }};(charges, None)}@@ -3010,32 +3018,38 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for ChargeRefundRequest {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {let amount = item.request.minor_refund_amount;- match item.request.charges.as_ref() {+ match item.request.split_refunds.as_ref() {None => Err(errors::ConnectorError::MissingRequiredField {- field_name: "charges",+ field_name: "split_refunds",}.into()),- Some(charges) => {- let (refund_application_fee, reverse_transfer) = match charges.options {- types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {- revert_platform_fee,- }) => (Some(revert_platform_fee), None),- types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund {- revert_platform_fee,- revert_transfer,- }) => (Some(revert_platform_fee), Some(revert_transfer)),- };- Ok(Self {- charge: charges.charge_id.clone(),- refund_application_fee,- reverse_transfer,- amount: Some(amount),- meta_data: StripeMetadata {- order_id: Some(item.request.refund_id.clone()),- is_refund_id_as_reference: Some("true".to_string()),- },- })- }++ Some(split_refunds) => match split_refunds {+ types::SplitRefundsRequest::StripeSplitRefund(stripe_refund) => {+ let (refund_application_fee, reverse_transfer) = match &stripe_refund.options {+ types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {+ revert_platform_fee,+ }) => (Some(*revert_platform_fee), None),+ types::ChargeRefundsOptions::Destination(+ types::DestinationChargeRefund {+ revert_platform_fee,+ revert_transfer,+ },+ ) => (Some(*revert_platform_fee), Some(*revert_transfer)),+ };++ Ok(Self {+ charge: stripe_refund.charge_id.clone(),+ refund_application_fee,+ reverse_transfer,+ amount: Some(amount),+ meta_data: StripeMetadata {+ order_id: Some(item.request.refund_id.clone()),+ is_refund_id_as_reference: Some("true".to_string()),+ },+ })+ }+ },}}}diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 6265ac3f18..fa5f5e03e4 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -2,9 +2,7 @@ use std::{borrow::Cow, str::FromStr};use api_models::{mandates::RecurringDetails,- payments::{- additional_info as payment_additional_types, PaymentChargeRequest, RequestSurchargeDetails,- },+ payments::{additional_info as payment_additional_types, RequestSurchargeDetails},};use base64::Engine;use common_enums::ConnectorType;@@ -3492,7 +3490,7 @@ mod tests {.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),),request_external_three_ds_authentication: None,- charges: None,+ split_payments: None,frm_metadata: None,customer_details: None,billing_details: None,@@ -3562,7 +3560,7 @@ mod tests {created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),),request_external_three_ds_authentication: None,- charges: None,+ split_payments: None,frm_metadata: None,customer_details: None,billing_details: None,@@ -3630,7 +3628,7 @@ mod tests {.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),),request_external_three_ds_authentication: None,- charges: None,+ split_payments: None,frm_metadata: None,customer_details: None,billing_details: None,@@ -6131,26 +6129,28 @@ pub async fn validate_merchant_connector_ids_in_connector_mandate_details(pub fn validate_platform_fees_for_marketplace(amount: api::Amount,- charges: &PaymentChargeRequest,+ split_payments: Option<common_types::payments::SplitPaymentsRequest>,) -> Result<(), errors::ApiErrorResponse> {- match amount {- api::Amount::Zero => {- if charges.fees.get_amount_as_i64() != 0 {- Err(errors::ApiErrorResponse::InvalidDataValue {- field_name: "charges.fees",- })- } else {- Ok(())+ if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(+ stripe_split_payment,+ )) = split_payments+ {+ match amount {+ api::Amount::Zero => {+ if stripe_split_payment.application_fees.get_amount_as_i64() != 0 {+ return Err(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "split_payments.stripe_split_payment.application_fees",+ });+ }}- }- api::Amount::Value(amount) => {- if charges.fees.get_amount_as_i64() > amount.into() {- Err(errors::ApiErrorResponse::InvalidDataValue {- field_name: "charges.fees",- })- } else {- Ok(())+ api::Amount::Value(amount) => {+ if stripe_split_payment.application_fees.get_amount_as_i64() > amount.into() {+ return Err(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "split_payments.stripe_split_payment.application_fees",+ });+ }}}}+ Ok(())}diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex 9dd3cdaaa7..6a676af47b 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -1024,9 +1024,12 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentDat)?;}- if let Some(charges) = &request.charges {+ if request.split_payments.is_some() {let amount = request.amount.get_required_value("amount")?;- helpers::validate_platform_fees_for_marketplace(amount, charges)?;+ helpers::validate_platform_fees_for_marketplace(+ amount,+ request.split_payments.clone(),+ )?;};let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request@@ -1347,17 +1350,7 @@ impl PaymentCreate {request.capture_method,)?;- let charges = request- .charges- .as_ref()- .map(|charges| {- charges.encode_to_value().inspect_err(|err| {- logger::warn!("Failed to serialize PaymentCharges - {}", err);- })- })- .transpose()- .change_context(errors::ApiErrorResponse::InternalServerError)?- .map(Secret::new);+ let split_payments = request.split_payments.clone();// Derivation of directly supplied Customer data in our Payment Create Requestlet raw_customer_details = if request.customer_id.is_none()@@ -1479,7 +1472,7 @@ impl PaymentCreate {session_expiry: Some(session_expiry),request_external_three_ds_authentication: request.request_external_three_ds_authentication,- charges,+ split_payments,frm_metadata: request.frm_metadata.clone(),billing_details: encrypted_data.billing_details,customer_details: encrypted_data.customer_details,diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 668de68318..92486320cd 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -2,7 +2,7 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr};use api_models::payments::{Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage,- PaymentChargeRequest, PaymentChargeResponse, RequestSurchargeDetails,+ RequestSurchargeDetails,};use common_enums::{Currency, RequestIncrementalAuthorization};use common_utils::{@@ -20,7 +20,9 @@ use hyperswitch_domain_models::payments::{PaymentConfirmData, PaymentIntentData}#[cfg(feature = "v2")]use hyperswitch_domain_models::ApiModelToDieselModelConvertor;use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types};-use masking::{ExposeInterface, Maskable, PeekInterface, Secret};+#[cfg(feature = "v2")]+use masking::PeekInterface;+use masking::{ExposeInterface, Maskable, Secret};use router_env::{instrument, tracing};use super::{flows::Feature, types::AuthenticationData, OperationSessionGetters, PaymentData};@@ -284,7 +286,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>(metadata: payment_data.payment_intent.metadata.expose_option(),authentication_data: None,customer_acceptance: None,- charges: None,+ split_payments: None,merchant_order_reference_id: None,integrity_object: None,shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,@@ -436,7 +438,7 @@ pub async fn construct_router_data_for_psync<'a>(payment_method_type: Some(attempt.payment_method_subtype),currency: payment_intent.amount_details.currency,// TODO: Get the charges object from feature metadata- charges: None,+ split_payments: None,payment_experience: None,};@@ -1877,26 +1879,22 @@ where)});- let charges_response = match payment_intent.charges {+ let split_payments_response = match payment_intent.split_payments {None => None,- Some(charges) => {- let payment_charges: PaymentChargeRequest = charges- .peek()- .clone()- .parse_value("PaymentChargeRequest")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(format!(- "Failed to parse PaymentChargeRequest for payment_intent {:?}",- payment_intent.payment_id- ))?;-- Some(PaymentChargeResponse {- charge_id: payment_attempt.charge_id.clone(),- charge_type: payment_charges.charge_type,- application_fees: payment_charges.fees,- transfer_account_id: payment_charges.transfer_account_id,- })- }+ Some(split_payments) => match split_payments {+ common_types::payments::SplitPaymentsRequest::StripeSplitPayment(+ stripe_split_payment,+ ) => Some(+ api_models::payments::SplitPaymentsResponse::StripeSplitPayment(+ api_models::payments::StripeSplitPaymentsResponse {+ charge_id: payment_attempt.charge_id.clone(),+ charge_type: stripe_split_payment.charge_type,+ application_fees: stripe_split_payment.application_fees,+ transfer_account_id: stripe_split_payment.transfer_account_id,+ },+ ),+ ),+ },};let mandate_data = payment_data.get_setup_mandate().map(|d| api::MandateData {@@ -2077,7 +2075,7 @@ where.get_payment_method_info().map(|info| info.status),updated: Some(payment_intent.modified_at),- charges: charges_response,+ split_payments: split_payments_response,frm_metadata: payment_intent.frm_metadata,merchant_order_reference_id: payment_intent.merchant_order_reference_id,order_tax_amount,@@ -2334,7 +2332,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Paypayment_method_id: None,payment_method_status: None,updated: None,- charges: None,+ split_payments: None,frm_metadata: None,order_tax_amount: None,connector_mandate_id:None,@@ -2608,15 +2606,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz.as_ref().map(|data| data.customer_id.clone());- let charges = match payment_data.payment_intent.charges {- Some(charges) => charges- .peek()- .clone()- .parse_value("PaymentCharges")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse charges in to PaymentCharges")?,- None => None,- };+ let split_payments = payment_data.payment_intent.split_payments.clone();let merchant_order_reference_id = payment_data.payment_intent@@ -2666,7 +2656,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz.map(AuthenticationData::foreign_try_from).transpose()?,customer_acceptance: payment_data.customer_acceptance,- charges,+ split_payments,merchant_order_reference_id,integrity_object: None,additional_payment_method_data,@@ -2719,19 +2709,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData},payment_method_type,currency: payment_data.currency,- charges: payment_data- .payment_intent- .charges- .as_ref()- .map(|charges| {- charges- .peek()- .clone()- .parse_value("PaymentCharges")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse charges in to PaymentCharges")- })- .transpose()?,+ split_payments: payment_data.payment_intent.split_payments,payment_experience: payment_data.payment_attempt.payment_experience,})}diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rsindex 1a7e204767..80813ac29b 100644--- a/crates/router/src/core/payments/types.rs+++ b/crates/router/src/core/payments/types.rs@@ -9,7 +9,7 @@ use common_utils::{use error_stack::ResultExt;use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;pub use hyperswitch_domain_models::router_request_types::{- AuthenticationData, PaymentCharges, SurchargeDetails,+ AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails,};use redis_interface::errors::RedisError;use router_env::{instrument, logger, tracing};diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex b13fb930cd..373a268d69 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -7,14 +7,16 @@ use std::collections::HashMap;#[cfg(feature = "olap")]use api_models::admin::MerchantConnectorInfo;use common_utils::{- ext_traits::{AsyncExt, ValueExt},+ ext_traits::AsyncExt,types::{ConnectorTransactionId, MinorUnit},};use diesel_models::process_tracker::business_status;use error_stack::{report, ResultExt};-use hyperswitch_domain_models::router_data::ErrorResponse;+use hyperswitch_domain_models::{+ router_data::ErrorResponse,+ router_request_types::{SplitRefundsRequest, StripeSplitRefund},+};use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject};-use masking::PeekInterface;use router_env::{instrument, tracing};use scheduler::{consumer::types::process_data, utils as process_tracker_utils};#[cfg(feature = "olap")]@@ -24,7 +26,8 @@ use crate::{consts,core::{errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},- payments::{self, access_token, types::PaymentCharges},+ payments::{self, access_token},+ refunds::transformers::SplitRefundInput,utils as core_utils,},db, logger,@@ -35,8 +38,7 @@ use crate::{api::{self, refunds},domain,storage::{self, enums},- transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},- ChargeRefunds,+ transformers::{ForeignFrom, ForeignInto},},utils::{self, OptionExt},workflows::payment_sync,@@ -143,7 +145,7 @@ pub async fn trigger_refund_to_gateway(payment_attempt: &storage::PaymentAttempt,payment_intent: &storage::PaymentIntent,creds_identifier: Option<String>,- charges: Option<ChargeRefunds>,+ split_refunds: Option<SplitRefundsRequest>,) -> RouterResult<storage::Refund> {let routed_through = payment_attempt.connector@@ -182,7 +184,7 @@ pub async fn trigger_refund_to_gateway(payment_attempt,refund,creds_identifier.clone(),- charges,+ split_refunds,).await?;@@ -464,12 +466,16 @@ pub async fn refund_retrieve_core(.await.transpose()?;- let charges_req = payment_intent- .charges+ let split_refunds_req: Option<SplitRefundsRequest> = payment_intent+ .split_payments.clone()- .zip(refund.charges.clone())- .map(|(charges, refund_charges)| {- ForeignTryFrom::foreign_try_from((refund_charges, charges))+ .zip(refund.split_refunds.clone())+ .map(|(split_payments, split_refunds)| {+ SplitRefundsRequest::try_from(SplitRefundInput {+ refund_request: split_refunds,+ payment_charges: split_payments,+ charge_id: payment_attempt.charge_id.clone(),+ })}).transpose()?;@@ -482,7 +488,7 @@ pub async fn refund_retrieve_core(&payment_intent,&refund,creds_identifier,- charges_req,+ split_refunds_req,)).await} else {@@ -519,7 +525,7 @@ pub async fn sync_refund_with_gateway(payment_intent: &storage::PaymentIntent,refund: &storage::Refund,creds_identifier: Option<String>,- charges: Option<ChargeRefunds>,+ split_refunds: Option<SplitRefundsRequest>,) -> RouterResult<storage::Refund> {let connector_id = refund.connector.to_string();let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(@@ -545,7 +551,7 @@ pub async fn sync_refund_with_gateway(payment_attempt,refund,creds_identifier.clone(),- charges,+ split_refunds,).await?;@@ -737,35 +743,28 @@ pub async fn validate_and_create_refund() -> RouterResult<refunds::RefundResponse> {let db = &*state.store;- // Validate charge_id and refund options- let charges = match (- payment_intent.charges.as_ref(),- payment_attempt.charge_id.as_ref(),- ) {- (Some(charges), Some(charge_id)) => {- let refund_charge_request = req.charges.clone().get_required_value("charges")?;- utils::when(*charge_id != refund_charge_request.charge_id, || {- Err(report!(errors::ApiErrorResponse::InvalidDataValue {- field_name: "charges.charge_id"+ let split_refunds = match payment_intent.split_payments.as_ref() {+ Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(stripe_payment)) => {+ if let Some(charge_id) = payment_attempt.charge_id.clone() {+ let refund_request = req+ .split_refunds+ .clone()+ .get_required_value("split_refunds")?;++ let options = validator::validate_charge_refund(+ &refund_request,+ &stripe_payment.charge_type,+ )?;++ Some(SplitRefundsRequest::StripeSplitRefund(StripeSplitRefund {+ charge_id,+ charge_type: stripe_payment.charge_type.clone(),+ transfer_account_id: stripe_payment.transfer_account_id.clone(),+ options,}))- .attach_printable("charge_id sent in request mismatches with original charge_id")- })?;- let payment_charges: PaymentCharges = charges- .peek()- .clone()- .parse_value("PaymentCharges")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse charges in to PaymentCharges")?;- let options = validator::validate_charge_refund(- &refund_charge_request,- &payment_charges.charge_type,- )?;- Some(ChargeRefunds {- charge_id: charge_id.to_string(),- charge_type: payment_charges.charge_type,- transfer_account_id: payment_charges.transfer_account_id,- options,- })+ } else {+ None+ }}_ => None,};@@ -861,7 +860,8 @@ pub async fn validate_and_create_refund(refund_reason: req.reason,profile_id: payment_intent.profile_id.clone(),merchant_connector_id: payment_attempt.merchant_connector_id.clone(),- charges: req.charges,+ charges: None,+ split_refunds: req.split_refunds,connector_refund_id: None,sent_to_gateway: Default::default(),refund_arn: None,@@ -885,7 +885,7 @@ pub async fn validate_and_create_refund(payment_attempt,payment_intent,creds_identifier,- charges,+ split_refunds,)).await?}@@ -1198,7 +1198,7 @@ impl ForeignFrom<storage::Refund> for api::RefundResponse {updated_at: Some(refund.modified_at),connector: refund.connector,merchant_connector_id: refund.merchant_connector_id,- charges: refund.charges,+ split_refunds: refund.split_refunds,}}}@@ -1216,7 +1216,7 @@ pub async fn schedule_refund_execution(payment_attempt: &storage::PaymentAttempt,payment_intent: &storage::PaymentIntent,creds_identifier: Option<String>,- charges: Option<ChargeRefunds>,+ split_refunds: Option<SplitRefundsRequest>,) -> RouterResult<storage::Refund> {// refunds::RefundResponse> {let db = &*state.store;@@ -1253,7 +1253,7 @@ pub async fn schedule_refund_execution(payment_attempt,payment_intent,creds_identifier,- charges,+ split_refunds,)).await;@@ -1462,37 +1462,32 @@ pub async fn trigger_refund_execute_workflow(.await.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;- let charges = match (- payment_intent.charges.as_ref(),- payment_attempt.charge_id.as_ref(),- ) {- (Some(charges), Some(charge_id)) => {- let refund_charge_request =- refund.charges.clone().get_required_value("charges")?;- utils::when(*charge_id != refund_charge_request.charge_id, || {- Err(report!(errors::ApiErrorResponse::InvalidDataValue {- field_name: "charges.charge_id"- }))- .attach_printable(- "charge_id sent in request mismatches with original charge_id",- )- })?;- let payment_charges: PaymentCharges = charges- .peek()+ let split_refunds = match payment_intent.split_payments.as_ref() {+ Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(+ stripe_payment,+ )) => {+ let refund_request = refund+ .split_refunds.clone()- .parse_value("PaymentCharges")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse charges in to PaymentCharges")?;+ .get_required_value("split_refunds")?;+let options = validator::validate_charge_refund(- &refund_charge_request,- &payment_charges.charge_type,+ &refund_request,+ &stripe_payment.charge_type,)?;- Some(ChargeRefunds {- charge_id: charge_id.to_string(),- charge_type: payment_charges.charge_type,- transfer_account_id: payment_charges.transfer_account_id,++ let charge_id = payment_attempt.charge_id.clone().ok_or_else(|| {+ report!(errors::ApiErrorResponse::InternalServerError).attach_printable(+ "Transaction is invalid. Missing field \"charge_id\" in payment_attempt.",+ )+ })?;++ Some(SplitRefundsRequest::StripeSplitRefund(StripeSplitRefund {+ charge_id,+ charge_type: stripe_payment.charge_type.clone(),+ transfer_account_id: stripe_payment.transfer_account_id.clone(),options,- })+ }))}_ => None,};@@ -1506,7 +1501,7 @@ pub async fn trigger_refund_execute_workflow(&payment_attempt,&payment_intent,None,- charges,+ split_refunds,)).await?;add_refund_sync_task(diff --git a/crates/router/src/core/refunds/transformers.rs b/crates/router/src/core/refunds/transformers.rsindex e7cc0aa2ec..256e4c3452 100644--- a/crates/router/src/core/refunds/transformers.rs+++ b/crates/router/src/core/refunds/transformers.rs@@ -1,32 +1,54 @@-use common_utils::{ext_traits::ValueExt, pii, types::ChargeRefunds};-use error_stack::{Report, ResultExt};+use error_stack::{report, Report};use hyperswitch_domain_models::router_request_types;-use masking::PeekInterface;use super::validator;-use crate::{core::errors, types::transformers::ForeignTryFrom};+use crate::core::errors;-impl ForeignTryFrom<(ChargeRefunds, pii::SecretSerdeValue)>- for router_request_types::ChargeRefunds-{+pub struct SplitRefundInput {+ pub refund_request: common_types::refunds::SplitRefund,+ pub payment_charges: common_types::payments::SplitPaymentsRequest,+ pub charge_id: Option<String>,+}++impl TryFrom<SplitRefundInput> for router_request_types::SplitRefundsRequest {type Error = Report<errors::ApiErrorResponse>;- fn foreign_try_from(item: (ChargeRefunds, pii::SecretSerdeValue)) -> Result<Self, Self::Error> {- let (refund_charges, charges) = item;- let payment_charges: router_request_types::PaymentCharges = charges- .peek()- .clone()- .parse_value("PaymentCharges")- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to parse charges into PaymentCharges")?;- Ok(Self {- charge_id: refund_charges.charge_id.clone(),- charge_type: payment_charges.charge_type.clone(),- transfer_account_id: payment_charges.transfer_account_id,- options: validator::validate_charge_refund(- &refund_charges,- &payment_charges.charge_type,- )?,- })+ fn try_from(value: SplitRefundInput) -> Result<Self, Self::Error> {+ let SplitRefundInput {+ refund_request,+ payment_charges,+ charge_id,+ } = value;++ match refund_request {+ common_types::refunds::SplitRefund::StripeSplitRefund(stripe_refund) => {+ match payment_charges {+ common_types::payments::SplitPaymentsRequest::StripeSplitPayment(+ stripe_payment,+ ) => {+ let charge_id = charge_id.ok_or_else(|| {+ report!(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Missing `charge_id` in PaymentAttempt.")+ })?;++ let options = validator::validate_charge_refund(+ &common_types::refunds::SplitRefund::StripeSplitRefund(+ stripe_refund.clone(),+ ),+ &stripe_payment.charge_type,+ )?;++ Ok(Self::StripeSplitRefund(+ router_request_types::StripeSplitRefund {+ charge_id, // Use `charge_id` from `PaymentAttempt`+ transfer_account_id: stripe_payment.transfer_account_id,+ charge_type: stripe_payment.charge_type,+ options,+ },+ ))+ }+ }+ }+ }}}diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rsindex 1167fde567..2387f9a3b5 100644--- a/crates/router/src/core/refunds/validator.rs+++ b/crates/router/src/core/refunds/validator.rs@@ -147,26 +147,34 @@ pub fn validate_for_valid_refunds(}pub fn validate_charge_refund(- charges: &common_utils::types::ChargeRefunds,+ charges: &common_types::refunds::SplitRefund,charge_type: &api_enums::PaymentChargeType,) -> RouterResult<types::ChargeRefundsOptions> {match charge_type {- api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Direct) => Ok(- types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {- revert_platform_fee: charges- .revert_platform_fee- .get_required_value("revert_platform_fee")?,- }),- ),- api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Destination) => Ok(- types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund {- revert_platform_fee: charges- .revert_platform_fee- .get_required_value("revert_platform_fee")?,- revert_transfer: charges- .revert_transfer- .get_required_value("revert_transfer")?,- }),- ),+ api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Direct) => {+ let common_types::refunds::SplitRefund::StripeSplitRefund(stripe_charge) = charges;++ Ok(types::ChargeRefundsOptions::Direct(+ types::DirectChargeRefund {+ revert_platform_fee: stripe_charge+ .revert_platform_fee+ .get_required_value("revert_platform_fee")?,+ },+ ))+ }+ api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Destination) => {+ let common_types::refunds::SplitRefund::StripeSplitRefund(stripe_charge) = charges;++ Ok(types::ChargeRefundsOptions::Destination(+ types::DestinationChargeRefund {+ revert_platform_fee: stripe_charge+ .revert_platform_fee+ .get_required_value("revert_platform_fee")?,+ revert_transfer: stripe_charge+ .revert_transfer+ .get_required_value("revert_transfer")?,+ },+ ))+ }}}diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex 1f214f48ff..951d3c003f 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -14,7 +14,7 @@ use common_utils::{use error_stack::{report, ResultExt};use hyperswitch_domain_models::{merchant_connector_account::MerchantConnectorAccount, payment_address::PaymentAddress,- router_data::ErrorResponse, types::OrderDetailsWithAmount,+ router_data::ErrorResponse, router_request_types, types::OrderDetailsWithAmount,};#[cfg(feature = "payouts")]use masking::{ExposeInterface, PeekInterface};@@ -235,7 +235,7 @@ pub async fn construct_refund_router_data<'a, F>(_payment_attempt: &storage::PaymentAttempt,_refund: &'a storage::Refund,_creds_identifier: Option<String>,- _charges: Option<types::ChargeRefunds>,+ _split_refunds: Option<router_request_types::SplitRefundsRequest>,) -> RouterResult<types::RefundsRouterData<F>> {todo!()}@@ -253,7 +253,7 @@ pub async fn construct_refund_router_data<'a, F>(payment_attempt: &storage::PaymentAttempt,refund: &'a storage::Refund,creds_identifier: Option<String>,- charges: Option<types::ChargeRefunds>,+ split_refunds: Option<router_request_types::SplitRefundsRequest>,) -> RouterResult<types::RefundsRouterData<F>> {let profile_id = payment_intent.profile_id@@ -362,7 +362,7 @@ pub async fn construct_refund_router_data<'a, F>(reason: refund.refund_reason.clone(),connector_refund_id: connector_refund_id.clone(),browser_info,- charges,+ split_refunds,integrity_object: None,refund_status: refund.refund_status,},diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rsindex 745170d707..3a5c8b7da1 100644--- a/crates/router/src/db/refund.rs+++ b/crates/router/src/db/refund.rs@@ -433,6 +433,7 @@ mod storage {updated_by: new.updated_by.clone(),merchant_connector_id: new.merchant_connector_id.clone(),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(),@@ -927,6 +928,7 @@ impl RefundInterface for MockDb {updated_by: new.updated_by,merchant_connector_id: new.merchant_connector_id,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,diff --git a/crates/router/src/types.rs b/crates/router/src/types.rsindex e3d5b7246a..2ab4337851 100644--- a/crates/router/src/types.rs+++ b/crates/router/src/types.rs@@ -66,7 +66,7 @@ pub use hyperswitch_domain_models::{PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData,PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, ResponseId,RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,- SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData,+ SplitRefundsRequest, SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData,VerifyWebhookSourceRequestData,},router_response_types::{@@ -892,7 +892,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData {metadata: None,authentication_data: None,customer_acceptance: data.request.customer_acceptance.clone(),- charges: None, // TODO: allow charges on mandates?+ split_payments: None, // TODO: allow charges on mandates?merchant_order_reference_id: None,integrity_object: None,additional_payment_method_data: None,diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rsindex d046a57678..3bd3187313 100644--- a/crates/router/src/types/api/verify_connector.rs+++ b/crates/router/src/types/api/verify_connector.rs@@ -54,7 +54,7 @@ impl VerifyConnectorData {request_incremental_authorization: false,authentication_data: None,customer_acceptance: None,- charges: None,+ split_payments: None,merchant_order_reference_id: None,integrity_object: None,additional_payment_method_data: None,diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rsindex 600d610e42..09cd7cfa10 100644--- a/crates/router/src/utils/user/sample_data.rs+++ b/crates/router/src/utils/user/sample_data.rs@@ -263,7 +263,7 @@ pub async fn generate_sample_data(fingerprint_id: None,session_expiry: Some(session_expiry),request_external_three_ds_authentication: None,- charges: None,+ split_payments: None,frm_metadata: Default::default(),customer_details: None,billing_details: None,@@ -397,6 +397,7 @@ pub async fn generate_sample_data(updated_by: merchant_from_db.storage_scheme.to_string(),merchant_connector_id: payment_attempt.merchant_connector_id.clone(),charges: None,+ split_refunds: None,organization_id: org_id.clone(),connector_refund_data: None,connector_transaction_data,diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rsindex 19fb4a4372..f195aeaf7c 100644--- a/crates/router/tests/connectors/utils.rs+++ b/crates/router/tests/connectors/utils.rs@@ -404,7 +404,7 @@ pub trait ConnectorActions: Connector {reason: None,connector_refund_id: Some(refund_id),browser_info: None,- charges: None,+ split_refunds: None,integrity_object: None,refund_status: enums::RefundStatus::Pending,}),@@ -967,7 +967,7 @@ impl Default for PaymentAuthorizeType {metadata: None,authentication_data: None,customer_acceptance: None,- charges: None,+ split_payments: None,integrity_object: None,merchant_order_reference_id: None,additional_payment_method_data: None,@@ -1054,7 +1054,7 @@ impl Default for PaymentRefundType {reason: Some("Customer returned product".to_string()),connector_refund_id: None,browser_info: None,- charges: None,+ split_refunds: None,integrity_object: None,refund_status: enums::RefundStatus::Pending,};diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rsindex 68ca08c8bd..37fb57e05f 100644--- a/crates/router/tests/payments.rs+++ b/crates/router/tests/payments.rs@@ -444,7 +444,7 @@ async fn payments_create_core() {payment_method_id: None,payment_method_status: None,updated: None,- charges: None,+ split_payments: None,frm_metadata: None,merchant_order_reference_id: None,order_tax_amount: None,@@ -706,7 +706,7 @@ async fn payments_create_core_adyen_no_redirect() {payment_method_id: None,payment_method_status: None,updated: None,- charges: None,+ split_payments: None,frm_metadata: None,merchant_order_reference_id: None,order_tax_amount: None,diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rsindex 90fe3a1f84..415ea07cb9 100644--- a/crates/router/tests/payments2.rs+++ b/crates/router/tests/payments2.rs@@ -205,7 +205,7 @@ async fn payments_create_core() {payment_method_id: None,payment_method_status: None,updated: None,- charges: None,+ split_payments: None,frm_metadata: None,merchant_order_reference_id: None,order_tax_amount: None,@@ -476,7 +476,7 @@ async fn payments_create_core_adyen_no_redirect() {payment_method_id: None,payment_method_status: None,updated: None,- charges: None,+ split_payments: None,frm_metadata: None,merchant_order_reference_id: None,order_tax_amount: None,diff --git a/migrations/2024-11-22-091336_add_split_payments_in_payment_intent/down.sql b/migrations/2024-11-22-091336_add_split_payments_in_payment_intent/down.sqlnew file mode 100644index 0000000000..000b02a89c--- /dev/null+++ b/migrations/2024-11-22-091336_add_split_payments_in_payment_intent/down.sql@@ -0,0 +1,2 @@+-- This file should undo anything in `up.sql`+ALTER TABLE payment_intent DROP COLUMN IF EXISTS split_payments;diff --git a/migrations/2024-11-22-091336_add_split_payments_in_payment_intent/up.sql b/migrations/2024-11-22-091336_add_split_payments_in_payment_intent/up.sqlnew file mode 100644index 0000000000..b513f86444--- /dev/null+++ b/migrations/2024-11-22-091336_add_split_payments_in_payment_intent/up.sql@@ -0,0 +1,2 @@+-- Your SQL goes here+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS split_payments jsonb;\ No newline at end of filediff --git a/migrations/2024-11-28-103344_add_split_refunds/down.sql b/migrations/2024-11-28-103344_add_split_refunds/down.sqlnew file mode 100644index 0000000000..6eeb56a5e0--- /dev/null+++ b/migrations/2024-11-28-103344_add_split_refunds/down.sql@@ -0,0 +1,2 @@+-- This file should undo anything in `up.sql`+ALTER TABLE refund DROP COLUMN IF EXISTS split_refunds;diff --git a/migrations/2024-11-28-103344_add_split_refunds/up.sql b/migrations/2024-11-28-103344_add_split_refunds/up.sqlnew file mode 100644index 0000000000..4f36a1cb77--- /dev/null+++ b/migrations/2024-11-28-103344_add_split_refunds/up.sql@@ -0,0 +1,2 @@+-- Your SQL goes here+ALTER TABLE refund ADD COLUMN IF NOT EXISTS split_refunds jsonb;\ No newline at end of file