Skip to content

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

feat(core): Add net refund amount tracking and refund validation (#15105)

Swangi Kumarif45ef9148a52
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index c3cd571e9d..5c78ac1118 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -45086,10 +45086,22 @@
"amount": {
"type": "integer",
"format": "int64",
- "description": "The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc",
+ "description": "The refund amount excluding any refunded surcharge, in the currency's lowest denomination.",
"example": 6540,
"minimum": 100
},
+ "net_amount": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The total refund amount, including any refunded surcharge, in the currency's lowest denomination.",
+ "nullable": true
+ },
+ "surcharge_refund_amount": {
+ "type": "integer",
+ "format": "int64",
+ "description": "The surcharge amount included in this refund, in the currency's lowest denomination.",
+ "nullable": true
+ },
"currency": {
"type": "string",
"description": "The three-letter ISO currency code"
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index c0fe7e7c5e..78e00872e1 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -314,10 +314,18 @@ pub struct RefundResponse {
#[schema(value_type = String)]
#[smithy(value_type = "String")]
pub payment_id: common_utils::id_type::PaymentId,
- /// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc
+ /// The refund amount excluding any refunded surcharge, in the currency's lowest denomination.
#[schema(value_type = i64 , minimum = 100, example = 6540)]
#[smithy(value_type = "i64")]
pub amount: MinorUnit,
+ /// The total refund amount, including any refunded surcharge, in the currency's lowest denomination.
+ #[schema(value_type = Option<i64>)]
+ #[smithy(value_type = "Option<i64>")]
+ pub net_amount: Option<MinorUnit>,
+ /// The surcharge amount included in this refund, in the currency's lowest denomination.
+ #[schema(value_type = Option<i64>)]
+ #[smithy(value_type = "Option<i64>")]
+ pub surcharge_refund_amount: Option<MinorUnit>,
/// The three-letter ISO currency code
#[smithy(value_type = "String")]
pub currency: String,
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index 91d7fa92b1..15858cba12 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -72,6 +72,10 @@ pub struct Refund {
/// Settlement metadata supplied for this operation, retained across status updates.
#[serde(default)]
pub feature_metadata: Option<common_types::refunds::RefundFeatureMetadata>,
+ #[serde(default)]
+ pub refund_surcharge_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub net_refund_amount: Option<MinorUnit>,
}
impl Refund {
@@ -160,6 +164,10 @@ pub struct Refund {
/// Settlement metadata supplied for this operation, retained across status updates.
#[serde(default)]
pub feature_metadata: Option<common_types::refunds::RefundFeatureMetadata>,
+ #[serde(default)]
+ pub refund_surcharge_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub net_refund_amount: Option<MinorUnit>,
pub id: id_type::GlobalRefundId,
#[diesel(deserialize_as = RequiredFromNullable<id_type::RefundReferenceId>)]
pub merchant_reference_id: id_type::RefundReferenceId,
@@ -216,6 +224,10 @@ pub struct RefundNew {
/// Settlement metadata supplied for this operation, retained across status updates.
#[serde(default)]
pub feature_metadata: Option<common_types::refunds::RefundFeatureMetadata>,
+ #[serde(default)]
+ pub refund_surcharge_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub net_refund_amount: Option<MinorUnit>,
}
#[cfg(feature = "v2")]
@@ -268,6 +280,10 @@ pub struct RefundNew {
/// Settlement metadata supplied for this operation, retained across status updates.
#[serde(default)]
pub feature_metadata: Option<common_types::refunds::RefundFeatureMetadata>,
+ #[serde(default)]
+ pub refund_surcharge_amount: Option<MinorUnit>,
+ #[serde(default)]
+ pub net_refund_amount: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index c3ad0b93e6..7c03950dba 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1709,6 +1709,8 @@ diesel::table! {
#[max_length = 255]
created_by -> Nullable<Varchar>,
feature_metadata -> Nullable<Jsonb>,
+ refund_surcharge_amount -> Nullable<Int8>,
+ net_refund_amount -> Nullable<Int8>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index f313de76bd..b64d56099d 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1612,6 +1612,8 @@ diesel::table! {
#[max_length = 255]
created_by -> Nullable<Varchar>,
feature_metadata -> Nullable<Jsonb>,
+ refund_surcharge_amount -> Nullable<Int8>,
+ net_refund_amount -> Nullable<Int8>,
#[max_length = 64]
id -> Varchar,
#[max_length = 64]
diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs
index 8427a7098e..d1cd822132 100644
--- a/crates/hyperswitch_domain_models/src/refunds.rs
+++ b/crates/hyperswitch_domain_models/src/refunds.rs
@@ -1,8 +1,88 @@
+use common_utils::types::MinorUnit;
+
#[cfg(feature = "v2")]
use crate::business_profile::Profile;
#[cfg(feature = "v1")]
use crate::errors;
+/// Amounts that make up a refund. Older refunds have no surcharge component.
+#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct RefundAmountDetails {
+ refund_amount: MinorUnit,
+ #[serde(default)]
+ refund_surcharge_amount: Option<MinorUnit>,
+}
+
+impl RefundAmountDetails {
+ pub fn new(refund_amount: MinorUnit, refund_surcharge_amount: Option<MinorUnit>) -> Self {
+ Self {
+ refund_amount,
+ refund_surcharge_amount,
+ }
+ }
+
+ pub fn get_refund_amount(&self) -> MinorUnit {
+ self.refund_amount
+ }
+
+ pub fn get_refund_surcharge_amount(&self) -> Option<MinorUnit> {
+ self.refund_surcharge_amount
+ }
+
+ pub fn get_net_refund_amount(&self) -> MinorUnit {
+ self.refund_amount + self.refund_surcharge_amount.unwrap_or_default()
+ }
+
+ /// Values for the flat amount columns in the Diesel refund model.
+ pub fn into_storage_amounts(self) -> (MinorUnit, Option<MinorUnit>, MinorUnit) {
+ (
+ self.refund_amount,
+ self.refund_surcharge_amount,
+ self.get_net_refund_amount(),
+ )
+ }
+
+ pub fn get_remaining_refundable_amount(
+ amount_captured: MinorUnit,
+ previous_refunds: impl IntoIterator<Item = (diesel_models::enums::RefundStatus, Self)>,
+ ) -> MinorUnit {
+ let total_refunded: MinorUnit = previous_refunds
+ .into_iter()
+ .filter(|(status, _)| {
+ !matches!(
+ status,
+ diesel_models::enums::RefundStatus::Failure
+ | diesel_models::enums::RefundStatus::TransactionFailure
+ )
+ })
+ .map(|(_, amount_details)| amount_details.get_net_refund_amount())
+ .sum();
+
+ amount_captured - total_refunded
+ }
+
+ pub fn exceeds_remaining_refundable_amount(
+ &self,
+ amount_captured: MinorUnit,
+ previous_refunds: impl IntoIterator<Item = (diesel_models::enums::RefundStatus, Self)>,
+ ) -> bool {
+ self.get_net_refund_amount()
+ > Self::get_remaining_refundable_amount(amount_captured, previous_refunds)
+ }
+}
+
+impl From<MinorUnit> for RefundAmountDetails {
+ fn from(refund_amount: MinorUnit) -> Self {
+ Self::new(refund_amount, None)
+ }
+}
+
+impl From<&diesel_models::refund::Refund> for RefundAmountDetails {
+ fn from(refund: &diesel_models::refund::Refund) -> Self {
+ Self::new(refund.refund_amount, refund.refund_surcharge_amount)
+ }
+}
+
#[cfg(feature = "v1")]
pub struct RefundListConstraints {
pub payment_id: Option<common_utils::id_type::PaymentId>,
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index e8b0d6fa4a..9c9552fb3a 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -15,7 +15,8 @@ use error_stack::{report, ResultExt};
use external_services::grpc_client::LineageIds;
use hyperswitch_domain_models::{
payment_method_data::ApiPaymentMethodDataMandateIds, payments::HeaderPayload,
- router_data::ErrorResponse, router_request_types::SplitRefundsRequest,
+ refunds::RefundAmountDetails, router_data::ErrorResponse,
+ router_request_types::SplitRefundsRequest,
};
use hyperswitch_interfaces::{
consts as interfaces_consts,
@@ -1745,16 +1746,12 @@ pub async fn validate_and_create_refund(
),
})?;
+ let refund_amount_details = RefundAmountDetails::from(refund_amount);
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
-
- validator::validate_refund_amount(
- total_amount_captured.get_amount_as_i64(),
- &all_refunds,
- refund_amount.get_amount_as_i64(),
- )
- .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
+ validator::validate_refund_amount(total_amount_captured, &all_refunds, refund_amount_details)
+ .change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
@@ -1795,6 +1792,8 @@ pub async fn validate_and_create_refund(
req.feature_metadata,
&all_refunds,
)?;
+ let (refund_amount, refund_surcharge_amount, net_refund_amount) =
+ refund_amount_details.into_storage_amounts();
let refund_create_req = diesel_refund::RefundNew {
refund_id: refund_id.to_string(),
internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"),
@@ -1806,6 +1805,8 @@ pub async fn validate_and_create_refund(
refund_type: req.refund_type.unwrap_or_default().foreign_into(),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
+ refund_surcharge_amount,
+ net_refund_amount: Some(net_refund_amount),
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
@@ -2328,6 +2329,8 @@ impl ForeignFrom<diesel_refund::Refund> for api::RefundResponse {
payment_id: refund.payment_id,
refund_id: refund.refund_id,
amount: refund.refund_amount,
+ net_amount: refund.net_refund_amount,
+ surcharge_refund_amount: refund.refund_surcharge_amount,
currency: refund.currency.to_string(),
reason: refund.refund_reason,
status: refund.refund_status.foreign_into(),
@@ -2402,6 +2405,8 @@ impl
payment_id: refund.payment_id,
refund_id: refund.refund_id,
amount: refund.refund_amount,
+ net_amount: refund.net_refund_amount,
+ surcharge_refund_amount: refund.refund_surcharge_amount,
currency: refund.currency.to_string(),
reason: refund.refund_reason,
status: refund.refund_status.foreign_into(),
diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rs
index d0bbad9c1a..a97ea03592 100644
--- a/crates/router/src/core/refunds_v2.rs
+++ b/crates/router/src/core/refunds_v2.rs
@@ -1210,10 +1210,12 @@ pub async fn validate_and_create_refund(
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
+ let refund_amount_details =
+ hyperswitch_domain_models::refunds::RefundAmountDetails::from(refund_amount);
refunds_validator::validate_refund_amount(
- total_amount_captured.get_amount_as_i64(),
+ total_amount_captured,
&all_refunds,
- refund_amount.get_amount_as_i64(),
+ refund_amount_details,
)
.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
@@ -1241,6 +1243,7 @@ pub async fn validate_and_create_refund(
req.feature_metadata,
&all_refunds,
)?;
+ let (refund_amount, _, _) = refund_amount_details.into_storage_amounts();
let refund_create_req = diesel_refund::RefundNew {
id: global_refund_id,
merchant_reference_id: merchant_reference_id.clone(),
@@ -1258,6 +1261,8 @@ pub async fn validate_and_create_refund(
refund_status: enums::RefundStatus::Pending,
metadata: req.metadata,
feature_metadata: refund_feature_metadata,
+ refund_surcharge_amount: None,
+ net_refund_amount: None,
description: req.reason.clone(),
attempt_id: payment_attempt.id.clone(),
refund_reason: req.reason,
diff --git a/crates/router/src/core/utils/refunds_validator.rs b/crates/router/src/core/utils/refunds_validator.rs
index 72792a3a1c..b51f9da091 100644
--- a/crates/router/src/core/utils/refunds_validator.rs
+++ b/crates/router/src/core/utils/refunds_validator.rs
@@ -1,5 +1,7 @@
+use common_utils::types::MinorUnit;
use diesel_models::refund as diesel_refund;
use error_stack::report;
+use hyperswitch_domain_models::refunds::RefundAmountDetails;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::router_response_types::SupportedPaymentMethodsExt;
#[cfg(feature = "v1")]
@@ -49,25 +51,17 @@ pub fn validate_success_transaction(
#[instrument(skip_all)]
pub fn validate_refund_amount(
- amount_captured: i64,
+ amount_captured: MinorUnit,
all_refunds: &[diesel_refund::Refund],
- refund_amount: i64,
+ refund_amount_details: RefundAmountDetails,
) -> CustomResult<(), RefundValidationError> {
- let total_refunded_amount: i64 = all_refunds
- .iter()
- .filter_map(|refund| {
- if refund.refund_status != enums::RefundStatus::Failure
- && refund.refund_status != enums::RefundStatus::TransactionFailure
- {
- Some(refund.refund_amount.get_amount_as_i64())
- } else {
- None
- }
- })
- .sum();
-
utils::when(
- refund_amount > (amount_captured - total_refunded_amount),
+ refund_amount_details.exceeds_remaining_refundable_amount(
+ amount_captured,
+ all_refunds
+ .iter()
+ .map(|refund| (refund.refund_status, RefundAmountDetails::from(refund))),
+ ),
|| {
Err(report!(
RefundValidationError::RefundAmountExceedsPaymentAmount
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 9364e0e2ad..7064d29fbf 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -684,6 +684,8 @@ mod storage {
total_amount: new.total_amount,
currency: new.currency,
refund_amount: new.refund_amount,
+ refund_surcharge_amount: new.refund_surcharge_amount,
+ net_refund_amount: new.net_refund_amount,
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
refund_error_message: None,
@@ -1453,6 +1455,8 @@ impl RefundInterface for MockDb {
total_amount: new.total_amount,
currency: new.currency,
refund_amount: new.refund_amount,
+ refund_surcharge_amount: new.refund_surcharge_amount,
+ net_refund_amount: new.net_refund_amount,
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
refund_error_message: None,
@@ -1509,6 +1513,8 @@ impl RefundInterface for MockDb {
total_amount: new.total_amount,
currency: new.currency,
refund_amount: new.refund_amount,
+ refund_surcharge_amount: new.refund_surcharge_amount,
+ net_refund_amount: new.net_refund_amount,
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
refund_error_message: None,
diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs
index 60d76d0a3d..42c66646cf 100644
--- a/crates/router/src/services/kafka/refund.rs
+++ b/crates/router/src/services/kafka/refund.rs
@@ -166,6 +166,8 @@ impl<'a> KafkaRefund<'a> {
processor_merchant_id,
created_by,
feature_metadata: _,
+ refund_surcharge_amount: _,
+ net_refund_amount: _,
} = refund;
Self {
diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs
index 9a284a1ecd..dc2e769568 100644
--- a/crates/router/src/services/kafka/refund_event.rs
+++ b/crates/router/src/services/kafka/refund_event.rs
@@ -168,6 +168,8 @@ impl<'a> KafkaRefundEvent<'a> {
processor_merchant_id,
created_by,
feature_metadata: _,
+ refund_surcharge_amount: _,
+ net_refund_amount: _,
} = refund;
Self {
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index f502223a25..3225005b52 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -451,6 +451,8 @@ pub async fn generate_sample_data(
.unwrap_or(&common_enums::Currency::USD),
total_amount: MinorUnit::new(amount * 100),
refund_amount: MinorUnit::new(amount * 100),
+ refund_surcharge_amount: None,
+ net_refund_amount: Some(MinorUnit::new(amount * 100)),
refund_status: common_enums::RefundStatus::Success,
sent_to_gateway: true,
refund_type: diesel_models::enums::RefundType::InstantRefund,
diff --git a/migrations/2026-10-27-000000_add_refund_net_amount/down.sql b/migrations/2026-10-27-000000_add_refund_net_amount/down.sql
new file mode 100644
index 0000000000..b311743a7f
--- /dev/null
+++ b/migrations/2026-10-27-000000_add_refund_net_amount/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE refund DROP COLUMN IF EXISTS net_refund_amount;
+ALTER TABLE refund DROP COLUMN IF EXISTS refund_surcharge_amount;
diff --git a/migrations/2026-10-27-000000_add_refund_net_amount/up.sql b/migrations/2026-10-27-000000_add_refund_net_amount/up.sql
new file mode 100644
index 0000000000..2bdd7c3995
--- /dev/null
+++ b/migrations/2026-10-27-000000_add_refund_net_amount/up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE refund ADD COLUMN IF NOT EXISTS refund_surcharge_amount BIGINT;
+ALTER TABLE refund ADD COLUMN IF NOT EXISTS net_refund_amount BIGINT;