Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

refactor(subscription): move subscription related modules in router to new crate (#9863)

Jaganaec128802e87
diff --git a/Cargo.lock b/Cargo.lock
index a0cef58bdb..1eb8340252 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7359,6 +7359,7 @@ dependencies = [
"sha2",
"storage_impl",
"strum 0.26.3",
+ "subscriptions",
"tera",
"test_utils",
"thiserror 1.0.69",
@@ -8881,6 +8882,28 @@ dependencies = [
"syn 2.0.101",
]
+[[package]]
+name = "subscriptions"
+version = "0.1.0"
+dependencies = [
+ "api_models",
+ "async-trait",
+ "common_enums",
+ "common_types",
+ "common_utils",
+ "dyn-clone",
+ "error-stack 0.4.1",
+ "hyperswitch_domain_models",
+ "hyperswitch_interfaces",
+ "masking 0.1.0",
+ "router_env",
+ "scheduler",
+ "serde",
+ "serde_json",
+ "storage_impl",
+ "time",
+]
+
[[package]]
name = "subtle"
version = "2.6.1"
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index 1fb3976376..345be79bdf 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -18,6 +18,7 @@ pub mod ext_traits;
pub mod gsm;
pub mod invoice;
pub mod mandates;
+pub mod master_key;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_context;
diff --git a/crates/hyperswitch_domain_models/src/master_key.rs b/crates/hyperswitch_domain_models/src/master_key.rs
new file mode 100644
index 0000000000..45e78a86d3
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/master_key.rs
@@ -0,0 +1,3 @@
+pub trait MasterKeyInterface {
+ fn get_master_key(&self) -> &[u8];
+}
diff --git a/crates/hyperswitch_domain_models/src/subscription.rs b/crates/hyperswitch_domain_models/src/subscription.rs
index 785679279b..fc161a963c 100644
--- a/crates/hyperswitch_domain_models/src/subscription.rs
+++ b/crates/hyperswitch_domain_models/src/subscription.rs
@@ -43,14 +43,12 @@ impl std::fmt::Display for ClientSecret {
impl ApiEventMetric for ClientSecret {}
-#[cfg(feature = "v1")]
impl From<api_models::subscription::ClientSecret> for ClientSecret {
fn from(api_secret: api_models::subscription::ClientSecret) -> Self {
Self::new(api_secret.as_str().to_string())
}
}
-#[cfg(feature = "v1")]
impl From<ClientSecret> for api_models::subscription::ClientSecret {
fn from(domain_secret: ClientSecret) -> Self {
Self::new(domain_secret.to_string())
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 2a3cf49f6c..d8ba677935 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -33,8 +33,8 @@ payouts = ["api_models/payouts", "common_enums/payouts", "hyperswitch_connectors
payout_retry = ["payouts"]
recon = ["email", "api_models/recon"]
retry = []
-v2 = [ "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2", "hyperswitch_interfaces/v2", "common_types/v2", "revenue_recovery", "scheduler/v2", "euclid/v2", "payment_methods/v2", "tokenization_v2"]
-v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1", "scheduler/v1", "payment_methods/v1"]
+v2 = [ "common_default", "api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2", "common_utils/v2", "hyperswitch_connectors/v2", "hyperswitch_interfaces/v2", "common_types/v2", "revenue_recovery", "scheduler/v2", "euclid/v2", "payment_methods/v2", "tokenization_v2", "subscriptions/v2"]
+v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1", "common_utils/v1", "hyperswitch_connectors/v1", "common_types/v1", "scheduler/v1", "payment_methods/v1", "subscriptions/v1"]
dynamic_routing = ["external_services/dynamic_routing", "storage_impl/dynamic_routing", "api_models/dynamic_routing"]
revenue_recovery = ["api_models/revenue_recovery", "hyperswitch_interfaces/revenue_recovery", "hyperswitch_domain_models/revenue_recovery", "hyperswitch_connectors/revenue_recovery", "external_services/revenue_recovery", "dep:prost-types"]
tokenization_v2 = ["api_models/tokenization_v2", "diesel_models/tokenization_v2", "hyperswitch_domain_models/tokenization_v2", "storage_impl/tokenization_v2"]
@@ -142,6 +142,7 @@ router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra
scheduler = { version = "0.1.0", path = "../scheduler", default-features = false }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
payment_methods = { version = "0.1.0", path = "../payment_methods", default-features = false }
+subscriptions = { version = "0.1.0", path = "../subscriptions", default-features = false }
[build-dependencies]
router_env = { version = "0.1.0", path = "../router_env", default-features = false }
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index e180c1a9af..2bbad32e49 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -59,8 +59,6 @@ pub mod revenue_recovery;
#[cfg(feature = "v2")]
pub mod revenue_recovery_data_backfill;
pub mod routing;
-#[cfg(feature = "v1")]
-pub mod subscription;
pub mod surcharge_decision_config;
pub mod three_ds_decision_rule;
pub mod tokenization;
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index aecacf5393..4ff7c4c06e 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -17,7 +17,6 @@ use common_utils::{
use diesel_models::{refund as diesel_refund, ConnectorMandateReferenceId};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
- invoice::InvoiceUpdateRequest,
mandates::CommonMandateReference,
payments::{payment_attempt::PaymentAttempt, HeaderPayload},
router_request_types::VerifyWebhookSourceRequestData,
@@ -35,9 +34,7 @@ use crate::{
errors::{self, ConnectorErrorExt, CustomResult, RouterResponse, StorageErrorExt},
metrics, payment_methods,
payments::{self, tokenization},
- refunds, relay,
- subscription::subscription_handler::SubscriptionHandler,
- unified_connector_service, utils as core_utils,
+ refunds, relay, unified_connector_service, utils as core_utils,
webhooks::{network_tokenization_incoming, utils::construct_webhook_router_data},
},
db::StorageInterface,
@@ -835,20 +832,21 @@ async fn process_webhook_business_logic(
.await
.attach_printable("Incoming webhook flow for payouts failed"),
- api::WebhookFlow::Subscription => Box::pin(subscription_incoming_webhook_flow(
- state.clone(),
- req_state,
- merchant_context.clone(),
- business_profile,
- webhook_details,
- source_verified,
- connector,
- request_details,
- event_type,
- billing_connector_mca_id,
- ))
- .await
- .attach_printable("Incoming webhook flow for subscription failed"),
+ api::WebhookFlow::Subscription => {
+ Box::pin(subscriptions::webhooks::incoming_webhook_flow(
+ state.clone().into(),
+ merchant_context.clone(),
+ business_profile,
+ webhook_details,
+ source_verified,
+ connector,
+ request_details,
+ event_type,
+ billing_connector_mca_id,
+ ))
+ .await
+ .attach_printable("Incoming webhook flow for subscription failed")
+ }
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unsupported Flow Type received in incoming webhooks"),
@@ -2582,146 +2580,3 @@ fn insert_mandate_details(
)?;
Ok(connector_mandate_details)
}
-
-#[allow(clippy::too_many_arguments)]
-#[instrument(skip_all)]
-async fn subscription_incoming_webhook_flow(
- state: SessionState,
- _req_state: ReqState,
- merchant_context: domain::MerchantContext,
- business_profile: domain::Profile,
- _webhook_details: api::IncomingWebhookDetails,
- source_verified: bool,
- connector_enum: &ConnectorEnum,
- request_details: &IncomingWebhookRequestDetails<'_>,
- event_type: webhooks::IncomingWebhookEvent,
- billing_connector_mca_id: common_utils::id_type::MerchantConnectorAccountId,
-) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
- // Only process invoice_generated events for MIT payments
- if event_type != webhooks::IncomingWebhookEvent::InvoiceGenerated {
- return Ok(WebhookResponseTracker::NoEffect);
- }
-
- if !source_verified {
- logger::error!("Webhook source verification failed for subscription webhook flow");
- return Err(report!(
- errors::ApiErrorResponse::WebhookAuthenticationFailed
- ));
- }
-
- let connector_name = connector_enum.id().to_string();
-
- let connector = Connector::from_str(&connector_name)
- .change_context(errors::ConnectorError::InvalidConnectorName)
- .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
- .attach_printable_lazy(|| format!("unable to parse connector name {connector_name}"))?;
-
- let mit_payment_data = connector_enum
- .get_subscription_mit_payment_data(request_details)
- .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
- .attach_printable("Failed to extract MIT payment data from subscription webhook")?;
-
- let profile_id = business_profile.get_id().clone();
-
- let profile =
- SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
- .await
- .attach_printable(
- "subscriptions: failed to find business profile in get_subscription",
- )?;
-
- let handler = SubscriptionHandler::new(&state, &merchant_context);
-
- let subscription_id = mit_payment_data.subscription_id.clone();
-
- let subscription_with_handler = handler
- .find_subscription(subscription_id.clone())
- .await
- .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?;
-
- let invoice_handler = subscription_with_handler.get_invoice_handler(profile.clone());
- let invoice = invoice_handler
- .find_invoice_by_subscription_id_connector_invoice_id(
- &state,
- subscription_id,
- mit_payment_data.invoice_id.clone(),
- )
- .await
- .attach_printable(
- "subscriptions: failed to get invoice by subscription id and connector invoice id",
- )?;
- if let Some(invoice) = invoice {
- // During CIT payment we would have already created invoice entry with status as PaymentPending or Paid.
- // So we skip incoming webhook for the already processed invoice
- if invoice.status != InvoiceStatus::InvoiceCreated {
- logger::info!("Invoice is already being processed, skipping MIT payment creation");
- return Ok(WebhookResponseTracker::NoEffect);
- }
- }
-
- let payment_method_id = subscription_with_handler
- .subscription
- .payment_method_id
- .clone()
- .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
- message: "No payment method found for subscription".to_string(),
- })
- .attach_printable("No payment method found for subscription")?;
-
- logger::info!("Payment method ID found: {}", payment_method_id);
-
- let payment_id = generate_id(consts::ID_LENGTH, "pay");
- let payment_id = common_utils::id_type::PaymentId::wrap(payment_id).change_context(
- errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_id",
- },
- )?;
-
- // Multiple MIT payments for the same invoice_generated event is avoided by having the unique constraint on (subscription_id, connector_invoice_id) in the invoices table
- let invoice_entry = invoice_handler
- .create_invoice_entry(
- &state,
- billing_connector_mca_id.clone(),
- Some(payment_id),
- mit_payment_data.amount_due,
- mit_payment_data.currency_code,
- InvoiceStatus::PaymentPending,
- connector,
- None,
- Some(mit_payment_data.invoice_id.clone()),
- )
- .await?;
-
- // Create a sync job for the invoice with generated payment_id before initiating MIT payment creation.
- // This ensures that if payment creation call fails, the sync job can still retrieve the payment status
- invoice_handler
- .create_invoice_sync_job(
- &state,
- &invoice_entry,
- Some(mit_payment_data.invoice_id.clone()),
- connector,
- )
- .await?;
-
- let payment_response = invoice_handler
- .create_mit_payment(
- &state,
- mit_payment_data.amount_due,
- mit_payment_data.currency_code,
- &payment_method_id.clone(),
- )
- .await?;
-
- let update_request = InvoiceUpdateRequest::update_payment_and_status(
- payment_response.payment_method_id,
- Some(payment_response.payment_id.clone()),
- InvoiceStatus::from(payment_response.status),
- Some(mit_payment_data.invoice_id.clone()),
- );
-
- let _updated_invoice = invoice_handler
- .update_invoice(&state, invoice_entry.id.clone(), update_request)
- .await?;
-
- Ok(WebhookResponseTracker::NoEffect)
-}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index bc307de04f..c349a23fcb 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -54,12 +54,12 @@ use hyperswitch_domain_models::payouts::{
};
use hyperswitch_domain_models::{
cards_info::CardsInfoInterface,
+ master_key::MasterKeyInterface,
payment_methods::PaymentMethodInterface,
payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},
};
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
-use masking::PeekInterface;
use redis_interface::errors::RedisError;
use router_env::logger;
use storage_impl::{
@@ -151,6 +151,8 @@ pub trait StorageInterface:
{
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;
fn get_payment_methods_store(&self) -> Box<dyn PaymentMethodsStorageInterface>;
+ fn get_subscription_store(&self)
+ -> Box<dyn subscriptions::state::SubscriptionStorageInterface>;
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static>;
}
@@ -195,26 +197,6 @@ pub trait CommonStorageInterface:
fn get_accounts_storage_interface(&self) -> Box<dyn AccountsStorageInterface>;
}
-pub trait MasterKeyInterface {
- fn get_master_key(&self) -> &[u8];
-}
-
-impl MasterKeyInterface for Store {
- fn get_master_key(&self) -> &[u8] {
- self.master_key().peek()
- }
-}
-
-/// Default dummy key for MockDb
-impl MasterKeyInterface for MockDb {
- fn get_master_key(&self) -> &[u8] {
- &[
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
- 25, 26, 27, 28, 29, 30, 31, 32,
- ]
- }
-}
-
#[async_trait::async_trait]
impl StorageInterface for Store {
fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface> {
@@ -227,6 +209,12 @@ impl StorageInterface for Store {
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
+
+ fn get_subscription_store(
+ &self,
+ ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> {
+ Box::new(self.clone())
+ }
}
#[async_trait::async_trait]
@@ -250,6 +238,11 @@ impl StorageInterface for MockDb {
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
+ fn get_subscription_store(
+ &self,
+ ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> {
+ Box::new(self.clone())
+ }
}
#[async_trait::async_trait]
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 2366fc01ab..aab325fc8b 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -856,7 +856,9 @@ mod tests {
events::EventMetadata,
};
use futures::future::join_all;
- use hyperswitch_domain_models::merchant_account::MerchantAccountSetter;
+ use hyperswitch_domain_models::{
+ master_key::MasterKeyInterface, merchant_account::MerchantAccountSetter,
+ };
use time::macros::datetime;
use tokio::time::{timeout, Duration};
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index befb7329b7..063a660531 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3341,6 +3341,12 @@ impl StorageInterface for KafkaStore {
fn get_cache_store(&self) -> Box<dyn RedisConnInterface + Send + Sync + 'static> {
Box::new(self.clone())
}
+
+ fn get_subscription_store(
+ &self,
+ ) -> Box<dyn subscriptions::state::SubscriptionStorageInterface> {
+ Box::new(self.clone())
+ }
}
impl GlobalStorageInterface for KafkaStore {
@@ -3352,6 +3358,8 @@ impl AccountsStorageInterface for KafkaStore {}
impl PaymentMethodsStorageInterface for KafkaStore {}
+impl subscriptions::state::SubscriptionStorageInterface for KafkaStore {}
+
impl CommonStorageInterface for KafkaStore {
fn get_storage_interface(&self) -> Box<dyn StorageInterface> {
Box::new(self.clone())
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 8495c344bb..7b4faf922c 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -110,6 +110,7 @@ mod merchant_connector_account_cache_tests {
use common_utils::{date_time, type_name, types::keymanager::Identifier};
use diesel_models::enums::ConnectorType;
use error_stack::ResultExt;
+ use hyperswitch_domain_models::master_key::MasterKeyInterface;
use masking::PeekInterface;
use storage_impl::redis::{
cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE},
diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs
index 204544ac5f..60c4fa0033 100644
--- a/crates/router/src/db/merchant_key_store.rs
+++ b/crates/router/src/db/merchant_key_store.rs
@@ -5,6 +5,7 @@ mod tests {
use std::{borrow::Cow, sync::Arc};
use common_utils::{type_name, types::keymanager::Identifier};
+ use hyperswitch_domain_models::master_key::MasterKeyInterface;
use time::macros::datetime;
use tokio::sync::oneshot;
diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs
index 26bc5e7f70..f85f2dc195 100644
--- a/crates/router/src/routes/subscription.rs
+++ b/crates/router/src/routes/subscription.rs
@@ -15,7 +15,7 @@ use router_env::{
};
use crate::{
- core::{api_locking, subscription},
+ core::api_locking,
headers::X_PROFILE_ID,
routes::AppState,
services::{api as oss_api, authentication as auth, authorization::permissions::Permission},
@@ -71,8 +71,8 @@ pub async fn create_subscription(
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- subscription::create_subscription(
- state,
+ subscriptions::create_subscription(
+ state.into(),
merchant_context,
profile_id.clone(),
payload.clone(),
@@ -125,8 +125,8 @@ pub async fn confirm_subscription(
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- subscription::confirm_subscription(
- state,
+ subscriptions::confirm_subscription(
+ state.into(),
merchant_context,
profile_id.clone(),
payload.clone(),
@@ -174,7 +174,12 @@ pub async fn get_subscription_plans(
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- subscription::get_subscription_plans(state, merchant_context, profile_id.clone(), query)
+ subscriptions::get_subscription_plans(
+ state.into(),
+ merchant_context,
+ profile_id.clone(),
+ query,
+ )
},
auth::auth_type(
&*auth_type,
@@ -211,8 +216,8 @@ pub async fn get_subscription(
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- subscription::get_subscription(
- state,
+ subscriptions::get_subscription(
+ state.into(),
merchant_context,
profile_id.clone(),
subscription_id.clone(),
@@ -253,8 +258,8 @@ pub async fn create_and_confirm_subscription(
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- subscription::create_and_confirm_subscription(
- state,
+ subscriptions::create_and_confirm_subscription(
+ state.into(),
merchant_context,
profile_id.clone(),
payload.clone(),
@@ -304,7 +309,7 @@ pub async fn get_estimate(
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- subscription::get_estimate(state, merchant_context, profile_id.clone(), query)
+ subscriptions::get_estimate(state.into(), merchant_context, profile_id.clone(), query)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
@@ -334,8 +339,8 @@ pub async fn update_subscription(
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
- subscription::update_subscription(
- state,
+ subscriptions::update_subscription(
+ state.into(),
merchant_context,
profile_id.clone(),
subscription_id.clone(),
diff --git a/crates/router/src/types/domain/types.rs b/crates/router/src/types/domain/types.rs
index bbf1ad7bb7..909369901c 100644
--- a/crates/router/src/types/domain/types.rs
+++ b/crates/router/src/types/domain/types.rs
@@ -4,7 +4,7 @@ pub use hyperswitch_domain_models::type_encryption::{
crypto_operation, AsyncLift, CryptoOperation, Lift, OptionalEncryptableJsonType,
};
-use crate::routes::app;
+use crate::{routes::app, types::api as api_types};
impl From<&app::SessionState> for KeyManagerState {
fn from(state: &app::SessionState) -> Self {
@@ -35,3 +35,40 @@ impl From<&app::SessionState> for pm_state::PaymentMethodsState {
}
}
}
+
+pub struct ConnectorConversionHandler;
+
+impl hyperswitch_interfaces::api_client::ConnectorConverter for ConnectorConversionHandler {
+ fn get_connector_enum_by_name(
+ &self,
+ connector: &str,
+ ) -> common_utils::errors::CustomResult<
+ hyperswitch_interfaces::connector_integration_interface::ConnectorEnum,
+ hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse,
+ > {
+ api_types::ConnectorData::convert_connector(connector)
+ }
+}
+
+impl From<app::SessionState> for subscriptions::state::SubscriptionState {
+ fn from(state: app::SessionState) -> Self {
+ Self {
+ store: state.store.get_subscription_store(),
+ key_store: None,
+ key_manager_state: (&state).into(),
+ api_client: state.api_client.clone(),
+ conf: subscriptions::state::SubscriptionConfig {
+ proxy: state.conf.proxy.clone(),
+ internal_merchant_id_profile_id_auth: state
+ .conf
+ .internal_merchant_id_profile_id_auth
+ .clone(),
+ internal_services: state.conf.internal_services.clone(),
+ connectors: state.conf.connectors.clone(),
+ },
+ tenant: state.tenant.clone(),
+ event_handler: Box::new(state.event_handler.clone()),
+ connector_converter: Box::new(ConnectorConversionHandler),
+ }
+ }
+}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 5f4c0cd8c6..9e4e9ca30b 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -22,8 +22,6 @@ pub mod fraud_check;
pub mod generic_link;
pub mod gsm;
pub mod hyperswitch_ai_interaction;
-pub mod invoice;
-pub mod invoice_sync;
#[cfg(feature = "kv_store")]
pub mod kv;
pub mod locker_mock_up;
@@ -44,7 +42,6 @@ pub mod revenue_recovery_redis_operation;
pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
-pub mod subscription;
pub mod unified_translations;
pub mod user;
pub mod user_authentication_method;
@@ -78,9 +75,9 @@ pub use self::{
blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*,
capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*,
dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*,
- generic_link::*, gsm::*, hyperswitch_ai_interaction::*, invoice::*, locker_mock_up::*,
- mandate::*, merchant_account::*, merchant_connector_account::*, merchant_key_store::*,
- payment_link::*, payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,
- routing_algorithm::*, subscription::*, unified_translations::*, user::*,
- user_authentication_method::*, user_role::*,
+ generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*,
+ merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,
+ payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,
+ routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*,
+ user_role::*,
};
diff --git a/crates/router/src/types/storage/invoice.rs b/crates/router/src/types/storage/invoice.rs
deleted file mode 100644
index ac16c517ef..0000000000
--- a/crates/router/src/types/storage/invoice.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub use diesel_models::invoice::{Invoice, InvoiceNew, InvoiceUpdate};
diff --git a/crates/router/src/types/storage/subscription.rs b/crates/router/src/types/storage/subscription.rs
deleted file mode 100644
index 973c228349..0000000000
--- a/crates/router/src/types/storage/subscription.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub use diesel_models::subscription::{Subscription, SubscriptionNew, SubscriptionUpdate};
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 123d723e56..5e1a8c7c77 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -41,11 +41,11 @@ use masking::{ExposeInterface, SwitchStrategy};
use nanoid::nanoid;
use serde::de::DeserializeOwned;
use serde_json::Value;
+#[cfg(feature = "v1")]
+use subscriptions::subscription_handler::SubscriptionHandler;
use tracing_futures::Instrument;
pub use self::ext_traits::{OptionExt, ValidateCall};
-#[cfg(feature = "v1")]
-use crate::core::subscription::subscription_handler::SubscriptionHandler;
use crate::{
consts,
core::{
@@ -643,7 +643,9 @@ pub async fn get_mca_from_object_reference_id(
webhooks::ObjectReferenceId::SubscriptionId(subscription_id_type) => {
#[cfg(feature = "v1")]
{
- let subscription_handler = SubscriptionHandler::new(state, merchant_context);
+ let subscription_state = state.clone().into();
+ let subscription_handler =
+ SubscriptionHandler::new(&subscription_state, merchant_context);
let mut subscription_with_handler = subscription_handler
.find_subscription(subscription_id_type)
.await?;
diff --git a/crates/router/src/workflows/invoice_sync.rs b/crates/router/src/workflows/invoice_sync.rs
index 14762eed36..b1fcfe5cb4 100644
--- a/crates/router/src/workflows/invoice_sync.rs
+++ b/crates/router/src/workflows/invoice_sync.rs
@@ -1,299 +1,16 @@
-#[cfg(feature = "v1")]
-use api_models::subscription as subscription_types;
use async_trait::async_trait;
-use common_utils::{
- errors::CustomResult,
- ext_traits::{StringExt, ValueExt},
-};
-use diesel_models::process_tracker::business_status;
-use error_stack::ResultExt;
-use hyperswitch_domain_models::invoice::InvoiceUpdateRequest;
+use common_utils::{errors::CustomResult, ext_traits::ValueExt};
use router_env::logger;
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
- types::process_data,
- utils as scheduler_utils,
};
-#[cfg(feature = "v1")]
-use crate::core::subscription::{
- billing_processor_handler as billing, invoice_handler, payments_api_client,
-};
-use crate::{
- db::StorageInterface,
- errors as router_errors,
- routes::SessionState,
- types::{domain, storage},
-};
+use crate::{routes::SessionState, types::storage};
const INVOICE_SYNC_WORKFLOW: &str = "INVOICE_SYNC";
-const INVOICE_SYNC_WORKFLOW_TAG: &str = "INVOICE";
-pub struct InvoiceSyncWorkflow;
-
-pub struct InvoiceSyncHandler<'a> {
- pub state: &'a SessionState,
- pub tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
- pub key_store: domain::MerchantKeyStore,
- pub merchant_account: domain::MerchantAccount,
- pub customer: domain::Customer,
- pub profile: domain::Profile,
- pub subscription: hyperswitch_domain_models::subscription::Subscription,
- pub invoice: hyperswitch_domain_models::invoice::Invoice,
-}
-
-#[cfg(feature = "v1")]
-impl<'a> InvoiceSyncHandler<'a> {
- pub async fn create(
- state: &'a SessionState,
- tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
- ) -> Result<Self, errors::ProcessTrackerError> {
- let key_manager_state = &state.into();
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &tracking_data.merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .attach_printable("Failed to fetch Merchant key store from DB")?;
-
- let merchant_account = state
- .store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- &tracking_data.merchant_id,
- &key_store,
- )
- .await
- .attach_printable("Subscriptions: Failed to fetch Merchant Account from DB")?;
-
- let profile = state
- .store
- .find_business_profile_by_profile_id(
- &(state).into(),
- &key_store,
- &tracking_data.profile_id,
- )
- .await
- .attach_printable("Subscriptions: Failed to fetch Business Profile from DB")?;
-
- let customer = state
- .store
- .find_customer_by_customer_id_merchant_id(
- &(state).into(),
- &tracking_data.customer_id,
- merchant_account.get_id(),
- &key_store,
- merchant_account.storage_scheme,
- )
- .await
- .attach_printable("Subscriptions: Failed to fetch Customer from DB")?;
-
- let subscription = state
- .store
- .find_by_merchant_id_subscription_id(
- &state.into(),
- &key_store,
- merchant_account.get_id(),
- tracking_data.subscription_id.get_string_repr().to_string(),
- )
- .await
- .attach_printable("Subscriptions: Failed to fetch subscription from DB")?;
-
- let invoice = state
- .store
- .find_invoice_by_invoice_id(
- &state.into(),
- &key_store,
- tracking_data.invoice_id.get_string_repr().to_string(),
- )
- .await
- .attach_printable("invoices: unable to get latest invoice from database")?;
-
- Ok(Self {
- state,
- tracking_data,
- key_store,
- merchant_account,
- customer,
- profile,
- subscription,
- invoice,
- })
- }
-
- async fn finish_process_with_business_status(
- &self,
- process: &storage::ProcessTracker,
- business_status: &'static str,
- ) -> CustomResult<(), router_errors::ApiErrorResponse> {
- self.state
- .store
- .as_scheduler()
- .finish_process_with_business_status(process.clone(), business_status)
- .await
- .change_context(router_errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to update process tracker status")
- }
-
- pub async fn perform_payments_sync(
- &self,
- ) -> CustomResult<subscription_types::PaymentResponseData, router_errors::ApiErrorResponse>
- {
- let payment_id = self.invoice.payment_intent_id.clone().ok_or(
- router_errors::ApiErrorResponse::SubscriptionError {
- operation: "Invoice_sync: Missing Payment Intent ID in Invoice".to_string(),
- },
- )?;
- let payments_response = payments_api_client::PaymentsApiClient::sync_payment(
- self.state,
- payment_id.get_string_repr().to_string(),
- self.merchant_account.get_id().get_string_repr(),
- self.profile.get_id().get_string_repr(),
- )
- .await
- .change_context(router_errors::ApiErrorResponse::SubscriptionError {
- operation: "Invoice_sync: Failed to sync payment status from payments microservice"
- .to_string(),
- })
- .attach_printable("Failed to sync payment status from payments microservice")?;
-
- Ok(payments_response)
- }
-
- pub async fn perform_billing_processor_record_back_if_possible(
- &self,
- payment_response: subscription_types::PaymentResponseData,
- payment_status: common_enums::AttemptStatus,
- connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
- invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus,
- ) -> CustomResult<(), router_errors::ApiErrorResponse> {
- if let Some(connector_invoice_id) = connector_invoice_id {
- Box::pin(self.perform_billing_processor_record_back(
- payment_response,
- payment_status,
- connector_invoice_id,
- invoice_sync_status,
- ))
- .await
- .attach_printable("Failed to record back to billing processor")?;
- }
- Ok(())
- }
-
- pub async fn perform_billing_processor_record_back(
- &self,
- payment_response: subscription_types::PaymentResponseData,
- payment_status: common_enums::AttemptStatus,
- connector_invoice_id: common_utils::id_type::InvoiceId,
- invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus,
- ) -> CustomResult<(), router_errors::ApiErrorResponse> {
- logger::info!("perform_billing_processor_record_back");
-
- let billing_handler = billing::BillingHandler::create(
- self.state,
- &self.merchant_account,
- &self.key_store,
- self.profile.clone(),
- )
- .await
- .attach_printable("Failed to create billing handler")?;
-
- let invoice_handler = invoice_handler::InvoiceHandler::new(
- self.subscription.clone(),
- self.merchant_account.clone(),
- self.profile.clone(),
- self.key_store.clone(),
- );
-
- // TODO: Handle retries here on failure
- billing_handler
- .record_back_to_billing_processor(
- self.state,
- connector_invoice_id.clone(),
- payment_response.payment_id.to_owned(),
- payment_status,
- payment_response.amount,
- payment_response.currency,
- payment_response.payment_method_type,
- )
- .await
- .attach_printable("Failed to record back to billing processor")?;
-
- let update_request = InvoiceUpdateRequest::update_connector_and_status(
- connector_invoice_id,
- common_enums::connector_enums::InvoiceStatus::from(invoice_sync_status),
- );
-
- invoice_handler
- .update_invoice(self.state, self.invoice.id.to_owned(), update_request)
- .await
- .attach_printable("Failed to update invoice in DB")?;
-
- Ok(())
- }
-
- pub async fn transition_workflow_state(
- &self,
- process: storage::ProcessTracker,
- payment_response: subscription_types::PaymentResponseData,
- connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
- ) -> CustomResult<(), router_errors::ApiErrorResponse> {
- let invoice_sync_status =
- storage::invoice_sync::InvoiceSyncPaymentStatus::from(payment_response.status);
- match invoice_sync_status {
- storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentSucceeded => {
- Box::pin(self.perform_billing_processor_record_back_if_possible(
- payment_response.clone(),
- common_enums::AttemptStatus::Charged,
- connector_invoice_id,
- invoice_sync_status.clone(),
- ))
- .await
- .attach_printable("Failed to record back success status to billing processor")?;
- self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT)
- .await
- .change_context(router_errors::ApiErrorResponse::SubscriptionError {
- operation: "Invoice_sync process_tracker task completion".to_string(),
- })
- .attach_printable("Failed to update process tracker status")
- }
- storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentProcessing => {
- retry_subscription_invoice_sync_task(
- &*self.state.store,
- self.tracking_data.connector_name.to_string().clone(),
- self.merchant_account.get_id().to_owned(),
- process,
- )
- .await
- .change_context(router_errors::ApiErrorResponse::SubscriptionError {
- operation: "Invoice_sync process_tracker task retry".to_string(),
- })
- .attach_printable("Failed to update process tracker status")
- }
- storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentFailed => {
- Box::pin(self.perform_billing_processor_record_back_if_possible(
- payment_response.clone(),
- common_enums::AttemptStatus::Charged,
- connector_invoice_id,
- invoice_sync_status.clone(),
- ))
- .await
- .attach_printable("Failed to record back failure status to billing processor")?;
-
- self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT)
- .await
- .change_context(router_errors::ApiErrorResponse::SubscriptionError {
- operation: "Invoice_sync process_tracker task completion".to_string(),
- })
- .attach_printable("Failed to update process tracker status")
- }
- }
- }
-}
+pub struct InvoiceSyncWorkflow;
#[async_trait]
impl ProcessTrackerWorkflow<SessionState> for InvoiceSyncWorkflow {
@@ -306,14 +23,14 @@ impl ProcessTrackerWorkflow<SessionState> for InvoiceSyncWorkflow {
let tracking_data = process
.tracking_data
.clone()
- .parse_value::<storage::invoice_sync::InvoiceSyncTrackingData>(
+ .parse_value::<subscriptions::storage::invoice_sync::InvoiceSyncTrackingData>(
"InvoiceSyncTrackingData",
)?;
-
+ let subscription_state = state.clone().into();
match process.name.as_deref() {
Some(INVOICE_SYNC_WORKFLOW) => {
- Box::pin(perform_subscription_invoice_sync(
- state,
+ Box::pin(subscriptions::workflows::perform_subscription_invoice_sync(
+ &subscription_state,
process,
tracking_data,
))
@@ -342,120 +59,3 @@ impl ProcessTrackerWorkflow<SessionState> for InvoiceSyncWorkflow {
Ok(())
}
}
-
-#[cfg(feature = "v1")]
-async fn perform_subscription_invoice_sync(
- state: &SessionState,
- process: storage::ProcessTracker,
- tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
-) -> Result<(), errors::ProcessTrackerError> {
- let handler = InvoiceSyncHandler::create(state, tracking_data).await?;
-
- let payment_status = handler.perform_payments_sync().await?;
-
- Box::pin(handler.transition_workflow_state(
- process,
- payment_status,
- handler.tracking_data.connector_invoice_id.clone(),
- ))
- .await?;
-
- Ok(())
-}
-
-pub async fn create_invoice_sync_job(
- state: &SessionState,
- request: storage::invoice_sync::InvoiceSyncRequest,
-) -> CustomResult<(), router_errors::ApiErrorResponse> {
- let tracking_data = storage::invoice_sync::InvoiceSyncTrackingData::from(request);
-
- let process_tracker_entry = diesel_models::ProcessTrackerNew::new(
- common_utils::generate_id(crate::consts::ID_LENGTH, "proc"),
- INVOICE_SYNC_WORKFLOW.to_string(),
- common_enums::ProcessTrackerRunner::InvoiceSyncflow,
- vec![INVOICE_SYNC_WORKFLOW_TAG.to_string()],
- tracking_data,
- Some(0),
- common_utils::date_time::now(),
- common_types::consts::API_VERSION,
- )
- .change_context(router_errors::ApiErrorResponse::InternalServerError)
- .attach_printable("subscriptions: unable to form process_tracker type")?;
-
- state
- .store
- .insert_process(process_tracker_entry)
- .await
- .change_context(router_errors::ApiErrorResponse::InternalServerError)
- .attach_printable("subscriptions: unable to insert process_tracker entry in DB")?;
-
- Ok(())
-}
-
-pub async fn get_subscription_invoice_sync_process_schedule_time(
- db: &dyn StorageInterface,
- connector: &str,
- merchant_id: &common_utils::id_type::MerchantId,
- retry_count: i32,
-) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
- let mapping: CustomResult<
- process_data::SubscriptionInvoiceSyncPTMapping,
- router_errors::StorageError,
- > = db
- .find_config_by_key(&format!("invoice_sync_pt_mapping_{connector}"))
- .await
- .map(|value| value.config)
- .and_then(|config| {
- config
- .parse_struct("SubscriptionInvoiceSyncPTMapping")
- .change_context(router_errors::StorageError::DeserializationFailed)
- .attach_printable("Failed to deserialize invoice_sync_pt_mapping config to struct")
- });
- let mapping = match mapping {
- Ok(x) => x,
- Err(error) => {
- logger::info!(?error, "Redis Mapping Error");
- process_data::SubscriptionInvoiceSyncPTMapping::default()
- }
- };
-
- let time_delta = scheduler_utils::get_subscription_invoice_sync_retry_schedule_time(
- mapping,
- merchant_id,
- retry_count,
- );
-
- Ok(scheduler_utils::get_time_from_delta(time_delta))
-}
-
-pub async fn retry_subscription_invoice_sync_task(
- db: &dyn StorageInterface,
- connector: String,
- merchant_id: common_utils::id_type::MerchantId,
- pt: storage::ProcessTracker,
-) -> Result<(), errors::ProcessTrackerError> {
- let schedule_time = get_subscription_invoice_sync_process_schedule_time(
- db,
- connector.as_str(),
- &merchant_id,
- pt.retry_count + 1,
- )
- .await?;
-
- match schedule_time {
- Some(s_time) => {
- db.as_scheduler()
- .retry_process(pt, s_time)
- .await
- .attach_printable("Failed to retry subscription invoice sync task")?;
- }
- None => {
- db.as_scheduler()
- .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
- .await
- .attach_printable("Failed to finish subscription invoice sync task")?;
- }
- }
-
- Ok(())
-}
diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs
index 64a92348ce..d8c736b774 100644
--- a/crates/storage_impl/src/config.rs
+++ b/crates/storage_impl/src/config.rs
@@ -1,5 +1,8 @@
use common_utils::DbConnectionParams;
-use masking::Secret;
+use hyperswitch_domain_models::master_key::MasterKeyInterface;
+use masking::{PeekInterface, Secret};
+
+use crate::{kv_router_store, DatabaseStore, MockDb, RouterStore};
#[derive(Debug, Clone, serde::Deserialize)]
pub struct Database {
@@ -66,3 +69,22 @@ impl Default for Database {
}
}
}
+
+impl<T: DatabaseStore> MasterKeyInterface for kv_router_store::KVRouterStore<T> {
+ fn get_master_key(&self) -> &[u8] {
+ self.master_key().peek()
+ }
+}
+
+impl<T: DatabaseStore> MasterKeyInterface for RouterStore<T> {
+ fn get_master_key(&self) -> &[u8] {
+ self.master_key().peek()
+ }
+}
+
+/// Default dummy key for MockDb
+impl MasterKeyInterface for MockDb {
+ fn get_master_key(&self) -> &[u8] {
+ self.master_key()
+ }
+}
diff --git a/crates/storage_impl/src/merchant_account.rs b/crates/storage_impl/src/merchant_account.rs
index 79f2687396..8462950cf6 100644
--- a/crates/storage_impl/src/merchant_account.rs
+++ b/crates/storage_impl/src/merchant_account.rs
@@ -6,6 +6,7 @@ use diesel_models::merchant_account as storage;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
+ master_key::MasterKeyInterface,
merchant_account::{self as domain, MerchantAccountInterface},
merchant_key_store::{MerchantKeyStore, MerchantKeyStoreInterface},
};
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 8b40907cb0..d7f78de500 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -232,7 +232,7 @@ impl MockDb {
}
}
- pub fn get_master_key(&self) -> &[u8] {
+ pub fn master_key(&self) -> &[u8] {
&[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32,
diff --git a/crates/subscriptions/Cargo.toml b/crates/subscriptions/Cargo.toml
new file mode 100644
index 0000000000..08da62a478
--- /dev/null
+++ b/crates/subscriptions/Cargo.toml
@@ -0,0 +1,33 @@
+[package]
+name = "subscriptions"
+version = "0.1.0"
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+
+[dependencies]
+async-trait = "0.1.88"
+dyn-clone = "1.0.19"
+error-stack = "0.4.1"
+masking = { version = "0.1.0", path = "../masking" }
+serde = { version = "1.0.219", features = ["derive"] }
+serde_json = "1.0.140"
+time = { version = "0.3.41", features = ["serde", "std"] }
+
+api_models = { version = "0.1.0", path = "../api_models", features = ["errors", "control_center_theme"] }
+common_types = { version = "0.1.0", path = "../common_types" }
+common_enums = { version = "0.1.0", path = "../common_enums" }
+common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] }
+hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
+router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
+scheduler = { version = "0.1.0", path = "../scheduler", default-features = false }
+storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
+hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false }
+
+[lints]
+workspace = true
+
+[features]
+default = ["v1"]
+v1 = ["hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1", "scheduler/v1", "common_types/v1"]
+v2 = ["common_utils/v2", "scheduler/v2", "common_types/v2"]
diff --git a/crates/router/src/core/subscription.rs b/crates/subscriptions/src/core.rs
similarity index 97%
rename from crates/router/src/core/subscription.rs
rename to crates/subscriptions/src/core.rs
index 1943006897..d86d7ad9f9 100644
--- a/crates/router/src/core/subscription.rs
+++ b/crates/subscriptions/src/core.rs
@@ -8,16 +8,18 @@ use hyperswitch_domain_models::{
api::ApplicationResponse, invoice::InvoiceUpdateRequest, merchant_context::MerchantContext,
};
-use super::errors::{self, RouterResponse};
+pub type RouterResponse<T> =
+ Result<ApplicationResponse<T>, error_stack::Report<errors::ApiErrorResponse>>;
use crate::{
- core::subscription::{
+ core::{
billing_processor_handler::BillingHandler, invoice_handler::InvoiceHandler,
subscription_handler::SubscriptionHandler,
},
- routes::SessionState,
+ state::SubscriptionState as SessionState,
};
pub mod billing_processor_handler;
+pub mod errors;
pub mod invoice_handler;
pub mod payments_api_client;
pub mod subscription_handler;
@@ -54,7 +56,7 @@ pub async fn create_subscription(
.create_subscription_entry(
subscription_id,
&request.customer_id,
- billing_handler.connector_data.connector_name,
+ billing_handler.connector_name,
billing_handler.merchant_connector_id.clone(),
request.merchant_reference_id.clone(),
&profile.clone(),
@@ -93,7 +95,7 @@ pub async fn create_subscription(
estimate.total,
estimate.currency,
connector_enums::InvoiceStatus::InvoiceCreated,
- billing_handler.connector_data.connector_name,
+ billing_handler.connector_name,
None,
None,
)
@@ -198,7 +200,7 @@ pub async fn create_and_confirm_subscription(
.create_subscription_entry(
subscription_id.clone(),
&request.customer_id,
- billing_handler.connector_data.connector_name,
+ billing_handler.connector_name,
billing_handler.merchant_connector_id.clone(),
request.merchant_reference_id.clone(),
&profile.clone(),
@@ -260,7 +262,7 @@ pub async fn create_and_confirm_subscription(
.clone()
.and_then(|invoice| invoice.status)
.unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated),
- billing_handler.connector_data.connector_name,
+ billing_handler.connector_name,
None,
invoice_details.clone().map(|invoice| invoice.id),
)
@@ -271,7 +273,7 @@ pub async fn create_and_confirm_subscription(
&state,
&invoice_entry,
invoice_details.clone().map(|details| details.id),
- billing_handler.connector_data.connector_name,
+ billing_handler.connector_name,
)
.await?;
@@ -390,7 +392,6 @@ pub async fn confirm_subscription(
.await?;
let invoice_details = subscription_create_response.invoice_details;
-
let update_request = InvoiceUpdateRequest::update_payment_and_status(
payment_response.payment_method_id.clone(),
Some(payment_response.payment_id.clone()),
@@ -409,7 +410,7 @@ pub async fn confirm_subscription(
&state,
&invoice_entry,
invoice_details.map(|invoice| invoice.id),
- billing_handler.connector_data.connector_name,
+ billing_handler.connector_name,
)
.await?;
@@ -562,5 +563,11 @@ pub async fn update_subscription(
)
.await?;
- get_subscription(state, merchant_context, profile_id, subscription.id).await
+ Box::pin(get_subscription(
+ state,
+ merchant_context,
+ profile_id,
+ subscription.id,
+ ))
+ .await
}
diff --git a/crates/router/src/core/subscription/billing_processor_handler.rs b/crates/subscriptions/src/core/billing_processor_handler.rs
similarity index 80%
rename from crates/router/src/core/subscription/billing_processor_handler.rs
rename to crates/subscriptions/src/core/billing_processor_handler.rs
index 00ca480e5e..0ff36777d9 100644
--- a/crates/router/src/core/subscription/billing_processor_handler.rs
+++ b/crates/subscriptions/src/core/billing_processor_handler.rs
@@ -1,9 +1,11 @@
use std::str::FromStr;
-use common_enums::connector_enums;
+use api_models::subscription as subscription_types;
+use common_enums::{connector_enums, CallConnectorAction};
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
+ errors::api_error_response as errors,
router_data_v2::flow_common_types::{
GetSubscriptionEstimateData, GetSubscriptionPlanPricesData, GetSubscriptionPlansData,
InvoiceRecordBackData, SubscriptionCreateData, SubscriptionCustomerData,
@@ -17,18 +19,16 @@ use hyperswitch_domain_models::{
ConnectorCustomerResponseData, PaymentsResponseData,
},
};
-
-use super::errors;
-use crate::{
- core::{payments as payments_core, subscription::subscription_types},
- routes::SessionState,
- services,
- types::api as api_types,
+use hyperswitch_interfaces::{
+ api_client, configs::MerchantConnectorAccountType, connector_integration_interface,
};
+use crate::{errors::SubscriptionResult, state::SubscriptionState as SessionState};
+
pub struct BillingHandler {
pub auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType,
- pub connector_data: api_types::ConnectorData,
+ pub connector_name: connector_enums::Connector,
+ pub connector_enum: connector_integration_interface::ConnectorEnum,
pub connector_params: hyperswitch_domain_models::connector_endpoints::ConnectorParams,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
@@ -41,7 +41,7 @@ impl BillingHandler {
merchant_account: &hyperswitch_domain_models::merchant_account::MerchantAccount,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
profile: hyperswitch_domain_models::business_profile::Profile,
- ) -> errors::RouterResult<Self> {
+ ) -> SubscriptionResult<Self> {
let merchant_connector_id = profile.get_billing_processor_id()?;
let billing_processor_mca = state
@@ -60,35 +60,30 @@ impl BillingHandler {
let connector_name = billing_processor_mca.connector_name.clone();
let auth_type: hyperswitch_domain_models::router_data::ConnectorAuthType =
- payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new(
- billing_processor_mca.clone(),
- ))
- .get_connector_account_details()
- .parse_value("ConnectorAuthType")
- .change_context(errors::ApiErrorResponse::InvalidDataFormat {
- field_name: "connector_account_details".to_string(),
- expected_format: "auth_type and api_key".to_string(),
- })?;
-
- let connector_data = api_types::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &connector_name,
- api_types::GetToken::Connector,
- Some(billing_processor_mca.get_id()),
- )
- .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
- .attach_printable(
- "invalid connector name received in billing merchant connector account",
- )?;
-
- let connector_enum = connector_enums::Connector::from_str(connector_name.as_str())
+ MerchantConnectorAccountType::DbVal(Box::new(billing_processor_mca.clone()))
+ .get_connector_account_details()
+ .parse_value("ConnectorAuthType")
+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "connector_account_details".to_string(),
+ expected_format: "auth_type and api_key".to_string(),
+ })?;
+
+ let connector_enum = state
+ .connector_converter
+ .get_connector_enum_by_name(&connector_name)
+ .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
+ .attach_printable(
+ "invalid connector name received in billing merchant connector account",
+ )?;
+
+ let connector_data = connector_enums::Connector::from_str(connector_name.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("unable to parse connector name {connector_name:?}"))?;
let connector_params =
hyperswitch_domain_models::connector_endpoints::Connectors::get_connector_params(
&state.conf.connectors,
- connector_enum,
+ connector_data,
)
.change_context(errors::ApiErrorResponse::ConfigNotFound)
.attach_printable(format!(
@@ -97,7 +92,8 @@ impl BillingHandler {
Ok(Self {
auth_type,
- connector_data,
+ connector_enum,
+ connector_name: connector_data,
connector_params,
connector_metadata: billing_processor_mca.metadata.clone(),
merchant_connector_id,
@@ -110,7 +106,7 @@ impl BillingHandler {
customer_id: common_utils::id_type::CustomerId,
billing_address: Option<api_models::payments::Address>,
payment_method_data: Option<api_models::payments::PaymentMethodData>,
- ) -> errors::RouterResult<Option<ConnectorCustomerResponseData>> {
+ ) -> SubscriptionResult<Option<ConnectorCustomerResponseData>> {
let connector_customer_map = customer.get_connector_customer_map();
if connector_customer_map.contains_key(&self.merchant_connector_id) {
// Customer already exists on the connector, no need to create again
@@ -139,7 +135,7 @@ impl BillingHandler {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
- let connector_integration = self.connector_data.connector.get_connector_integration();
+ let connector_integration = self.connector_enum.get_connector_integration();
let response = Box::pin(self.call_connector(
state,
@@ -162,7 +158,7 @@ impl BillingHandler {
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
- connector: self.connector_data.connector_name.to_string(),
+ connector: self.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
@@ -175,7 +171,7 @@ impl BillingHandler {
subscription: hyperswitch_domain_models::subscription::Subscription,
item_price_id: Option<String>,
billing_address: Option<api_models::payments::Address>,
- ) -> errors::RouterResult<subscription_response_types::SubscriptionCreateResponse> {
+ ) -> SubscriptionResult<subscription_response_types::SubscriptionCreateResponse> {
let subscription_item = subscription_request_types::SubscriptionItem {
item_price_id: item_price_id.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "item_price_id",
@@ -202,7 +198,7 @@ impl BillingHandler {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
- let connector_integration = self.connector_data.connector.get_connector_integration();
+ let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
@@ -218,7 +214,7 @@ impl BillingHandler {
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
- connector: self.connector_data.connector_name.to_string(),
+ connector: self.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
@@ -235,7 +231,7 @@ impl BillingHandler {
amount: common_utils::types::MinorUnit,
currency: common_enums::Currency,
payment_method_type: Option<common_enums::PaymentMethodType>,
- ) -> errors::RouterResult<InvoiceRecordBackResponse> {
+ ) -> SubscriptionResult<InvoiceRecordBackResponse> {
let invoice_record_back_req = InvoiceRecordBackRequest {
amount,
currency,
@@ -260,7 +256,7 @@ impl BillingHandler {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
- let connector_integration = self.connector_data.connector.get_connector_integration();
+ let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
@@ -276,7 +272,7 @@ impl BillingHandler {
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
- connector: self.connector_data.connector_name.to_string(),
+ connector: self.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
@@ -288,7 +284,7 @@ impl BillingHandler {
&self,
state: &SessionState,
estimate_request: subscription_types::EstimateSubscriptionQuery,
- ) -> errors::RouterResult<subscription_response_types::GetSubscriptionEstimateResponse> {
+ ) -> SubscriptionResult<subscription_response_types::GetSubscriptionEstimateResponse> {
let estimate_req = subscription_request_types::GetSubscriptionEstimateRequest {
price_id: estimate_request.item_price_id.clone(),
};
@@ -300,7 +296,7 @@ impl BillingHandler {
connector_meta_data: self.connector_metadata.clone(),
},
)?;
- let connector_integration = self.connector_data.connector.get_connector_integration();
+ let connector_integration = self.connector_enum.get_connector_integration();
let response = Box::pin(self.call_connector(
state,
@@ -315,7 +311,7 @@ impl BillingHandler {
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
- connector: self.connector_data.connector_name.to_string(),
+ connector: self.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
@@ -328,7 +324,7 @@ impl BillingHandler {
state: &SessionState,
limit: Option<u32>,
offset: Option<u32>,
- ) -> errors::RouterResult<subscription_response_types::GetSubscriptionPlansResponse> {
+ ) -> SubscriptionResult<subscription_response_types::GetSubscriptionPlansResponse> {
let get_plans_request =
subscription_request_types::GetSubscriptionPlansRequest::new(limit, offset);
@@ -340,7 +336,7 @@ impl BillingHandler {
},
)?;
- let connector_integration = self.connector_data.connector.get_connector_integration();
+ let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
@@ -356,7 +352,7 @@ impl BillingHandler {
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
- connector: self.connector_data.connector_name.to_string().clone(),
+ connector: self.connector_name.to_string().clone(),
status_code: err.status_code,
reason: err.reason,
}
@@ -368,7 +364,7 @@ impl BillingHandler {
&self,
state: &SessionState,
plan_price_id: String,
- ) -> errors::RouterResult<subscription_response_types::GetSubscriptionPlanPricesResponse> {
+ ) -> SubscriptionResult<subscription_response_types::GetSubscriptionPlanPricesResponse> {
let get_plan_prices_request =
subscription_request_types::GetSubscriptionPlanPricesRequest { plan_price_id };
@@ -380,7 +376,7 @@ impl BillingHandler {
},
)?;
- let connector_integration = self.connector_data.connector.get_connector_integration();
+ let connector_integration = self.connector_enum.get_connector_integration();
let response = self
.call_connector(
@@ -395,7 +391,7 @@ impl BillingHandler {
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
- connector: self.connector_data.connector_name.to_string().clone(),
+ connector: self.connector_name.to_string().clone(),
status_code: err.status_code,
reason: err.reason,
}
@@ -413,19 +409,19 @@ impl BillingHandler {
Resp,
>,
operation_name: &str,
- connector_integration: hyperswitch_interfaces::connector_integration_interface::BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>,
- ) -> errors::RouterResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>>
+ connector_integration: connector_integration_interface::BoxedConnectorIntegrationInterface<
+ F,
+ ResourceCommonData,
+ Req,
+ Resp,
+ >,
+ ) -> SubscriptionResult<Result<Resp, hyperswitch_domain_models::router_data::ErrorResponse>>
where
F: Clone + std::fmt::Debug + 'static,
Req: Clone + std::fmt::Debug + 'static,
Resp: Clone + std::fmt::Debug + 'static,
ResourceCommonData:
- hyperswitch_interfaces::connector_integration_interface::RouterDataConversion<
- F,
- Req,
- Resp,
- > + Clone
- + 'static,
+ connector_integration_interface::RouterDataConversion<F, Req, Resp> + Clone + 'static,
{
let old_router_data = ResourceCommonData::to_old_router_data(router_data).change_context(
errors::ApiErrorResponse::SubscriptionError {
@@ -433,11 +429,11 @@ impl BillingHandler {
},
)?;
- let router_resp = services::execute_connector_processing_step(
+ let router_resp = api_client::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
- payments_core::CallConnectorAction::Trigger,
+ CallConnectorAction::Trigger,
None,
None,
)
@@ -457,7 +453,7 @@ impl BillingHandler {
state: &SessionState,
req: Req,
resource_common_data: ResourceCommonData,
- ) -> errors::RouterResult<
+ ) -> SubscriptionResult<
hyperswitch_domain_models::router_data_v2::RouterDataV2<F, ResourceCommonData, Req, Resp>,
> {
Ok(hyperswitch_domain_models::router_data_v2::RouterDataV2 {
diff --git a/crates/subscriptions/src/core/errors.rs b/crates/subscriptions/src/core/errors.rs
new file mode 100644
index 0000000000..f0fd7a76f1
--- /dev/null
+++ b/crates/subscriptions/src/core/errors.rs
@@ -0,0 +1,7 @@
+pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
+pub use hyperswitch_domain_models::{
+ api,
+ errors::api_error_response::{self, *},
+};
+
+pub type SubscriptionResult<T> = CustomResult<T, ApiErrorResponse>;
diff --git a/crates/router/src/core/subscription/invoice_handler.rs b/crates/subscriptions/src/core/invoice_handler.rs
similarity index 92%
rename from crates/router/src/core/subscription/invoice_handler.rs
rename to crates/subscriptions/src/core/invoice_handler.rs
index 7576e95ce8..4208b05ab2 100644
--- a/crates/router/src/core/subscription/invoice_handler.rs
+++ b/crates/subscriptions/src/core/invoice_handler.rs
@@ -9,8 +9,8 @@ use hyperswitch_domain_models::router_response_types::subscriptions as subscript
use super::errors;
use crate::{
- core::subscription::payments_api_client, routes::SessionState, types::storage as storage_types,
- workflows::invoice_sync as invoice_sync_workflow,
+ core::payments_api_client, state::SubscriptionState as SessionState,
+ types::storage as storage_types, workflows::invoice_sync as invoice_sync_workflow,
};
pub struct InvoiceHandler {
@@ -47,7 +47,7 @@ impl InvoiceHandler {
provider_name: connector_enums::Connector,
metadata: Option<pii::SecretSerdeValue>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
- ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> {
+ ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
let invoice_new = hyperswitch_domain_models::invoice::Invoice::to_invoice(
self.subscription.id.to_owned(),
self.subscription.merchant_id.to_owned(),
@@ -82,7 +82,7 @@ impl InvoiceHandler {
state: &SessionState,
invoice_id: common_utils::id_type::InvoiceId,
update_request: hyperswitch_domain_models::invoice::InvoiceUpdateRequest,
- ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> {
+ ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
let update_invoice: hyperswitch_domain_models::invoice::InvoiceUpdate =
update_request.into();
let key_manager_state = &(state).into();
@@ -120,7 +120,7 @@ impl InvoiceHandler {
request: &subscription_types::CreateSubscriptionRequest,
amount: MinorUnit,
currency: api_enums::Currency,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_details = &request.payment_details;
let payment_request = subscription_types::CreatePaymentsRequestData {
amount,
@@ -147,7 +147,7 @@ impl InvoiceHandler {
&self,
state: &SessionState,
payment_id: common_utils::id_type::PaymentId,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
payments_api_client::PaymentsApiClient::sync_payment(
state,
payment_id.get_string_repr().to_string(),
@@ -163,7 +163,7 @@ impl InvoiceHandler {
request: &subscription_types::CreateAndConfirmSubscriptionRequest,
amount: MinorUnit,
currency: common_enums::Currency,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_details = &request.payment_details;
let payment_request = subscription_types::CreateAndConfirmPaymentsRequestData {
amount,
@@ -197,7 +197,7 @@ impl InvoiceHandler {
state: &SessionState,
payment_id: common_utils::id_type::PaymentId,
request: &subscription_types::ConfirmSubscriptionRequest,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_details = &request.payment_details;
let cit_payment_request = subscription_types::ConfirmPaymentsRequestData {
billing: request.get_billing_address(),
@@ -222,7 +222,7 @@ impl InvoiceHandler {
pub async fn get_latest_invoice(
&self,
state: &SessionState,
- ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> {
+ ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
let key_manager_state = &(state).into();
state
.store
@@ -242,7 +242,7 @@ impl InvoiceHandler {
&self,
state: &SessionState,
invoice_id: common_utils::id_type::InvoiceId,
- ) -> errors::RouterResult<hyperswitch_domain_models::invoice::Invoice> {
+ ) -> errors::SubscriptionResult<hyperswitch_domain_models::invoice::Invoice> {
let key_manager_state = &(state).into();
state
.store
@@ -263,7 +263,7 @@ impl InvoiceHandler {
state: &SessionState,
subscription_id: common_utils::id_type::SubscriptionId,
connector_invoice_id: common_utils::id_type::InvoiceId,
- ) -> errors::RouterResult<Option<hyperswitch_domain_models::invoice::Invoice>> {
+ ) -> errors::SubscriptionResult<Option<hyperswitch_domain_models::invoice::Invoice>> {
let key_manager_state = &(state).into();
state
.store
@@ -286,7 +286,7 @@ impl InvoiceHandler {
invoice: &hyperswitch_domain_models::invoice::Invoice,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
connector_name: connector_enums::Connector,
- ) -> errors::RouterResult<()> {
+ ) -> errors::SubscriptionResult<()> {
let request = storage_types::invoice_sync::InvoiceSyncRequest::new(
self.subscription.id.to_owned(),
invoice.id.to_owned(),
@@ -309,7 +309,7 @@ impl InvoiceHandler {
amount: MinorUnit,
currency: common_enums::Currency,
payment_method_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let mit_payment_request = subscription_types::CreateMitPaymentRequestData {
amount,
currency,
@@ -337,7 +337,7 @@ impl InvoiceHandler {
amount: MinorUnit,
currency: common_enums::Currency,
payment_id: common_utils::id_type::PaymentId,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let payment_update_request = subscription_types::CreatePaymentsRequestData {
amount,
currency,
diff --git a/crates/router/src/core/subscription/payments_api_client.rs b/crates/subscriptions/src/core/payments_api_client.rs
similarity index 89%
rename from crates/router/src/core/subscription/payments_api_client.rs
rename to crates/subscriptions/src/core/payments_api_client.rs
index 2f79238d94..6fcfc86a19 100644
--- a/crates/router/src/core/subscription/payments_api_client.rs
+++ b/crates/subscriptions/src/core/payments_api_client.rs
@@ -1,8 +1,9 @@
use api_models::subscription as subscription_types;
use common_utils::{ext_traits::BytesExt, request as services};
use error_stack::ResultExt;
+use hyperswitch_interfaces::api_client as api;
-use crate::{core::errors, headers, routes::SessionState, services::api};
+use crate::{core::errors, helpers, state::SubscriptionState as SessionState};
pub struct PaymentsApiClient;
@@ -27,7 +28,7 @@ impl PaymentsApiClient {
) -> Vec<(String, masking::Maskable<String>)> {
vec![
(
- headers::X_INTERNAL_API_KEY.to_string(),
+ helpers::X_INTERNAL_API_KEY.to_string(),
masking::Maskable::Masked(
state
.conf
@@ -37,15 +38,15 @@ impl PaymentsApiClient {
),
),
(
- headers::X_TENANT_ID.to_string(),
+ helpers::X_TENANT_ID.to_string(),
masking::Maskable::Normal(state.tenant.tenant_id.get_string_repr().to_string()),
),
(
- headers::X_MERCHANT_ID.to_string(),
+ helpers::X_MERCHANT_ID.to_string(),
masking::Maskable::Normal(merchant_id.to_string()),
),
(
- headers::X_PROFILE_ID.to_string(),
+ helpers::X_PROFILE_ID.to_string(),
masking::Maskable::Normal(profile_id.to_string()),
),
]
@@ -60,7 +61,7 @@ impl PaymentsApiClient {
operation_name: &str,
merchant_id: &str,
profile_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let subscription_error = errors::ApiErrorResponse::SubscriptionError {
operation: operation_name.to_string(),
};
@@ -111,7 +112,7 @@ impl PaymentsApiClient {
request: subscription_types::CreatePaymentsRequestData,
merchant_id: &str,
profile_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments", base_url);
@@ -134,7 +135,7 @@ impl PaymentsApiClient {
request: subscription_types::CreateAndConfirmPaymentsRequestData,
merchant_id: &str,
profile_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments", base_url);
@@ -158,7 +159,7 @@ impl PaymentsApiClient {
payment_id: String,
merchant_id: &str,
profile_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments/{}/confirm", base_url, payment_id);
@@ -181,7 +182,7 @@ impl PaymentsApiClient {
payment_id: String,
merchant_id: &str,
profile_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments/{}", base_url, payment_id);
@@ -202,7 +203,7 @@ impl PaymentsApiClient {
request: subscription_types::CreateMitPaymentRequestData,
merchant_id: &str,
profile_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments", base_url);
@@ -226,7 +227,7 @@ impl PaymentsApiClient {
payment_id: String,
merchant_id: &str,
profile_id: &str,
- ) -> errors::RouterResult<subscription_types::PaymentResponseData> {
+ ) -> errors::SubscriptionResult<subscription_types::PaymentResponseData> {
let base_url = &state.conf.internal_services.payments_base_url;
let url = format!("{}/payments/{}", base_url, payment_id);
diff --git a/crates/router/src/core/subscription/subscription_handler.rs b/crates/subscriptions/src/core/subscription_handler.rs
similarity index 89%
rename from crates/router/src/core/subscription/subscription_handler.rs
rename to crates/subscriptions/src/core/subscription_handler.rs
index 16136a1b69..071fa70397 100644
--- a/crates/router/src/core/subscription/subscription_handler.rs
+++ b/crates/subscriptions/src/core/subscription_handler.rs
@@ -8,6 +8,7 @@ use common_enums::connector_enums;
use common_utils::{consts, ext_traits::OptionExt};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
+ customer, merchant_connector_account,
merchant_context::MerchantContext,
router_response_types::{self, subscriptions as subscription_response_types},
subscription::{Subscription, SubscriptionStatus},
@@ -16,13 +17,10 @@ use masking::Secret;
use super::errors;
use crate::{
- core::{
- errors::StorageErrorExt, payments as payments_core,
- subscription::invoice_handler::InvoiceHandler,
- },
- db::CustomResult,
- routes::SessionState,
- types::{domain, transformers::ForeignTryFrom},
+ core::invoice_handler::InvoiceHandler,
+ errors::CustomResult,
+ helpers::{ForeignTryFrom, StorageErrorExt},
+ state::SubscriptionState as SessionState,
};
pub struct SubscriptionHandler<'a> {
@@ -38,8 +36,8 @@ impl<'a> SubscriptionHandler<'a> {
}
}
- /// Helper function to create a subscription entry in the database.
#[allow(clippy::too_many_arguments)]
+ /// Helper function to create a subscription entry in the database.
pub async fn create_subscription_entry(
&self,
subscription_id: common_utils::id_type::SubscriptionId,
@@ -50,7 +48,7 @@ impl<'a> SubscriptionHandler<'a> {
profile: &hyperswitch_domain_models::business_profile::Profile,
plan_id: Option<String>,
item_price_id: Option<String>,
- ) -> errors::RouterResult<SubscriptionWithHandler<'_>> {
+ ) -> errors::SubscriptionResult<SubscriptionWithHandler<'_>> {
let store = self.state.store.clone();
let db = store.as_ref();
@@ -99,7 +97,7 @@ impl<'a> SubscriptionHandler<'a> {
state: &SessionState,
merchant_context: &MerchantContext,
customer_id: &common_utils::id_type::CustomerId,
- ) -> errors::RouterResult<hyperswitch_domain_models::customer::Customer> {
+ ) -> errors::SubscriptionResult<customer::Customer> {
let key_manager_state = &(state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
let merchant_id = merchant_context.get_merchant_account().get_id();
@@ -121,12 +119,12 @@ impl<'a> SubscriptionHandler<'a> {
state: &SessionState,
merchant_context: &MerchantContext,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
- customer: &hyperswitch_domain_models::customer::Customer,
+ customer: &customer::Customer,
customer_create_response: Option<router_response_types::ConnectorCustomerResponseData>,
- ) -> errors::RouterResult<hyperswitch_domain_models::customer::Customer> {
+ ) -> errors::SubscriptionResult<customer::Customer> {
match customer_create_response {
Some(customer_response) => {
- match payments_core::customers::update_connector_customer_in_customers(
+ match customer::update_connector_customer_in_customers(
merchant_connector_id.get_string_repr(),
Some(customer),
Some(customer_response.connector_customer_id),
@@ -151,9 +149,9 @@ impl<'a> SubscriptionHandler<'a> {
pub async fn update_customer(
state: &SessionState,
merchant_context: &MerchantContext,
- customer: hyperswitch_domain_models::customer::Customer,
- customer_update: domain::CustomerUpdate,
- ) -> errors::RouterResult<hyperswitch_domain_models::customer::Customer> {
+ customer: customer::Customer,
+ customer_update: customer::CustomerUpdate,
+ ) -> errors::SubscriptionResult<customer::Customer> {
let key_manager_state = &(state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
let merchant_id = merchant_context.get_merchant_account().get_id();
@@ -181,7 +179,7 @@ impl<'a> SubscriptionHandler<'a> {
state: &SessionState,
merchant_context: &MerchantContext,
profile_id: &common_utils::id_type::ProfileId,
- ) -> errors::RouterResult<hyperswitch_domain_models::business_profile::Profile> {
+ ) -> errors::SubscriptionResult<hyperswitch_domain_models::business_profile::Profile> {
let key_manager_state = &(state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
@@ -197,7 +195,7 @@ impl<'a> SubscriptionHandler<'a> {
pub async fn find_and_validate_subscription(
&self,
client_secret: &hyperswitch_domain_models::subscription::ClientSecret,
- ) -> errors::RouterResult<()> {
+ ) -> errors::SubscriptionResult<()> {
let subscription_id = client_secret.get_subscription_id()?;
let key_manager_state = &(self.state).into();
@@ -227,7 +225,7 @@ impl<'a> SubscriptionHandler<'a> {
&self,
client_secret: &hyperswitch_domain_models::subscription::ClientSecret,
subscription: &Subscription,
- ) -> errors::RouterResult<()> {
+ ) -> errors::SubscriptionResult<()> {
let stored_client_secret = subscription
.client_secret
.clone()
@@ -256,7 +254,7 @@ impl<'a> SubscriptionHandler<'a> {
pub async fn find_subscription(
&self,
subscription_id: common_utils::id_type::SubscriptionId,
- ) -> errors::RouterResult<SubscriptionWithHandler<'_>> {
+ ) -> errors::SubscriptionResult<SubscriptionWithHandler<'_>> {
let subscription = self
.state
.store
@@ -293,7 +291,7 @@ impl SubscriptionWithHandler<'_> {
invoice: &hyperswitch_domain_models::invoice::Invoice,
payment_response: &subscription_types::PaymentResponseData,
status: subscription_response_types::SubscriptionStatus,
- ) -> errors::RouterResult<subscription_types::ConfirmSubscriptionResponse> {
+ ) -> errors::SubscriptionResult<subscription_types::ConfirmSubscriptionResponse> {
Ok(subscription_types::ConfirmSubscriptionResponse {
id: self.subscription.id.clone(),
merchant_reference_id: self.subscription.merchant_reference_id.clone(),
@@ -313,7 +311,7 @@ impl SubscriptionWithHandler<'_> {
&self,
payment: Option<subscription_types::PaymentResponseData>,
invoice: Option<&hyperswitch_domain_models::invoice::Invoice>,
- ) -> errors::RouterResult<SubscriptionResponse> {
+ ) -> errors::SubscriptionResult<SubscriptionResponse> {
Ok(SubscriptionResponse::new(
self.subscription.id.clone(),
self.subscription.merchant_reference_id.clone(),
@@ -328,7 +326,7 @@ impl SubscriptionWithHandler<'_> {
payment,
invoice
.map(
- |invoice| -> errors::RouterResult<subscription_types::Invoice> {
+ |invoice| -> errors::SubscriptionResult<subscription_types::Invoice> {
subscription_types::Invoice::foreign_try_from(invoice)
},
)
@@ -339,7 +337,7 @@ impl SubscriptionWithHandler<'_> {
pub async fn update_subscription(
&mut self,
subscription_update: hyperswitch_domain_models::subscription::SubscriptionUpdate,
- ) -> errors::RouterResult<()> {
+ ) -> errors::SubscriptionResult<()> {
let db = self.handler.state.store.as_ref();
let updated_subscription = db
.update_subscription_entry(
@@ -381,7 +379,8 @@ impl SubscriptionWithHandler<'_> {
pub async fn get_mca(
&mut self,
connector_name: &str,
- ) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {
+ ) -> CustomResult<merchant_connector_account::MerchantConnectorAccount, errors::ApiErrorResponse>
+ {
let db = self.handler.state.store.as_ref();
let key_manager_state = &(self.handler.state).into();
@@ -405,15 +404,6 @@ impl SubscriptionWithHandler<'_> {
},
)
}
- #[cfg(feature = "v2")]
- {
- //get mca using id
- let _ = key_manager_state;
- let _ = connector_name;
- let _ = merchant_context.get_merchant_key_store();
- let _ = subscription.profile_id;
- todo!()
- }
}
None => {
// Fallback to profile-based lookup when merchant_connector_id is not set
@@ -435,15 +425,6 @@ impl SubscriptionWithHandler<'_> {
},
)
}
- #[cfg(feature = "v2")]
- {
- //get mca using id
- let _ = key_manager_state;
- let _ = connector_name;
- let _ = self.handler.merchant_context.get_merchant_key_store();
- let _ = self.subscription.profile_id;
- todo!()
- }
}
}
}
diff --git a/crates/subscriptions/src/helpers.rs b/crates/subscriptions/src/helpers.rs
new file mode 100644
index 0000000000..1a7643c3c8
--- /dev/null
+++ b/crates/subscriptions/src/helpers.rs
@@ -0,0 +1,61 @@
+pub use hyperswitch_domain_models::errors::api_error_response;
+
+pub const X_PROFILE_ID: &str = "X-Profile-Id";
+pub const X_TENANT_ID: &str = "x-tenant-id";
+pub const X_MERCHANT_ID: &str = "X-Merchant-Id";
+pub const X_INTERNAL_API_KEY: &str = "X-Internal-Api-Key";
+
+pub trait ForeignFrom<F> {
+ fn foreign_from(from: F) -> Self;
+}
+
+/// Trait for converting from one foreign type to another
+pub trait ForeignTryFrom<F>: Sized {
+ /// Custom error for conversion failure
+ type Error;
+ /// Convert from a foreign type to the current type and return an error if the conversion fails
+ fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
+}
+
+pub trait StorageErrorExt<T, E> {
+ #[track_caller]
+ fn to_not_found_response(self, not_found_response: E) -> error_stack::Result<T, E>;
+
+ #[track_caller]
+ fn to_duplicate_response(self, duplicate_response: E) -> error_stack::Result<T, E>;
+}
+
+impl<T> StorageErrorExt<T, api_error_response::ApiErrorResponse>
+ for error_stack::Result<T, storage_impl::StorageError>
+{
+ #[track_caller]
+ fn to_not_found_response(
+ self,
+ not_found_response: api_error_response::ApiErrorResponse,
+ ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {
+ self.map_err(|err| {
+ let new_err = match err.current_context() {
+ storage_impl::StorageError::ValueNotFound(_) => not_found_response,
+ storage_impl::StorageError::CustomerRedacted => {
+ api_error_response::ApiErrorResponse::CustomerRedacted
+ }
+ _ => api_error_response::ApiErrorResponse::InternalServerError,
+ };
+ err.change_context(new_err)
+ })
+ }
+
+ #[track_caller]
+ fn to_duplicate_response(
+ self,
+ duplicate_response: api_error_response::ApiErrorResponse,
+ ) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {
+ self.map_err(|err| {
+ let new_err = match err.current_context() {
+ storage_impl::StorageError::DuplicateValue { .. } => duplicate_response,
+ _ => api_error_response::ApiErrorResponse::InternalServerError,
+ };
+ err.change_context(new_err)
+ })
+ }
+}
diff --git a/crates/subscriptions/src/lib.rs b/crates/subscriptions/src/lib.rs
new file mode 100644
index 0000000000..c5617619ff
--- /dev/null
+++ b/crates/subscriptions/src/lib.rs
@@ -0,0 +1,21 @@
+//! Subscription management crate for Hyperswitch
+//!
+//! This crate provides functionality for managing subscriptions, including:
+//! - Subscription creation and management
+//! - Invoice handling
+//! - Billing processor integration
+//! - Payment processing for subscriptions
+
+#[cfg(feature = "v1")]
+pub mod core;
+pub mod helpers;
+pub mod state;
+pub mod types;
+#[cfg(feature = "v1")]
+pub mod workflows;
+
+pub mod webhooks;
+
+pub use core::*;
+
+pub use types::*;
diff --git a/crates/subscriptions/src/state.rs b/crates/subscriptions/src/state.rs
new file mode 100644
index 0000000000..363dc78c71
--- /dev/null
+++ b/crates/subscriptions/src/state.rs
@@ -0,0 +1,100 @@
+use common_utils::types::keymanager;
+use hyperswitch_domain_models::{
+ business_profile, configs as domain_configs, customer, invoice as invoice_domain, master_key,
+ merchant_account, merchant_connector_account, merchant_key_store,
+ subscription as subscription_domain,
+};
+use hyperswitch_interfaces::configs;
+use router_env::tracing_actix_web::RequestId;
+use storage_impl::{errors, kv_router_store::KVRouterStore, DatabaseStore, MockDb, RouterStore};
+
+#[async_trait::async_trait]
+pub trait SubscriptionStorageInterface:
+ Send
+ + Sync
+ + dyn_clone::DynClone
+ + master_key::MasterKeyInterface
+ + scheduler::SchedulerInterface
+ + subscription_domain::SubscriptionInterface<Error = errors::StorageError>
+ + invoice_domain::InvoiceInterface<Error = errors::StorageError>
+ + business_profile::ProfileInterface<Error = errors::StorageError>
+ + domain_configs::ConfigInterface<Error = errors::StorageError>
+ + customer::CustomerInterface<Error = errors::StorageError>
+ + merchant_account::MerchantAccountInterface<Error = errors::StorageError>
+ + merchant_key_store::MerchantKeyStoreInterface<Error = errors::StorageError>
+ + merchant_connector_account::MerchantConnectorAccountInterface<Error = errors::StorageError>
+ + 'static
+{
+}
+dyn_clone::clone_trait_object!(SubscriptionStorageInterface);
+
+#[async_trait::async_trait]
+impl SubscriptionStorageInterface for MockDb {}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for RouterStore<T> where
+ Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface
+{
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore + 'static> SubscriptionStorageInterface for KVRouterStore<T> where
+ Self: scheduler::SchedulerInterface + master_key::MasterKeyInterface
+{
+}
+
+pub struct SubscriptionState {
+ pub store: Box<dyn SubscriptionStorageInterface>,
+ pub key_store: Option<merchant_key_store::MerchantKeyStore>,
+ pub key_manager_state: keymanager::KeyManagerState,
+ pub api_client: Box<dyn hyperswitch_interfaces::api_client::ApiClient>,
+ pub conf: SubscriptionConfig,
+ pub tenant: configs::Tenant,
+ pub event_handler: Box<dyn hyperswitch_interfaces::events::EventHandlerInterface>,
+ pub connector_converter: Box<dyn hyperswitch_interfaces::api_client::ConnectorConverter>,
+}
+
+#[derive(Clone)]
+pub struct SubscriptionConfig {
+ pub proxy: hyperswitch_interfaces::types::Proxy,
+ pub internal_merchant_id_profile_id_auth: configs::InternalMerchantIdProfileIdAuthSettings,
+ pub internal_services: configs::InternalServicesConfig,
+ pub connectors: configs::Connectors,
+}
+
+impl From<&SubscriptionState> for keymanager::KeyManagerState {
+ fn from(state: &SubscriptionState) -> Self {
+ state.key_manager_state.clone()
+ }
+}
+
+impl hyperswitch_interfaces::api_client::ApiClientWrapper for SubscriptionState {
+ fn get_proxy(&self) -> hyperswitch_interfaces::types::Proxy {
+ self.conf.proxy.clone()
+ }
+
+ fn get_api_client(&self) -> &dyn hyperswitch_interfaces::api_client::ApiClient {
+ self.api_client.as_ref()
+ }
+
+ fn get_request_id(&self) -> Option<RequestId> {
+ self.api_client.get_request_id()
+ }
+ fn get_request_id_str(&self) -> Option<String> {
+ self.api_client
+ .get_request_id()
+ .map(|req_id| req_id.as_hyphenated().to_string())
+ }
+
+ fn get_tenant(&self) -> configs::Tenant {
+ self.tenant.clone()
+ }
+
+ fn get_connectors(&self) -> configs::Connectors {
+ self.conf.connectors.clone()
+ }
+
+ fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface {
+ self.event_handler.as_ref()
+ }
+}
diff --git a/crates/subscriptions/src/types.rs b/crates/subscriptions/src/types.rs
new file mode 100644
index 0000000000..b19b0a925c
--- /dev/null
+++ b/crates/subscriptions/src/types.rs
@@ -0,0 +1,8 @@
+//! Types module for subscription functionality
+//!
+//! This module contains type definitions and storage types for subscriptions
+
+pub mod storage;
+
+// Re-export subscription types from api_models for convenience
+pub use api_models::subscription as subscription_types;
diff --git a/crates/subscriptions/src/types/storage.rs b/crates/subscriptions/src/types/storage.rs
new file mode 100644
index 0000000000..792ca899f1
--- /dev/null
+++ b/crates/subscriptions/src/types/storage.rs
@@ -0,0 +1 @@
+pub mod invoice_sync;
diff --git a/crates/router/src/types/storage/invoice_sync.rs b/crates/subscriptions/src/types/storage/invoice_sync.rs
similarity index 100%
rename from crates/router/src/types/storage/invoice_sync.rs
rename to crates/subscriptions/src/types/storage/invoice_sync.rs
diff --git a/crates/subscriptions/src/webhooks.rs b/crates/subscriptions/src/webhooks.rs
new file mode 100644
index 0000000000..8dc28720b9
--- /dev/null
+++ b/crates/subscriptions/src/webhooks.rs
@@ -0,0 +1,161 @@
+use std::str::FromStr;
+
+use api_models::webhooks::WebhookResponseTracker;
+use common_enums::{connector_enums::Connector, InvoiceStatus};
+use common_utils::{consts, errors::CustomResult, generate_id};
+use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ business_profile, errors::api_error_response as errors, invoice, merchant_context,
+};
+use hyperswitch_interfaces::{
+ api::ConnectorCommon, connector_integration_interface, errors::ConnectorError,
+ webhooks::IncomingWebhook,
+};
+use router_env::{instrument, logger, tracing};
+
+use crate::state::SubscriptionState as SessionState;
+#[cfg(feature = "v1")]
+use crate::subscription_handler::SubscriptionHandler;
+
+#[cfg(feature = "v1")]
+#[allow(clippy::too_many_arguments)]
+#[instrument(skip_all)]
+pub async fn incoming_webhook_flow(
+ state: SessionState,
+ merchant_context: merchant_context::MerchantContext,
+ business_profile: business_profile::Profile,
+ _webhook_details: api_models::webhooks::IncomingWebhookDetails,
+ source_verified: bool,
+ connector_enum: &connector_integration_interface::ConnectorEnum,
+ request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
+ event_type: api_models::webhooks::IncomingWebhookEvent,
+ billing_connector_mca_id: common_utils::id_type::MerchantConnectorAccountId,
+) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
+ // Only process invoice_generated events for MIT payments
+ if event_type != api_models::webhooks::IncomingWebhookEvent::InvoiceGenerated {
+ return Ok(WebhookResponseTracker::NoEffect);
+ }
+
+ if !source_verified {
+ logger::error!("Webhook source verification failed for subscription webhook flow");
+ return Err(report!(
+ errors::ApiErrorResponse::WebhookAuthenticationFailed
+ ));
+ }
+
+ let connector_name = connector_enum.id().to_string();
+
+ let connector = Connector::from_str(&connector_name)
+ .change_context(ConnectorError::InvalidConnectorName)
+ .change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
+ .attach_printable_lazy(|| format!("unable to parse connector name {connector_name}"))?;
+
+ let mit_payment_data = connector_enum
+ .get_subscription_mit_payment_data(request_details)
+ .change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
+ .attach_printable("Failed to extract MIT payment data from subscription webhook")?;
+
+ let profile_id = business_profile.get_id().clone();
+
+ let profile =
+ SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
+ .await
+ .attach_printable(
+ "subscriptions: failed to find business profile in get_subscription",
+ )?;
+
+ let handler = SubscriptionHandler::new(&state, &merchant_context);
+
+ let subscription_id = mit_payment_data.subscription_id.clone();
+
+ let subscription_with_handler = handler
+ .find_subscription(subscription_id.clone())
+ .await
+ .attach_printable("subscriptions: failed to get subscription entry in get_subscription")?;
+
+ let invoice_handler = subscription_with_handler.get_invoice_handler(profile.clone());
+ let invoice = invoice_handler
+ .find_invoice_by_subscription_id_connector_invoice_id(
+ &state,
+ subscription_id,
+ mit_payment_data.invoice_id.clone(),
+ )
+ .await
+ .attach_printable(
+ "subscriptions: failed to get invoice by subscription id and connector invoice id",
+ )?;
+ if let Some(invoice) = invoice {
+ // During CIT payment we would have already created invoice entry with status as PaymentPending or Paid.
+ // So we skip incoming webhook for the already processed invoice
+ if invoice.status != InvoiceStatus::InvoiceCreated {
+ logger::info!("Invoice is already being processed, skipping MIT payment creation");
+ return Ok(WebhookResponseTracker::NoEffect);
+ }
+ }
+
+ let payment_method_id = subscription_with_handler
+ .subscription
+ .payment_method_id
+ .clone()
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "No payment method found for subscription".to_string(),
+ })
+ .attach_printable("No payment method found for subscription")?;
+
+ logger::info!("Payment method ID found: {}", payment_method_id);
+
+ let payment_id = generate_id(consts::ID_LENGTH, "pay");
+ let payment_id = common_utils::id_type::PaymentId::wrap(payment_id).change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_id",
+ },
+ )?;
+
+ // Multiple MIT payments for the same invoice_generated event is avoided by having the unique constraint on (subscription_id, connector_invoice_id) in the invoices table
+ let invoice_entry = invoice_handler
+ .create_invoice_entry(
+ &state,
+ billing_connector_mca_id.clone(),
+ Some(payment_id),
+ mit_payment_data.amount_due,
+ mit_payment_data.currency_code,
+ InvoiceStatus::PaymentPending,
+ connector,
+ None,
+ Some(mit_payment_data.invoice_id.clone()),
+ )
+ .await?;
+
+ // Create a sync job for the invoice with generated payment_id before initiating MIT payment creation.
+ // This ensures that if payment creation call fails, the sync job can still retrieve the payment status
+ invoice_handler
+ .create_invoice_sync_job(
+ &state,
+ &invoice_entry,
+ Some(mit_payment_data.invoice_id.clone()),
+ connector,
+ )
+ .await?;
+
+ let payment_response = invoice_handler
+ .create_mit_payment(
+ &state,
+ mit_payment_data.amount_due,
+ mit_payment_data.currency_code,
+ &payment_method_id.clone(),
+ )
+ .await?;
+
+ let update_request = invoice::InvoiceUpdateRequest::update_payment_and_status(
+ payment_response.payment_method_id,
+ Some(payment_response.payment_id.clone()),
+ InvoiceStatus::from(payment_response.status),
+ Some(mit_payment_data.invoice_id.clone()),
+ );
+
+ let _updated_invoice = invoice_handler
+ .update_invoice(&state, invoice_entry.id.clone(), update_request)
+ .await?;
+
+ Ok(WebhookResponseTracker::NoEffect)
+}
diff --git a/crates/subscriptions/src/workflows.rs b/crates/subscriptions/src/workflows.rs
new file mode 100644
index 0000000000..d97e89c4cb
--- /dev/null
+++ b/crates/subscriptions/src/workflows.rs
@@ -0,0 +1,8 @@
+//! Workflows module for subscription functionality
+//!
+//! This module contains workflow definitions for subscription-related operations
+
+pub mod invoice_sync;
+
+// Re-export workflow types for easier access
+pub use invoice_sync::*;
diff --git a/crates/subscriptions/src/workflows/invoice_sync.rs b/crates/subscriptions/src/workflows/invoice_sync.rs
new file mode 100644
index 0000000000..082b3b532e
--- /dev/null
+++ b/crates/subscriptions/src/workflows/invoice_sync.rs
@@ -0,0 +1,405 @@
+#[cfg(feature = "v1")]
+use api_models::subscription as subscription_types;
+use common_utils::{errors::CustomResult, ext_traits::StringExt};
+use error_stack::ResultExt;
+use hyperswitch_domain_models::invoice::InvoiceUpdateRequest;
+use router_env::logger;
+use scheduler::{
+ errors,
+ types::process_data,
+ utils as scheduler_utils,
+ workflows::storage::{business_status, ProcessTracker, ProcessTrackerNew},
+};
+use storage_impl::StorageError;
+
+use crate::{
+ core::{
+ billing_processor_handler as billing, errors as router_errors, invoice_handler,
+ payments_api_client,
+ },
+ state::{SubscriptionState as SessionState, SubscriptionStorageInterface as StorageInterface},
+ types::storage,
+};
+
+const INVOICE_SYNC_WORKFLOW: &str = "INVOICE_SYNC";
+const INVOICE_SYNC_WORKFLOW_TAG: &str = "INVOICE";
+
+pub struct InvoiceSyncHandler<'a> {
+ pub state: &'a SessionState,
+ pub tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
+ pub key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
+ pub merchant_account: hyperswitch_domain_models::merchant_account::MerchantAccount,
+ pub customer: hyperswitch_domain_models::customer::Customer,
+ pub profile: hyperswitch_domain_models::business_profile::Profile,
+ pub subscription: hyperswitch_domain_models::subscription::Subscription,
+ pub invoice: hyperswitch_domain_models::invoice::Invoice,
+}
+
+#[cfg(feature = "v1")]
+impl<'a> InvoiceSyncHandler<'a> {
+ pub async fn create(
+ state: &'a SessionState,
+ tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
+ ) -> Result<Self, errors::ProcessTrackerError> {
+ let key_manager_state = &state.into();
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ key_manager_state,
+ &tracking_data.merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .attach_printable("Failed to fetch Merchant key store from DB")?;
+
+ let merchant_account = state
+ .store
+ .find_merchant_account_by_merchant_id(
+ key_manager_state,
+ &tracking_data.merchant_id,
+ &key_store,
+ )
+ .await
+ .attach_printable("Subscriptions: Failed to fetch Merchant Account from DB")?;
+
+ let profile = state
+ .store
+ .find_business_profile_by_profile_id(
+ &(state).into(),
+ &key_store,
+ &tracking_data.profile_id,
+ )
+ .await
+ .attach_printable("Subscriptions: Failed to fetch Business Profile from DB")?;
+
+ let customer = state
+ .store
+ .find_customer_by_customer_id_merchant_id(
+ &(state).into(),
+ &tracking_data.customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .attach_printable("Subscriptions: Failed to fetch Customer from DB")?;
+
+ let subscription = state
+ .store
+ .find_by_merchant_id_subscription_id(
+ &state.into(),
+ &key_store,
+ merchant_account.get_id(),
+ tracking_data.subscription_id.get_string_repr().to_string(),
+ )
+ .await
+ .attach_printable("Subscriptions: Failed to fetch subscription from DB")?;
+
+ let invoice = state
+ .store
+ .find_invoice_by_invoice_id(
+ &state.into(),
+ &key_store,
+ tracking_data.invoice_id.get_string_repr().to_string(),
+ )
+ .await
+ .attach_printable("invoices: unable to get latest invoice from database")?;
+
+ Ok(Self {
+ state,
+ tracking_data,
+ key_store,
+ merchant_account,
+ customer,
+ profile,
+ subscription,
+ invoice,
+ })
+ }
+
+ async fn finish_process_with_business_status(
+ &self,
+ process: &ProcessTracker,
+ business_status: &'static str,
+ ) -> CustomResult<(), router_errors::ApiErrorResponse> {
+ self.state
+ .store
+ .as_scheduler()
+ .finish_process_with_business_status(process.clone(), business_status)
+ .await
+ .change_context(router_errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update process tracker status")
+ }
+
+ pub async fn perform_payments_sync(
+ &self,
+ ) -> CustomResult<subscription_types::PaymentResponseData, router_errors::ApiErrorResponse>
+ {
+ logger::info!(
+ "perform_payments_sync called for invoice_id: {:?} and payment_id: {:?}",
+ self.invoice.id,
+ self.invoice.payment_intent_id
+ );
+ let payment_id = self.invoice.payment_intent_id.clone().ok_or(
+ router_errors::ApiErrorResponse::SubscriptionError {
+ operation: "Invoice_sync: Missing Payment Intent ID in Invoice".to_string(),
+ },
+ )?;
+ let payments_response = payments_api_client::PaymentsApiClient::sync_payment(
+ self.state,
+ payment_id.get_string_repr().to_string(),
+ self.merchant_account.get_id().get_string_repr(),
+ self.profile.get_id().get_string_repr(),
+ )
+ .await
+ .change_context(router_errors::ApiErrorResponse::SubscriptionError {
+ operation: "Invoice_sync: Failed to sync payment status from payments microservice"
+ .to_string(),
+ })
+ .attach_printable("Failed to sync payment status from payments microservice")?;
+
+ Ok(payments_response)
+ }
+
+ pub async fn perform_billing_processor_record_back_if_possible(
+ &self,
+ payment_response: subscription_types::PaymentResponseData,
+ payment_status: common_enums::AttemptStatus,
+ connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
+ invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus,
+ ) -> CustomResult<(), router_errors::ApiErrorResponse> {
+ if let Some(connector_invoice_id) = connector_invoice_id {
+ Box::pin(self.perform_billing_processor_record_back(
+ payment_response,
+ payment_status,
+ connector_invoice_id,
+ invoice_sync_status,
+ ))
+ .await
+ .attach_printable("Failed to record back to billing processor")?;
+ }
+ Ok(())
+ }
+
+ pub async fn perform_billing_processor_record_back(
+ &self,
+ payment_response: subscription_types::PaymentResponseData,
+ payment_status: common_enums::AttemptStatus,
+ connector_invoice_id: common_utils::id_type::InvoiceId,
+ invoice_sync_status: storage::invoice_sync::InvoiceSyncPaymentStatus,
+ ) -> CustomResult<(), router_errors::ApiErrorResponse> {
+ logger::info!("perform_billing_processor_record_back");
+
+ let billing_handler = billing::BillingHandler::create(
+ self.state,
+ &self.merchant_account,
+ &self.key_store,
+ self.profile.clone(),
+ )
+ .await
+ .attach_printable("Failed to create billing handler")?;
+
+ let invoice_handler = invoice_handler::InvoiceHandler::new(
+ self.subscription.clone(),
+ self.merchant_account.clone(),
+ self.profile.clone(),
+ self.key_store.clone(),
+ );
+
+ // TODO: Handle retries here on failure
+ billing_handler
+ .record_back_to_billing_processor(
+ self.state,
+ connector_invoice_id.clone(),
+ payment_response.payment_id.to_owned(),
+ payment_status,
+ payment_response.amount,
+ payment_response.currency,
+ payment_response.payment_method_type,
+ )
+ .await
+ .attach_printable("Failed to record back to billing processor")?;
+
+ let update_request = InvoiceUpdateRequest::update_connector_and_status(
+ connector_invoice_id,
+ common_enums::connector_enums::InvoiceStatus::from(invoice_sync_status),
+ );
+
+ invoice_handler
+ .update_invoice(self.state, self.invoice.id.to_owned(), update_request)
+ .await
+ .attach_printable("Failed to update invoice in DB")?;
+
+ Ok(())
+ }
+
+ pub async fn transition_workflow_state(
+ &self,
+ process: ProcessTracker,
+ payment_response: subscription_types::PaymentResponseData,
+ connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
+ ) -> CustomResult<(), router_errors::ApiErrorResponse> {
+ logger::info!(
+ "transition_workflow_state called with status: {:?}",
+ payment_response.status
+ );
+ let invoice_sync_status =
+ storage::invoice_sync::InvoiceSyncPaymentStatus::from(payment_response.status);
+ let (payment_status, status) = match invoice_sync_status {
+ storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentSucceeded => (common_enums::AttemptStatus::Charged, "succeeded"),
+ storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentFailed => (common_enums::AttemptStatus::Failure, "failed"),
+ storage::invoice_sync::InvoiceSyncPaymentStatus::PaymentProcessing => return Err(
+ router_errors::ApiErrorResponse::SubscriptionError {
+ operation: "Invoice_sync: Payment in processing state, cannot transition workflow state"
+ .to_string(),
+ },
+ )?,
+ };
+ logger::info!("Performing billing processor record back for status: {status}");
+ Box::pin(self.perform_billing_processor_record_back_if_possible(
+ payment_response.clone(),
+ payment_status,
+ connector_invoice_id,
+ invoice_sync_status.clone(),
+ ))
+ .await
+ .attach_printable(format!(
+ "Failed to record back {status} status to billing processor"
+ ))?;
+
+ self.finish_process_with_business_status(&process, business_status::COMPLETED_BY_PT)
+ .await
+ .change_context(router_errors::ApiErrorResponse::SubscriptionError {
+ operation: "Invoice_sync process_tracker task completion".to_string(),
+ })
+ .attach_printable("Failed to update process tracker status")
+ }
+}
+
+#[cfg(feature = "v1")]
+pub async fn perform_subscription_invoice_sync(
+ state: &SessionState,
+ process: ProcessTracker,
+ tracking_data: storage::invoice_sync::InvoiceSyncTrackingData,
+) -> Result<(), errors::ProcessTrackerError> {
+ let handler = InvoiceSyncHandler::create(state, tracking_data).await?;
+
+ let payment_status = handler.perform_payments_sync().await?;
+
+ if let Err(e) = Box::pin(handler.transition_workflow_state(
+ process.clone(),
+ payment_status,
+ handler.tracking_data.connector_invoice_id.clone(),
+ ))
+ .await
+ {
+ logger::error!(?e, "Error in transitioning workflow state");
+ retry_subscription_invoice_sync_task(
+ &*handler.state.store,
+ handler.tracking_data.connector_name.to_string().clone(),
+ handler.merchant_account.get_id().to_owned(),
+ process,
+ )
+ .await
+ .change_context(router_errors::ApiErrorResponse::SubscriptionError {
+ operation: "Invoice_sync process_tracker task retry".to_string(),
+ })
+ .attach_printable("Failed to update process tracker status")?;
+ };
+
+ Ok(())
+}
+
+pub async fn create_invoice_sync_job(
+ state: &SessionState,
+ request: storage::invoice_sync::InvoiceSyncRequest,
+) -> CustomResult<(), router_errors::ApiErrorResponse> {
+ let tracking_data = storage::invoice_sync::InvoiceSyncTrackingData::from(request);
+
+ let process_tracker_entry = ProcessTrackerNew::new(
+ common_utils::generate_id(common_utils::consts::ID_LENGTH, "proc"),
+ INVOICE_SYNC_WORKFLOW.to_string(),
+ common_enums::ProcessTrackerRunner::InvoiceSyncflow,
+ vec![INVOICE_SYNC_WORKFLOW_TAG.to_string()],
+ tracking_data,
+ Some(0),
+ common_utils::date_time::now(),
+ common_types::consts::API_VERSION,
+ )
+ .change_context(router_errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("subscriptions: unable to form process_tracker type")?;
+
+ state
+ .store
+ .insert_process(process_tracker_entry)
+ .await
+ .change_context(router_errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("subscriptions: unable to insert process_tracker entry in DB")?;
+
+ Ok(())
+}
+
+pub async fn get_subscription_invoice_sync_process_schedule_time(
+ db: &dyn StorageInterface,
+ connector: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
+ retry_count: i32,
+) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
+ let mapping: CustomResult<process_data::SubscriptionInvoiceSyncPTMapping, StorageError> = db
+ .find_config_by_key(&format!("invoice_sync_pt_mapping_{connector}"))
+ .await
+ .map(|value| value.config)
+ .and_then(|config| {
+ config
+ .parse_struct("SubscriptionInvoiceSyncPTMapping")
+ .change_context(StorageError::DeserializationFailed)
+ .attach_printable("Failed to deserialize invoice_sync_pt_mapping config to struct")
+ });
+ let mapping = match mapping {
+ Ok(x) => x,
+ Err(error) => {
+ logger::info!(?error, "Redis Mapping Error");
+ process_data::SubscriptionInvoiceSyncPTMapping::default()
+ }
+ };
+
+ let time_delta = scheduler_utils::get_subscription_invoice_sync_retry_schedule_time(
+ mapping,
+ merchant_id,
+ retry_count,
+ );
+
+ Ok(scheduler_utils::get_time_from_delta(time_delta))
+}
+
+pub async fn retry_subscription_invoice_sync_task(
+ db: &dyn StorageInterface,
+ connector: String,
+ merchant_id: common_utils::id_type::MerchantId,
+ pt: ProcessTracker,
+) -> Result<(), errors::ProcessTrackerError> {
+ let schedule_time = get_subscription_invoice_sync_process_schedule_time(
+ db,
+ connector.as_str(),
+ &merchant_id,
+ pt.retry_count + 1,
+ )
+ .await?;
+
+ match schedule_time {
+ Some(s_time) => {
+ db.as_scheduler()
+ .retry_process(pt, s_time)
+ .await
+ .attach_printable("Failed to retry subscription invoice sync task")?;
+ }
+ None => {
+ db.as_scheduler()
+ .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
+ .await
+ .attach_printable("Failed to finish subscription invoice sync task")?;
+ }
+ }
+
+ Ok(())
+}