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(payments): support offers during payments flow (#13553)
Apoorv Dixit1483ebf1dbd5
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex bc5256efa6..5f72edef71 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -11008,6 +11008,39 @@}}},+ "AppliedOffer": {+ "type": "object",+ "description": "Normalized applied-offer details exposed in payment responses.",+ "required": [+ "offer_engine_merchant_id",+ "offer_engine_txn_id",+ "offer_id",+ "offer_amount",+ "currency"+ ],+ "properties": {+ "offer_engine_merchant_id": {+ "type": "string",+ "description": "Offer Engine merchant id the offer was applied under."+ },+ "offer_engine_txn_id": {+ "type": "string",+ "description": "Offer Engine transaction id (the payment attempt id used at `/apply`)."+ },+ "offer_id": {+ "type": "string",+ "description": "Offer Engine offer id that was applied."+ },+ "offer_amount": {+ "type": "integer",+ "format": "int64",+ "description": "Charge-reducing offer amount, in minor units."+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ }+ }+ },"AttemptStatus": {"type": "string","description": "The status of the attempt",@@ -20961,6 +20994,30 @@}]},+ "EligibilityAmountDetails": {+ "type": "object",+ "description": "Payable amount details returned during eligibility, before and after the\nOffer Engine discount.",+ "required": [+ "total_amount",+ "net_amount",+ "currency"+ ],+ "properties": {+ "total_amount": {+ "type": "integer",+ "format": "int64",+ "description": "Payable amount before the Offer Engine discount, in minor units."+ },+ "net_amount": {+ "type": "integer",+ "format": "int64",+ "description": "Payable amount after the uplifted offer discount, in minor units."+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ }+ }+ },"EligibilityCard": {"type": "object","description": "Card data for eligibility check — only card_number is required, no CVV needed",@@ -21039,6 +21096,26 @@}}},+ "EligibilityOfferDetails": {+ "type": "object",+ "description": "Offer Engine eligibility details returned to the client.",+ "properties": {+ "uplifted_offer_quote_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Quote ids of the uplifted (selected) offers. First launch selects one."+ },+ "eligible_offers": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/EligibleOffer"+ },+ "description": "All eligible offers returned to the client."+ }+ }+ },"EligibilityPaymentMethodData": {"oneOf": [{@@ -21291,6 +21368,44 @@}]},+ "EligibleOffer": {+ "type": "object",+ "description": "A single eligible offer returned to the client during eligibility.",+ "required": [+ "offer_quote_id",+ "offer_amount",+ "currency",+ "code"+ ],+ "properties": {+ "offer_quote_id": {+ "type": "string",+ "description": "Quote id the client sends back in confirm to apply this offer."+ },+ "offer_amount": {+ "type": "integer",+ "format": "int64",+ "description": "Charge-reducing offer amount, in minor units."+ },+ "currency": {+ "$ref": "#/components/schemas/Currency"+ },+ "code": {+ "type": "string",+ "description": "Offer code."+ },+ "title": {+ "type": "string",+ "description": "Offer title, if provided.",+ "nullable": true+ },+ "description": {+ "type": "string",+ "description": "Offer description, if provided.",+ "nullable": true+ }+ }+ },"EliminationAnalyserConfig": {"type": "object","properties": {@@ -27751,6 +27866,22 @@}}},+ "OfferSelection": {+ "type": "object",+ "description": "Offer selection sent in a confirm request to apply an offer.",+ "required": [+ "offer_quote_ids"+ ],+ "properties": {+ "offer_quote_ids": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Quote ids of the offers to apply. First launch applies a single offer."+ }+ }+ },"OnlineMandate": {"type": "object","description": "Details of online mandate",@@ -32163,6 +32294,14 @@"description": "Custom payment link config id set at business profile, send only if business_specific_configs is configured","nullable": true},+ "offer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/OfferSelection"+ }+ ],+ "nullable": true+ },"payment_type": {"allOf": [{@@ -32717,6 +32856,14 @@],"nullable": true},+ "offer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/OfferSelection"+ }+ ],+ "nullable": true+ },"payment_type": {"allOf": [{@@ -33428,6 +33575,14 @@],"nullable": true},+ "applied_offer": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AppliedOffer"+ }+ ],+ "nullable": true+ },"attempt_count": {"type": "integer","format": "int32",@@ -33916,6 +34071,22 @@}],"nullable": true+ },+ "amount_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/EligibilityAmountDetails"+ }+ ],+ "nullable": true+ },+ "offer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/EligibilityOfferDetails"+ }+ ],+ "nullable": true}}},@@ -34480,6 +34651,14 @@],"nullable": true},+ "offer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/OfferSelection"+ }+ ],+ "nullable": true+ },"payment_type": {"allOf": [{@@ -35217,6 +35396,14 @@],"nullable": true},+ "applied_offer": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AppliedOffer"+ }+ ],+ "nullable": true+ },"attempt_count": {"type": "integer","format": "int32",@@ -35996,6 +36183,14 @@],"nullable": true},+ "offer_details": {+ "allOf": [+ {+ "$ref": "#/components/schemas/OfferSelection"+ }+ ],+ "nullable": true+ },"payment_type": {"allOf": [{diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 4e9df6eeeb..13732bc493 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -1437,6 +1437,11 @@ pub struct PaymentsRequest {#[smithy(value_type = "Option<RequestSurchargeDetails>")]pub surcharge_details: Option<RequestSurchargeDetails>,+ /// Offer Engine offer selection to apply during confirm. When present, the+ /// referenced quote is applied via Offer Engine `/apply` before the PSP call.+ #[schema(value_type = Option<OfferSelection>)]+ pub offer_details: Option<OfferSelection>,+/// The type of the payment that differentiates between normal and various types of mandate payments#[schema(value_type = Option<PaymentType>)]#[smithy(value_type = "Option<PaymentType>")]@@ -7645,6 +7650,10 @@ pub struct PaymentsResponse {#[smithy(value_type = "Option<RequestSurchargeDetails>")]pub surcharge_details: Option<RequestSurchargeDetails>,+ /// Applied Offer Engine offer details for this payment, if an offer was applied.+ #[schema(value_type = Option<AppliedOffer>)]+ pub applied_offer: Option<AppliedOffer>,+/// Total number of attempts associated with this payment#[smithy(value_type = "i16")]pub attempt_count: i16,@@ -13225,6 +13234,85 @@ pub struct PaymentsEligibilityResponse {/// or no surcharge connector is configured for this merchant.#[schema(value_type = Option<SurchargeDetailsResponse>)]pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>,+ /// Payable amount details before and after any Offer Engine discount.+ /// Present when Offer Engine eligibility is evaluated.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub amount_details: Option<EligibilityAmountDetails>,+ /// Offer Engine eligibility result: selected quote ids and all eligible offers.+ /// Present when Offer Engine eligibility is evaluated.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub offer_details: Option<EligibilityOfferDetails>,+}++/// Payable amount details returned during eligibility, before and after the+/// Offer Engine discount.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct EligibilityAmountDetails {+ /// Payable amount before the Offer Engine discount, in minor units.+ #[schema(value_type = i64)]+ pub total_amount: MinorUnit,+ /// Payable amount after the uplifted offer discount, in minor units.+ #[schema(value_type = i64)]+ pub net_amount: MinorUnit,+ /// Currency of the amounts.+ #[schema(value_type = Currency, example = "USD")]+ pub currency: common_enums::Currency,+}++/// Offer Engine eligibility details returned to the client.+#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct EligibilityOfferDetails {+ /// Quote ids of the uplifted (selected) offers. First launch selects one.+ #[serde(default)]+ pub uplifted_offer_quote_ids: Vec<String>,+ /// All eligible offers returned to the client.+ #[serde(default)]+ pub eligible_offers: Vec<EligibleOffer>,+}++/// A single eligible offer returned to the client during eligibility.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct EligibleOffer {+ /// Quote id the client sends back in confirm to apply this offer.+ pub offer_quote_id: String,+ /// Charge-reducing offer amount, in minor units.+ #[schema(value_type = i64)]+ pub offer_amount: MinorUnit,+ /// Currency of the offer amount.+ #[schema(value_type = Currency, example = "USD")]+ pub currency: common_enums::Currency,+ /// Offer code.+ pub code: String,+ /// Offer title, if provided.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub title: Option<String>,+ /// Offer description, if provided.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+}++/// Offer selection sent in a confirm request to apply an offer.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct OfferSelection {+ /// Quote ids of the offers to apply. First launch applies a single offer.+ pub offer_quote_ids: Vec<String>,+}++/// Normalized applied-offer details exposed in payment responses.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct AppliedOffer {+ /// Offer Engine merchant id the offer was applied under.+ pub offer_engine_merchant_id: String,+ /// Offer Engine transaction id (the payment attempt id used at `/apply`).+ pub offer_engine_txn_id: String,+ /// Offer Engine offer id that was applied.+ pub offer_id: String,+ /// Charge-reducing offer amount, in minor units.+ #[schema(value_type = i64)]+ pub offer_amount: MinorUnit,+ /// Currency of the offer amount.+ #[schema(value_type = Currency, example = "USD")]+ pub currency: common_enums::Currency,}#[cfg(feature = "v1")]diff --git a/crates/common_types/src/payments.rs b/crates/common_types/src/payments.rsindex 24b8897187..ddae2e6adb 100644--- a/crates/common_types/src/payments.rs+++ b/crates/common_types/src/payments.rs@@ -1652,3 +1652,58 @@ pub struct ExternalSurchargeDetails {}impl_to_sql_from_sql_json!(ExternalSurchargeDetails);++/// Applied-offer details from Offer Engine `/apply`, persisted on `payment_attempt`+/// as JSONB. Versioned (tagged by `version`) for forward-compatible schema evolution.+#[derive(+ Clone,+ Debug,+ serde::Deserialize,+ Eq,+ ToSchema,+ PartialEq,+ serde::Serialize,+ diesel::AsExpression,+)]+#[diesel(sql_type = Jsonb)]+#[serde(tag = "version", rename_all = "snake_case")]+pub enum AppliedOfferDetails {+ /// Version 1 of the applied-offer details.+ V1(AppliedOfferDetailsV1),+}++impl AppliedOfferDetails {+ /// Borrow the inner current-version details.+ pub fn inner(&self) -> &AppliedOfferDetailsV1 {+ match self {+ Self::V1(details) => details,+ }+ }++ /// Consume into the inner current-version details.+ pub fn into_inner(self) -> AppliedOfferDetailsV1 {+ match self {+ Self::V1(details) => details,+ }+ }+}++/// Version 1 of the applied-offer details.+#[derive(Clone, Debug, serde::Deserialize, Eq, ToSchema, PartialEq, serde::Serialize)]+pub struct AppliedOfferDetailsV1 {+ /// Quote id issued at eligibility and echoed back at confirm to apply this offer+ pub offer_quote_id: String,+ /// Offer Engine merchant id the offer was applied under+ pub offer_engine_merchant_id: String,+ /// Offer Engine transaction id (the Hyperswitch payment attempt id used at `/apply`)+ pub offer_engine_txn_id: String,+ /// Offer Engine offer id that was applied+ pub offer_id: String,+ /// Charge-reducing offer amount in minor units+ pub offer_amount: MinorUnit,+ /// Currency of the applied offer amount+ #[schema(value_type = Currency, example = "USD")]+ pub currency: enums::Currency,+}++impl_to_sql_from_sql_json!(AppliedOfferDetails);diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rsindex df84b1401d..8004e6fe5d 100644--- a/crates/diesel_models/src/payment_attempt.rs+++ b/crates/diesel_models/src/payment_attempt.rs@@ -172,6 +172,7 @@ pub struct PaymentAttempt {pub network_transaction_link_id: Option<String>,pub sender_payment_instrument_id: Option<String>,pub external_threeds_authentication_type: Option<common_enums::DecoupledAuthenticationType>,+ pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,#[diesel(deserialize_as = RequiredFromNullable<storage_enums::PaymentMethod>)]pub payment_method_type_v2: storage_enums::PaymentMethod,pub connector_payment_id: Option<ConnectorTransactionId>,@@ -310,6 +311,7 @@ pub struct PaymentAttempt {/// A connector-specific identifier representing the stored payment instrumentpub sender_payment_instrument_id: Option<String>,pub external_threeds_authentication_type: Option<common_enums::DecoupledAuthenticationType>,+ pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,}#[cfg(feature = "v1")]@@ -466,6 +468,7 @@ pub struct PaymentAttemptNew {pub error_details: Option<ErrorDetails>,pub retry_type: Option<storage_enums::RetryType>,pub external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,+ pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,}#[cfg(feature = "v1")]@@ -564,6 +567,7 @@ pub struct PaymentAttemptNew {pub network_transaction_link_id: Option<String>,pub sender_payment_instrument_id: Option<String>,pub external_threeds_authentication_type: Option<common_enums::DecoupledAuthenticationType>,+ pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,}#[cfg(feature = "v1")]@@ -652,6 +656,7 @@ pub enum PaymentAttemptUpdate {is_stored_credential: Option<bool>,request_extended_authorization: Option<RequestExtendedAuthorizationBool>,external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,+ applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,},VoidUpdate {status: storage_enums::AttemptStatus,@@ -1139,6 +1144,7 @@ pub struct PaymentAttemptUpdateInternal {pub error_details: Option<Option<ErrorDetails>>,pub sender_payment_instrument_id: Option<String>,pub external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,+ pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,}#[cfg(feature = "v1")]@@ -2563,6 +2569,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::AuthenticationTypeUpdate {authentication_type,@@ -2642,6 +2649,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::ConfirmUpdate {amount,@@ -2687,6 +2695,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {is_stored_credential,request_extended_authorization,external_surcharge_details,+ applied_offer_details,} => Self {amount: Some(amount),currency: Some(currency),@@ -2762,6 +2771,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,external_surcharge_details,+ applied_offer_details,},PaymentAttemptUpdate::VoidUpdate {status,@@ -2842,6 +2852,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::RejectUpdate {status,@@ -2923,6 +2934,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::BlocklistUpdate {status,@@ -3004,6 +3016,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::ConnectorMandateDetailUpdate {connector_mandate_detail,@@ -3084,6 +3097,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::PaymentMethodDetailsUpdate {payment_method_id,@@ -3163,6 +3177,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::ResponseUpdate {status,@@ -3280,6 +3295,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {installment_data: None,sender_payment_instrument_id,external_surcharge_details: None,+ applied_offer_details: None,}}PaymentAttemptUpdate::ErrorUpdate {@@ -3383,6 +3399,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,}}PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {@@ -3460,6 +3477,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::UpdateTrackers {payment_token,@@ -3547,6 +3565,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,error_details: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::UnresolvedResponseUpdate {status,@@ -3641,6 +3660,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,}}PaymentAttemptUpdate::PreprocessingUpdate {@@ -3732,6 +3752,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,}}PaymentAttemptUpdate::CaptureUpdate {@@ -3813,6 +3834,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::AmountToCaptureUpdate {status,@@ -3893,6 +3915,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::ConnectorResponse {authentication_data,@@ -3982,6 +4005,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,}}PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {@@ -4062,6 +4086,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::AuthenticationUpdate {status,@@ -4145,6 +4170,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::ManualUpdate {status,@@ -4237,6 +4263,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,}}PaymentAttemptUpdate::PostSessionTokensUpdate {@@ -4317,6 +4344,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {error_details: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::RecurrenceUpdate {status,@@ -4400,6 +4428,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {encrypted_payment_method_data: None,sender_payment_instrument_id: None,external_surcharge_details: None,+ applied_offer_details: None,},PaymentAttemptUpdate::ExternalSurchargeUpdate {updated_by,@@ -4479,6 +4508,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {sender_payment_instrument_id: None,external_surcharge_details: Some(external_surcharge_details),external_threeds_authentication_type: None,+ applied_offer_details: None,},}}diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex b3224b511a..7ab84fe862 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -1251,6 +1251,7 @@ diesel::table! {sender_payment_instrument_id -> Nullable<Varchar>,#[max_length = 64]external_threeds_authentication_type -> Nullable<Varchar>,+ applied_offer_details -> Nullable<Jsonb>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 6007546543..1d35bd1ed5 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -1192,6 +1192,7 @@ diesel::table! {sender_payment_instrument_id -> Nullable<Varchar>,#[max_length = 64]external_threeds_authentication_type -> Nullable<Varchar>,+ applied_offer_details -> Nullable<Jsonb>,payment_method_type_v2 -> Nullable<Varchar>,#[max_length = 128]connector_payment_id -> Nullable<Varchar>,diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rsindex 3ec205e2e6..e6303f2014 100644--- a/crates/diesel_models/src/user/sample_data.rs+++ b/crates/diesel_models/src/user/sample_data.rs@@ -326,6 +326,7 @@ impl PaymentAttemptBatchNew {retry_type: None,installment_data: None,external_surcharge_details: None,+ applied_offer_details: None,sender_payment_instrument_id: None,external_threeds_authentication_type: None,}diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rsindex 94c1ff9835..ab6b1ad8a2 100644--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs@@ -409,6 +409,14 @@ impl EligibilityPaymentMethodData {}}+ pub fn get_card_data(&self) -> Option<&EligibilityCard> {+ if let Self::Card(card) = self {+ Some(card)+ } else {+ None+ }+ }+/// 8-digit BIN of a wallet's decrypted token. `None` while the token is still encrypted.pub fn get_decrypted_token_extended_bin(&self) -> Option<String> {match self {diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex 645b6ddd0d..d0de125fce 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -826,6 +826,8 @@ pub struct PaymentAttempt {pub authorized_amount: Option<MinorUnit>,/// External surcharge details from InterPaymentspub external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,+ /// Normalized applied-offer details from Offer Engine+ pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,}impl PaymentAttempt {@@ -994,6 +996,7 @@ impl PaymentAttempt {network_transaction_link_id: None,authorized_amount: None,external_surcharge_details: None,+ applied_offer_details: None,})}@@ -1089,6 +1092,7 @@ impl PaymentAttempt {network_transaction_link_id: None,authorized_amount: None,external_surcharge_details: None,+ applied_offer_details: None,})}@@ -1191,6 +1195,7 @@ impl PaymentAttempt {network_transaction_link_id: None,authorized_amount: None,external_surcharge_details: None,+ applied_offer_details: None,})}@@ -1318,6 +1323,7 @@ impl PaymentAttempt {network_transaction_link_id: None,authorized_amount: None,external_surcharge_details: None,+ applied_offer_details: None,})}@@ -1438,6 +1444,8 @@ pub struct PaymentAttempt {pub installment_data: Option<common_types::payments::InstallmentData>,/// External surcharge details from InterPayments (stored as JSONB)pub external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,+ /// Normalized applied-offer details from Offer Engine+ pub applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,/// Sender payment instrument IDpub sender_payment_instrument_id: Option<String>,}@@ -1457,6 +1465,8 @@ pub struct NetAmount {tax_on_surcharge: Option<MinorUnit>,/// Installment interest amount for installment paymentsinstallment_interest: Option<MinorUnit>,+ /// Offer Engine charge-reducing discount amount, subtracted from the total+ offer_amount: Option<MinorUnit>,}#[cfg(feature = "v1")]@@ -1468,6 +1478,7 @@ impl NetAmount {surcharge_amount: Option<MinorUnit>,tax_on_surcharge: Option<MinorUnit>,installment_interest: Option<MinorUnit>,+ offer_amount: Option<MinorUnit>,) -> Self {Self {order_amount,@@ -1476,6 +1487,7 @@ impl NetAmount {surcharge_amount,tax_on_surcharge,installment_interest,+ offer_amount,}}@@ -1503,6 +1515,14 @@ impl NetAmount {self.installment_interest}+ pub fn get_offer_amount(&self) -> Option<MinorUnit> {+ self.offer_amount+ }++ pub fn set_offer_amount(&mut self, offer_amount: Option<MinorUnit>) {+ self.offer_amount = offer_amount;+ }+pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> {self.surcharge_amount.map(|surcharge_amount| surcharge_amount + self.tax_on_surcharge.unwrap_or_default())@@ -1515,6 +1535,7 @@ impl NetAmount {+ self.surcharge_amount.unwrap_or_default()+ self.tax_on_surcharge.unwrap_or_default()+ self.installment_interest.unwrap_or_default()+ - self.offer_amount.unwrap_or_default()}pub fn get_additional_amount(&self) -> MinorUnit {@@ -1564,6 +1585,7 @@ impl NetAmount {surcharge_amount,tax_on_surcharge,installment_interest: None,+ offer_amount: None,}}@@ -1600,6 +1622,8 @@ impl NetAmount {});let installment_interest = payment_attempt.and_then(|payment_attempt| payment_attempt.net_amount.get_installment_interest());+ let offer_amount = payment_attempt+ .and_then(|payment_attempt| payment_attempt.net_amount.get_offer_amount());Self {order_amount,shipping_cost,@@ -1607,6 +1631,7 @@ impl NetAmount {surcharge_amount,tax_on_surcharge,installment_interest,+ offer_amount,}})}@@ -2011,6 +2036,7 @@ pub enum PaymentAttemptUpdate {is_stored_credential: Option<bool>,request_extended_authorization: Option<RequestExtendedAuthorizationBool>,external_surcharge_details: Option<common_types::payments::ExternalSurchargeDetails>,+ applied_offer_details: Option<common_types::payments::AppliedOfferDetails>,},RejectUpdate {status: storage_enums::AttemptStatus,@@ -2343,6 +2369,7 @@ impl PaymentAttemptUpdate {is_stored_credential,request_extended_authorization,external_surcharge_details,+ applied_offer_details,} => DieselPaymentAttemptUpdate::ConfirmUpdate {amount: net_amount.get_order_amount(),currency,@@ -2394,6 +2421,7 @@ impl PaymentAttemptUpdate {is_stored_credential,request_extended_authorization,external_surcharge_details,+ applied_offer_details,},Self::VoidUpdate {status,@@ -3019,6 +3047,7 @@ impl behaviour::Conversion for PaymentAttempt {encrypted_payment_method_data: self.encrypted_payment_method_data.map(Encryption::from),retry_type: self.retry_type,external_surcharge_details: self.external_surcharge_details,+ applied_offer_details: self.applied_offer_details,sender_payment_instrument_id: self.sender_payment_instrument_id,})}@@ -3070,6 +3099,10 @@ impl behaviour::Conversion for PaymentAttempt {.installment_data.as_ref().and_then(|d| d.installment_interest),+ storage_model+ .applied_offer_details+ .as_ref()+ .map(|applied_offer_details| applied_offer_details.inner().offer_amount),),currency: storage_model.currency,save_to_locker: storage_model.save_to_locker,@@ -3157,6 +3190,7 @@ impl behaviour::Conversion for PaymentAttempt {retry_type: storage_model.retry_type,installment_data: storage_model.installment_data,external_surcharge_details: storage_model.external_surcharge_details,+ applied_offer_details: storage_model.applied_offer_details,sender_payment_instrument_id: storage_model.sender_payment_instrument_id,})}@@ -3261,6 +3295,7 @@ impl behaviour::Conversion for PaymentAttempt {retry_type: self.retry_type,installment_data: self.installment_data,external_surcharge_details: self.external_surcharge_details,+ applied_offer_details: self.applied_offer_details,sender_payment_instrument_id: self.sender_payment_instrument_id,})}@@ -3340,6 +3375,7 @@ impl behaviour::Conversion for PaymentAttempt {network_transaction_link_id,authorized_amount,external_surcharge_details,+ applied_offer_details,} = self;let AttemptAmountDetails {@@ -3452,6 +3488,7 @@ impl behaviour::Conversion for PaymentAttempt {retry_type: None,installment_data: None,external_surcharge_details: None,+ applied_offer_details,sender_payment_instrument_id: None,})}@@ -3569,6 +3606,7 @@ impl behaviour::Conversion for PaymentAttempt {authentication_applied: storage_model.authentication_applied,external_reference_id: storage_model.external_reference_id,external_surcharge_details: storage_model.external_surcharge_details,+ applied_offer_details: storage_model.applied_offer_details,connector: storage_model.connector,payment_method_billing_address,connector_token_details: storage_model.connector_token_details,@@ -3649,6 +3687,7 @@ impl behaviour::Conversion for PaymentAttempt {network_transaction_link_id,authorized_amount,external_surcharge_details: _,+ applied_offer_details: _,} = self;let card_network = payment_method_data@@ -3745,6 +3784,7 @@ impl behaviour::Conversion for PaymentAttempt {processor_merchant_id: Some(processor_merchant_id),created_by: created_by.map(|created_by| created_by.to_string()),external_surcharge_details: None,+ applied_offer_details: None,connector_request_reference_id,network_details: None,tokenization: None,diff --git a/crates/hyperswitch_interfaces/src/micro_service.rs b/crates/hyperswitch_interfaces/src/micro_service.rsindex 4a9360a09b..c153782010 100644--- a/crates/hyperswitch_interfaces/src/micro_service.rs+++ b/crates/hyperswitch_interfaces/src/micro_service.rs@@ -57,4 +57,10 @@ pub trait MicroserviceClient {fn parent_headers(&self) -> &Headers;/// Trace identifier configuration.fn trace(&self) -> &RequestIdentifier;+ /// Whether the caller's tenant id (`x-tenant-id`) should be forwarded to the+ /// service. Internal microservices rely on it; external third-party services+ /// that do their own tenant resolution (e.g. from the API key) return `false`.+ fn should_forward_tenant_header(&self) -> bool {+ true+ }}diff --git a/crates/hyperswitch_interfaces/src/micro_service/executor.rs b/crates/hyperswitch_interfaces/src/micro_service/executor.rsindex f5fa913742..7c180c165c 100644--- a/crates/hyperswitch_interfaces/src/micro_service/executor.rs+++ b/crates/hyperswitch_interfaces/src/micro_service/executor.rs@@ -53,6 +53,7 @@ impl<O: ClientOperation> TransformedRequest<O> {base_url: &Url,parent_headers: Headers,trace_header: &RequestIdentifier,+ should_forward_tenant: bool,) -> Result<Executed<O>, MicroserviceClientError> {let operation = std::any::type_name::<O>();// Step 1: Build path and URL.@@ -103,11 +104,13 @@ impl<O: ClientOperation> TransformedRequest<O> {Maskable::Normal(trace_id.to_string()),));- let tenant_id = state.get_tenant().tenant_id.get_string_repr().to_string();- if !tenant_id.is_empty() {- http_request- .headers- .insert((TENANT_HEADER.to_string(), Maskable::Normal(tenant_id)));+ if should_forward_tenant {+ let tenant_id = state.get_tenant().tenant_id.get_string_repr().to_string();+ if !tenant_id.is_empty() {+ http_request+ .headers+ .insert((TENANT_HEADER.to_string(), Maskable::Normal(tenant_id)));+ }}}@@ -202,6 +205,7 @@ pub async fn execute_microservice_operation<O: ClientOperation>(client.base_url(),client.parent_headers().clone(),client.trace(),+ client.should_forward_tenant_header(),).await?;Ok(executed.into_transformed_response()?.output)diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 202c2f7b85..8a91791ce7 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -827,6 +827,11 @@ Never share your secret api keys. Keep them guarded and secure.api_models::enums::SurchargeStrategy,api_models::payments::PaymentsEligibilityRequest,api_models::payments::PaymentsEligibilityResponse,+ api_models::payments::EligibilityAmountDetails,+ api_models::payments::EligibilityOfferDetails,+ api_models::payments::EligibleOffer,+ api_models::payments::OfferSelection,+ api_models::payments::AppliedOffer,api_models::payment_methods::PaymentMethodCollectLinkRequest,api_models::payment_methods::PaymentMethodCollectLinkResponse,api_models::payment_methods::CardType,diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex 41105c50d5..fdbe1ce1cb 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -369,6 +369,24 @@ impl SecretsHandler for settings::NetworkTokenizationService {}}+#[async_trait::async_trait]+impl SecretsHandler for settings::OfferEngineConfig {+ async fn convert_to_raw_secret(+ value: SecretStateContainer<Self, SecuredSecret>,+ secret_management_client: &dyn SecretManagementInterface,+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {+ let offer_engine = value.get_inner();+ let api_key = secret_management_client+ .get_secret(offer_engine.api_key.clone())+ .await?;++ Ok(value.transition_state(|offer_engine| Self {+ api_key,+ ..offer_engine+ }))+ }+}+#[async_trait::async_trait]impl SecretsHandler for settings::OidcSettings {async fn convert_to_raw_secret(@@ -593,6 +611,19 @@ pub(crate) async fn fetch_raw_secrets(}).await;+ #[allow(clippy::expect_used)]+ let offer_engine = conf+ .offer_engine+ .async_map(|offer_engine| async {+ settings::OfferEngineConfig::convert_to_raw_secret(+ offer_engine,+ secret_management_client,+ )+ .await+ .expect("Failed to decrypt offer engine configs")+ })+ .await;+#[allow(clippy::expect_used)]let chat = settings::ChatSettings::convert_to_raw_secret(conf.chat, secret_management_client).await@@ -762,7 +793,7 @@ pub(crate) async fn fetch_raw_secrets(internal_services: conf.internal_services,micro_services: conf.micro_services,superposition,- offer_engine: conf.offer_engine,+ offer_engine,comparison_service: conf.comparison_service,authentication_service_enabled_connectors: conf.authentication_service_enabled_connectors,save_payment_method_on_session: conf.save_payment_method_on_session,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex d7b817c026..9cbb866656 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -194,7 +194,7 @@ pub struct Settings<S: SecretState> {#[serde(default)]pub enhancement: Option<HashMap<String, String>>,pub superposition: SecretStateContainer<SuperpositionClientConfig, S>,- pub offer_engine: Option<OfferEngineConfig>,+ pub offer_engine: Option<SecretStateContainer<OfferEngineConfig, S>>,pub proxy_status_mapping: ProxyStatusMapping,pub trace_header: TraceHeaderConfig,pub internal_services: InternalServicesConfig,@@ -1530,7 +1530,7 @@ impl Settings<SecuredSecret> {self.offer_engine.as_ref()- .map(|offer_engine| offer_engine.validate())+ .map(|offer_engine| offer_engine.get_inner().validate()).transpose()?;self.account_updaterdiff --git a/crates/router/src/core/offer_engine.rs b/crates/router/src/core/offer_engine.rsindex 5a0bd16158..98527b4c0d 100644--- a/crates/router/src/core/offer_engine.rs+++ b/crates/router/src/core/offer_engine.rs@@ -1,6 +1,9 @@+pub mod amount;+pub mod apply;pub mod client;pub mod config;pub mod connectivity;+pub mod eligibility;pub mod types;pub use client::OfferEngineClient;diff --git a/crates/router/src/core/offer_engine/amount.rs b/crates/router/src/core/offer_engine/amount.rsnew file mode 100644index 0000000000..ed1ee2ce73--- /dev/null+++ b/crates/router/src/core/offer_engine/amount.rs@@ -0,0 +1,50 @@+use common_utils::types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForCore};+use error_stack::ResultExt;+use rust_decimal::{prelude::ToPrimitive, Decimal};++use super::types::OfferEngineError;++/// Convert Hyperswitch minor units to an Offer Engine decimal string.+pub fn to_offer_engine_amount(+ amount: MinorUnit,+ currency: common_enums::Currency,+) -> error_stack::Result<StringMajorUnit, OfferEngineError> {+ StringMajorUnitForCore+ .convert(amount, currency)+ .change_context(OfferEngineError::AmountConversion)+ .attach_printable("Failed to convert minor units to Offer Engine amount string")+}++/// Convert an Offer Engine decimal string into Hyperswitch minor units.+pub fn from_offer_engine_amount(+ amount: &StringMajorUnit,+ currency: common_enums::Currency,+) -> error_stack::Result<MinorUnit, OfferEngineError> {+ let decimal = Decimal::from_str_exact(&amount.get_amount_as_string())+ .change_context(OfferEngineError::AmountConversion)+ .attach_printable("Offer Engine amount is not a valid decimal")?;++ common_utils::fp_utils::when(decimal.is_sign_negative(), || {+ Err(error_stack::report!(OfferEngineError::AmountConversion)+ .attach_printable("Offer Engine amount is negative"))+ })?;++ let decimals = u32::from(currency.number_of_digits_after_decimal_point());+ let factor = Decimal::from(10_u64.pow(decimals));+ let scaled = decimal * factor;++ common_utils::fp_utils::when(scaled.fract() != Decimal::ZERO, || {+ Err(+ error_stack::report!(OfferEngineError::AmountConversion).attach_printable(+ "Offer Engine amount has more decimal places than the currency allows",+ ),+ )+ })?;++ let minor = scaled+ .to_i64()+ .ok_or(OfferEngineError::AmountConversion)+ .attach_printable("Offer Engine amount does not fit in minor units")?;++ Ok(MinorUnit::new(minor))+}diff --git a/crates/router/src/core/offer_engine/apply.rs b/crates/router/src/core/offer_engine/apply.rsnew file mode 100644index 0000000000..270d0aa1c8--- /dev/null+++ b/crates/router/src/core/offer_engine/apply.rs@@ -0,0 +1,117 @@+use common_utils::{errors::CustomResult, id_type, types::MinorUnit};++use super::{+ client::OfferEngineClient,+ types::{+ OfferApplyRequest, OfferCustomer, OfferEngineError, OfferOrder, OfferOrderType,+ OfferPaymentMethodInfo, ResolvedOfferEngineConfig,+ },+};+use crate::routes::SessionState;++#[derive(Debug, Clone)]+pub struct OfferQuoteRef {+ pub offer_id: String,+ pub offer_amount: MinorUnit,+ pub currency: common_enums::Currency,+}++/// Non-sensitive context needed to build an Offer Engine `/apply` request.+pub struct OfferApplyContext {+ /// Hyperswitch payment id, used as the Offer Engine order id.+ pub payment_id: id_type::PaymentId,+ /// Current payment attempt id, used as the Offer Engine `txn_id`.+ pub attempt_id: String,+ /// Order amount (not surcharge-inclusive), in minor units.+ pub order_amount: MinorUnit,+ /// Order currency.+ pub currency: common_enums::Currency,+ /// Customer id, if available.+ pub customer_id: Option<id_type::CustomerId>,+ /// Offer Engine payment method type (e.g. `CARD`).+ pub payment_method_type: String,+ /// Card network, if available.+ pub payment_method: Option<String>,+ /// Card BIN/IIN, if available.+ pub card_bin: Option<String>,+ /// Card type, if available.+ pub card_type: Option<String>,+ /// Issuing bank code, if available.+ pub bank_code: Option<String>,+ /// Card issuing country, if available.+ pub card_country: Option<String>,+}++#[derive(Debug, Clone)]+pub struct AppliedOfferResult {+ pub offer_id: String,+ pub offer_amount: MinorUnit,+ pub currency: common_enums::Currency,+ pub offer_engine_merchant_id: String,+ pub offer_engine_txn_id: String,+}++pub async fn run_offer_apply(+ state: &SessionState,+ config: ResolvedOfferEngineConfig,+ quote: &OfferQuoteRef,+ ctx: OfferApplyContext,+) -> CustomResult<AppliedOfferResult, OfferEngineError> {+ common_utils::fp_utils::when(quote.currency != ctx.currency, || {+ Err(error_stack::report!(OfferEngineError::ApplyRejected)+ .attach_printable("Offer quote currency does not match payment currency"))+ })?;++ let order = OfferOrder {+ order_id: ctx.payment_id.get_string_repr().to_string(),+ merchant_id: config.merchant_id.clone(),+ amount: super::amount::to_offer_engine_amount(ctx.order_amount, ctx.currency)?,+ currency: ctx.currency,+ order_type: OfferOrderType::OrderPayment,+ };++ let request = OfferApplyRequest {+ txn_id: ctx.attempt_id.clone(),+ offers: vec![quote.offer_id.clone()],+ order,+ payment_method_info: OfferPaymentMethodInfo {+ payment_method_reference: ctx.attempt_id.clone(),+ payment_method_type: ctx.payment_method_type.clone(),+ payment_method: ctx.payment_method.clone(),+ card_bin: ctx.card_bin.clone(),+ card_type: ctx.card_type.clone(),+ bank_code: ctx.bank_code.clone(),+ card_country: ctx.card_country.clone(),+ },+ customer: ctx.customer_id.map(|id| OfferCustomer {+ id: id.get_string_repr().to_string(),+ }),+ };++ let merchant_id = config.merchant_id.clone();+ let client = OfferEngineClient::new(config, &state.conf.trace_header.header_name);+ let response = client.apply_offer(state, request).await?;++ let applied = response.single_applied_offer(ctx.currency)?;++ common_utils::fp_utils::when(applied.offer_id != quote.offer_id, || {+ Err(error_stack::report!(OfferEngineError::ApplyRejected)+ .attach_printable("Applied offer id does not match the eligibility quote"))+ })?;+ common_utils::fp_utils::when(applied.offer_amount != quote.offer_amount, || {+ Err(error_stack::report!(OfferEngineError::ApplyRejected)+ .attach_printable("Applied offer amount does not match the eligibility quote"))+ })?;+ common_utils::fp_utils::when(ctx.order_amount <= applied.offer_amount, || {+ Err(error_stack::report!(OfferEngineError::ApplyRejected)+ .attach_printable("Offer-adjusted net amount is not positive"))+ })?;++ Ok(AppliedOfferResult {+ offer_id: applied.offer_id,+ offer_amount: applied.offer_amount,+ currency: ctx.currency,+ offer_engine_merchant_id: merchant_id,+ offer_engine_txn_id: ctx.attempt_id,+ })+}diff --git a/crates/router/src/core/offer_engine/client.rs b/crates/router/src/core/offer_engine/client.rsindex 34e69da723..64362ceb20 100644--- a/crates/router/src/core/offer_engine/client.rs+++ b/crates/router/src/core/offer_engine/client.rs@@ -1,15 +1,22 @@use base64::Engine;-use common_utils::request::{Headers, Method, RequestContent};+use common_utils::{+ errors::CustomResult,+ request::{Headers, Method, RequestContent},+};use hyperswitch_interfaces::micro_service::{MicroserviceClient, MicroserviceClientError, MicroserviceClientErrorKind,};use hyperswitch_masking::{Mask, PeekInterface};use router_env::{IdReuse, RequestIdentifier};-use super::types::ResolvedOfferEngineConfig;+use super::types::{+ OfferApplyRequest, OfferApplyResponse, OfferEngineError, OfferListRequest, OfferListResponse,+ ResolvedOfferEngineConfig,+};use crate::{consts::BASE64_ENGINE, routes::SessionState};const OFFERS_LIST_PATH: &str = "v1/offers/list";+const OFFERS_APPLY_PATH: &str = "offers/apply";#[derive(Debug)]pub struct OfferEngineClient {@@ -42,6 +49,28 @@ impl OfferEngineClient {&self.merchant_id}+ pub async fn list_offers(+ &self,+ state: &SessionState,+ request: OfferListRequest,+ ) -> CustomResult<OfferListResponse, OfferEngineError> {+ OfferList::call(state, self, OfferListV1Request(request))+ .await+ .map(|response| response.0)+ .map_err(map_offer_engine_error)+ }++ pub async fn apply_offer(+ &self,+ state: &SessionState,+ request: OfferApplyRequest,+ ) -> CustomResult<OfferApplyResponse, OfferEngineError> {+ OfferApply::call(state, self, OfferApplyV1Request(request))+ .await+ .map(|response| response.0)+ .map_err(map_offer_engine_error)+ }+pub async fn check_connectivity(&self, state: &SessionState) -> ConnectivityResult {match OfferConnectivity::call(state, self, OfferConnectivityRequest).await {Ok(_) => ConnectivityResult {@@ -88,6 +117,21 @@ impl MicroserviceClient for OfferEngineClient {fn trace(&self) -> &RequestIdentifier {&self.trace}++ // Offer Engine is an external third-party service that resolves the tenant+ // from the API key, not hyperswitch's `x-tenant-id`. Forwarding our tenant+ // header makes it reject the request ("Merchant tenantAccId not present").+ fn should_forward_tenant_header(&self) -> bool {+ false+ }+}++fn map_offer_engine_error(err: MicroserviceClientError) -> error_stack::Report<OfferEngineError> {+ let variant = match err.kind {+ MicroserviceClientErrorKind::Deserialize(_) => OfferEngineError::ResponseParseFailed,+ _ => OfferEngineError::RequestFailed,+ };+ error_stack::report!(variant).attach_printable(format!("Offer Engine call failed: {err:?}"))}pub struct OfferConnectivity;@@ -122,6 +166,78 @@ hyperswitch_interfaces::impl_microservice_flow!()));+pub struct OfferList;+pub struct OfferListV1Request(pub OfferListRequest);+pub struct OfferListV1Response(pub OfferListResponse);++impl TryFrom<&OfferListV1Request> for OfferListRequest {+ type Error = MicroserviceClientError;+ fn try_from(value: &OfferListV1Request) -> Result<Self, Self::Error> {+ Ok(value.0.clone())+ }+}++impl TryFrom<OfferListResponse> for OfferListV1Response {+ type Error = MicroserviceClientError;+ fn try_from(value: OfferListResponse) -> Result<Self, Self::Error> {+ Ok(Self(value))+ }+}++impl OfferList {+ fn build_body(&self, request: OfferListRequest) -> Option<RequestContent> {+ Some(RequestContent::Json(Box::new(request)))+ }+}++hyperswitch_interfaces::impl_microservice_flow!(+ OfferList,+ method = Method::Post,+ path = OFFERS_LIST_PATH,+ v1_request = OfferListV1Request,+ v2_request = OfferListRequest,+ v2_response = OfferListResponse,+ v1_response = OfferListV1Response,+ client = OfferEngineClient,+ body = OfferList::build_body+);++pub struct OfferApply;+pub struct OfferApplyV1Request(pub OfferApplyRequest);+pub struct OfferApplyV1Response(pub OfferApplyResponse);++impl TryFrom<&OfferApplyV1Request> for OfferApplyRequest {+ type Error = MicroserviceClientError;+ fn try_from(value: &OfferApplyV1Request) -> Result<Self, Self::Error> {+ Ok(value.0.clone())+ }+}++impl TryFrom<OfferApplyResponse> for OfferApplyV1Response {+ type Error = MicroserviceClientError;+ fn try_from(value: OfferApplyResponse) -> Result<Self, Self::Error> {+ Ok(Self(value))+ }+}++impl OfferApply {+ fn build_body(&self, request: OfferApplyRequest) -> Option<RequestContent> {+ Some(RequestContent::Json(Box::new(request)))+ }+}++hyperswitch_interfaces::impl_microservice_flow!(+ OfferApply,+ method = Method::Post,+ path = OFFERS_APPLY_PATH,+ v1_request = OfferApplyV1Request,+ v2_request = OfferApplyRequest,+ v2_response = OfferApplyResponse,+ v1_response = OfferApplyV1Response,+ client = OfferEngineClient,+ body = OfferApply::build_body+);+#[derive(Debug, Clone, serde::Serialize)]pub struct ConnectivityResult {pub reachable: bool,diff --git a/crates/router/src/core/offer_engine/config.rs b/crates/router/src/core/offer_engine/config.rsindex 07d3c6a10f..1e04a9f029 100644--- a/crates/router/src/core/offer_engine/config.rs+++ b/crates/router/src/core/offer_engine/config.rs@@ -1,23 +1,39 @@use common_utils::errors::CustomResult;use super::types::{OfferEngineCredentialSource, OfferEngineError, ResolvedOfferEngineConfig};-use crate::{core::configs::dimension_state, routes::SessionState};+use crate::{+ core::configs::{self, dimension_config, dimension_state},+ routes::SessionState,+};-pub async fn resolve_offer_engine_config(+/// Resolve the Offer Engine config for the given dimensions. Generic over the+/// dimension so callers can target at any level (connectivity uses the global+/// dimension; payments pass merchant/org/profile for superposition targeting).+pub async fn resolve_offer_engine_config<D>(state: &SessionState,- dimensions: &dimension_state::DimensionsGlobal,-) -> CustomResult<Option<ResolvedOfferEngineConfig>, OfferEngineError> {+ dimensions: &D,+) -> CustomResult<Option<ResolvedOfferEngineConfig>, OfferEngineError>+where+ D: dimension_state::DimensionsBase,+{let store = state.store.as_ref();let superposition = state.superposition_service.as_ref();- let enabled = dimensions- .get_offer_engine_enabled(store, superposition, None)- .await;+ let enabled = configs::fetch_db_config_for_dimensions::<dimension_config::OfferEngineEnabled>(+ store,+ superposition,+ dimensions,+ None,+ )+ .await;if enabled {- let source = dimensions- .get_offer_engine_credential_source(store, superposition, None)- .await;+ let source = configs::fetch_db_config_for_string_enum::<+ dimension_config::OfferEngineCredentialSource,+ OfferEngineCredentialSource,+ >(store, superposition, dimensions, None)+ .await+ .unwrap_or(OfferEngineCredentialSource::None);match source {OfferEngineCredentialSource::None => Ok(None),@@ -31,11 +47,16 @@ pub async fn resolve_offer_engine_config(fn resolve_application_config(state: &SessionState,) -> CustomResult<ResolvedOfferEngineConfig, OfferEngineError> {- let app_config = state.conf.offer_engine.as_ref().ok_or_else(|| {- error_stack::report!(OfferEngineError::MissingApplicationConfig(- "offer_engine application config is not set".to_string()- ))- })?;+ let app_config = state+ .conf+ .offer_engine+ .as_ref()+ .ok_or_else(|| {+ error_stack::report!(OfferEngineError::MissingApplicationConfig(+ "offer_engine application config is not set".to_string()+ ))+ })?+ .get_inner();Ok(ResolvedOfferEngineConfig {base_url: app_config.base_url.clone(),diff --git a/crates/router/src/core/offer_engine/eligibility.rs b/crates/router/src/core/offer_engine/eligibility.rsnew file mode 100644index 0000000000..e9f813bb00--- /dev/null+++ b/crates/router/src/core/offer_engine/eligibility.rs@@ -0,0 +1,82 @@+use common_utils::{errors::CustomResult, id_type, types::MinorUnit};++use super::{+ amount,+ client::OfferEngineClient,+ types::{+ OfferCustomer, OfferEngineError, OfferListRequest, OfferOrder, OfferOrderType,+ OfferPaymentMethodInfo, ResolvedOfferEngineConfig, SelectedOffer,+ },+};+use crate::routes::SessionState;++pub struct OfferEligibilityContext {+ /// Hyperswitch payment id, used as the Offer Engine order id.+ pub payment_id: id_type::PaymentId,+ /// Order amount (not surcharge-inclusive), in minor units.+ pub order_amount: MinorUnit,+ /// Order currency.+ pub currency: common_enums::Currency,+ /// Customer id, if available.+ pub customer_id: Option<id_type::CustomerId>,+ /// Reference for the payment method (active attempt id, or payment id).+ pub payment_method_reference: String,+ /// Offer Engine payment method type (e.g. `CARD`).+ pub payment_method_type: String,+ /// Card network, if available.+ pub payment_method: Option<String>,+ /// Card BIN/IIN, if available.+ pub card_bin: Option<String>,+ /// Card type (e.g. `CREDIT`), if available.+ pub card_type: Option<String>,+ /// Issuing bank code, if available.+ pub bank_code: Option<String>,+ /// Card issuing country, if available.+ pub card_country: Option<String>,+}++impl OfferEligibilityContext {+ fn to_payment_method_info(&self) -> OfferPaymentMethodInfo {+ OfferPaymentMethodInfo {+ payment_method_reference: self.payment_method_reference.clone(),+ payment_method_type: self.payment_method_type.clone(),+ payment_method: self.payment_method.clone(),+ card_bin: self.card_bin.clone(),+ card_type: self.card_type.clone(),+ bank_code: self.bank_code.clone(),+ card_country: self.card_country.clone(),+ }+ }++ fn to_order(&self, merchant_id: &str) -> CustomResult<OfferOrder, OfferEngineError> {+ Ok(OfferOrder {+ order_id: self.payment_id.get_string_repr().to_string(),+ merchant_id: merchant_id.to_string(),+ amount: amount::to_offer_engine_amount(self.order_amount, self.currency)?,+ currency: self.currency,+ order_type: OfferOrderType::OrderPayment,+ })+ }++ fn to_customer(&self) -> Option<OfferCustomer> {+ self.customer_id.as_ref().map(|id| OfferCustomer {+ id: id.get_string_repr().to_string(),+ })+ }+}++pub async fn run_offer_eligibility(+ state: &SessionState,+ config: ResolvedOfferEngineConfig,+ ctx: OfferEligibilityContext,+) -> CustomResult<Option<SelectedOffer>, OfferEngineError> {+ let request = OfferListRequest {+ order: ctx.to_order(&config.merchant_id)?,+ payment_method_info: vec![ctx.to_payment_method_info()],+ customer: ctx.to_customer(),+ };++ let client = OfferEngineClient::new(config, &state.conf.trace_header.header_name);+ let response = client.list_offers(state, request).await?;+ response.select_best_offer(ctx.order_amount, ctx.currency)+}diff --git a/crates/router/src/core/offer_engine/types.rs b/crates/router/src/core/offer_engine/types.rsindex 1e91890613..50ee702988 100644--- a/crates/router/src/core/offer_engine/types.rs+++ b/crates/router/src/core/offer_engine/types.rs@@ -1,5 +1,8 @@+use common_utils::types::StringMajorUnit;use hyperswitch_masking::Secret;+use super::amount;+#[derive(Debug,Clone,@@ -33,4 +36,251 @@ pub enum OfferEngineError {RequestFailed,#[error("Failed to parse Offer Engine response")]ResponseParseFailed,+ #[error("Offer Engine amount conversion failed")]+ AmountConversion,+ #[error("Offer Engine /apply rejected the offer")]+ ApplyRejected,+}++/// Offer Engine order type.+#[derive(Debug, Clone, serde::Serialize)]+pub enum OfferOrderType {+ #[serde(rename = "ORDER_PAYMENT")]+ OrderPayment,+}++/// Order context sent to Offer Engine.+#[derive(Debug, Clone, serde::Serialize)]+pub struct OfferOrder {+ pub order_id: String,+ pub merchant_id: String,+ pub amount: StringMajorUnit,+ pub currency: common_enums::Currency,+ pub order_type: OfferOrderType,+}++/// Payment-method attributes sent to Offer Engine.+#[derive(Debug, Clone, serde::Serialize)]+pub struct OfferPaymentMethodInfo {+ pub payment_method_reference: String,+ pub payment_method_type: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub payment_method: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub card_bin: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub card_type: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub bank_code: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub card_country: Option<String>,+}++/// Customer sent to Offer Engine.+#[derive(Debug, Clone, serde::Serialize)]+pub struct OfferCustomer {+ pub id: String,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]+pub enum OfferStatus {+ #[serde(rename = "ELIGIBLE")]+ Eligible,+ #[serde(other)]+ Unknown,+}++#[derive(Debug, Clone, serde::Serialize)]+pub struct OfferListRequest {+ pub order: OfferOrder,+ pub payment_method_info: Vec<OfferPaymentMethodInfo>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub customer: Option<OfferCustomer>,+}++/// Response body for `/offers/list`.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct OfferListResponse {+ #[serde(default)]+ pub best_offer_combinations: Vec<OfferCombination>,+ #[serde(default)]+ pub offers: Vec<OfferListEntry>,+}++/// A candidate offer combination.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct OfferCombination {+ #[serde(default)]+ pub offers: Vec<OfferCombinationEntry>,+}++/// An offer inside a combination.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct OfferCombinationEntry {+ pub offer_id: String,+ pub discount_amount: StringMajorUnit,+}++/// A per-offer entry in `offers[]`.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct OfferListEntry {+ pub offer_id: String,+ pub status: OfferStatus,+ // Offer Engine always returns a code (mandatory `Text` in the `/list` response).+ pub offer_code: String,+ #[serde(default)]+ pub offer_description: Option<OfferDescription>,+}++/// Nested `offer_description` display copy.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct OfferDescription {+ #[serde(default)]+ pub title: Option<String>,+ #[serde(default)]+ pub description: Option<String>,+}++/// Request body for `/offers/apply`.+#[derive(Debug, Clone, serde::Serialize)]+pub struct OfferApplyRequest {+ pub txn_id: String,+ pub offers: Vec<String>,+ pub order: OfferOrder,+ pub payment_method_info: OfferPaymentMethodInfo,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub customer: Option<OfferCustomer>,+}++/// Response body for `/offers/apply`.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct OfferApplyResponse {+ #[serde(default)]+ pub offers: Vec<AppliedOfferEntry>,+}++/// An applied offer with its order breakup.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct AppliedOfferEntry {+ pub offer_id: String,+ pub status: OfferStatus,+ #[serde(default)]+ pub order_breakup: Option<OfferOrderBreakup>,+}++/// Per-offer order breakup.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct OfferOrderBreakup {+ pub discount_amount: StringMajorUnit,+}++// Selection helpers++/// A selected offer resolved from `/list` (discount in minor units).+#[derive(Debug, Clone)]+pub struct SelectedOffer {+ pub offer_id: String,+ pub offer_amount: common_utils::types::MinorUnit,+ pub currency: common_enums::Currency,+ pub code: String,+ pub title: Option<String>,+ pub description: Option<String>,+}++impl OfferListResponse {+ /// First-launch selection: `best_offer_combinations[0]` must hold exactly one+ /// `ELIGIBLE` offer. Returns `Ok(None)` when there's no supported offer.+ pub fn select_best_offer(+ &self,+ order_amount: common_utils::types::MinorUnit,+ currency: common_enums::Currency,+ ) -> error_stack::Result<Option<SelectedOffer>, OfferEngineError> {+ let Some(best) = self.best_offer_combinations.first() else {+ return Ok(None);+ };++ // First launch supports single-offer combinations only.+ let [combination_offer] = best.offers.as_slice() else {+ return Ok(None);+ };++ let list_entry = self+ .offers+ .iter()+ .find(|entry| entry.offer_id == combination_offer.offer_id);++ let Some(list_entry) = list_entry else {+ return Ok(None);+ };++ if list_entry.status != OfferStatus::Eligible {+ return Ok(None);+ }++ // Offer Engine settles the order at `orderAmount - discountAmount`;+ // `merchantDiscountAmount` is merchant-funded (display only), so the+ // customer's charge is reduced by `discountAmount` alone.+ let offer_amount =+ amount::from_offer_engine_amount(&combination_offer.discount_amount, currency)?;++ // Net amount after the offer must be positive; otherwise it isn't a+ // supported offer (same rule enforced at `/apply`).+ if order_amount <= offer_amount {+ return Ok(None);+ }++ Ok(Some(SelectedOffer {+ offer_id: combination_offer.offer_id.clone(),+ offer_amount,+ currency,+ code: list_entry.offer_code.clone(),+ title: list_entry+ .offer_description+ .as_ref()+ .and_then(|description| description.title.clone()),+ description: list_entry+ .offer_description+ .as_ref()+ .and_then(|description| description.description.clone()),+ }))+ }+}++/// An applied offer resolved from `/apply`.+#[derive(Debug, Clone)]+pub struct AppliedOffer {+ pub offer_id: String,+ pub offer_amount: common_utils::types::MinorUnit,+}++impl OfferApplyResponse {+ /// Extract the single `ELIGIBLE` applied offer (discount in minor units).+ /// Quote consistency is enforced by the confirm caller.+ pub fn single_applied_offer(+ &self,+ currency: common_enums::Currency,+ ) -> error_stack::Result<AppliedOffer, OfferEngineError> {+ let [applied] = self.offers.as_slice() else {+ return Err(error_stack::report!(OfferEngineError::ApplyRejected)+ .attach_printable("Offer Engine /apply did not return exactly one applied offer"));+ };++ common_utils::fp_utils::when(applied.status != OfferStatus::Eligible, || {+ Err(error_stack::report!(OfferEngineError::ApplyRejected)+ .attach_printable("Offer Engine /apply returned a non-eligible offer"))+ })?;++ let order_breakup = applied.order_breakup.as_ref().ok_or_else(|| {+ error_stack::report!(OfferEngineError::ApplyRejected)+ .attach_printable("Offer Engine /apply response is missing order_breakup")+ })?;+ // Charge reduction is `discountAmount` only (see `select_best_offer`).+ let offer_amount =+ amount::from_offer_engine_amount(&order_breakup.discount_amount, currency)?;++ Ok(AppliedOffer {+ offer_id: applied.offer_id.clone(),+ offer_amount,+ })+ }}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex aef3197f6a..0ee9ef16e1 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -172,7 +172,7 @@ use crate::{core::revenue_recovery::get_workflow_entries, db::storage::payment_m#[cfg(feature = "v1")]use crate::{core::{- authentication as authentication_core,+ authentication as authentication_core, offer_engine,unified_connector_service::update_gateway_system_in_feature_metadata,},types::{api::authentication, BrowserInformation},@@ -14806,6 +14806,34 @@ pub async fn payments_submit_eligibility(let state_for_surcharge = state.clone();let platform_for_surcharge = platform.clone();+ // Capture Offer Engine inputs (order amount, currency, customer, card BIN)+ // before the eligibility handler takes ownership of the eligibility data.+ let offer_order_amount = payment_eligibility_data.payment_intent.amount;+ let offer_currency = payment_eligibility_data.payment_intent.currency;+ let offer_customer_id = payment_eligibility_data.payment_intent.customer_id.clone();+ let offer_card_bin = payment_eligibility_data+ .payment_method_data+ .as_ref()+ .and_then(|pmd| pmd.get_card_iin());+ // Forward whatever card attributes the request carried; Offer Engine uses+ // them when present and ignores the rest.+ let offer_card = payment_eligibility_data+ .payment_method_data+ .as_ref()+ .and_then(|pmd| pmd.get_card_data());+ let offer_card_network = offer_card.and_then(|card| {+ card.card_network+ .as_ref()+ .map(|network| network.to_string())+ });+ let offer_card_type = offer_card.and_then(|card| card.card_type.clone());+ let offer_bank_code = offer_card.and_then(|card| card.bank_code.clone());+ let offer_card_country = offer_card.and_then(|card| card.card_issuing_country.clone());+ let offer_payment_method_type = eligibility_req+ .payment_method_type+ .to_string()+ .to_uppercase();+let eligibility_handler =EligibilityHandler::new(state, platform, payment_eligibility_data, business_profile);let sdk_next_action = eligibility_handler.run_all_eligiblity_checks().await?;@@ -14826,15 +14854,168 @@ pub async fn payments_submit_eligibility(}};+ // Offer Engine eligibility: resolve `/list` and, when an offer is selected,+ // store the quote for confirm to validate `/apply` against.+ let (amount_details, offer_details) = resolve_offer_eligibility_details(+ &state_for_surcharge,+ platform_for_surcharge.get_processor(),+ &profile_id,+ &payment_id,+ &sdk_next_action.next_action,+ offer_order_amount,+ offer_currency,+ offer_customer_id.as_ref(),+ offer_payment_method_type,+ offer_card_bin,+ offer_card_network,+ offer_card_type,+ offer_bank_code,+ offer_card_country,+ )+ .await?;+Ok(services::ApplicationResponse::Json(api_models::payments::PaymentsEligibilityResponse {payment_id,sdk_next_action,surcharge_details,+ amount_details,+ offer_details,},))}+/// Resolve Offer Engine eligibility into `(amount_details, offer_details)` for the+/// eligibility response.+///+/// Both are `None` when eligibility is denied or Offer Engine is not available+/// (config resolution failures are treated as "offers not available"). A `/list`+/// failure while Offer Engine is enabled fails eligibility. When enabled but no+/// offer is selected, the payable amount is returned unchanged with an empty+/// offer list.+#[cfg(all(feature = "oltp", feature = "v1"))]+#[allow(clippy::too_many_arguments)]+async fn resolve_offer_eligibility_details(+ state: &SessionState,+ processor: &domain::Processor,+ profile_id: &id_type::ProfileId,+ payment_id: &id_type::PaymentId,+ next_action: &api_models::payments::NextActionCall,+ order_amount: MinorUnit,+ currency: Option<common_enums::Currency>,+ customer_id: Option<&id_type::CustomerId>,+ payment_method_type: String,+ card_bin: Option<String>,+ card_network: Option<String>,+ card_type: Option<String>,+ bank_code: Option<String>,+ card_country: Option<String>,+) -> RouterResult<(+ Option<api_models::payments::EligibilityAmountDetails>,+ Option<api_models::payments::EligibilityOfferDetails>,+)> {+ // Offers apply only when eligibility is not denied, an Offer Engine config+ // resolves, and the currency is known (config-resolution failures are treated+ // as "offers not available").+ let offer_context = if matches!(+ next_action,+ api_models::payments::NextActionCall::Deny { .. }+ ) {+ None+ } else {+ // Target config at merchant/org/profile so superposition can override per+ // dimension; falls back to global when no override is configured.+ let offer_dimensions = Dimensions::new()+ .with_processor_merchant_id(processor.get_processor_merchant_id())+ .with_organization_id(processor.get_account().get_org_id().clone())+ .with_profile_id(profile_id.clone());+ offer_engine::resolve_offer_engine_config(state, &offer_dimensions)+ .await+ .ok()+ .flatten()+ .zip(currency)+ };++ match offer_context {+ None => Ok((None, None)),+ Some((offer_config, currency)) => {+ let ctx = offer_engine::eligibility::OfferEligibilityContext {+ payment_id: payment_id.clone(),+ order_amount,+ currency,+ customer_id: customer_id.cloned(),+ payment_method_reference: payment_id.get_string_repr().to_string(),+ payment_method_type,+ payment_method: card_network,+ card_bin,+ card_type,+ bank_code,+ card_country,+ };++ // A `/list` failure while Offer Engine is enabled fails eligibility.+ let selected =+ offer_engine::eligibility::run_offer_eligibility(state, offer_config, ctx)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Offer Engine /list failed")?;++ match selected {+ // Enabled but no eligible offer: payable amount unchanged.+ None => Ok((+ Some(api_models::payments::EligibilityAmountDetails {+ total_amount: order_amount,+ net_amount: order_amount,+ currency,+ }),+ Some(api_models::payments::EligibilityOfferDetails::default()),+ )),+ // Eligible offer: store the quote for confirm to validate `/apply`+ // against (keyed by offer id, the first-launch quote id; TTL kept).+ Some(selected) => {+ let processor_merchant_id = processor.get_account().get_id().clone();+ // Issue a unique quote id; confirm echoes it back to apply this offer.+ let offer_quote_id = common_utils::generate_time_ordered_id("offer_quote");+ let quotes = HashMap::from([(+ offer_quote_id.clone(),+ client_session::OfferQuote {+ offer_id: selected.offer_id.clone(),+ offer_amount: selected.offer_amount,+ currency: selected.currency,+ },+ )]);+ client_session::ClientSessionManager::store_offer_quotes(+ state,+ &processor_merchant_id,+ payment_id,+ quotes,+ )+ .await?;++ Ok((+ Some(api_models::payments::EligibilityAmountDetails {+ total_amount: order_amount,+ net_amount: order_amount - selected.offer_amount,+ currency,+ }),+ Some(api_models::payments::EligibilityOfferDetails {+ uplifted_offer_quote_ids: vec![offer_quote_id.clone()],+ eligible_offers: vec![api_models::payments::EligibleOffer {+ offer_quote_id,+ offer_amount: selected.offer_amount,+ currency: selected.currency,+ code: selected.code,+ title: selected.title,+ description: selected.description,+ }],+ }),+ ))+ }+ }+ }+ }+}+pub trait PaymentMethodChecker<F> {fn should_update_in_post_update_tracker(&self) -> bool;fn should_update_in_update_tracker(&self) -> bool;diff --git a/crates/router/src/core/payments/client_session.rs b/crates/router/src/core/payments/client_session.rsindex dd9db9978b..0f3275ab1c 100644--- a/crates/router/src/core/payments/client_session.rs+++ b/crates/router/src/core/payments/client_session.rs@@ -1,5 +1,7 @@//! Core client session ID management for SDK authorization.+use std::collections::HashMap;+use common_utils::{errors::CustomResult,id_type::{self, GenerateId, MerchantId, PaymentId},@@ -20,6 +22,21 @@ pub struct ClientSessionData {pub created_at: PrimitiveDateTime,/// Session expiry timepub expires_at: PrimitiveDateTime,+ /// Offer Engine eligibility quotes, keyed by `offer_quote_id`. Populated by+ /// `/eligibility` and consumed by `/confirm` to validate `/apply`.+ #[serde(default)]+ pub offer_quotes: HashMap<String, OfferQuote>,+}++/// A single Offer Engine eligibility quote stored in the client session.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OfferQuote {+ /// Offer Engine offer id.+ pub offer_id: String,+ /// Charge-reducing offer amount, in minor units.+ pub offer_amount: common_utils::types::MinorUnit,+ /// Currency of the offer amount.+ pub currency: common_enums::Currency,}/// Report of session invalidation results@@ -95,6 +112,7 @@ impl ClientSessionManager {client_session_id: client_session_id.clone(),created_at: now,expires_at: session_expiry,+ offer_quotes: HashMap::new(),};// Store session data as JSON with TTL@@ -166,6 +184,63 @@ impl ClientSessionManager {}}+ /// Store Offer Engine eligibility quotes into the existing client session+ #[instrument(skip_all)]+ pub async fn store_offer_quotes<S>(+ state: &S,+ processor_merchant_id: &MerchantId,+ payment_id: &PaymentId,+ offer_quotes: HashMap<String, OfferQuote>,+ ) -> CustomResult<(), errors::ApiErrorResponse>+ where+ S: SessionStateInfo + Sync,+ {+ let Some(session_data) =+ Self::get_session(state, processor_merchant_id, payment_id).await?+ else {+ logger::warn!(+ payment_id = %payment_id.get_string_repr(),+ "No client session found; skipping Offer Engine quote storage"+ );+ return Ok(());+ };++ let session_data = ClientSessionData {+ offer_quotes,+ ..session_data+ };++ let redis_conn = state+ .store()+ .get_redis_conn()+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let key = Self::get_session_key(processor_merchant_id, payment_id);++ // Update the session JSON without resetting its TTL.+ redis_conn+ .serialize_and_set_key_without_modifying_ttl(&key.into(), &session_data)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;++ Ok(())+ }++ /// Look up a stored Offer Engine quote by `offer_quote_id`.+ #[instrument(skip_all)]+ pub async fn get_offer_quote<S>(+ state: &S,+ processor_merchant_id: &MerchantId,+ payment_id: &PaymentId,+ offer_quote_id: &str,+ ) -> CustomResult<Option<OfferQuote>, errors::ApiErrorResponse>+ where+ S: SessionStateInfo + Sync,+ {+ Ok(Self::get_session(state, processor_merchant_id, payment_id)+ .await?+ .and_then(|session| session.offer_quotes.get(offer_quote_id).cloned()))+ }+/// Validate session ID against stored value////// # Argumentsdiff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex d534fabad4..b23baa5d6b 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -5692,6 +5692,7 @@ impl AttemptType {retry_type: Some(enums::RetryType::ManualRetry),installment_data: None,external_surcharge_details: None,+ applied_offer_details: None,sender_payment_instrument_id: None,}}diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex c9ae22b136..b02bb47baf 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -41,7 +41,7 @@ use crate::{configs::dimension_state,errors::{self, CustomResult, RouterResult, StorageErrorExt},mandate::helpers as m_helpers,- metrics,+ metrics, offer_engine,payment_methods::transformers as pm_transformers,payments::{self, helpers, operations, populate_installment_details, CustomerDetails,@@ -962,6 +962,14 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>update_request_fields: None,};+ let payment_data = Box::pin(apply_offer_engine_offer(+ state,+ request,+ platform.get_processor(),+ payment_data,+ ))+ .await?;+let get_trackers_response = operations::GetTrackerResponse {operation: Box::new(self),customer_details: Some(customer_details),@@ -2837,6 +2845,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for.payment_attempt.net_amount.get_installment_interest(),+ payment_data.payment_attempt.net_amount.get_offer_amount(),),connector_mandate_detail: payment_data@@ -2864,6 +2873,10 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for.payment_attempt.external_surcharge_details.clone(),+ applied_offer_details: payment_data+ .payment_attempt+ .applied_offer_details+ .clone(),},storage_scheme,&cloned_key_store,@@ -3097,3 +3110,176 @@ impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentDat))}}++/// Apply a confirm-time Offer Engine offer before the PSP call. No-op when the+/// request carries no offer. An attempt is locked to its applied offer: the same+/// offer re-requested is idempotent, a different one is rejected.+#[cfg(feature = "v1")]+async fn apply_offer_engine_offer<F: Clone + Send + Sync>(+ state: &SessionState,+ request: &api::PaymentsRequest,+ processor: &domain::Processor,+ payment_data: PaymentData<F>,+) -> RouterResult<PaymentData<F>> {+ // First launch supports a single offer; reject multiple rather than picking one.+ let requested_offer_id = match request+ .offer_details+ .as_ref()+ .map(|details| details.offer_quote_ids.as_slice())+ {+ None | Some([]) => None,+ Some([offer_quote_id]) => Some(offer_quote_id.clone()),+ Some(_) => {+ return Err(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "Only a single offer can be applied to a payment".to_string(),+ }))+ }+ };++ let existing_offer_quote_id = payment_data+ .payment_attempt+ .applied_offer_details+ .as_ref()+ .map(|existing| existing.inner().offer_quote_id.clone());++ match (existing_offer_quote_id, requested_offer_id) {+ (_, None) => Ok(payment_data),+ (Some(existing), Some(requested)) if existing == requested => Ok(payment_data),+ (Some(_), Some(_)) => Err(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "A different offer is already applied to this payment attempt".to_string(),+ })),+ (None, Some(requested)) => {+ Box::pin(apply_selected_offer(+ state,+ processor,+ requested,+ payment_data,+ ))+ .await+ }+ }+}++/// Call Offer Engine `/apply` for the selected quote and persist the applied+/// offer on the attempt before the PSP call.+#[cfg(feature = "v1")]+async fn apply_selected_offer<F: Clone + Send + Sync>(+ state: &SessionState,+ processor: &domain::Processor,+ offer_quote_id: String,+ mut payment_data: PaymentData<F>,+) -> RouterResult<PaymentData<F>> {+ // An offer was selected, so Offer Engine must be available. Target config at+ // merchant/org/profile (same as eligibility) so overrides resolve consistently.+ let profile_id = payment_data+ .payment_intent+ .profile_id+ .clone()+ .ok_or(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "Profile is required to apply an offer".to_string(),+ }))?;+ let offer_dimensions = dimension_state::Dimensions::new()+ .with_processor_merchant_id(processor.get_processor_merchant_id())+ .with_organization_id(processor.get_account().get_org_id().clone())+ .with_profile_id(profile_id);+ let offer_config = offer_engine::resolve_offer_engine_config(state, &offer_dimensions)+ .await+ .ok()+ .flatten()+ .ok_or(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "Offer Engine is not available for this offer selection".to_string(),+ }))?;++ let processor_merchant_id = processor.get_account().get_id().clone();+ let payment_id = payment_data.payment_attempt.payment_id.clone();++ // Recover the eligibility quote stored at `/eligibility`.+ let quote = payments::client_session::ClientSessionManager::get_offer_quote(+ state,+ &processor_merchant_id,+ &payment_id,+ &offer_quote_id,+ )+ .await?+ .ok_or(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "Offer quote not found or expired".to_string(),+ }))?;++ let currency = payment_data.payment_attempt.currency.ok_or(report!(+ errors::ApiErrorResponse::PreconditionFailed {+ message: "Payment currency is required to apply an offer".to_string(),+ }+ ))?;++ // Forward the same payment-method attributes eligibility sent, sourced from the+ // resolved attempt and card data, so `/apply` matches the `/list` quote.+ let payment_method_type = payment_data+ .payment_attempt+ .payment_method+ .map(|payment_method| payment_method.to_string().to_uppercase())+ .ok_or(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "Payment method is required to apply an offer".to_string(),+ }))?;+ let offer_card = payment_data+ .payment_method_data+ .as_ref()+ .and_then(|payment_method_data| payment_method_data.get_card_data());++ let ctx = offer_engine::apply::OfferApplyContext {+ payment_id,+ attempt_id: payment_data.payment_attempt.attempt_id.clone(),+ order_amount: payment_data.payment_attempt.net_amount.get_order_amount(),+ currency,+ customer_id: payment_data.payment_intent.customer_id.clone(),+ payment_method_type,+ payment_method: offer_card.and_then(|card| {+ card.card_network+ .as_ref()+ .map(|network| network.to_string())+ }),+ card_bin: payment_data+ .payment_method_data+ .as_ref()+ .and_then(|payment_method_data| payment_method_data.get_card_iin()),+ card_type: offer_card.and_then(|card| card.card_type.clone()),+ bank_code: offer_card.and_then(|card| card.bank_code.clone()),+ card_country: offer_card.and_then(|card| card.card_issuing_country.clone()),+ };++ let applied = Box::pin(offer_engine::apply::run_offer_apply(+ state,+ offer_config,+ &offer_engine::apply::OfferQuoteRef {+ offer_id: quote.offer_id,+ offer_amount: quote.offer_amount,+ currency: quote.currency,+ },+ ctx,+ ))+ .await+ .change_context(errors::ApiErrorResponse::PreconditionFailed {+ message: "Offer Engine /apply failed or did not match the eligibility quote".to_string(),+ })?;++ let applied_offer_details = common_types::payments::AppliedOfferDetails::V1(+ common_types::payments::AppliedOfferDetailsV1 {+ offer_quote_id,+ offer_engine_merchant_id: applied.offer_engine_merchant_id,+ offer_engine_txn_id: applied.offer_engine_txn_id,+ offer_id: applied.offer_id,+ offer_amount: applied.offer_amount,+ currency: applied.currency,+ },+ );++ // Offer-adjust the in-memory attempt; the confirm UpdateTracker (`ConfirmUpdate`)+ // persists both the offer-adjusted net amount and `applied_offer_details`, so no+ // standalone DB write is needed here (mirrors surcharge).+ payment_data+ .payment_attempt+ .net_amount+ .set_offer_amount(Some(applied.offer_amount));+ payment_data.payment_attempt.applied_offer_details = Some(applied_offer_details);++ Ok(payment_data)+}diff --git a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rsindex eacac75769..b4f2ec5d3b 100644--- a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs@@ -598,6 +598,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>.payment_attempt.net_amount.get_installment_interest(),+ payment_data.payment_attempt.net_amount.get_offer_amount(),),connector_mandate_detail: payment_data.payment_attempt@@ -621,6 +622,10 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsRequest>.payment_attempt.external_surcharge_details.clone(),+ applied_offer_details: payment_data+ .payment_attempt+ .applied_offer_details+ .clone(),},storage_scheme,key_store,diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex 6eb940baa4..ca798db656 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -1749,6 +1749,7 @@ impl PaymentCreate {retry_type: None,installment_data: None,external_surcharge_details: None,+ applied_offer_details: None,sender_payment_instrument_id: None,},additional_pm_data,diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rsindex 44c48e9842..401b85667d 100644--- a/crates/router/src/core/payments/operations/payment_response.rs+++ b/crates/router/src/core/payments/operations/payment_response.rs@@ -901,6 +901,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAuNone,None,None,+ None,),amount_capturable: incremental_authorization_details.total_amount,},@@ -2876,7 +2877,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(.convert().await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Error while construcing diesel attempt model")?;+ .attach_printable("Error while constructing diesel attempt model")?;let payment_attempt = payment_attempt_update.map(|payment_attempt_update| {@@ -2893,7 +2894,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>().await.change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Error while construcing domain attempt model")+ .attach_printable("Error while constructing domain attempt model")}).await.transpose()?diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex a00a619f36..a0543a62f6 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -1143,6 +1143,11 @@ impl PaymentUpdate {.surcharge_details.as_ref().map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);+ let offer_amount = payment_data+ .payment_attempt+ .applied_offer_details+ .as_ref()+ .map(|applied_offer_details| applied_offer_details.inner().offer_amount);let network_transaction_id = payment_data.payment_attempt.network_transaction_id.clone();let network_transaction_link_id = payment_data.payment_attempt@@ -1175,6 +1180,7 @@ impl PaymentUpdate {surcharge_amount,tax_amount,None,+ offer_amount,),shipping_cost: payment_data.payment_intent.shipping_cost,order_tax_amount: payment_datadiff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rsindex 3b715a1878..50336473b4 100644--- a/crates/router/src/core/payments/retry.rs+++ b/crates/router/src/core/payments/retry.rs@@ -876,6 +876,8 @@ pub fn make_new_auto_retry_payment_attempt(retry_type: Some(storage_enums::RetryType::AutoRetry),installment_data: Default::default(),external_surcharge_details: Default::default(),+ // Carry the offer forward so the auto-retry keeps the same offer-reduced amount.+ applied_offer_details: old_payment_attempt.applied_offer_details,sender_payment_instrument_id: Default::default(),}}diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 0270e7a0c2..facbeb3747 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -4262,10 +4262,12 @@ wherelet connector_response_metadata =payment_attempt.get_connector_response_metadata_from_attempt_metadata();+ let applied_offer = applied_offer_response(payment_attempt.applied_offer_details.clone());let payments_response = api::PaymentsResponse {payment_id: payment_intent.payment_id,merchant_id: payment_intent.merchant_id,status: payment_intent.status,+ applied_offer,connector_customer_id: payment_data.get_connector_customer_id(),amount: payment_attempt.net_amount.get_order_amount(),net_amount: payment_attempt.get_total_amount(),@@ -4596,6 +4598,22 @@ pub fn construct_connector_invoke_hidden_frame(Ok(api_models::payments::NextActionData::InvokeHiddenIframe { iframe_data })}+#[cfg(feature = "v1")]+fn applied_offer_response(+ details: Option<common_types::payments::AppliedOfferDetails>,+) -> Option<api_models::payments::AppliedOffer> {+ details.map(|offer| {+ let offer = offer.into_inner();+ api_models::payments::AppliedOffer {+ offer_engine_merchant_id: offer.offer_engine_merchant_id,+ offer_engine_txn_id: offer.offer_engine_txn_id,+ offer_id: offer.offer_id,+ offer_amount: offer.offer_amount,+ currency: offer.currency,+ }+ })+}+#[cfg(feature = "v1")]impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse {fn foreign_from((pi, pa): (storage::PaymentIntent, storage::PaymentAttempt)) -> Self {@@ -4647,6 +4665,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay});Self {connector_response_metadata: pa.get_connector_response_metadata_from_attempt_metadata(),+ applied_offer: applied_offer_response(pa.applied_offer_details.clone()),payment_id: pi.payment_id,merchant_id: pi.merchant_id,status: pi.status,diff --git a/crates/router/src/core/split_payments.rs b/crates/router/src/core/split_payments.rsindex 389a224b6d..a6fffdfded 100644--- a/crates/router/src/core/split_payments.rs+++ b/crates/router/src/core/split_payments.rs@@ -598,5 +598,6 @@ pub async fn create_domain_model_for_split_payment(network_transaction_link_id: None,authorized_amount: None,external_surcharge_details: None,+ applied_offer_details: None,})}diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rsindex 763d943857..c95e8d3878 100644--- a/crates/router/src/db/events.rs+++ b/crates/router/src/db/events.rs@@ -2122,6 +2122,7 @@ mod tests {processor_merchant_id: merchant_id,initiator: None,sdk_authorization: None,+ applied_offer: None,connector: None,customer: None,disputes: None,diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rsindex 7a52440368..e1dcdb1045 100644--- a/crates/router/src/services/kafka/payment_attempt.rs+++ b/crates/router/src/services/kafka/payment_attempt.rs@@ -289,6 +289,7 @@ impl<'a> KafkaPaymentAttempt<'a> {network_transaction_link_id: _,authorized_amount: _,external_surcharge_details: _,+ applied_offer_details: _,} = attempt;let (connector_payment_id, connector_payment_data) = connector_payment_iddiff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rsindex 2c6ecece51..68ed8156f7 100644--- a/crates/router/src/services/kafka/payment_attempt_event.rs+++ b/crates/router/src/services/kafka/payment_attempt_event.rs@@ -291,6 +291,7 @@ impl<'a> KafkaPaymentAttemptEvent<'a> {network_transaction_link_id: _,authorized_amount: _,external_surcharge_details: _,+ applied_offer_details: _,} = attempt;let (connector_payment_id, connector_payment_data) = connector_payment_iddiff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rsindex 747bd65ffe..9f19dd94d3 100644--- a/crates/router/src/types/storage/payment_attempt.rs+++ b/crates/router/src/types/storage/payment_attempt.rs@@ -176,6 +176,7 @@ mod tests {save_to_locker: Default::default(),error_message: Default::default(),offer_amount: Default::default(),+ applied_offer_details: Default::default(),payment_method_id: Default::default(),payment_method: Default::default(),capture_method: Default::default(),@@ -300,6 +301,7 @@ mod tests {save_to_locker: Default::default(),error_message: Default::default(),offer_amount: Default::default(),+ applied_offer_details: Default::default(),payment_method_id: Default::default(),payment_method: Default::default(),capture_method: Default::default(),@@ -439,6 +441,7 @@ mod tests {save_to_locker: Default::default(),error_message: Default::default(),offer_amount: Default::default(),+ applied_offer_details: Default::default(),payment_method_id: Default::default(),payment_method: Default::default(),capture_method: Default::default(),diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rsindex fa692ab5f3..046963ba51 100644--- a/crates/router/tests/payments.rs+++ b/crates/router/tests/payments.rs@@ -374,6 +374,7 @@ async fn payments_create_core() {let expected_response = api::PaymentsResponse {payment_id,+ applied_offer: None,status: api_enums::IntentStatus::Succeeded,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),@@ -681,6 +682,7 @@ async fn payments_create_core_adyen_no_redirect() {let expected_response = services::ApplicationResponse::JsonWithHeaders((api::PaymentsResponse {payment_id: payment_id.clone(),+ applied_offer: None,status: api_enums::IntentStatus::Processing,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rsindex c671411586..a651c6b371 100644--- a/crates/router/tests/payments2.rs+++ b/crates/router/tests/payments2.rs@@ -134,6 +134,7 @@ async fn payments_create_core() {let expected_response = api::PaymentsResponse {payment_id,+ applied_offer: None,status: api_enums::IntentStatus::Succeeded,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),@@ -450,6 +451,7 @@ async fn payments_create_core_adyen_no_redirect() {let expected_response = services::ApplicationResponse::JsonWithHeaders((api::PaymentsResponse {payment_id: payment_id.clone(),+ applied_offer: None,status: api_enums::IntentStatus::Processing,amount: MinorUnit::new(6540),amount_capturable: MinorUnit::new(0),diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rsindex 06b16ae9bf..0b93dfcc71 100644--- a/crates/storage_impl/src/mock_db/payment_attempt.rs+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs@@ -254,6 +254,7 @@ impl PaymentAttemptInterface for MockDb {retry_type: payment_attempt.retry_type,installment_data: payment_attempt.installment_data,external_surcharge_details: payment_attempt.external_surcharge_details,+ applied_offer_details: payment_attempt.applied_offer_details,sender_payment_instrument_id: payment_attempt.sender_payment_instrument_id,};payment_attempts.push(payment_attempt.clone());diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rsindex 2ed9053012..f7036a93aa 100644--- a/crates/storage_impl/src/payments/payment_attempt.rs+++ b/crates/storage_impl/src/payments/payment_attempt.rs@@ -821,6 +821,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {retry_type: payment_attempt.retry_type,installment_data: payment_attempt.installment_data.clone(),external_surcharge_details: payment_attempt.external_surcharge_details.clone(),+ applied_offer_details: payment_attempt.applied_offer_details.clone(),sender_payment_instrument_id: payment_attempt.sender_payment_instrument_id.clone(),diff --git a/migrations/2026-08-04-000001_add_applied_offer_details_to_payment_attempt/down.sql b/migrations/2026-08-04-000001_add_applied_offer_details_to_payment_attempt/down.sqlnew file mode 100644index 0000000000..69f0942f3a--- /dev/null+++ b/migrations/2026-08-04-000001_add_applied_offer_details_to_payment_attempt/down.sql@@ -0,0 +1,2 @@+-- Remove applied_offer_details from payment_attempt table+ALTER TABLE payment_attempt DROP COLUMN IF EXISTS applied_offer_details;diff --git a/migrations/2026-08-04-000001_add_applied_offer_details_to_payment_attempt/up.sql b/migrations/2026-08-04-000001_add_applied_offer_details_to_payment_attempt/up.sqlnew file mode 100644index 0000000000..95f84c0747--- /dev/null+++ b/migrations/2026-08-04-000001_add_applied_offer_details_to_payment_attempt/up.sql@@ -0,0 +1,2 @@+-- Add applied_offer_details to payment_attempt table+ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS applied_offer_details JSONB;