Skip to content

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

feat: Subscription list API (#10275)

Sarthak Soniea976ae22604
diff --git a/crates/api_models/src/subscription.rs b/crates/api_models/src/subscription.rs
index d076b78e40..421c72ee70 100644
--- a/crates/api_models/src/subscription.rs
+++ b/crates/api_models/src/subscription.rs
@@ -557,6 +557,17 @@ pub struct EstimateSubscriptionQuery {
impl ApiEventMetric for EstimateSubscriptionQuery {}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ListSubscriptionQuery {
+ /// Number of records to return.
+ pub limit: Option<i64>,
+
+ /// Offset for pagination.
+ pub offset: Option<i64>,
+}
+
+impl ApiEventMetric for ListSubscriptionQuery {}
+
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct EstimateSubscriptionResponse {
/// Estimated amount to be charged for the invoice.
diff --git a/crates/diesel_models/src/query/subscription.rs b/crates/diesel_models/src/query/subscription.rs
index 7a6bdd19c1..1a7593c40e 100644
--- a/crates/diesel_models/src/query/subscription.rs
+++ b/crates/diesel_models/src/query/subscription.rs
@@ -56,4 +56,23 @@ impl Subscription {
.attach_printable("Error while updating subscription entry")
})
}
+
+ pub async fn list_by_merchant_id_profile_id(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::profile_id.eq(profile_id.to_owned())),
+ limit,
+ offset,
+ Some(dsl::created_at.desc()),
+ )
+ .await
+ }
}
diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs
index 10d7c07cf7..0aff6997b2 100644
--- a/crates/diesel_models/src/query/utils.rs
+++ b/crates/diesel_models/src/query/utils.rs
@@ -102,6 +102,7 @@ impl_get_primary_key!(
schema::merchant_account::table,
schema::process_tracker::table,
schema::invoice::table,
+ schema::subscription::table,
// v2 tables
schema_v2::dashboard_metadata::table,
schema_v2::merchant_connector_account::table,
diff --git a/crates/hyperswitch_domain_models/src/subscription.rs b/crates/hyperswitch_domain_models/src/subscription.rs
index 2c3a36aac2..36110a1f19 100644
--- a/crates/hyperswitch_domain_models/src/subscription.rs
+++ b/crates/hyperswitch_domain_models/src/subscription.rs
@@ -214,6 +214,15 @@ pub trait SubscriptionInterface {
subscription_id: String,
data: SubscriptionUpdate,
) -> CustomResult<Subscription, Self::Error>;
+
+ async fn list_by_merchant_id_profile_id(
+ &self,
+ key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ ) -> CustomResult<Vec<Subscription>, Self::Error>;
}
pub struct SubscriptionUpdate {
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 075f2e7fb2..97e4f114be 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -4293,4 +4293,18 @@ impl SubscriptionInterface for KafkaStore {
.update_subscription_entry(key_store, merchant_id, subscription_id, data)
.await
}
+
+ #[instrument(skip_all)]
+ async fn list_by_merchant_id_profile_id(
+ &self,
+ key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
+ merchant_id: &id_type::MerchantId,
+ profile_id: &id_type::ProfileId,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ ) -> CustomResult<Vec<DomainSubscription>, errors::StorageError> {
+ self.diesel_store
+ .list_by_merchant_id_profile_id(key_store, merchant_id, profile_id, limit, offset)
+ .await
+ }
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 4542ac35c2..381d89bd59 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1307,6 +1307,7 @@ impl Subscription {
.service(
web::resource("/plans").route(web::get().to(subscription::get_subscription_plans)),
)
+ .service(web::resource("/list").route(web::get().to(subscription::list_subscriptions)))
.service(
web::resource("/{subscription_id}/confirm").route(web::post().to(
|state, req, id, payload| {
diff --git a/crates/router/src/routes/subscription.rs b/crates/router/src/routes/subscription.rs
index b1a38a6605..0cabcc8eed 100644
--- a/crates/router/src/routes/subscription.rs
+++ b/crates/router/src/routes/subscription.rs
@@ -446,3 +446,45 @@ pub async fn update_subscription(
))
.await
}
+
+#[instrument(skip_all)]
+pub async fn list_subscriptions(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<subscription_types::ListSubscriptionQuery>,
+) -> impl Responder {
+ let flow = Flow::GetSubscription;
+ let query = query.into_inner();
+ let profile_id = match extract_profile_id(&req) {
+ Ok(id) => id,
+ Err(response) => return response,
+ };
+
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _, _| {
+ let platform = auth.into();
+ subscriptions::list_subscriptions(
+ state.into(),
+ platform,
+ profile_id.clone(),
+ query.clone(),
+ )
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::ProfileSubscriptionRead,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/storage_impl/src/subscription.rs b/crates/storage_impl/src/subscription.rs
index ee081eb803..f85b396c6a 100644
--- a/crates/storage_impl/src/subscription.rs
+++ b/crates/storage_impl/src/subscription.rs
@@ -67,6 +67,29 @@ impl<T: DatabaseStore> SubscriptionInterface for RouterStore<T> {
)
.await
}
+
+ #[instrument(skip_all)]
+ async fn list_by_merchant_id_profile_id(
+ &self,
+ key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ ) -> CustomResult<Vec<DomainSubscription>, StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ self.find_resources(
+ key_store,
+ Subscription::list_by_merchant_id_profile_id(
+ &conn,
+ merchant_id,
+ profile_id,
+ limit,
+ offset,
+ ),
+ )
+ .await
+ }
}
#[async_trait::async_trait]
@@ -107,6 +130,20 @@ impl<T: DatabaseStore> SubscriptionInterface for KVRouterStore<T> {
.update_subscription_entry(key_store, merchant_id, subscription_id, data)
.await
}
+
+ #[instrument(skip_all)]
+ async fn list_by_merchant_id_profile_id(
+ &self,
+ key_store: &MerchantKeyStore,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ ) -> CustomResult<Vec<DomainSubscription>, StorageError> {
+ self.router_store
+ .list_by_merchant_id_profile_id(key_store, merchant_id, profile_id, limit, offset)
+ .await
+ }
}
#[async_trait::async_trait]
@@ -140,4 +177,16 @@ impl SubscriptionInterface for MockDb {
) -> CustomResult<DomainSubscription, StorageError> {
Err(StorageError::MockDbError)?
}
+
+ #[instrument(skip_all)]
+ async fn list_by_merchant_id_profile_id(
+ &self,
+ _key_store: &MerchantKeyStore,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _profile_id: &common_utils::id_type::ProfileId,
+ _limit: Option<i64>,
+ _offset: Option<i64>,
+ ) -> CustomResult<Vec<DomainSubscription>, StorageError> {
+ Err(StorageError::MockDbError)?
+ }
}
diff --git a/crates/subscriptions/src/core.rs b/crates/subscriptions/src/core.rs
index f01549ed9e..741b0d1b41 100644
--- a/crates/subscriptions/src/core.rs
+++ b/crates/subscriptions/src/core.rs
@@ -13,8 +13,9 @@ use api_models::enums::SubscriptionStatus;
use crate::{
core::{
- billing_processor_handler::BillingHandler, invoice_handler::InvoiceHandler,
- subscription_handler::SubscriptionHandler,
+ billing_processor_handler::BillingHandler,
+ invoice_handler::InvoiceHandler,
+ subscription_handler::{SubscriptionHandler, SubscriptionWithHandler},
},
state::SubscriptionState as SessionState,
};
@@ -25,8 +26,7 @@ pub mod invoice_handler;
pub mod payments_api_client;
pub mod subscription_handler;
-pub const SUBSCRIPTION_CONNECTOR_ID: &str = "DefaultSubscriptionConnectorId";
-pub const SUBSCRIPTION_PAYMENT_ID: &str = "DefaultSubscriptionPaymentId";
+pub const SUBSCRIPTIONS_MAX_LIST_COUNT: i64 = 10;
pub async fn create_subscription(
state: SessionState,
@@ -112,7 +112,11 @@ pub async fn create_subscription(
.await
.attach_printable("subscriptions: failed to update subscription")?;
- let response = subscription.to_subscription_response(Some(payment), Some(&invoice))?;
+ let response = SubscriptionWithHandler::to_subscription_response(
+ &subscription.subscription,
+ Some(payment),
+ Some(&invoice),
+ )?;
Ok(ApplicationResponse::Json(response))
}
@@ -455,7 +459,8 @@ pub async fn get_subscription(
.await
.attach_printable("subscriptions: failed to get subscription entry in get_subscription")?;
- let response = subscription.to_subscription_response(None, None)?;
+ let response =
+ SubscriptionWithHandler::to_subscription_response(&subscription.subscription, None, None)?;
Ok(ApplicationResponse::Json(response))
}
@@ -712,3 +717,34 @@ pub async fn update_subscription(
))
.await
}
+
+pub async fn list_subscriptions(
+ state: SessionState,
+ platform: Platform,
+ profile_id: common_utils::id_type::ProfileId,
+ query: subscription_types::ListSubscriptionQuery,
+) -> RouterResponse<Vec<SubscriptionResponse>> {
+ SubscriptionHandler::find_business_profile(&state, &platform, &profile_id)
+ .await
+ .attach_printable("subscriptions: failed to find business profile in list_subscriptions")?;
+
+ let handler = SubscriptionHandler::new(&state, &platform);
+
+ let subscriptions = handler
+ .list_subscriptions_by_profile_id(
+ &profile_id,
+ Some(query.limit.unwrap_or(SUBSCRIPTIONS_MAX_LIST_COUNT)),
+ Some(query.offset.unwrap_or_default()),
+ )
+ .await
+ .attach_printable("subscriptions: failed to list subscriptions by profile id")?;
+
+ let mut subscriptions_resonse = Vec::new();
+ for subscription in subscriptions {
+ let response = SubscriptionWithHandler::to_subscription_response(&subscription, None, None)
+ .attach_printable("subscriptions: failed to convert subscription entry to response")?;
+ subscriptions_resonse.push(response);
+ }
+
+ Ok(ApplicationResponse::Json(subscriptions_resonse))
+}
diff --git a/crates/subscriptions/src/core/subscription_handler.rs b/crates/subscriptions/src/core/subscription_handler.rs
index 35c0892190..0181d6d7a5 100644
--- a/crates/subscriptions/src/core/subscription_handler.rs
+++ b/crates/subscriptions/src/core/subscription_handler.rs
@@ -260,6 +260,29 @@ impl<'a> SubscriptionHandler<'a> {
merchant_account: self.platform.get_processor().get_account().clone(),
})
}
+
+ pub async fn list_subscriptions_by_profile_id(
+ &self,
+ profile_id: &common_utils::id_type::ProfileId,
+ limit: Option<i64>,
+ offset: Option<i64>,
+ ) -> errors::SubscriptionResult<Vec<Subscription>> {
+ let subscriptions = self
+ .state
+ .store
+ .list_by_merchant_id_profile_id(
+ self.platform.get_processor().get_key_store(),
+ self.platform.get_processor().get_account().get_id(),
+ profile_id,
+ limit,
+ offset,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("subscriptions: unable to fetch subscriptions from database")?;
+
+ Ok(subscriptions)
+ }
}
pub struct SubscriptionWithHandler<'a> {
pub handler: &'a SubscriptionHandler<'a>,
@@ -290,21 +313,21 @@ impl SubscriptionWithHandler<'_> {
}
pub fn to_subscription_response(
- &self,
+ subscription: &Subscription,
payment: Option<subscription_types::PaymentResponseData>,
invoice: Option<&hyperswitch_domain_models::invoice::Invoice>,
) -> errors::SubscriptionResult<SubscriptionResponse> {
Ok(SubscriptionResponse::new(
- self.subscription.id.clone(),
- self.subscription.merchant_reference_id.clone(),
- common_enums::SubscriptionStatus::from_str(&self.subscription.status)
+ subscription.id.clone(),
+ subscription.merchant_reference_id.clone(),
+ common_enums::SubscriptionStatus::from_str(&subscription.status)
.unwrap_or(common_enums::SubscriptionStatus::Created),
- self.subscription.plan_id.clone(),
- self.subscription.item_price_id.clone(),
- self.subscription.profile_id.to_owned(),
- self.subscription.merchant_id.to_owned(),
- self.subscription.client_secret.clone().map(Secret::new),
- self.subscription.customer_id.clone(),
+ subscription.plan_id.clone(),
+ subscription.item_price_id.clone(),
+ subscription.profile_id.to_owned(),
+ subscription.merchant_id.to_owned(),
+ subscription.client_secret.clone().map(Secret::new),
+ subscription.customer_id.clone(),
payment,
invoice
.map(