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(router): enhance conflicted payment handling (#14288)
Akshaya Shankar224584ba80f8
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex 0f77408a55..2b4d6dd8e8 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -652,21 +652,43 @@ pub enum TokenStatus {/// Enum representing the allowed intent statuses for manual status update/// Only Succeeded and Failed are valid transitions from Review state-#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+#[derive(+ Debug, serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq, Hash, ToSchema,+)]#[serde(rename_all = "snake_case")]pub enum ManualUpdateIntentStatus {/// Transition the payment to succeeded stateSucceeded,/// Transition the payment to failed stateFailed,+ /// Transition the payment to partially captured state+ PartiallyCaptured,+ /// Transition the payment to requires capture state+ RequiresCapture,+ /// Transition the payment to partially authorized, requires capture state+ PartiallyAuthorizedAndRequiresCapture,+ /// Transition the payment to partially captured and still capturable state+ PartiallyCapturedAndCapturable,}impl ManualUpdateIntentStatus {- /// Convert ManualUpdateIntentStatus to the corresponding IntentStatus- pub fn to_intent_status(&self) -> IntentStatus {+ /// Convert ManualUpdateIntentStatus to the corresponding IntentStatus.+ /// Goes via `to_attempt_status()` and the existing `AttemptStatus -> IntentStatus`+ /// conversion, rather than hand-maintaining a second, independent mapping that could+ /// drift out of sync with it.+ pub fn to_intent_status(self) -> IntentStatus {+ self.to_attempt_status().into()+ }++ /// Convert ManualUpdateIntentStatus to the corresponding AttemptStatus+ pub fn to_attempt_status(self) -> AttemptStatus {match self {- Self::Succeeded => IntentStatus::Succeeded,- Self::Failed => IntentStatus::Failed,+ Self::Succeeded => AttemptStatus::Charged,+ Self::Failed => AttemptStatus::Failure,+ Self::PartiallyCaptured => AttemptStatus::PartialCharged,+ Self::RequiresCapture => AttemptStatus::Authorized,+ Self::PartiallyAuthorizedAndRequiresCapture => AttemptStatus::PartiallyAuthorized,+ Self::PartiallyCapturedAndCapturable => AttemptStatus::PartialChargedAndChargeable,}}}diff --git a/crates/api_models/src/errors/types.rs b/crates/api_models/src/errors/types.rsindex 6abd2d1005..abe94a8d6f 100644--- a/crates/api_models/src/errors/types.rs+++ b/crates/api_models/src/errors/types.rs@@ -166,6 +166,7 @@ impl ApiErrorResponse {| Self::NotFound(_)| Self::BadRequest(_) => "invalid_request",Self::InternalServerError(_) => "api",+ Self::DomainError(err) if err.sub_code == "IE" => "integrity_check_failed",Self::DomainError(_) => "blocked",Self::ConnectorError(_, _) => "connector",}diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex fa4d984df5..8eb3220b49 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -39,11 +39,11 @@ use crate::{PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,- PaymentsManualStatusUpdateRequest, PaymentsManualStatusUpdateResponse,- PaymentsManualUpdateRequest, PaymentsManualUpdateResponse,- PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest,- PaymentsRetrieveRequest, PaymentsStartRequest, PaymentsUpdateMetadataRequest,- PaymentsUpdateMetadataResponse,+ PaymentsManualStatusUpdateEligibleStatusesResponse, PaymentsManualStatusUpdateRequest,+ PaymentsManualStatusUpdateResponse, PaymentsManualUpdateRequest,+ PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest,+ PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest,+ PaymentsStartRequest, PaymentsUpdateMetadataRequest, PaymentsUpdateMetadataResponse,},};@@ -650,6 +650,15 @@ impl ApiEventMetric for PaymentsManualStatusUpdateResponse {}}+#[cfg(feature = "v1")]+impl ApiEventMetric for PaymentsManualStatusUpdateEligibleStatusesResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payment {+ payment_id: self.payment_id.clone(),+ })+ }+}+impl ApiEventMetric for PaymentsSessionResponse {fn get_api_event_type(&self) -> Option<ApiEventsType> {Some(ApiEventsType::Payment {diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex c183cb498a..9e10ed0ec5 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -11953,10 +11953,12 @@ pub struct PaymentsManualUpdateResponse {pub amount_captured: Option<MinorUnit>,}-/// Request to manually update payment status from Review state (Dashboard API)+/// Request to manually update payment status from the Review or Conflicted state (Dashboard API)#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]pub struct PaymentsManualStatusUpdateRequest {- /// The target status to transition to (Succeeded or Failed)+ /// The target status to transition to. From `review`, only Succeeded or Failed are valid;+ /// from `conflicted`, the valid subset is returned by the `/manual-status-update` (GET)+ /// eligibility check.pub intent_status: enums::ManualUpdateIntentStatus,}@@ -11973,6 +11975,17 @@ pub struct PaymentsManualStatusUpdateResponse {pub attempt_status: enums::AttemptStatus,}+/// Response listing which statuses a payment is currently eligible for a manual status update+/// to. Only returned for payments in the `conflicted` state.+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+pub struct PaymentsManualStatusUpdateEligibleStatusesResponse {+ /// The identifier for the payment+ pub payment_id: id_type::PaymentId,+ /// The statuses that a manual status update for this payment may currently target,+ /// computed from the payment's capture method and requested/received/capturable amounts.+ pub eligible_statuses: HashSet<enums::ManualUpdateIntentStatus>,+}+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, SmithyModel)]#[smithy(namespace = "com.hyperswitch.smithy.types")]/// Indicates if 3DS method data was successfully completed or notdiff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rsindex 1df1811525..22e9fa1ea4 100644--- a/crates/common_utils/src/errors.rs+++ b/crates/common_utils/src/errors.rs@@ -88,6 +88,8 @@ pub struct IntegrityCheckError {pub field_names: String,/// Connector transaction reference idpub connector_transaction_id: Option<String>,+ /// Amount actually received/reported by the connector, as seen at integrity check time+ pub amount: Option<MinorUnit>,}/// Cryptographic algorithm errorsdiff --git a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs b/crates/hyperswitch_domain_models/src/errors/api_error_response.rsindex 884e64649c..d120643c9a 100644--- a/crates/hyperswitch_domain_models/src/errors/api_error_response.rs+++ b/crates/hyperswitch_domain_models/src/errors/api_error_response.rs@@ -336,6 +336,7 @@ pub enum ApiErrorResponse {WebhookInvalidMerchantSecret,#[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}")]IntegrityCheckFailed {+ payment_id: Option<common_utils::id_type::PaymentId>,reason: String,field_names: String,connector_transaction_id: Option<String>,@@ -744,13 +745,15 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponSelf::IntegrityCheckFailed {reason,field_names,- connector_transaction_id- } => AER::InternalServerError(ApiError::new(+ connector_transaction_id,+ payment_id+ } => AER::DomainError(ApiError::new("IE",0,format!("{reason} as data mismatched for {field_names}"),Some(Extra {connector_transaction_id: connector_transaction_id.to_owned(),+ payment_id: payment_id.to_owned(),..Default::default()}))),diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex 9360620070..a2fb0dd4e5 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -351,6 +351,10 @@ pub struct PaymentsCaptureData {pub integrity_object: Option<CaptureIntegrityObject>,pub webhook_url: Option<String>,pub merchant_order_reference_id: Option<String>,+ /// Whether the merchant is allowed to capture more than the originally authorized/requested+ /// amount for this payment. Used to avoid treating a legitimate overcapture as an integrity+ /// mismatch.+ pub is_overcapture_enabled: Option<common_types::primitive_wrappers::OvercaptureEnabledBool>,}#[derive(Debug, Clone, PartialEq, Serialize)]@@ -1023,6 +1027,7 @@ pub struct CompleteAuthorizeData {pub connector_intent_metadata: Option<ConnectorMetadata>,pub order_id: Option<String>,pub force_3ds_challenge: Option<bool>,+ pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,}#[derive(Debug, Clone, Serialize)]diff --git a/crates/hyperswitch_interfaces/src/integrity.rs b/crates/hyperswitch_interfaces/src/integrity.rsindex 6fd3be9e5f..6b4095e775 100644--- a/crates/hyperswitch_interfaces/src/integrity.rs+++ b/crates/hyperswitch_interfaces/src/integrity.rs@@ -1,9 +1,72 @@-use common_utils::errors::IntegrityCheckError;+use common_utils::{errors::IntegrityCheckError, types::MinorUnit};use hyperswitch_domain_models::router_request_types::{AuthoriseIntegrityObject, CaptureIntegrityObject, PaymentsAuthorizeData, PaymentsCaptureData,PaymentsSyncData, RefundIntegrityObject, RefundsData, SyncIntegrityObject,};+/// Whether the connector may report a lower amount than requested (e.g. partial authorization).+#[derive(Debug, Clone, Copy)]+pub struct AllowLowerAmount(bool);+impl AllowLowerAmount {+ /// Creates a new instance of `AllowLowerAmount`+ pub fn new(value: bool) -> Self {+ Self(value)+ }+}+impl std::ops::Deref for AllowLowerAmount {+ type Target = bool;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++/// Whether the connector may report a higher amount than requested (e.g. overcapture).+#[derive(Debug, Clone, Copy)]+pub struct AllowHigherAmount(bool);+impl AllowHigherAmount {+ /// Creates a new instance of `AllowHigherAmount`+ pub fn new(value: bool) -> Self {+ Self(value)+ }+}+impl std::ops::Deref for AllowHigherAmount {+ type Target = bool;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++/// Governs whether a connector-reported amount that differs from the amount we requested+/// should still be treated as an integrity failure. Some payment features intentionally+/// authorize/capture a different amount than requested (e.g. partial authorization,+/// overcapture), so those differences must not be conflated with genuine data-integrity+/// mismatches.+#[derive(Debug, Clone, Copy)]+pub struct AmountMismatchTolerance {+ /// The connector may report a lower amount than requested (e.g. partial authorization).+ pub allow_lower: AllowLowerAmount,+ /// The connector may report a higher amount than requested (e.g. overcapture).+ pub allow_higher: AllowHigherAmount,+}++impl AmountMismatchTolerance {+ /// No tolerance: the connector-reported amount must exactly match what was requested.+ fn strict() -> Self {+ Self {+ allow_lower: AllowLowerAmount::new(false),+ allow_higher: AllowHigherAmount::new(false),+ }+ }++ fn permits(self, expected: MinorUnit, actual: MinorUnit) -> bool {+ actual == expected+ || (*self.allow_lower && actual < expected)+ || (*self.allow_higher && actual > expected)+ }+}+/// Connector Integrity trait to check connector data integritypub trait FlowIntegrity {/// Output type for the connector@@ -13,6 +76,7 @@ pub trait FlowIntegrity {req_integrity_object: Self::IntegrityObject,res_integrity_object: Self::IntegrityObject,connector_transaction_id: Option<String>,+ amount_tolerance: AmountMismatchTolerance,) -> Result<(), IntegrityCheckError>;}@@ -51,6 +115,7 @@ wherereq_integrity_object,res_integrity_object,connector_refund_id,+ AmountMismatchTolerance::strict(),)}None => Ok(()),@@ -71,10 +136,20 @@ wherematch request.get_response_integrity_object() {Some(res_integrity_object) => {let req_integrity_object = request.get_request_integrity_object();+ // Partial authorization: the connector may legitimately authorize less than+ // requested. It must never authorize more, so `allow_higher` stays false.+ let amount_tolerance = AmountMismatchTolerance {+ allow_lower: AllowLowerAmount::new(+ self.enable_partial_authorization+ .is_some_and(|enabled| enabled.is_true()),+ ),+ allow_higher: AllowHigherAmount::new(false),+ };T::compare(req_integrity_object,res_integrity_object,connector_transaction_id,+ amount_tolerance,)}None => Ok(()),@@ -95,10 +170,20 @@ wherematch request.get_response_integrity_object() {Some(res_integrity_object) => {let req_integrity_object = request.get_request_integrity_object();+ // Overcapture: the merchant may be allowed to capture more than the originally+ // requested amount. Capturing less is a separate, unrelated concern, so+ // `allow_lower` stays false.+ let amount_tolerance = AmountMismatchTolerance {+ allow_lower: AllowLowerAmount::new(false),+ allow_higher: AllowHigherAmount::new(+ self.is_overcapture_enabled.is_some_and(|enabled| *enabled),+ ),+ };T::compare(req_integrity_object,res_integrity_object,connector_transaction_id,+ amount_tolerance,)}None => Ok(()),@@ -119,10 +204,16 @@ wherematch request.get_response_integrity_object() {Some(res_integrity_object) => {let req_integrity_object = request.get_request_integrity_object();+ // TODO: `PaymentsSyncData` has no `enable_partial_authorization`/+ // `is_overcapture_enabled` field today, so a payment left partially+ // authorized or overcaptured will keep failing every subsequent sync's+ // integrity check with strict tolerance. Needs the same plumbing added to+ // `PaymentsSyncData` as was done for `PaymentsAuthorizeData`/`PaymentsCaptureData`.T::compare(req_integrity_object,res_integrity_object,connector_transaction_id,+ AmountMismatchTolerance::strict(),)}None => Ok(()),@@ -136,6 +227,7 @@ impl FlowIntegrity for RefundIntegrityObject {req_integrity_object: Self,res_integrity_object: Self,connector_transaction_id: Option<String>,+ amount_tolerance: AmountMismatchTolerance,) -> Result<(), IntegrityCheckError> {let mut mismatched_fields = Vec::new();@@ -147,7 +239,10 @@ impl FlowIntegrity for RefundIntegrityObject {));}- if req_integrity_object.refund_amount != res_integrity_object.refund_amount {+ if !amount_tolerance.permits(+ req_integrity_object.refund_amount,+ res_integrity_object.refund_amount,+ ) {mismatched_fields.push(format_mismatch("refund_amount",&req_integrity_object.refund_amount.to_string(),@@ -163,6 +258,10 @@ impl FlowIntegrity for RefundIntegrityObject {Err(IntegrityCheckError {field_names,connector_transaction_id,+ // TODO: Currently the refund amount returned by the connector is+ // not captured in the refund data. Hence validate_refund_amount keeps summing the originally+ // requested amount for ManualReview/ VoidPostRefund flows instead of what was actually refunded.+ amount: Some(res_integrity_object.refund_amount),})}}@@ -174,10 +273,11 @@ impl FlowIntegrity for AuthoriseIntegrityObject {req_integrity_object: Self,res_integrity_object: Self,connector_transaction_id: Option<String>,+ amount_tolerance: AmountMismatchTolerance,) -> Result<(), IntegrityCheckError> {let mut mismatched_fields = Vec::new();- if req_integrity_object.amount != res_integrity_object.amount {+ if !amount_tolerance.permits(req_integrity_object.amount, res_integrity_object.amount) {mismatched_fields.push(format_mismatch("amount",&req_integrity_object.amount.to_string(),@@ -201,6 +301,12 @@ impl FlowIntegrity for AuthoriseIntegrityObject {Err(IntegrityCheckError {field_names,connector_transaction_id,+ // TODO: Handle amount when there is a currency mismatch.+ // We store the amount actually received/reported by the connector even in case of a currency mismatch,+ // so that further operations on the payment are not blocked.+ // If the connector ignored the currency provided in the payment request, currently we assume the same behavior+ // from the connector for subsequent operations.+ amount: Some(res_integrity_object.amount),})}}@@ -212,6 +318,7 @@ impl FlowIntegrity for SyncIntegrityObject {req_integrity_object: Self,res_integrity_object: Self,connector_transaction_id: Option<String>,+ amount_tolerance: AmountMismatchTolerance,) -> Result<(), IntegrityCheckError> {let mut mismatched_fields = Vec::new();@@ -219,7 +326,7 @@ impl FlowIntegrity for SyncIntegrityObject {.amount.zip(req_integrity_object.amount).map(|(res_amount, req_amount)| {- if res_amount != req_amount {+ if !amount_tolerance.permits(req_amount, res_amount) {mismatched_fields.push(format_mismatch("amount",&req_amount.to_string(),@@ -249,6 +356,7 @@ impl FlowIntegrity for SyncIntegrityObject {Err(IntegrityCheckError {field_names,connector_transaction_id,+ amount: res_integrity_object.amount,})}}@@ -260,6 +368,7 @@ impl FlowIntegrity for CaptureIntegrityObject {req_integrity_object: Self,res_integrity_object: Self,connector_transaction_id: Option<String>,+ amount_tolerance: AmountMismatchTolerance,) -> Result<(), IntegrityCheckError> {let mut mismatched_fields = Vec::new();@@ -267,7 +376,7 @@ impl FlowIntegrity for CaptureIntegrityObject {.capture_amount.zip(req_integrity_object.capture_amount).map(|(res_amount, req_amount)| {- if res_amount != req_amount {+ if !amount_tolerance.permits(req_amount, res_amount) {mismatched_fields.push(format_mismatch("capture_amount",&req_amount.to_string(),@@ -292,6 +401,7 @@ impl FlowIntegrity for CaptureIntegrityObject {Err(IntegrityCheckError {field_names,connector_transaction_id,+ amount: res_integrity_object.capture_amount,})}}diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex 97a6d02fc9..c9c3117d33 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -540,13 +540,10 @@ impl ForeignTryFrom<(payments_grpc::PaymentServiceGetResponse, AttemptStatus)>let response = if let Some(error_code) =connector_details.and_then(|details| details.code.clone()){- let attempt_status = match response.status() {- payments_grpc::PaymentStatus::Unspecified => None,- _ => Some(AttemptStatus::foreign_try_from((- response.status(),- prev_status,- ))?),- };+ let attempt_status = Some(AttemptStatus::foreign_try_from((+ response.status(),+ prev_status,+ ))?);Err(ErrorResponse {code: error_code,diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rsindex 66b9d577f5..c98f1c4282 100644--- a/crates/router/src/compatibility/stripe/errors.rs+++ b/crates/router/src/compatibility/stripe/errors.rs@@ -280,6 +280,7 @@ pub enum StripeErrorCode {LinkConfigurationError { message: String },#[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")]IntegrityCheckFailed {+ payment_id: Option<id_type::PaymentId>,reason: String,field_names: String,connector_transaction_id: Option<String>,@@ -701,10 +702,12 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {reason,field_names,connector_transaction_id,+ payment_id,} => Self::IntegrityCheckFailed {reason,field_names,connector_transaction_id,+ payment_id,},errors::ApiErrorResponse::InvalidTenant { tenant_id: _ }| errors::ApiErrorResponse::MissingTenantId => Self::InvalidTenant,@@ -824,7 +827,7 @@ impl actix_web::ResponseError for StripeErrorCode {Self::ExternalConnectorError { status_code, .. } => {StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)}- Self::IntegrityCheckFailed { .. } => StatusCode::INTERNAL_SERVER_ERROR,+ Self::IntegrityCheckFailed { .. } => StatusCode::OK,Self::PaymentBlockedError { code, .. } => {StatusCode::from_u16(*code).unwrap_or(StatusCode::OK)}diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rsindex 00312b54a8..8d78c8cbd3 100644--- a/crates/router/src/connector/utils.rs+++ b/crates/router/src/connector/utils.rs@@ -232,6 +232,7 @@ where.payment_attempt.connector_transaction_id.clone(),+ payment_id: Some(payment_data.payment_intent.payment_id.clone()),})?} else if capturable_amount.is_some_and(|capturable_amount| {MinorUnit::new(capturable_amount) > total_capturable_amount@@ -245,6 +246,7 @@ where.payment_attempt.connector_transaction_id.clone(),+ payment_id: Some(payment_data.payment_intent.payment_id.clone()),})?} else {Ok(self.status)diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 4beddea20a..390b7cda95 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -14169,6 +14169,145 @@ pub async fn payments_manual_update())}+// The next incrementable status is determined based on the merchant's intended+// capture amount. For example, if the authorized amount is 100 and the merchant+// attempts to capture 50, but the connector captures 110, the status will still+// be `partially_captured` since only the merchant's intended capture amount is+// considered when determining the next incrementable status.+//+// The merchant can update the status only to the next incrementable status or+// `failed`. Any attempt to update it to another status will be rejected.+#[cfg(all(feature = "olap", feature = "v1"))]+fn get_eligible_manual_update_statuses(+ payment_intent: &storage::PaymentIntent,+ payment_attempt: &storage::PaymentAttempt,+) -> HashSet<enums::ManualUpdateIntentStatus> {+ let total_amount = payment_attempt.net_amount.get_total_amount();+ let amount_to_capture = payment_attempt.amount_to_capture.unwrap_or(total_amount);+ let amount_capturable = payment_attempt.amount_capturable;+ let amount_received = payment_intent.amount_captured;++ // `Failed` is always a valid target alongside whichever single status the payment's+ // capture method and amounts point to below, so it's factored out here instead of+ // repeating it in every match arm.+ let mut eligible_statuses = HashSet::from([enums::ManualUpdateIntentStatus::Failed]);++ let non_failed_status = match payment_attempt.capture_method.unwrap_or_default() {+ // Scheduled behaves like Automatic capture for this purpose.+ enums::CaptureMethod::Automatic | enums::CaptureMethod::Scheduled => {+ enums::ManualUpdateIntentStatus::Succeeded+ }+ enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => {+ match amount_received {+ None if payment_intent+ .enable_partial_authorization+ .map(|enable_partial_authorization| enable_partial_authorization.is_true())+ .unwrap_or(false)+ && amount_capturable < total_amount =>+ {+ enums::ManualUpdateIntentStatus::PartiallyAuthorizedAndRequiresCapture+ }+ None => enums::ManualUpdateIntentStatus::RequiresCapture,+ Some(_) if amount_to_capture < total_amount => {+ enums::ManualUpdateIntentStatus::PartiallyCaptured+ }+ Some(_) => enums::ManualUpdateIntentStatus::Succeeded,+ }+ }+ enums::CaptureMethod::ManualMultiple => match amount_received {+ None if payment_intent+ .enable_partial_authorization+ .map(|enable_partial_authorization| enable_partial_authorization.is_true())+ .unwrap_or(false)+ && amount_capturable < total_amount =>+ {+ enums::ManualUpdateIntentStatus::PartiallyAuthorizedAndRequiresCapture+ }+ None => enums::ManualUpdateIntentStatus::RequiresCapture,+ Some(_) if amount_capturable != MinorUnit::zero() => {+ enums::ManualUpdateIntentStatus::PartiallyCapturedAndCapturable+ }++ Some(_) => enums::ManualUpdateIntentStatus::Succeeded,+ },+ };++ eligible_statuses.insert(non_failed_status);+ eligible_statuses+}++#[cfg(all(feature = "olap", feature = "v1"))]+pub async fn payments_manual_status_update_eligible_statuses(+ state: SessionState,+ platform: domain::Platform,+ payment_id: id_type::PaymentId,+) -> RouterResponse<api_models::payments::PaymentsManualStatusUpdateEligibleStatusesResponse> {+ let merchant_id = platform.get_processor().get_account().get_id();++ let key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)+ .attach_printable("Error while fetching the key store by merchant_id")?;++ let merchant_account = state+ .store+ .find_merchant_account_by_merchant_id(merchant_id, &key_store)+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)+ .attach_printable("Error while fetching the merchant_account by merchant_id")?;++ let payment_intent = state+ .store+ .find_payment_intent_by_payment_id_processor_merchant_id(+ &payment_id,+ merchant_account.get_id(),+ &key_store,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Error while fetching the payment_intent by payment_id, merchant_id")?;++ if payment_intent.status != enums::IntentStatus::Conflicted {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "Payment status must be 'conflicted' to check eligible manual update statuses, current status is '{}'",+ payment_intent.status+ ),+ }+ .into());+ }++ let attempt_id = payment_intent.active_attempt.get_id();++ let payment_attempt = state+ .store+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(+ &payment_id,+ merchant_id,+ &attempt_id,+ merchant_account.storage_scheme,+ &key_store,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Error while fetching the payment_attempt")?;++ let eligible_statuses = get_eligible_manual_update_statuses(&payment_intent, &payment_attempt);++ Ok(services::ApplicationResponse::Json(+ api_models::payments::PaymentsManualStatusUpdateEligibleStatusesResponse {+ payment_id,+ eligible_statuses,+ },+ ))+}+#[cfg(all(feature = "olap", feature = "v1"))]pub async fn payments_manual_status_update(state: SessionState,@@ -14209,10 +14348,13 @@ pub async fn payments_manual_status_update(.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound).attach_printable("Error while fetching the payment_intent by payment_id, merchant_id")?;- if payment_intent.status != enums::IntentStatus::Review {+ if !matches!(+ payment_intent.status,+ enums::IntentStatus::Review | enums::IntentStatus::Conflicted+ ) {return Err(errors::ApiErrorResponse::InvalidRequestData {message: format!(- "Payment status must be 'review' to perform manual status update, current status is '{}'",+ "Payment status must be 'review' or 'conflicted' to perform manual status update, current status is '{}'",payment_intent.status),}@@ -14221,11 +14363,6 @@ pub async fn payments_manual_status_update(let attempt_id = payment_intent.active_attempt.get_id();- let attempt_status = match intent_status {- enums::ManualUpdateIntentStatus::Succeeded => enums::AttemptStatus::Charged,- enums::ManualUpdateIntentStatus::Failed => enums::AttemptStatus::Failure,- };-let payment_attempt = state.store.find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(@@ -14239,18 +14376,41 @@ pub async fn payments_manual_status_update(.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound).attach_printable("Error while fetching the payment_attempt")?;- if payment_attempt.status != enums::AttemptStatus::CaptureReview {- return Err(errors::ApiErrorResponse::InvalidRequestData {- message: format!(- "Payment attempt status must be 'capture_review' to perform manual status update, current status is '{}'",- payment_attempt.status- ),+ if payment_intent.status == enums::IntentStatus::Review {+ if !matches!(+ intent_status,+ enums::ManualUpdateIntentStatus::Succeeded | enums::ManualUpdateIntentStatus::Failed+ ) {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: "Only 'succeeded' or 'failed' are valid manual status update targets from the 'review' state".to_string(),+ }+ .into());+ }++ if payment_attempt.status != enums::AttemptStatus::CaptureReview {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "Payment attempt status must be 'capture_review' to perform manual status update, current status is '{}'",+ payment_attempt.status+ ),+ }+ .into());+ }+ } else {+ let eligible_statuses =+ get_eligible_manual_update_statuses(&payment_intent, &payment_attempt);+ if !eligible_statuses.contains(&intent_status) {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "'{intent_status:?}' is not a valid manual status update target for this payment's current state. Eligible statuses are '{eligible_statuses:?}'"+ ),+ }+ .into());}- .into());}let attempt_update = storage::PaymentAttemptUpdate::StatusUpdate {- status: attempt_status,+ status: intent_status.to_attempt_status(),updated_by: merchant_account.storage_scheme.to_string(),};diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rsindex 20cca3e7fe..395e2c7ae4 100644--- a/crates/router/src/core/payments/flows/authorize_flow.rs+++ b/crates/router/src/core/payments/flows/authorize_flow.rs@@ -1357,6 +1357,9 @@ impl<F>split_payments: item.request.split_payments,webhook_url: item.request.webhook_url,merchant_order_reference_id: item.request.merchant_order_reference_id,+ is_overcapture_enabled: item.request.enable_overcapture.map(|enable_overcapture| {+ common_types::primitive_wrappers::OvercaptureEnabledBool::new(*enable_overcapture)+ }),})}}diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rsindex 8190a50b7e..d5ada11e83 100644--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs@@ -1308,6 +1308,9 @@ impl<F>split_payments: None,webhook_url: None,merchant_order_reference_id: item.request.merchant_order_reference_id,+ is_overcapture_enabled: item.request.enable_overcapture.map(|enable_overcapture| {+ common_types::primitive_wrappers::OvercaptureEnabledBool::new(*enable_overcapture)+ }),})}}diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex a7ee29cfc4..b37592d7c9 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -2675,7 +2675,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(error_reason: Some(Some(format!("Integrity Check Failed! Value mismatched for fields {field_name}"))),- amount_capturable: None,+ amount_capturable: router_data.minor_amount_capturable,updated_by: processor.get_account().storage_scheme.to_string(),unified_code: None,unified_message: None,@@ -3342,41 +3342,32 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(offer_engine::schedule_payment_notification_for_attempt(state, &payment_data.payment_attempt).await;- match router_data.integrity_check {- Ok(()) => Ok(payment_data),- Err(err) => {- metrics::INTEGRITY_CHECK_FAILED.add(- 1,- router_env::metric_attributes!(- (- "connector",- payment_data- .payment_attempt- .connector- .clone()- .unwrap_or_default(),- ),- (- "merchant_id",- payment_data.payment_attempt.merchant_id.clone(),- )- ),- );- Err(error_stack::Report::new(- errors::ApiErrorResponse::IntegrityCheckFailed {- connector_transaction_id: payment_data+ if router_data.integrity_check.is_err() {+ metrics::INTEGRITY_CHECK_FAILED.add(+ 1,+ router_env::metric_attributes!(+ (+ "connector",+ payment_data.payment_attempt- .get_connector_payment_id()- .map(ToString::to_string),- reason: payment_data- .payment_attempt- .error_message+ .connector+ .clone().unwrap_or_default(),- field_names: err.field_names,- },- ))- }+ ),+ (+ "merchant_id",+ payment_data.payment_attempt.merchant_id.clone(),+ )+ ),+ );}++ // The attempt/intent were already persisted above with the `IntegrityFailure`/`Conflicted`+ // status and error fields (error_code, error_message, error_reason) when the integrity+ // check failed, so `payment_data` here already reflects that outcome. Return it as a normal+ // successful payment response — same shape as a genuinely declined payment — rather than a+ // distinct top-level error envelope.+ Ok(payment_data)}#[cfg(feature = "v1")]diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex af96906a5f..157d34bdbe 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -1122,6 +1122,7 @@ pub async fn construct_payment_router_data_for_capture<'a>(split_payments: None,webhook_url: None,merchant_order_reference_id: None,+ is_overcapture_enabled: None,};// TODO: evaluate the fields in router data, if they are required or not@@ -5838,6 +5839,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureDsplit_payments: None,webhook_url: None,merchant_order_reference_id: None,+ is_overcapture_enabled: None,})}}@@ -5923,6 +5925,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureDsplit_payments: payment_data.payment_intent.split_payments,webhook_url,merchant_order_reference_id: payment_data.payment_intent.merchant_order_reference_id,+ is_overcapture_enabled: payment_data.payment_attempt.is_overcapture_enabled,})}}@@ -7469,6 +7472,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthoriz.force_3ds_challenge_trigger.filter(|trigger| *trigger).or(payment_data.payment_intent.force_3ds_challenge),+ enable_overcapture: payment_data.payment_intent.enable_overcapture,})}}diff --git a/crates/router/src/core/relay/utils.rs b/crates/router/src/core/relay/utils.rsindex 32f8361453..7e5cdd8949 100644--- a/crates/router/src/core/relay/utils.rs+++ b/crates/router/src/core/relay/utils.rs@@ -257,6 +257,7 @@ pub async fn construct_relay_capture_router_data(integrity_object: None,webhook_url,merchant_order_reference_id: None,+ is_overcapture_enabled: None,},response: Err(ErrorResponse::default()),diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 418a331160..60d788772d 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1021,7 +1021,11 @@ impl Payments {).service(web::resource("/{payment_id}/manual-status-update")- .route(web::post().to(payments::payments_manual_status_update)),+ .route(web::post().to(payments::payments_manual_status_update))+ .route(+ web::get()+ .to(payments::payments_manual_status_update_eligible_statuses),+ ),)}#[cfg(feature = "oltp")]diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 8c188247bc..7300903b7a 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -191,6 +191,7 @@ impl From<Flow> for ApiIdentifier {| Flow::PaymentsCompleteAuthorize| Flow::PaymentsManualUpdate| Flow::PaymentsManualStatusUpdate+ | Flow::PaymentsManualStatusUpdateEligibleStatuses| Flow::SessionUpdateTaxCalculation| Flow::PaymentsConfirmIntent| Flow::PaymentsCreateIntentdiff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex c999be47cb..32d1f6f3b0 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -3327,6 +3327,60 @@ pub async fn payments_manual_status_update(.await}+#[cfg(all(feature = "olap", feature = "v1"))]+/// List the statuses a conflicted payment is currently eligible for a manual status update to+/// (Dashboard or API-key auth, mirroring the payment retrieve endpoint's auth).+#[instrument(skip_all, fields(flow = ?Flow::PaymentsManualStatusUpdateEligibleStatuses, payment_id))]+pub async fn payments_manual_status_update_eligible_statuses(+ state: web::Data<app::AppState>,+ req: actix_web::HttpRequest,+ path: web::Path<common_utils::id_type::PaymentId>,+) -> impl Responder {+ let flow = Flow::PaymentsManualStatusUpdateEligibleStatuses;+ let payment_id = path.into_inner();++ tracing::Span::current().record("payment_id", payment_id.get_string_repr());++ let api_auth = auth::ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: false,+ };++ let (auth_type, _auth_flow) = match auth::check_internal_api_key_auth_no_client_secret(+ req.headers(),+ api_auth,+ state.conf.internal_merchant_id_profile_id_auth.clone(),+ ) {+ Ok(auth) => auth,+ Err(err) => return api::log_and_return_error_response(report!(err)),+ };++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ (),+ |state, auth: auth::AuthenticationData, _req, _req_state| {+ payments::payments_manual_status_update_eligible_statuses(+ state,+ auth.platform,+ payment_id.clone(),+ )+ },+ auth::auth_type(+ &*auth_type,+ &auth::JWTAuth {+ permission: Permission::ProfilePaymentRead,+ allow_connected: true,+ allow_platform: false,+ },+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(feature = "v1")]/// Retrieve endpoint for merchant to fetch the encrypted customer payment method data#[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))]diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex ac849eb771..e128f7f6ec 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -669,8 +669,11 @@ pub enum Flow {RefundsManualUpdate,/// Manually update the payment details like status, error code, error message etc.PaymentsManualUpdate,- /// Manually update payment status from dashboard (Review → Succeeded/Failed)+ /// Manually update payment status from dashboard (Review → Succeeded/Failed, or Conflicted →+ /// one of the statuses eligible for its capture method/amounts)PaymentsManualStatusUpdate,+ /// List the statuses a conflicted payment is currently eligible for a manual status update to+ PaymentsManualStatusUpdateEligibleStatuses,#[cfg(feature = "payouts")]/// Manually update the payout details like status, error code, error message etc.PayoutsManualUpdate,