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
feat(core): Added Dual Refunds Validation - Chargeback+Refund (#10533)
Sayak Bhattacharya89fce11d63e5
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex a182aa9a18..f47b55a377 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -17494,7 +17494,8 @@"connector","connector_status","connector_dispute_id",- "created_at"+ "created_at",+ "is_already_refunded"],"properties": {"dispute_id": {@@ -17575,6 +17576,10 @@"type": "string","description": "The `merchant_connector_id` of the connector / processor through which the dispute was processed","nullable": true+ },+ "is_already_refunded": {+ "type": "boolean",+ "description": "Shows if the disputed amount(dispute_lost statuses only) + refunded amount is greater than captured amount"}}},@@ -17582,6 +17587,7 @@"type": "object","required": ["dispute_id",+ "amount","dispute_stage","dispute_status","connector_status",@@ -17593,6 +17599,9 @@"type": "string","description": "The identifier for dispute"},+ "amount": {+ "$ref": "#/components/schemas/StringMinorUnit"+ },"dispute_stage": {"$ref": "#/components/schemas/DisputeStage"},diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex b834e5ebad..80c0f3a6e2 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -11238,7 +11238,8 @@"connector","connector_status","connector_dispute_id",- "created_at"+ "created_at",+ "is_already_refunded"],"properties": {"dispute_id": {@@ -11319,6 +11320,10 @@"type": "string","description": "The `merchant_connector_id` of the connector / processor through which the dispute was processed","nullable": true+ },+ "is_already_refunded": {+ "type": "boolean",+ "description": "Shows if the disputed amount(dispute_lost statuses only) + refunded amount is greater than captured amount"}}},@@ -11326,6 +11331,7 @@"type": "object","required": ["dispute_id",+ "amount","dispute_stage","dispute_status","connector_status",@@ -11337,6 +11343,9 @@"type": "string","description": "The identifier for dispute"},+ "amount": {+ "$ref": "#/components/schemas/StringMinorUnit"+ },"dispute_stage": {"$ref": "#/components/schemas/DisputeStage"},diff --git a/crates/api_models/src/disputes.rs b/crates/api_models/src/disputes.rsindex d84cdd58c0..bf59a4871d 100644--- a/crates/api_models/src/disputes.rs+++ b/crates/api_models/src/disputes.rs@@ -10,7 +10,7 @@ use utoipa::ToSchema;use super::enums::{Currency, DisputeStage, DisputeStatus};use crate::{admin::MerchantConnectorInfo, files};-#[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)]+#[derive(Clone, Debug, Serialize, ToSchema)]pub struct DisputeResponse {/// The identifier for disputepub dispute_id: String,@@ -56,6 +56,8 @@ pub struct DisputeResponse {/// The `merchant_connector_id` of the connector / processor through which the dispute was processed#[schema(value_type = Option<String>)]pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,+ /// Shows if the disputed amount(dispute_lost statuses only) + refunded amount is greater than captured amount+ pub is_already_refunded: bool,}#[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq, SmithyModel)]@@ -64,6 +66,9 @@ pub struct DisputeResponsePaymentsRetrieve {/// The identifier for dispute#[smithy(value_type = "String")]pub dispute_id: String,+ /// The dispute amount+ #[smithy(value_type = "String")]+ pub amount: StringMinorUnit,/// Stage of the dispute#[smithy(value_type = "DisputeStage")]pub dispute_stage: DisputeStage,diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex a32af5b963..c9a65f330e 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -2876,6 +2876,12 @@ pub enum RefundStatus {TransactionFailure,}+impl RefundStatus {+ pub fn is_success(self) -> bool {+ matches!(self, Self::Success)+ }+}+#[derive(Clone,Copy,diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex a941df13b5..4574947f66 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -973,6 +973,55 @@ pub struct PartnerMerchantIdentifierDetails {impl_to_sql_from_sql_json!(PartnerMerchantIdentifierDetails);+/// Additional metadata for payment intent state containing refunded and disputed amounts+#[derive(+ Default,+ Serialize,+ Deserialize,+ Debug,+ Clone,+ PartialEq,+ Eq,+ AsExpression,+ FromSqlRow,+ utoipa::ToSchema,+)]+#[diesel(sql_type = Jsonb)]+pub struct PaymentIntentStateMetadata {+ /// Shows up the total refunded amount for a payment+ pub total_refunded_amount: Option<MinorUnit>,+ /// Shows up the total disputed amount across all disputes for a particular payment+ pub total_disputed_amount: Option<MinorUnit>,+}++impl PaymentIntentStateMetadata {+ /// Builder method to set total_refunded_amount+ pub fn with_total_refunded_amount(mut self, amount: MinorUnit) -> Self {+ self.total_refunded_amount = Some(amount);+ self+ }+ /// Builder method to set total_disputed_amount+ pub fn with_total_disputed_amount(mut self, amount: MinorUnit) -> Self {+ self.total_disputed_amount = Some(amount);+ self+ }+ /// Get the blocked amount which is the sum of total disputed and total refunded amounts+ pub fn get_blocked_amount(self) -> MinorUnit {+ let blocked_amount = self+ .total_disputed_amount+ .unwrap_or(MinorUnit::zero())+ .get_amount_as_i64()+ + self+ .total_refunded_amount+ .unwrap_or(MinorUnit::zero())+ .get_amount_as_i64();++ MinorUnit::new(blocked_amount)+ }+}++common_utils::impl_to_sql_from_sql_json!(PaymentIntentStateMetadata);+/// List of custom T&C messages grouped by payment method#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, utoipa::ToSchema)]pub struct PaymentMethodsConfig(diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rsindex 70ae34ad1d..322c9808f1 100644--- a/crates/diesel_models/src/dispute.rs+++ b/crates/diesel_models/src/dispute.rs@@ -68,6 +68,16 @@ pub struct Dispute {pub dispute_currency: Option<storage_enums::Currency>,}+impl Dispute {+ /// Returns true if the dispute_status is either DisputeLost, or the option is None+ pub fn is_not_lost_or_none(option: &Option<Self>) -> bool {+ option+ .as_ref()+ .map(|d| d.dispute_status != common_enums::DisputeStatus::DisputeLost)+ .unwrap_or(true)+ }+}+#[derive(Debug)]pub enum DisputeUpdate {Update {diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rsindex a58c50fb01..647bd9d919 100644--- a/crates/diesel_models/src/payment_intent.rs+++ b/crates/diesel_models/src/payment_intent.rs@@ -1,6 +1,7 @@use common_enums::{PaymentMethodType, RequestIncrementalAuthorization};-use common_types::primitive_wrappers::{- EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool,+use common_types::{+ payments::PaymentIntentStateMetadata,+ primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool},};use common_utils::{encryption::Encryption, pii, types::MinorUnit};use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};@@ -85,6 +86,7 @@ pub struct PaymentIntent {pub tokenization: Option<common_enums::Tokenization>,pub partner_merchant_identifier_details:Option<common_types::payments::PartnerMerchantIdentifierDetails>,+ pub state_metadata: Option<PaymentIntentStateMetadata>,pub merchant_reference_id: Option<common_utils::id_type::PaymentReferenceId>,pub billing_address: Option<Encryption>,pub shipping_address: Option<Encryption>,@@ -194,6 +196,7 @@ pub struct PaymentIntent {pub tokenization: Option<common_enums::Tokenization>,pub partner_merchant_identifier_details:Option<common_types::payments::PartnerMerchantIdentifierDetails>,+ pub state_metadata: Option<PaymentIntentStateMetadata>,}#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, diesel::AsExpression, PartialEq)]@@ -407,6 +410,7 @@ pub struct PaymentIntentNew {pub tokenization: Option<common_enums::Tokenization>,pub active_attempts_group_id: Option<common_utils::id_type::GlobalAttemptGroupId>,pub active_attempt_id_type: Option<common_enums::ActiveAttemptIDType>,+ pub state_metadata: Option<PaymentIntentStateMetadata>,}#[cfg(feature = "v1")]@@ -496,6 +500,7 @@ pub struct PaymentIntentNew {pub tokenization: Option<common_enums::Tokenization>,pub partner_merchant_identifier_details:Option<common_types::payments::PartnerMerchantIdentifierDetails>,+ pub state_metadata: Option<PaymentIntentStateMetadata>,}#[cfg(feature = "v2")]@@ -531,6 +536,10 @@ pub enum PaymentIntentUpdate {updated_by: String,},Update(Box<PaymentIntentUpdateFields>),+ StateMetadataUpdate {+ state_metadata: PaymentIntentStateMetadata,+ updated_by: String,+ },PaymentCreateUpdate {return_url: Option<String>,status: Option<storage_enums::IntentStatus>,@@ -715,6 +724,7 @@ pub struct PaymentIntentUpdateInternal {pub force_3ds_challenge: Option<bool>,pub is_iframe_redirection_enabled: Option<bool>,pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,+ pub state_metadata: Option<PaymentIntentStateMetadata>,}#[cfg(feature = "v2")]@@ -761,6 +771,7 @@ impl PaymentIntentUpdateInternal {force_3ds_challenge,is_iframe_redirection_enabled,enable_partial_authorization,+ state_metadata,} = self;PaymentIntent {@@ -847,6 +858,7 @@ impl PaymentIntentUpdateInternal {billing_descriptor: source.billing_descriptor,tokenization: None,partner_merchant_identifier_details: source.partner_merchant_identifier_details,+ state_metadata,}}}@@ -905,6 +917,7 @@ pub struct PaymentIntentUpdateInternal {pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,pub shipping_cost: Option<MinorUnit>,+ pub state_metadata: Option<PaymentIntentStateMetadata>,}#[cfg(feature = "v1")]@@ -960,6 +973,7 @@ impl PaymentIntentUpdate {enable_partial_authorization,enable_overcapture,shipping_cost,+ ..} = self.into();PaymentIntent {amount: amount.unwrap_or(source.amount),@@ -1041,11 +1055,67 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {amount: None,currency: None,status: None,+ state_metadata: None,+ amount_captured: None,+ customer_id: None,+ return_url: None,+ setup_future_usage: None,+ off_session: None,+ billing_address_id: None,+ shipping_address_id: None,+ active_attempt_id: None,+ business_country: None,+ business_label: None,+ description: None,+ statement_descriptor_name: None,+ statement_descriptor_suffix: None,+ order_details: None,+ attempt_count: None,+ merchant_decision: None,+ payment_confirm_source: None,+ surcharge_applicable: None,+ incremental_authorization_allowed: None,+ authorization_count: None,+ session_expiry: None,+ fingerprint_id: None,+ request_external_three_ds_authentication: None,+ frm_metadata: None,+ customer_details: None,+ billing_details: None,+ merchant_order_reference_id: None,+ shipping_details: None,+ is_payment_processor_token_flow: None,+ tax_details: None,+ force_3ds_challenge: None,+ is_iframe_redirection_enabled: None,+ extended_return_url: None,+ payment_channel: None,+ feature_metadata: None,+ tax_status: None,+ discount_amount: None,+ order_date: None,+ shipping_amount_tax: None,+ duty_amount: None,+ enable_partial_authorization: None,+ enable_overcapture: None,+ shipping_cost: None,+ },+ PaymentIntentUpdate::StateMetadataUpdate {+ state_metadata,+ updated_by,+ } => Self {+ state_metadata: Some(state_metadata),+ modified_at: common_utils::date_time::now(),+ updated_by,+ amount: None,+ currency: None,+ status: None,amount_captured: None,customer_id: None,return_url: None,setup_future_usage: None,off_session: None,+ metadata: None,billing_address_id: None,shipping_address_id: None,active_attempt_id: None,@@ -1136,6 +1206,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {enable_partial_authorization: value.enable_partial_authorization,enable_overcapture: value.enable_overcapture,shipping_cost: value.shipping_cost,+ state_metadata: None,},PaymentIntentUpdate::PaymentCreateUpdate {return_url,@@ -1187,6 +1258,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: return_url,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1243,6 +1315,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1299,6 +1372,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1363,6 +1437,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1418,6 +1493,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1474,6 +1550,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1529,6 +1606,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1584,6 +1662,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1638,6 +1717,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1689,6 +1769,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1742,6 +1823,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1795,6 +1877,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1846,6 +1929,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,@@ -1902,6 +1986,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {extended_return_url: None,payment_channel: None,feature_metadata: None,+ state_metadata: None,tax_status: None,discount_amount: None,order_date: None,diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 024418e5a5..3890954941 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -1246,6 +1246,7 @@ diesel::table! {#[max_length = 64]tokenization -> Nullable<Varchar>,partner_merchant_identifier_details -> Nullable<Jsonb>,+ state_metadata -> Nullable<Jsonb>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 4700e6f300..29dc664d20 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -1181,6 +1181,7 @@ diesel::table! {#[max_length = 64]tokenization -> Nullable<Varchar>,partner_merchant_identifier_details -> Nullable<Jsonb>,+ state_metadata -> Nullable<Jsonb>,#[max_length = 64]merchant_reference_id -> Nullable<Varchar>,billing_address -> Nullable<Bytea>,diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rsindex 9d3bfdc338..118e0347e0 100644--- a/crates/hyperswitch_domain_models/src/payments.rs+++ b/crates/hyperswitch_domain_models/src/payments.rs@@ -23,6 +23,7 @@ use common_utils::{types::{keymanager::ToEncryptable, CreatedBy, MinorUnit},};use diesel_models::payment_intent::TaxDetails;+use error_stack::Report;#[cfg(feature = "v2")]use error_stack::ResultExt;use masking::Secret;@@ -137,6 +138,7 @@ pub struct PaymentIntent {pub tokenization: Option<common_enums::Tokenization>,pub partner_merchant_identifier_details:Option<common_types::payments::PartnerMerchantIdentifierDetails>,+ pub state_metadata: Option<common_types::payments::PaymentIntentStateMetadata>,}impl PaymentIntent {@@ -335,6 +337,47 @@ impl PaymentIntent {}})}++ #[cfg(feature = "v1")]+ pub fn validate_amount_against_intent_state_metadata(+ &self,+ requested_amount: Option<MinorUnit>,+ ) -> CustomResult<(), common_utils::errors::ValidationError> {+ let captured = self+ .amount_captured+ .unwrap_or(MinorUnit::zero())+ .get_amount_as_i64();++ let blocked_amount = self+ .state_metadata+ .clone()+ .unwrap_or_default()+ .get_blocked_amount()+ .get_amount_as_i64();+ let requested = requested_amount+ .unwrap_or(MinorUnit::zero())+ .get_amount_as_i64();++ let total = blocked_amount + requested;++ if total > captured {+ Err(+ Report::new(common_utils::errors::ValidationError::InvalidValue {+ message: "Requested amount exceeds available captured amount.".to_string(),+ })+ .attach_printable(format!(+ "Validation failed because blocked_amount ({}) + requested_amount ({}) \+ exceeds amount_captured ({}). Available amount: {}",+ blocked_amount,+ requested,+ captured,+ (captured - blocked_amount).max(0),+ )),+ )+ } else {+ Ok(())+ }+ }}#[cfg(feature = "v2")]diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex ab3eaa602c..28f58635b5 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -331,6 +331,10 @@ pub enum PaymentIntentUpdate {updated_by: String,shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,},+ StateMetadataUpdate {+ state_metadata: common_types::payments::PaymentIntentStateMetadata,+ updated_by: String,+ },}#[cfg(feature = "v1")]@@ -461,6 +465,7 @@ pub struct PaymentIntentUpdateInternal {pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>,pub shipping_cost: Option<MinorUnit>,+ pub state_metadata: Option<common_types::payments::PaymentIntentStateMetadata>,}// This conversion is used in the `update_payment_intent` function@@ -514,6 +519,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::ConfirmIntentPostUpdate {@@ -562,6 +568,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::SyncUpdate {status,@@ -608,6 +615,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::CaptureUpdate {status,@@ -654,6 +662,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::SessionIntentUpdate {prerouting_algorithm,@@ -703,6 +712,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::UpdateIntent(boxed_intent) => {let PaymentIntentUpdateFields {@@ -791,6 +801,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge,is_iframe_redirection_enabled,enable_partial_authorization,+ state_metadata: None,})}PaymentIntentUpdate::RecordUpdate {@@ -840,6 +851,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::VoidUpdate { status, updated_by } => Ok(Self {status: Some(status),@@ -883,6 +895,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::AttemptGroupUpdate {updated_by,@@ -929,6 +942,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),PaymentIntentUpdate::SplitPaymentStatusUpdate { status, updated_by } => Ok(Self {status: Some(status),@@ -971,6 +985,7 @@ impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternalforce_3ds_challenge: None,is_iframe_redirection_enabled: None,enable_partial_authorization: None,+ state_metadata: None,}),}}@@ -1177,6 +1192,60 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {shipping_details,..Default::default()},+ PaymentIntentUpdate::StateMetadataUpdate {+ state_metadata,+ updated_by,+ } => Self {+ state_metadata: Some(state_metadata),+ updated_by,+ amount: None,+ currency: None,+ status: None,+ amount_captured: None,+ customer_id: None,+ return_url: None,+ setup_future_usage: None,+ off_session: None,+ metadata: None,+ billing_address_id: None,+ shipping_address_id: None,+ modified_at: None,+ active_attempt_id: None,+ business_country: None,+ business_label: None,+ description: None,+ statement_descriptor_name: None,+ statement_descriptor_suffix: None,+ order_details: None,+ attempt_count: None,+ merchant_decision: None,+ payment_confirm_source: None,+ surcharge_applicable: None,+ incremental_authorization_allowed: None,+ authorization_count: None,+ fingerprint_id: None,+ session_expiry: None,+ request_external_three_ds_authentication: None,+ frm_metadata: None,+ customer_details: None,+ billing_details: None,+ merchant_order_reference_id: None,+ shipping_details: None,+ is_payment_processor_token_flow: None,+ tax_details: None,+ force_3ds_challenge: None,+ is_iframe_redirection_enabled: None,+ payment_channel: None,+ feature_metadata: None,+ tax_status: None,+ discount_amount: None,+ order_date: None,+ shipping_amount_tax: None,+ duty_amount: None,+ enable_partial_authorization: None,+ enable_overcapture: None,+ shipping_cost: None,+ },}}}@@ -1228,6 +1297,13 @@ impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {metadata,updated_by,},+ PaymentIntentUpdate::StateMetadataUpdate {+ state_metadata,+ updated_by,+ } => Self::StateMetadataUpdate {+ state_metadata,+ updated_by,+ },PaymentIntentUpdate::Update(value) => {Self::Update(Box::new(DieselPaymentIntentUpdateFields {amount: value.amount,@@ -1440,6 +1516,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateIntenable_partial_authorization,enable_overcapture,shipping_cost,+ state_metadata,} = value;Self {amount,@@ -1491,6 +1568,7 @@ impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateIntenable_partial_authorization,enable_overcapture,shipping_cost,+ state_metadata,}}}@@ -1979,6 +2057,7 @@ impl behaviour::Conversion for PaymentIntent {billing_descriptor: None,tokenization: None,partner_merchant_identifier_details: None,+ state_metadata: None,})}async fn convert_back(@@ -2241,6 +2320,7 @@ impl behaviour::Conversion for PaymentIntent {tokenization: None,active_attempt_id_type: Some(self.active_attempt_id_type),active_attempts_group_id: self.active_attempts_group_id,+ state_metadata: None,})}}@@ -2328,6 +2408,7 @@ impl behaviour::Conversion for PaymentIntent {billing_descriptor: self.billing_descriptor,tokenization: self.tokenization,partner_merchant_identifier_details: self.partner_merchant_identifier_details,+ state_metadata: self.state_metadata,})}@@ -2442,6 +2523,7 @@ impl behaviour::Conversion for PaymentIntent {tokenization: storage_model.tokenization,partner_merchant_identifier_details: storage_model.partner_merchant_identifier_details,+ state_metadata: storage_model.state_metadata,})}.await@@ -2527,6 +2609,7 @@ impl behaviour::Conversion for PaymentIntent {billing_descriptor: self.billing_descriptor,tokenization: self.tokenization,partner_merchant_identifier_details: self.partner_merchant_identifier_details,+ state_metadata: self.state_metadata,})}}diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rsindex 90fd39751a..14bcb113d2 100644--- a/crates/router/src/core/disputes.rs+++ b/crates/router/src/core/disputes.rs@@ -63,24 +63,26 @@ pub async fn retrieve_dispute().await.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {- dispute_id: req.dispute_id,+ dispute_id: req.dispute_id.clone(),})?;core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?;+ let db = &state.store;+ #[cfg(feature = "v1")]+ let payment_intent = db+ .find_payment_intent_by_payment_id_merchant_id(+ &dispute.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;+#[cfg(feature = "v1")]- let dispute_response =+ let mut dispute_response =if should_call_connector_for_dispute_sync(req.force_sync, dispute.dispute_status) {- let db = &state.store;core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?;- let payment_intent = db- .find_payment_intent_by_payment_id_merchant_id(- &dispute.payment_id,- platform.get_processor().get_account().get_id(),- platform.get_processor().get_key_store(),- platform.get_processor().get_account().storage_scheme,- )- .await- .change_context(errors::ApiErrorResponse::PaymentNotFound)?;let payment_attempt = db.find_payment_attempt_by_attempt_id_merchant_id(@@ -147,7 +149,7 @@ pub async fn retrieve_dispute(update_dispute_data(&state,- platform,+ platform.clone(),business_profile,Some(dispute.clone()),dispute_sync_response,@@ -157,9 +159,20 @@ pub async fn retrieve_dispute(.await.attach_printable("Dispute update failed")?} else {- api_models::disputes::DisputeResponse::foreign_from(dispute)+ api_models::disputes::DisputeResponse::foreign_from(dispute.clone())};+ #[cfg(feature = "v1")]+ {+ let validation_result = payment_intent.validate_amount_against_intent_state_metadata(None);+ if let Err(err) = &validation_result {+ logger::debug!(+ ?err,+ "Dispute validation failed against intent state metadata"+ );+ }+ dispute_response.is_already_refunded = validation_result.is_err();+ }#[cfg(not(feature = "v1"))]let dispute_response = api_models::disputes::DisputeResponse::foreign_from(dispute);@@ -183,10 +196,32 @@ pub async fn retrieve_disputes_list(.await.to_not_found_response(errors::ApiErrorResponse::InternalServerError).attach_printable("Unable to retrieve disputes")?;- let disputes_list = disputes+ let mut disputes_list: Vec<api_models::disputes::DisputeResponse> = disputes.into_iter().map(api_models::disputes::DisputeResponse::foreign_from).collect();+ #[cfg(feature = "v1")]+ for dispute_response in &mut disputes_list {+ let payment_intent = state+ .store+ .find_payment_intent_by_payment_id_merchant_id(+ &dispute_response.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::PaymentNotFound)?;+ let validation_result = payment_intent.validate_amount_against_intent_state_metadata(None);++ if let Err(err) = &validation_result {+ logger::debug!(+ ?err,+ "Dispute validation failed against intent state metadata"+ );+ }+ dispute_response.is_already_refunded = validation_result.is_err();+ }Ok(services::ApplicationResponse::Json(disputes_list))}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 4ee21e3689..ef49d053d5 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -13645,3 +13645,116 @@ impl<F: Clone> OperationSessionSetters<F> for PaymentCancelData<F> {self.payment_attempt.cancellation_reason = cancellation_reason;}}++#[derive(Debug, Clone)]+pub struct PaymentIntentStateMetadataExt(pub common_payments_types::PaymentIntentStateMetadata);++impl From<common_payments_types::PaymentIntentStateMetadata> for PaymentIntentStateMetadataExt {+ fn from(meta: common_payments_types::PaymentIntentStateMetadata) -> Self {+ Self(meta)+ }+}++#[cfg(feature = "v1")]+impl PaymentIntentStateMetadataExt {+ pub async fn update_intent_state_metadata_for_refund(+ self,+ state: &SessionState,+ platform: &domain::Platform,+ payment_intent: payments::PaymentIntent,+ ) -> CustomResult<(), errors::ApiErrorResponse> {+ let db = state.store.clone();+ let key_store = platform.get_processor().get_key_store().clone();+ let merchant_account = platform.get_processor().get_account().clone();+ // Update payment_intent for the refund's payment_id+ // Calculate total_refunded_amount based on all succeeded refunds for that payment_id+ let all_refunds_for_payment = db+ .find_refund_by_payment_id_merchant_id(+ &payment_intent.payment_id,+ merchant_account.get_id(),+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to fetch refunds for payment_id: {:?}",+ payment_intent.payment_id+ )+ })?;++ let total_refunded_amount: i64 = all_refunds_for_payment+ .iter()+ .filter(|r| r.refund_status.is_success())+ .map(|r| r.refund_amount.get_amount_as_i64())+ .sum();++ let current_state = payment_intent+ .state_metadata+ .clone()+ .unwrap_or_default()+ .with_total_refunded_amount(MinorUnit::new(total_refunded_amount));++ let domain_update = payments::payment_intent::PaymentIntentUpdate::StateMetadataUpdate {+ state_metadata: current_state.clone(),+ updated_by: merchant_account.storage_scheme.to_string(),+ };++ db.update_payment_intent(+ payment_intent.clone(),+ domain_update,+ &key_store,+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update payment intent with total_refunded_amount")?;++ Ok(())+ }++ pub async fn update_intent_state_metadata_for_dispute(+ self,+ state: &SessionState,+ platform: &domain::Platform,+ payment_intent: payments::PaymentIntent,+ dispute: &diesel_models::dispute::Dispute,+ ) -> CustomResult<(), errors::ApiErrorResponse> {+ let db = state.store.clone();+ let key_store = platform.get_processor().get_key_store().clone();+ let merchant_account = platform.get_processor().get_account().clone();+ let dispute_clone = dispute.clone();+ let total_disputed_amount = payment_intent+ .state_metadata+ .clone()+ .unwrap_or_default()+ .total_disputed_amount+ .map(|amount| amount + dispute_clone.dispute_amount)+ .or(Some(dispute_clone.dispute_amount));++ if let Some(disputed_amount) = total_disputed_amount {+ let current_state = payment_intent+ .state_metadata+ .clone()+ .unwrap_or_default()+ .with_total_disputed_amount(disputed_amount);++ let domain_update =+ payments::payment_intent::PaymentIntentUpdate::StateMetadataUpdate {+ state_metadata: current_state,+ updated_by: merchant_account.storage_scheme.to_string(),+ };++ db.update_payment_intent(+ payment_intent,+ domain_update,+ &key_store,+ merchant_account.storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update payment_intent.state metadata")?;+ }+ Ok(())+ }+}diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 34096e6be4..25820bcf80 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -4251,6 +4251,7 @@ mod tests {enable_overcapture: None,billing_descriptor: None,partner_merchant_identifier_details: None,+ state_metadata: None,};let req_cs = Some("1".to_string());assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());@@ -4340,6 +4341,7 @@ mod tests {billing_descriptor: None,tokenization: None,partner_merchant_identifier_details: None,+ state_metadata: None,};let req_cs = Some("1".to_string());assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())@@ -4427,6 +4429,7 @@ mod tests {enable_overcapture: None,billing_descriptor: None,partner_merchant_identifier_details: None,+ state_metadata: 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/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex 8222fe7bb4..d3b39ebf1b 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -1692,6 +1692,7 @@ impl PaymentCreate {partner_merchant_identifier_details: request.partner_merchant_identifier_details.clone(),+ state_metadata: None,})}}diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex bd8edcc69a..3e6aa6fed1 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -27,7 +27,7 @@ use crate::{errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},payments::{self, access_token, gateway::context as gateway_context, helpers,- helpers::MerchantConnectorAccountType,+ helpers::MerchantConnectorAccountType, PaymentIntentStateMetadataExt,},refunds::transformers::SplitRefundInput,unified_connector_service,@@ -87,6 +87,13 @@ pub async fn refund_create_core(},)?;+ payment_intent+ .validate_amount_against_intent_state_metadata(req.amount)+ .map_err(|err| {+ err.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)+ .attach_printable("refund amount validation against payment intent failed")+ })?;+// Amount is not passed in request refer from payment intent.amount = req.amount@@ -1017,6 +1024,26 @@ pub async fn sync_refund_with_gateway(},};+ // If the original refund status was not success and upon a force sync it is now success, in that case we update the state metadata of the payment intent+ tokio::spawn({+ let state = state.clone();+ let platform = platform.clone();+ let payment_intent = payment_intent.clone();+ let state_metadata = payment_intent.state_metadata.clone().unwrap_or_default();++ async move {+ if let Err(err) = PaymentIntentStateMetadataExt::from(state_metadata)+ .update_intent_state_metadata_for_refund(&state, &platform, payment_intent)+ .await+ {+ logger::error!(+ ?err,+ "Failed to update payment intent state metadata after refund sync"+ );+ }+ }+ });+let response = state.store.update_refund(@@ -1337,7 +1364,7 @@ pub async fn validate_and_create_refund(.await{Ok(refund) => {- Box::pin(schedule_refund_execution(+ let (updated_refund, raw_response) = Box::pin(schedule_refund_execution(state,refund.clone(),refund_type,@@ -1348,7 +1375,34 @@ pub async fn validate_and_create_refund(split_refunds,req.all_keys_required,))- .await?+ .await?;++ // Update the state metadata of the payment intent if the refund is successful+ if updated_refund.refund_status.is_success() {+ tokio::spawn({+ let state = state.clone();+ let platform = platform.clone();+ let payment_intent = payment_intent.clone();+ let state_metadata = payment_intent.state_metadata.clone().unwrap_or_default();++ async move {+ if let Err(err) = PaymentIntentStateMetadataExt::from(state_metadata)+ .update_intent_state_metadata_for_refund(+ &state,+ &platform,+ payment_intent,+ )+ .await+ {+ logger::error!(+ ?err,+ "Failed to update payment intent state metadata during refund creation"+ );+ }+ }+ });+ }+ (updated_refund, raw_response)}Err(err) => {if err.current_context().is_db_unique_violation() {diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex 1e69287328..d571283077 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -38,7 +38,7 @@ use crate::{errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},metrics, payment_methods,payment_methods::cards,- payments::{self, tokenization},+ payments::{self, tokenization, PaymentIntentStateMetadataExt},refunds, relay, unified_connector_service, utils as core_utils,webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data},},@@ -1999,6 +1999,39 @@ async fn refunds_incoming_webhook_flow(.attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))?.0};++ let payment_intent = db+ .find_payment_intent_by_payment_id_merchant_id(+ &refund.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!(+ "Failed to find payment intent for payment_id: {:?}",+ refund.payment_id+ )+ })?;+ let state_task = state.clone();+ let platform_task = platform.clone();+ let payment_intent_task = payment_intent.clone();+ tokio::spawn(async move {+ if let Err(err) = PaymentIntentStateMetadataExt::from(+ payment_intent_task+ .state_metadata+ .clone()+ .unwrap_or_default(),+ )+ .update_intent_state_metadata_for_refund(&state_task, &platform_task, payment_intent_task)+ .await+ {+ tracing::error!(?err, "Failed to update intent state metadata for refund");+ }+ });+let event_type: Option<enums::EventType> = updated_refund.refund_status.into();// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook@@ -2613,7 +2646,7 @@ async fn disputes_incoming_webhook_flow(let dispute_object = get_or_update_dispute_object(state.clone(),- option_dispute,+ option_dispute.clone(),dispute_details,platform.get_processor().get_account().get_id(),&platform.get_processor().get_account().organization_id,@@ -2623,6 +2656,46 @@ async fn disputes_incoming_webhook_flow(connector.id(),).await?;++ //Updating Payment Intent State Metadata if Dispute is lost and customer got their funds back+ if diesel_models::dispute::Dispute::is_not_lost_or_none(&option_dispute)+ && dispute_object.dispute_status == common_enums::DisputeStatus::DisputeLost+ {+ tokio::spawn({+ let state = state.clone();+ let platform = platform.clone();+ let payment_intent = db+ .find_payment_intent_by_payment_id_merchant_id(+ &payment_attempt.payment_id,+ platform.get_processor().get_account().get_id(),+ platform.get_processor().get_key_store(),+ platform.get_processor().get_account().storage_scheme,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to fetch payment_intent")?;+ let dispute_object = dispute_object.clone();+ let state_metadata = payment_intent.state_metadata.clone().unwrap_or_default();++ async move {+ if let Err(err) = PaymentIntentStateMetadataExt::from(state_metadata)+ .update_intent_state_metadata_for_dispute(+ &state,+ &platform,+ payment_intent,+ &dispute_object,+ )+ .await+ {+ logger::error!(+ ?err,+ "Failed to update payment intent state metadata after dispute lost"+ );+ }+ }+ });+ }+let disputes_response = Box::new(dispute_object.clone().foreign_into());let event_type: enums::EventType = dispute_object.dispute_status.into();diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 503ceb5f2d..d964d04abf 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -715,6 +715,7 @@ impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponse {created_at: dispute.created_at,profile_id: dispute.profile_id,merchant_connector_id: dispute.merchant_connector_id,+ is_already_refunded: false,}}}@@ -761,6 +762,7 @@ impl ForeignFrom<storage::Dispute> for api_models::disputes::DisputeResponsePaymfn foreign_from(dispute: storage::Dispute) -> Self {Self {dispute_id: dispute.dispute_id,+ amount: dispute.amount,dispute_stage: dispute.dispute_stage,dispute_status: dispute.dispute_status,connector_status: dispute.connector_status,diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rsindex d956bc7f5f..b4458a08b4 100644--- a/crates/router/src/utils/user/sample_data.rs+++ b/crates/router/src/utils/user/sample_data.rs@@ -298,6 +298,7 @@ pub async fn generate_sample_data(billing_descriptor: None,tokenization: None,partner_merchant_identifier_details: None,+ state_metadata: None,};let (connector_transaction_id, processor_transaction_data) =ConnectorTransactionId::form_id_and_data(attempt_id.clone());diff --git a/migrations/2025-12-03-122636_add_state_to_payment_intent/down.sql b/migrations/2025-12-03-122636_add_state_to_payment_intent/down.sqlnew file mode 100644index 0000000000..00ff8fce69--- /dev/null+++ b/migrations/2025-12-03-122636_add_state_to_payment_intent/down.sql@@ -0,0 +1,3 @@+-- This file should undo anything in `up.sql`+ALTER TABLE payment_intent+DROP COLUMN state_metadata;diff --git a/migrations/2025-12-03-122636_add_state_to_payment_intent/up.sql b/migrations/2025-12-03-122636_add_state_to_payment_intent/up.sqlnew file mode 100644index 0000000000..ecb57885f2--- /dev/null+++ b/migrations/2025-12-03-122636_add_state_to_payment_intent/up.sql@@ -0,0 +1,3 @@+-- Your SQL goes here+ALTER TABLE payment_intent+ADD COLUMN state_metadata JSONB NULL;