Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(payment_link): add list API with offset pagination, time-range filtering, and JWT auth (#14108)
Aniket Burmanffdaf0cef89e
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex 491d98f78a..faa22fd45b 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -1675,6 +1675,129 @@]}},+ "/payment_link/list": {+ "post": {+ "tags": [+ "Payment Links"+ ],+ "summary": "Payment Link - List",+ "description": "To list the payment links across all profiles for a merchant",+ "operationId": "List Payment Links",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PaymentLinkListConstraints"+ },+ "examples": {+ "List with default params": {+ "value": {}+ },+ "List with pagination and time range": {+ "value": {+ "end_time": "2025-03-31T23:59:59Z",+ "limit": 10,+ "offset": 0,+ "start_time": "2025-01-01T00:00:00Z"+ }+ }+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Payment links listed successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PaymentLinkListResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid request (e.g. end_time before start_time, range > 3 months)"+ },+ "401": {+ "description": "Unauthorized"+ },+ "500": {+ "description": "Internal server error"+ }+ },+ "security": [+ {+ "api_key": []+ },+ {+ "jwt_key": []+ }+ ]+ }+ },+ "/payment_link/profile/list": {+ "post": {+ "tags": [+ "Payment Links"+ ],+ "summary": "Payment Link - Profile List",+ "description": "To list payment links scoped to the authenticated business profile",+ "operationId": "List Profile Payment Links",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PaymentLinkListConstraints"+ },+ "examples": {+ "List with default params": {+ "value": {}+ },+ "List with pagination": {+ "value": {+ "limit": 5,+ "offset": 0,+ "start_time": "2025-01-01T00:00:00Z"+ }+ }+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Payment links listed successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PaymentLinkListResponse"+ }+ }+ }+ },+ "400": {+ "description": "Invalid request"+ },+ "401": {+ "description": "Unauthorized"+ },+ "500": {+ "description": "Internal server error"+ }+ },+ "security": [+ {+ "api_key": []+ },+ {+ "jwt_key": []+ }+ ]+ }+ },"/payments/{payment_id}/3ds/authentication": {"post": {"tags": [@@ -31735,6 +31858,56 @@}}},+ "PaymentLinkListConstraints": {+ "allOf": [+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/TimeRange"+ }+ ],+ "nullable": true+ },+ {+ "type": "object",+ "properties": {+ "limit": {+ "$ref": "#/components/schemas/common_utils.types.list.PageSize"+ },+ "offset": {+ "$ref": "#/components/schemas/common_utils.types.list.PageOffset"+ }+ }+ }+ ]+ },+ "PaymentLinkListResponse": {+ "type": "object",+ "required": [+ "size",+ "total_count",+ "data"+ ],+ "properties": {+ "size": {+ "type": "integer",+ "description": "The number of payment links included in the current page",+ "minimum": 0+ },+ "total_count": {+ "type": "integer",+ "format": "int64",+ "description": "The total number of payment links matching the given filters"+ },+ "data": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/RetrievePaymentLinkResponse"+ },+ "description": "The list of payment link response objects"+ }+ }+ },"PaymentLinkResponse": {"type": "object","required": [@@ -44282,6 +44455,7 @@"type": "object","required": ["payment_link_id",+ "payment_id","merchant_id","link_to_pay","amount",@@ -44293,6 +44467,10 @@"type": "string","description": "Identifier for Payment Link"},+ "payment_id": {+ "type": "string",+ "description": "Identifier for the associated Payment"+ },"merchant_id": {"type": "string","description": "Identifier for Merchant"@@ -44302,6 +44480,11 @@"description": "Identifier for the processor merchant","nullable": true},+ "profile_id": {+ "type": "string",+ "description": "Identifier for the business profile",+ "nullable": true+ },"link_to_pay": {"type": "string","description": "Open payment link (without any security checks and listing SPMs)"diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex f6d82705e4..81800d127b 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -31669,6 +31669,7 @@"type": "object","required": ["payment_link_id",+ "payment_id","merchant_id","link_to_pay","amount",@@ -31680,6 +31681,10 @@"type": "string","description": "Identifier for Payment Link"},+ "payment_id": {+ "type": "string",+ "description": "Identifier for the associated Payment"+ },"merchant_id": {"type": "string","description": "Identifier for Merchant"@@ -31689,6 +31694,11 @@"description": "Identifier for the processor merchant","nullable": true},+ "profile_id": {+ "type": "string",+ "description": "Identifier for the business profile",+ "nullable": true+ },"link_to_pay": {"type": "string","description": "Open payment link (without any security checks and listing SPMs)"diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex a1c33bd8d5..fa4d984df5 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -22,9 +22,9 @@ use crate::{PaymentMethodUpdate,},payments::{- self, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2,- PaymentListResponse, PaymentsAggregateResponse, PaymentsSessionResponse,- RedirectionResponse,+ self, PaymentLinkListResponse, PaymentListConstraints, PaymentListFilters,+ PaymentListFiltersV2, PaymentListResponse, PaymentsAggregateResponse,+ PaymentsSessionResponse, RedirectionResponse,},};#[cfg(feature = "v1")]@@ -551,6 +551,12 @@ impl ApiEventMetric for PaymentListResponse {}}+impl ApiEventMetric for PaymentLinkListResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::ResourceListAPI)+ }+}+#[cfg(feature = "v2")]impl ApiEventMetric for RecoveryPaymentsCreate {fn get_api_event_type(&self) -> Option<ApiEventsType> {diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex f334eb5ad5..95635acef5 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -29,7 +29,7 @@ use common_utils::{id_type,new_type::MaskedBankAccount,pii::{self, Email},- types::{AmountConvertor, MinorUnit, Percentage, SemanticVersion, StringMajorUnit},+ types::{AmountConvertor, MinorUnit, Percentage, SemanticVersion, StringMajorUnit, TimeRange},};use error_stack::ResultExt;@@ -9345,7 +9345,7 @@ pub struct PaymentListFilterConstraints {pub amount_filter: Option<AmountFilter>,/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).#[serde(flatten)]- pub time_range: Option<common_utils::types::TimeRange>,+ pub time_range: Option<TimeRange>,/// The list of connectors to filter payments listpub connector: Option<Vec<api_enums::Connector>>,/// The list of currencies to filter payments list@@ -13055,12 +13055,18 @@ pub struct PaymentLinkResponse {pub struct RetrievePaymentLinkResponse {/// Identifier for Payment Linkpub payment_link_id: String,+ /// Identifier for the associated Payment+ #[schema(value_type = String)]+ pub payment_id: id_type::PaymentId,/// Identifier for Merchant#[schema(value_type = String)]pub merchant_id: id_type::MerchantId,/// Identifier for the processor merchant#[schema(value_type = Option<String>)]pub processor_merchant_id: Option<id_type::MerchantId>,+ /// Identifier for the business profile+ #[schema(value_type = Option<String>)]+ pub profile_id: Option<id_type::ProfileId>,/// Open payment link (without any security checks and listing SPMs)pub link_to_pay: String,/// The payment amount. Amount for the payment in the lowest denomination of the currency@@ -13192,56 +13198,28 @@ pub struct PaymentLinkStatusDetails {}#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]-#[serde(deny_unknown_fields)]pub struct PaymentLinkListConstraints {- /// limit on the number of objects to return- pub limit: Option<i64>,-- /// The time at which payment link is created- #[schema(example = "2022-09-10T10:11:12Z")]- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]- pub created: Option<PrimitiveDateTime>,-- /// Time less than the payment link created time- #[schema(example = "2022-09-10T10:11:12Z")]- #[serde(- default,- with = "common_utils::custom_serde::iso8601::option",- rename = "created.lt"- )]- pub created_lt: Option<PrimitiveDateTime>,-- /// Time greater than the payment link created time- #[schema(example = "2022-09-10T10:11:12Z")]- #[serde(- default,- with = "common_utils::custom_serde::iso8601::option",- rename = "created.gt"- )]- pub created_gt: Option<PrimitiveDateTime>,+ /// Limit on the number of objects to return (default: 10, max: 100)+ #[serde(default)]+ pub limit: common_utils::types::list::PageSize,- /// Time less than or equals to the payment link created time- #[schema(example = "2022-09-10T10:11:12Z")]- #[serde(- default,- with = "common_utils::custom_serde::iso8601::option",- rename = "created.lte"- )]- pub created_lte: Option<PrimitiveDateTime>,+ /// Number of records to skip (default: 0)+ #[serde(default)]+ pub offset: common_utils::types::list::PageOffset,- /// Time greater than or equals to the payment link created time- #[schema(example = "2022-09-10T10:11:12Z")]- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]- #[serde(rename = "created.gte")]- pub created_gte: Option<PrimitiveDateTime>,+ /// Time range filter with start_time (mandatory) and optional end_time+ #[serde(flatten)]+ pub time_range: Option<TimeRange>,}#[derive(Clone, Debug, serde::Serialize, ToSchema)]pub struct PaymentLinkListResponse {- /// The number of payment links included in the list+ /// The number of payment links included in the current pagepub size: usize,- // The list of payment link response objects- pub data: Vec<PaymentLinkResponse>,+ /// The total number of payment links matching the given filters+ pub total_count: i64,+ /// The list of payment link response objects+ pub data: Vec<RetrievePaymentLinkResponse>,}/// Configure a custom payment link for the particular paymentdiff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 22e987151f..5bed0dd148 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -9664,6 +9664,7 @@ pub enum ParentGroup {#[serde(rename_all = "snake_case")]pub enum Resource {Payment,+ PaymentLink,Refund,ApiKey,Account,diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex f38382b990..cbd7247032 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -86,6 +86,8 @@ Never share your secret api keys. Keep them guarded and secure.routes::payments::payments_list,routes::payments::payments_incremental_authorization,routes::payment_link::payment_link_retrieve,+ routes::payment_link::payments_link_list,+ routes::payment_link::profile_payment_link_list,routes::payments::payments_external_authentication,routes::payments::payments_complete_authorize,routes::payments::payments_post_session_tokens,@@ -975,6 +977,8 @@ Never share your secret api keys. Keep them guarded and secure.api_models::payments::PaymentLinkResponse,api_models::payments::RetrievePaymentLinkResponse,api_models::payments::PaymentLinkInitiateRequest,+ api_models::payments::PaymentLinkListConstraints,+ api_models::payments::PaymentLinkListResponse,api_models::payouts::PayoutLinkInitiateRequest,api_models::payments::ExtendedCardInfoResponse,api_models::payments::GooglePayAssuranceDetails,diff --git a/crates/openapi/src/routes/payment_link.rs b/crates/openapi/src/routes/payment_link.rsindex 7d5ac5247b..a5c36bad6b 100644--- a/crates/openapi/src/routes/payment_link.rs+++ b/crates/openapi/src/routes/payment_link.rs@@ -17,3 +17,78 @@security(("api_key" = []), ("publishable_key" = [])))]pub async fn payment_link_retrieve() {}++/// Payment Link - List+///+/// To list the payment links across all profiles for a merchant+#[utoipa::path(+ post,+ path = "/payment_link/list",+ request_body(+ content = PaymentLinkListConstraints,+ examples(+ (+ "List with default params" = (+ value = json!({})+ )+ ),+ (+ "List with pagination and time range" = (+ value = json!({+ "limit": 10,+ "offset": 0,+ "start_time": "2025-01-01T00:00:00Z",+ "end_time": "2025-03-31T23:59:59Z"+ })+ )+ )+ )+ ),+ responses(+ (status = 200, description = "Payment links listed successfully", body = PaymentLinkListResponse),+ (status = 400, description = "Invalid request (e.g. end_time before start_time, range > 3 months)"),+ (status = 401, description = "Unauthorized"),+ (status = 500, description = "Internal server error"),+ ),+ tag = "Payment Links",+ operation_id = "List Payment Links",+ security(("api_key" = []), ("jwt_key" = []))+)]+pub async fn payments_link_list() {}++/// Payment Link - Profile List+///+/// To list payment links scoped to the authenticated business profile+#[utoipa::path(+ post,+ path = "/payment_link/profile/list",+ request_body(+ content = PaymentLinkListConstraints,+ examples(+ (+ "List with default params" = (+ value = json!({})+ )+ ),+ (+ "List with pagination" = (+ value = json!({+ "limit": 5,+ "offset": 0,+ "start_time": "2025-01-01T00:00:00Z"+ })+ )+ )+ )+ ),+ responses(+ (status = 200, description = "Payment links listed successfully", body = PaymentLinkListResponse),+ (status = 400, description = "Invalid request"),+ (status = 401, description = "Unauthorized"),+ (status = 500, description = "Internal server error"),+ ),+ tag = "Payment Links",+ operation_id = "List Profile Payment Links",+ security(("api_key" = []), ("jwt_key" = []))+)]+pub async fn profile_payment_link_list() {}diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rsindex 6ba1e56cdf..7db306457b 100644--- a/crates/router/src/core/payment_link.rs+++ b/crates/router/src/core/payment_link.rs@@ -539,19 +539,65 @@ fn validate_sdk_requirements(pub async fn list_payment_link(state: SessionState,merchant: domain::MerchantAccount,- constraints: api_models::payments::PaymentLinkListConstraints,-) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> {+ mut constraints: api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,+) -> RouterResponse<api_models::payments::PaymentLinkListResponse> {let db = state.store.as_ref();- let payment_link = db- .list_payment_link_by_processor_merchant_id(merchant.get_id(), constraints)+ let now = common_utils::date_time::now();++ let time_range = match constraints.time_range {+ None => common_utils::types::TimeRange {+ start_time: now.saturating_sub(time::Duration::days(30)),+ end_time: Some(now),+ },+ Some(tr) => {+ let end = tr.end_time.unwrap_or(now);+ if end <= tr.start_time {+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: "end_time must be after start_time".to_string(),+ }));+ } else if (end - tr.start_time) > time::Duration::days(90) {+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: "time range cannot exceed 3 months".to_string(),+ }));+ } else {+ common_utils::types::TimeRange {+ start_time: tr.start_time,+ end_time: Some(end),+ }+ }+ }+ };+ constraints.time_range = Some(time_range);++ let payment_links = db+ .list_payment_link_by_processor_merchant_id(+ merchant.get_id(),+ &constraints,+ profile_id.clone(),+ ).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Unable to retrieve payment link")?;- let payment_link_list = future::try_join_all(payment_link.into_iter().map(|payment_link| {++ let total_count = db+ .get_total_count_of_payment_links(merchant.get_id(), &constraints, profile_id)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Unable to retrieve total count of payment links")?;++ let data = future::try_join_all(payment_links.into_iter().map(|payment_link| {api_models::payments::RetrievePaymentLinkResponse::from_db_payment_link(payment_link)})).await?;- Ok(services::ApplicationResponse::Json(payment_link_list))+ let size = data.len();+ Ok(services::ApplicationResponse::Json(+ api_models::payments::PaymentLinkListResponse {+ size,+ total_count,+ data,+ },+ ))}pub fn check_payment_link_status(diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 004f2c75f8..ad9d45792e 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -1266,12 +1266,29 @@ impl PaymentLinkInterface for KafkaStore {async fn list_payment_link_by_processor_merchant_id(&self,processor_merchant_id: &id_type::MerchantId,- payment_link_constraints: api_models::payments::PaymentLinkListConstraints,+ payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<id_type::ProfileId>,) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {self.diesel_store.list_payment_link_by_processor_merchant_id(processor_merchant_id,payment_link_constraints,+ profile_id,+ )+ .await+ }++ async fn get_total_count_of_payment_links(+ &self,+ processor_merchant_id: &id_type::MerchantId,+ payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<id_type::ProfileId>,+ ) -> CustomResult<i64, errors::StorageError> {+ self.diesel_store+ .get_total_count_of_payment_links(+ processor_merchant_id,+ payment_link_constraints,+ profile_id,).await}diff --git a/crates/router/src/db/payment_link.rs b/crates/router/src/db/payment_link.rsindex f203e737f5..de78e2cfcb 100644--- a/crates/router/src/db/payment_link.rs+++ b/crates/router/src/db/payment_link.rs@@ -24,8 +24,16 @@ pub trait PaymentLinkInterface {async fn list_payment_link_by_processor_merchant_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,- payment_link_constraints: api_models::payments::PaymentLinkListConstraints,+ payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError>;++ async fn get_total_count_of_payment_links(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,+ ) -> CustomResult<i64, errors::StorageError>;}#[async_trait::async_trait]@@ -57,13 +65,33 @@ impl PaymentLinkInterface for Store {async fn list_payment_link_by_processor_merchant_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,- payment_link_constraints: api_models::payments::PaymentLinkListConstraints,+ payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;storage::PaymentLink::filter_by_constraints(&conn,processor_merchant_id,payment_link_constraints,+ profile_id,+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }++ #[instrument(skip_all)]+ async fn get_total_count_of_payment_links(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,+ ) -> CustomResult<i64, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ storage::PaymentLink::get_total_count_of_payment_links(+ &conn,+ processor_merchant_id,+ payment_link_constraints,+ profile_id,).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -84,16 +112,27 @@ impl PaymentLinkInterface for MockDb {&self,_payment_link_id: &str,) -> CustomResult<storage::PaymentLink, errors::StorageError> {- // TODO: Implement function for `MockDb`x+ // TODO: Implement function for `MockDb`Err(errors::StorageError::MockDbError)?}async fn list_payment_link_by_processor_merchant_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,- _payment_link_constraints: api_models::payments::PaymentLinkListConstraints,+ _payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ _profile_id: Option<common_utils::id_type::ProfileId>,) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {- // TODO: Implement function for `MockDb`x+ // TODO: Implement function for `MockDb`+ Err(errors::StorageError::MockDbError)?+ }++ async fn get_total_count_of_payment_links(+ &self,+ _processor_merchant_id: &common_utils::id_type::MerchantId,+ _payment_link_constraints: &api_models::payments::PaymentLinkListConstraints,+ _profile_id: Option<common_utils::id_type::ProfileId>,+ ) -> CustomResult<i64, errors::StorageError> {+ // TODO: Implement function for `MockDb`Err(errors::StorageError::MockDbError)?}}diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 7176686789..1b85e58562 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -2534,6 +2534,10 @@ impl PaymentLink {web::scope("/payment_link").app_data(web::Data::new(state)).service(web::resource("/list").route(web::post().to(payment_link::payments_link_list)))+ .service(+ web::resource("/profile/list")+ .route(web::post().to(payment_link::profile_payment_link_list)),+ ).service(web::resource("/{payment_link_id}").route(web::get().to(payment_link::payment_link_retrieve)),diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rsindex a6c0c92c09..6c0021d381 100644--- a/crates/router/src/routes/payment_link.rs+++ b/crates/router/src/routes/payment_link.rs@@ -3,7 +3,7 @@ use router_env::{instrument, tracing, Flow};use crate::{core::{api_locking, payment_link::*},- services::{api, authentication as auth},+ services::{api, authentication as auth, authorization::permissions::Permission},AppState,};@@ -124,12 +124,12 @@ pub async fn initiate_secure_payment_link(/// Payment Link - List///-/// To list the payment links+/// To list the payment links across all profiles for a merchant#[instrument(skip_all, fields(flow = ?Flow::PaymentLinkList))]pub async fn payments_link_list(state: web::Data<AppState>,req: actix_web::HttpRequest,- payload: web::Query<api_models::payments::PaymentLinkListConstraints>,+ payload: web::Json<api_models::payments::PaymentLinkListConstraints>,) -> impl Responder {let flow = Flow::PaymentLinkList;let payload = payload.into_inner();@@ -143,12 +143,62 @@ pub async fn payments_link_list(state,auth.platform.get_processor().get_account().clone(),payload,+ None,)},- &auth::HeaderAuth(auth::ApiKeyAuth {- allow_connected_scope_operation: true,- allow_platform_self_operation: false,- }),+ auth::auth_type(+ &auth::HeaderAuth(auth::ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: false,+ }),+ &auth::JWTAuth {+ permission: Permission::MerchantPaymentLinkRead,+ allow_connected: true,+ allow_platform: false,+ },+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++/// Payment Link - Profile List+///+/// To list payment links scoped to the authenticated business profile+#[instrument(skip_all, fields(flow = ?Flow::PaymentLinkList))]+pub async fn profile_payment_link_list(+ state: web::Data<AppState>,+ req: actix_web::HttpRequest,+ payload: web::Json<api_models::payments::PaymentLinkListConstraints>,+) -> impl Responder {+ let flow = Flow::PaymentLinkList;+ let payload = payload.into_inner();+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: auth::AuthenticationData, payload, _| {+ list_payment_link(+ state,+ auth.platform.get_processor().get_account().clone(),+ payload,+ auth.profile.map(|p| p.get_id().clone()),+ )+ },+ auth::auth_type(+ &auth::HeaderAuth(auth::ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: false,+ }),+ &auth::JWTAuth {+ permission: Permission::ProfilePaymentLinkRead,+ allow_connected: true,+ allow_platform: false,+ },+ req.headers(),+ ),api_locking::LockAction::NotApplicable,)).awaitdiff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rsindex a46d021da2..baf642f8ee 100644--- a/crates/router/src/services/authorization/permission_groups.rs+++ b/crates/router/src/services/authorization/permission_groups.rs@@ -273,8 +273,9 @@ impl ParentGroupExt for ParentGroup {}}-pub static OPERATIONS: [Resource; 8] = [+pub static OPERATIONS: [Resource; 9] = [Resource::Payment,+ Resource::PaymentLink,Resource::Refund,Resource::Mandate,Resource::Dispute,diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rsindex ea946791ca..2ce36b80e7 100644--- a/crates/router/src/services/authorization/permissions.rs+++ b/crates/router/src/services/authorization/permissions.rs@@ -7,6 +7,10 @@ generate_permissions! {scopes: [Read, Write],entities: [Profile, Merchant]},+ PaymentLink: {+ scopes: [Read],+ entities: [Profile, Merchant]+ },Refund: {scopes: [Read, Write],entities: [Profile, Merchant]@@ -121,6 +125,7 @@ generate_permissions! {pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> Option<&'static str> {match (resource, entity_type) {(Resource::Payment, _) => Some("Payments"),+ (Resource::PaymentLink, _) => Some("Payment Links"),(Resource::Refund, _) => Some("Refunds"),(Resource::Dispute, _) => Some("Disputes"),(Resource::Mandate, _) => Some("Mandates"),diff --git a/crates/router/src/types/api/payment_link.rs b/crates/router/src/types/api/payment_link.rsindex e7149efdf4..6bfa1d7325 100644--- a/crates/router/src/types/api/payment_link.rs+++ b/crates/router/src/types/api/payment_link.rs@@ -23,11 +23,13 @@ impl PaymentLinkResponseExt for RetrievePaymentLinkResponse {Ok(Self {link_to_pay: payment_link.link_to_pay,payment_link_id: payment_link.payment_link_id,+ payment_id: payment_link.payment_id,amount: payment_link.amount,description: payment_link.description,created_at: payment_link.created_at,merchant_id: payment_link.merchant_id,processor_merchant_id: payment_link.processor_merchant_id,+ profile_id: payment_link.profile_id,expiry: payment_link.fulfilment_time,currency: payment_link.currency,status,diff --git a/crates/router/src/types/storage/payment_link.rs b/crates/router/src/types/storage/payment_link.rsindex a74b89efb1..aa3f831bd0 100644--- a/crates/router/src/types/storage/payment_link.rs+++ b/crates/router/src/types/storage/payment_link.rs@@ -2,6 +2,7 @@ use async_bb8_diesel::AsyncRunQueryDsl;use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, QueryDsl};pub use diesel_models::{payment_link::{PaymentLink, PaymentLinkNew},+ query::generics::db_metrics,schema::payment_link::dsl,};use error_stack::ResultExt;@@ -17,8 +18,16 @@ pub trait PaymentLinkDbExt: Sized {async fn filter_by_constraints(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,- payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,+ payment_link_list_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,) -> CustomResult<Vec<Self>, errors::DatabaseError>;++ async fn get_total_count_of_payment_links(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ payment_link_list_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,+ ) -> CustomResult<i64, errors::DatabaseError>;}#[async_trait::async_trait]@@ -26,7 +35,8 @@ impl PaymentLinkDbExt for PaymentLink {async fn filter_by_constraints(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,- payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,+ payment_link_list_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,) -> CustomResult<Vec<Self>, errors::DatabaseError> {let mut filter = diesel_models::list::into_boxed_list(<Self as HasTable>::table()@@ -40,33 +50,81 @@ impl PaymentLinkDbExt for PaymentLink {.order(dsl::created_at.desc()),);- if let Some(created_time) = payment_link_list_constraints.created {- filter = filter.filter(dsl::created_at.eq(created_time));- }- if let Some(created_time_lt) = payment_link_list_constraints.created_lt {- filter = filter.filter(dsl::created_at.lt(created_time_lt));- }- if let Some(created_time_gt) = payment_link_list_constraints.created_gt {- filter = filter.filter(dsl::created_at.gt(created_time_gt));- }- if let Some(created_time_lte) = payment_link_list_constraints.created_lte {- filter = filter.filter(dsl::created_at.le(created_time_lte));- }- if let Some(created_time_gte) = payment_link_list_constraints.created_gte {- filter = filter.filter(dsl::created_at.ge(created_time_gte));- }- if let Some(limit) = payment_link_list_constraints.limit {- filter = filter.limit(limit);- }+ filter = match profile_id {+ Some(pid) => filter.filter(dsl::profile_id.eq(pid)),+ None => filter,+ };++ filter = match payment_link_list_constraints.time_range {+ Some(tr) => {+ let f = filter.filter(dsl::created_at.ge(tr.start_time));+ match tr.end_time {+ Some(end_time) => f.filter(dsl::created_at.le(end_time)),+ None => f,+ }+ }+ None => filter,+ };++ let filter = diesel_models::list::apply_pagination(+ filter,+ payment_link_list_constraints.limit,+ payment_link_list_constraints.offset,+ );logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg, _>(&filter).to_string());- filter- .get_results_async(conn.raw_connection())- .await- // The query built here returns an empty Vec when no records are found, and if any error does occur,- // it would be an internal database error, due to which we are raising a DatabaseError::Unknown error- .change_context(errors::DatabaseError::Others)- .attach_printable("Error filtering payment link by specified constraints")+ db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(+ conn.request_id(),+ conn.event_emitter(),+ db_metrics::DatabaseOperation::Filter,+ filter.get_results_async(conn.raw_connection()),+ )+ .await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error filtering payment link by specified constraints")+ }++ async fn get_total_count_of_payment_links(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ payment_link_list_constraints: &api_models::payments::PaymentLinkListConstraints,+ profile_id: Option<common_utils::id_type::ProfileId>,+ ) -> CustomResult<i64, errors::DatabaseError> {+ let mut filter = diesel_models::list::into_boxed_list(+ <Self as HasTable>::table().count().filter(+ dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .or(dsl::processor_merchant_id+ .is_null()+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))),+ ),+ );++ filter = match profile_id {+ Some(pid) => filter.filter(dsl::profile_id.eq(pid)),+ None => filter,+ };++ filter = match payment_link_list_constraints.time_range {+ Some(tr) => {+ let f = filter.filter(dsl::created_at.ge(tr.start_time));+ match tr.end_time {+ Some(end_time) => f.filter(dsl::created_at.le(end_time)),+ None => f,+ }+ }+ None => filter,+ };++ db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(+ conn.request_id(),+ conn.event_emitter(),+ db_metrics::DatabaseOperation::Count,+ filter.get_result_async(conn.raw_connection()),+ )+ .await+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error counting payment links by specified constraints")}}diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rsindex 766139deef..86606b9578 100644--- a/crates/router/src/types/transformers.rs+++ b/crates/router/src/types/transformers.rs@@ -1914,8 +1914,10 @@ impl ForeignFrom<(storage::PaymentLink, payments::PaymentLinkStatus)>) -> Self {Self {payment_link_id: payment_link_config.payment_link_id,+ payment_id: payment_link_config.payment_id,merchant_id: payment_link_config.merchant_id,processor_merchant_id: payment_link_config.processor_merchant_id,+ profile_id: payment_link_config.profile_id,link_to_pay: payment_link_config.link_to_pay,amount: payment_link_config.amount,created_at: payment_link_config.created_at,diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex e489ebf156..36af38c98f 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -10851,9 +10851,15 @@ Cypress.Commands.add("listPaymentLinksTest", (data, globalState) => {cy.wrap(response).then(() => {expect(response.status).to.equal(200);expect(response.headers["content-type"]).to.include("application/json");- expect(response.body).to.be.an("array");+ expect(response.body).to.be.an("object");+ expect(response.body).to.have.property("data").that.is.an("array");+ expect(response.body).to.have.property("size").that.is.a("number");+ expect(response.body).to.have.property("total_count").that.is.a("number");- cy.task("cli_log", `Listed ${response.body.length} payment links`);+ cy.task(+ "cli_log",+ `Listed ${response.body.size} payment links (total: ${response.body.total_count})`+ );});});});