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(router): separate payment and payout blocklists (#14722)
Ayush Anand697eb32304d2
diff --git a/api-reference/v1/blocklist/blocklist--lookup.mdx b/api-reference/v1/blocklist/blocklist--lookup.mdxindex 0a24445493..d4cc5e7ff9 100644--- a/api-reference/v1/blocklist/blocklist--lookup.mdx+++ b/api-reference/v1/blocklist/blocklist--lookup.mdx@@ -1,3 +1,4 @@---openapi: get /blocklist/lookup---+diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex b74fa66ae0..0a0d8d6f2f 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -7577,7 +7577,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/BlocklistRequest"+ "$ref": "#/components/schemas/BlocklistEntryRequest"}}},@@ -7625,6 +7625,20 @@"$ref": "#/components/schemas/BlocklistDataKind"}},+ {+ "name": "transaction_type",+ "in": "query",+ "description": "Blocklist flow: payment (default) or payout.",+ "required": false,+ "schema": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true+ }+ },{"name": "X-Profile-Id","in": "header",@@ -7706,7 +7720,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/BlocklistRequest"+ "$ref": "#/components/schemas/BlocklistEntryRequest"}}},@@ -7806,6 +7820,20 @@"$ref": "#/components/schemas/BlocklistDataKind"}},+ {+ "name": "transaction_type",+ "in": "query",+ "description": "Counts only payment or payout when selected. When omitted, counts both, including legacy NULL entries. Legacy NULL entries belong to payment when filtered.",+ "required": false,+ "schema": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true+ }+ },{"name": "X-Profile-Id","in": "header",@@ -7869,6 +7897,20 @@"type": "string"}},+ {+ "name": "transaction_type",+ "in": "query",+ "description": "Looks up only payment or payout when selected. When omitted, both are included. Legacy NULL transaction namespaces belong to payment.",+ "required": false,+ "schema": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true+ }+ },{"name": "X-Profile-Id","in": "header",@@ -7893,7 +7935,7 @@],"responses": {"200": {- "description": "Blocklist lookup result",+ "description": "All matches within the resolved profile, including merchant-wide entries. transaction_types contains distinct matching payment/payout namespaces, without data kinds or profile IDs.","content": {"application/json": {"schema": {@@ -7923,6 +7965,20 @@],"operationId": "Upload a batch blocklist CSV","parameters": [+ {+ "name": "transaction_type",+ "in": "query",+ "description": "Overrides every CSV row with payment or payout when selected. When omitted, row selections are used; missing or empty row values default to payment.",+ "required": false,+ "schema": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true+ }+ },{"name": "X-Profile-Id","in": "header",@@ -7946,7 +8002,7 @@}],"requestBody": {- "description": "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). The part's `filename` is recorded on the job and returned as `file_name`. The CSV must have a header row: `type,data,metadata`. `type`: one of `generic_card_bin` (6 to 10 digits), `fingerprint`. `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). Maximum 100,000 data rows.",+ "description": "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). The part's `filename` is recorded on the job and returned as `file_name`. The CSV header is `type,data,metadata,transaction_type`; older headers without `transaction_type` are accepted. `type`: one of `generic_card_bin` (6 to 10 digits), `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). `transaction_type`: optional, `payment` (default) or `payout`; selection may differ per row. Invalid CSV transaction-type values are rejected even when a query override is selected. Maximum 100,000 data rows.","content": {"multipart/form-data": {"schema": {@@ -8128,6 +8184,20 @@],"operationId": "Start a blocklist CSV export","parameters": [+ {+ "name": "transaction_type",+ "in": "query",+ "description": "Exports only `payment` or `payout` entries when selected. Both are exported when omitted.",+ "required": false,+ "schema": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true+ }+ },{"name": "X-Profile-Id","in": "header",@@ -8162,7 +8232,7 @@}},"400": {- "description": "No profile could be resolved"+ "description": "Invalid transaction type, or no profile could be resolved"}},"security": [@@ -16926,6 +16996,19 @@"profile_clone"]},+ "BatchBlocklistUploadQuery": {+ "type": "object",+ "properties": {+ "transaction_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true+ }+ }+ },"BatchBlocklistUploadResponse": {"type": "object","description": "Response returned on a successful `POST /blocklist/batch`.",@@ -17081,6 +17164,14 @@"properties": {"data_kind": {"$ref": "#/components/schemas/BlocklistDataKind"+ },+ "transaction_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true}}},@@ -17120,6 +17211,36 @@"generic_card_bin"]},+ "BlocklistEntryRequest": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistRequest"+ },+ {+ "type": "object",+ "properties": {+ "transaction_type": {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ }+ }+ ],+ "description": "A tagged single-entry request with an optional transaction namespace."+ },+ "BlocklistExportQuery": {+ "type": "object",+ "description": "Query parameters for `POST /blocklist/export`.",+ "properties": {+ "transaction_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true+ }+ }+ },"BlocklistExportResponse": {"type": "object","description": "Response for `POST /blocklist/export`.",@@ -17152,6 +17273,14 @@"type": "string","description": "The raw value to check against the blocklist, e.g. a card BIN. Limited to 20 characters,\nthe longest value a `fingerprint_id` can hold.","maxLength": 20+ },+ "transaction_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true}}},@@ -17159,7 +17288,8 @@"type": "object","required": ["data",- "blocked"+ "blocked",+ "transaction_types"],"properties": {"data": {@@ -17167,7 +17297,14 @@},"blocked": {"type": "boolean",- "description": "Whether an entry matching `data` exists in the blocklist, under any data_kind"+ "description": "Whether any entry matches within the resolved profile and selected transaction namespaces."+ },+ "transaction_types": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ },+ "description": "Distinct transaction types that block `data`, empty when `blocked` is false."}}},@@ -17260,6 +17397,7 @@"required": ["fingerprint_id","data_kind",+ "transaction_type","created_at"],"properties": {@@ -17269,6 +17407,9 @@"data_kind": {"$ref": "#/components/schemas/BlocklistDataKind"},+ "transaction_type": {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ },"created_at": {"type": "string","format": "date-time"@@ -17306,6 +17447,14 @@}}},+ "BlocklistTransactionType": {+ "type": "string",+ "description": "The transaction namespace of a blocklist entry, stored as text.",+ "enum": [+ "payment",+ "payout"+ ]+ },"BoletoAdditionalDetails": {"type": "object","properties": {@@ -19503,6 +19652,14 @@"items": {"type": "string"}+ },+ "transaction_type": {+ "allOf": [+ {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ }+ ],+ "nullable": true}}},@@ -27454,6 +27611,9 @@"data_kind": {"$ref": "#/components/schemas/BlocklistDataKind"},+ "transaction_type": {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ },"limit": {"type": "integer","format": "int32",diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.jsonindex e4a24f6a5a..46087ab1a2 100644--- a/api-reference/v2/openapi_spec_v2.json+++ b/api-reference/v2/openapi_spec_v2.json@@ -10709,6 +10709,7 @@"required": ["fingerprint_id","data_kind",+ "transaction_type","created_at"],"properties": {@@ -10718,6 +10719,9 @@"data_kind": {"$ref": "#/components/schemas/BlocklistDataKind"},+ "transaction_type": {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ },"created_at": {"type": "string","format": "date-time"@@ -10729,6 +10733,14 @@}}},+ "BlocklistTransactionType": {+ "type": "string",+ "description": "The transaction namespace of a blocklist entry, stored as text.",+ "enum": [+ "payment",+ "payout"+ ]+ },"BoletoAdditionalDetails": {"type": "object","properties": {@@ -18485,6 +18497,9 @@"data_kind": {"$ref": "#/components/schemas/BlocklistDataKind"},+ "transaction_type": {+ "$ref": "#/components/schemas/BlocklistTransactionType"+ },"limit": {"type": "integer","format": "int32",diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rsindex 449aa2538f..72fce16621 100644--- a/crates/api_models/src/blocklist.rs+++ b/crates/api_models/src/blocklist.rs@@ -31,11 +31,24 @@ pub struct Card {pub type AddToBlocklistRequest = BlocklistRequest;pub type DeleteFromBlocklistRequest = BlocklistRequest;+/// A tagged single-entry request with an optional transaction namespace.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct BlocklistEntryRequest {+ #[serde(flatten)]+ pub entry: BlocklistRequest,+ /// Only `payment` and `payout` are supported. Defaults to `payment`.+ #[serde(default)]+ #[schema(value_type = BlocklistTransactionType)]+ pub transaction_type: common_enums::BlocklistTransactionType,+}+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]pub struct BlocklistResponse {pub fingerprint_id: String,#[schema(value_type = BlocklistDataKind)]pub data_kind: enums::BlocklistDataKind,+ #[schema(value_type = BlocklistTransactionType)]+ pub transaction_type: common_enums::BlocklistTransactionType,#[serde(with = "common_utils::custom_serde::iso8601")]pub created_at: time::PrimitiveDateTime,#[schema(value_type = Option<String>, example = "pro_abcdefghijklmnop")]@@ -69,6 +82,10 @@ pub struct ListBlocklistResponse {pub struct ListBlocklistQuery {#[schema(value_type = BlocklistDataKind)]pub data_kind: enums::BlocklistDataKind,+ /// Only `payment` and `payout` are supported. Defaults to `payment`.+ #[serde(default)]+ #[schema(value_type = BlocklistTransactionType)]+ pub transaction_type: common_enums::BlocklistTransactionType,#[serde(default = "default_list_limit")]pub limit: u16,#[serde(default)]@@ -90,6 +107,10 @@ pub struct ToggleBlocklistQuery {pub struct BlocklistCountQuery {#[schema(value_type = BlocklistDataKind)]pub data_kind: enums::BlocklistDataKind,+ /// Counts only `payment` or `payout` when selected. When omitted, counts both,+ /// including legacy NULL entries, which belong to `payment` when filtered.+ #[schema(value_type = Option<BlocklistTransactionType>)]+ pub transaction_type: Option<common_enums::BlocklistTransactionType>,}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]@@ -112,13 +133,19 @@ pub struct BlocklistLookupQuery {/// the longest value a `fingerprint_id` can hold.#[schema(value_type = String, max_length = 20)]pub data: common_utils::types::BlocklistLookupData,+ /// Looks up only `payment` or `payout` when selected. Omission looks up both.+ #[schema(value_type = Option<BlocklistTransactionType>)]+ pub transaction_type: Option<common_enums::BlocklistTransactionType>,}#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]pub struct BlocklistLookupResponse {pub data: String,- /// Whether an entry matching `data` exists in the blocklist, under any data_kind+ /// Whether any entry matches within the resolved profile and selected transaction namespaces.pub blocked: bool,+ /// Distinct transaction types that block `data`, empty when `blocked` is false.+ #[schema(value_type = Vec<BlocklistTransactionType>)]+ pub transaction_types: Vec<common_enums::BlocklistTransactionType>,}impl ApiEventMetric for BlocklistCountQuery {}@@ -127,6 +154,7 @@ impl ApiEventMetric for BlocklistLookupQuery {}impl ApiEventMetric for BlocklistLookupResponse {}impl ApiEventMetric for BlocklistRequest {}+impl ApiEventMetric for BlocklistEntryRequest {}impl ApiEventMetric for BlocklistResponse {}impl ApiEventMetric for ListBlocklistResponse {}impl ApiEventMetric for ToggleBlocklistResponse {}@@ -149,6 +177,13 @@ pub struct BlocklistRowError {pub reason: String,}+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct BatchBlocklistUploadQuery {+ /// Overrides every CSV row when selected; omission preserves row selections.+ #[schema(value_type = Option<BlocklistTransactionType>)]+ pub transaction_type: Option<common_enums::BlocklistTransactionType>,+}+/// Response returned on a successful `POST /blocklist/batch`.#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]pub struct BatchBlocklistUploadResponse {@@ -222,6 +257,14 @@ pub struct ListBatchBlocklistJobsResponse {// ---- Blocklist CSV export types ----+/// Query parameters for `POST /blocklist/export`.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct BlocklistExportQuery {+ /// Exports only `payment` or `payout` entries when selected. Omission exports both.+ #[schema(value_type = Option<BlocklistTransactionType>)]+ pub transaction_type: Option<common_enums::BlocklistTransactionType>,+}+/// Response for `POST /blocklist/export`.#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]pub struct BlocklistExportResponse {@@ -233,11 +276,13 @@ pub struct BlocklistExportResponse {pub file_name: String,}+impl ApiEventMetric for BatchBlocklistUploadQuery {}impl ApiEventMetric for BatchBlocklistUploadResponse {}impl ApiEventMetric for BatchBlocklistJobStatusResponse {}impl ApiEventMetric for ListBatchBlocklistJobsQuery {}impl ApiEventMetric for ListBatchBlocklistJobsResponse {}impl ApiEventMetric for BlocklistExportResponse {}+impl ApiEventMetric for BlocklistExportQuery {}/// Progress of a profile-clone job across its target profiles.#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]@@ -262,6 +307,9 @@ pub struct ProfileCloneTargetMetadata {pub struct CloneBlocklistEntriesRequest {#[schema(value_type = Vec<String>)]pub target_profile_ids: HashSet<common_utils::id_type::ProfileId>,+ /// Clones only the selected namespace. Omission clones both payment and payout.+ #[schema(value_type = Option<BlocklistTransactionType>)]+ pub transaction_type: Option<common_enums::BlocklistTransactionType>,}impl CloneBlocklistEntriesRequest {@@ -295,3 +343,156 @@ pub struct CloneBlocklistEntriesResponse {impl ApiEventMetric for CloneBlocklistEntriesRequest {}impl ApiEventMetric for CloneBlocklistEntriesResponse {}++#[cfg(test)]+mod tests {+ use common_enums::BlocklistTransactionType;+ use serde_json::json;++ use super::{+ BlocklistCountQuery, BlocklistEntryRequest, BlocklistLookupQuery,+ CloneBlocklistEntriesRequest, ListBlocklistQuery,+ };++ #[test]+ fn omitted_selection_preserves_management_scopes() {+ let single: BlocklistEntryRequest =+ serde_json::from_value(json!({"type": "generic_card_bin", "data": "424242"})).unwrap();+ let list: ListBlocklistQuery =+ serde_json::from_value(json!({"data_kind": "generic_card_bin"})).unwrap();+ let count: BlocklistCountQuery =+ serde_json::from_value(json!({"data_kind": "generic_card_bin"})).unwrap();+ let lookup: BlocklistLookupQuery =+ serde_json::from_value(json!({"data": "424242"})).unwrap();++ assert_eq!(single.transaction_type, BlocklistTransactionType::Payment);+ assert_eq!(list.transaction_type, BlocklistTransactionType::Payment);+ assert_eq!(count.transaction_type, None);+ assert_eq!(lookup.transaction_type, None);+ }++ #[test]+ fn payout_selection_is_retained_by_management_requests_and_queries() {+ let single: BlocklistEntryRequest = serde_json::from_value(+ json!({"type": "generic_card_bin", "data": "424242", "transaction_type": "payout"}),+ )+ .unwrap();+ let list: ListBlocklistQuery = serde_json::from_value(+ json!({"data_kind": "generic_card_bin", "transaction_type": "payout"}),+ )+ .unwrap();+ let count: BlocklistCountQuery = serde_json::from_value(+ json!({"data_kind": "generic_card_bin", "transaction_type": "payout"}),+ )+ .unwrap();+ let lookup: BlocklistLookupQuery =+ serde_json::from_value(json!({"data": "424242", "transaction_type": "payout"}))+ .unwrap();++ assert_eq!(single.transaction_type, BlocklistTransactionType::Payout);+ assert_eq!(list.transaction_type, BlocklistTransactionType::Payout);+ assert_eq!(+ count.transaction_type,+ Some(BlocklistTransactionType::Payout)+ );+ assert_eq!(+ lookup.transaction_type,+ Some(BlocklistTransactionType::Payout)+ );+ }++ #[test]+ fn payment_selection_is_retained_by_count_query() {+ let count: BlocklistCountQuery = serde_json::from_value(+ json!({"data_kind": "generic_card_bin", "transaction_type": "payment"}),+ )+ .unwrap();++ assert_eq!(+ count.transaction_type,+ Some(BlocklistTransactionType::Payment)+ );+ }++ #[test]+ fn unsupported_selection_is_rejected_instead_of_defaulting() {+ for selection in ["three_ds_authentication", "unknown", ""] {+ assert!(serde_json::from_value::<BlocklistEntryRequest>(+ json!({"type": "generic_card_bin", "data": "424242", "transaction_type": selection}),+ )+ .is_err());+ assert!(serde_json::from_value::<ListBlocklistQuery>(+ json!({"data_kind": "generic_card_bin", "transaction_type": selection}),+ )+ .is_err());+ assert!(serde_json::from_value::<BlocklistCountQuery>(+ json!({"data_kind": "generic_card_bin", "transaction_type": selection}),+ )+ .is_err());+ assert!(serde_json::from_value::<BlocklistLookupQuery>(+ json!({"data": "424242", "transaction_type": selection}),+ )+ .is_err());+ assert!(serde_json::from_value::<CloneBlocklistEntriesRequest>(+ json!({"target_profile_ids": ["pro_target"], "transaction_type": selection}),+ )+ .is_err());+ }+ }++ #[test]+ fn legacy_single_entry_bodies_preserve_all_tagged_kinds_and_data() {+ for (kind, data) in [+ ("card_bin", "424242"),+ ("extended_card_bin", "42424242"),+ ("generic_card_bin", "4242424242"),+ ("fingerprint", "fingerprint_123"),+ ] {+ let legacy_body = json!({"type": kind, "data": data});+ let request: BlocklistEntryRequest =+ serde_json::from_value(legacy_body.clone()).unwrap();++ assert_eq!(request.transaction_type, BlocklistTransactionType::Payment);+ assert_eq!(serde_json::to_value(&request.entry).unwrap(), legacy_body);++ let payout_body = json!({+ "type": kind,+ "data": data,+ "transaction_type": "payout",+ });+ let request: BlocklistEntryRequest =+ serde_json::from_value(payout_body.clone()).unwrap();++ assert_eq!(request.transaction_type, BlocklistTransactionType::Payout);+ assert_eq!(serde_json::to_value(&request.entry).unwrap(), legacy_body);+ assert_eq!(serde_json::to_value(&request).unwrap(), payout_body);+ }+ }++ #[test]+ fn malformed_single_entry_bodies_are_rejected() {+ for body in [+ json!({}),+ json!({"data": "424242"}),+ json!({"type": "unknown", "data": "424242"}),+ json!({"entry": {"type": "generic_card_bin", "data": "424242"}}),+ ] {+ assert!(serde_json::from_value::<BlocklistEntryRequest>(body).is_err());+ }++ for kind in [+ "card_bin",+ "extended_card_bin",+ "generic_card_bin",+ "fingerprint",+ ] {+ let missing_data = json!({"type": kind});+ assert!(serde_json::from_value::<BlocklistEntryRequest>(missing_data).is_err());++ for data in [json!(null), json!(424242), json!([]), json!({})] {+ let body = json!({"type": kind, "data": data});+ assert!(serde_json::from_value::<BlocklistEntryRequest>(body).is_err());+ }+ }+ }+}diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex 9655cac56a..86578dd2fc 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -12392,6 +12392,29 @@ pub enum VaultEnv {Live,}+/// The transaction namespace of a blocklist entry, stored as text.+#[derive(+ Clone,+ Copy,+ Debug,+ Default,+ Eq,+ PartialEq,+ serde::Deserialize,+ serde::Serialize,+ strum::Display,+ strum::EnumString,+ ToSchema,+)]+#[router_derive::diesel_enum(storage_type = "text")]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum BlocklistTransactionType {+ #[default]+ Payment,+ Payout,+}+#[derive(Clone,Copy,diff --git a/crates/diesel_models/drop_id.patch b/crates/diesel_models/drop_id.patchindex c2cedabb3f..6c38a0f43e 100644--- a/crates/diesel_models/drop_id.patch+++ b/crates/diesel_models/drop_id.patch@@ -2,7 +2,7 @@ diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schemindex b35e809a0..749a5dd47 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs-@@ -142,14 +142,34 @@ diesel::table! {+@@ -142,14 +142,35 @@ diesel::table! {}diesel::table! {@@ -25,6 +25,7 @@ index b35e809a0..749a5dd47 100644+ created_by -> Nullable<Varchar>,+ #[max_length = 64]+ profile_id -> Nullable<Varchar>,++ transaction_type -> Nullable<Text>,+ }+}+@@ -39,7 +40,7 @@ index b35e809a0..749a5dd47 100644fingerprint_id -> Varchar,data_kind -> BlocklistDataKind,encrypted_fingerprint -> Text,-@@ -158,14 +178,13 @@ diesel::table! {+@@ -158,14 +179,13 @@ diesel::table! {}diesel::table! {@@ -55,7 +56,7 @@ index b35e809a0..749a5dd47 100644}}-@@ -300,13 +319,12 @@ diesel::table! {+@@ -300,13 +320,12 @@ diesel::table! {diesel::table! {use diesel::sql_types::*;@@ -69,7 +70,7 @@ index b35e809a0..749a5dd47 100644}}-@@ -615,14 +633,13 @@ diesel::table! {+@@ -615,14 +634,13 @@ diesel::table! {}diesel::table! {@@ -85,7 +86,7 @@ index b35e809a0..749a5dd47 100644external_id -> Varchar,#[max_length = 255]card_fingerprint -> Varchar,-@@ -1982,6 +1999,7 @@+@@ -1982,6 +2000,7 @@api_keys,authentication,batch_blocklist_jobs,diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rsindex e9bde1a382..bb2f7f57db 100644--- a/crates/diesel_models/src/blocklist.rs+++ b/crates/diesel_models/src/blocklist.rs@@ -14,6 +14,7 @@ pub struct BlocklistNew {pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub created_by: Option<String>,pub profile_id: Option<common_utils::id_type::ProfileId>,+ pub transaction_type: common_enums::BlocklistTransactionType,}#[derive(@@ -29,4 +30,5 @@ pub struct Blocklist {pub processor_merchant_id: Option<common_utils::id_type::MerchantId>,pub created_by: Option<String>,pub profile_id: Option<common_utils::id_type::ProfileId>,+ pub transaction_type: Option<common_enums::BlocklistTransactionType>,}diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rsindex 4b61c31d97..0eab77330b 100644--- a/crates/diesel_models/src/query/blocklist.rs+++ b/crates/diesel_models/src/query/blocklist.rs@@ -57,12 +57,8 @@ impl BlocklistNew {) -> StorageResult<usize> {let query = diesel::insert_into(<Blocklist as HasTable>::table()).values(entries)- .on_conflict((- dsl::processor_merchant_id,- dsl::profile_id,- dsl::fingerprint_id,- ))- .do_nothing();+ // Legacy and NULL-profile rows use different unique indexes from processor/profile rows.+ .on_conflict_do_nothing();generics::db_metrics::track_database_call::<<Blocklist as HasTable>::Table, _, _>(conn.request_id(),@@ -78,23 +74,127 @@ impl BlocklistNew {}impl Blocklist {- pub async fn find_by_processor_merchant_id_fingerprint_id(+ // Legacy NULL transaction namespaces match payment, never payout.++ pub async fn find_by_processor_merchant_id_fingerprint_id_for_payment(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ )+ .await+ }+ pub async fn find_by_processor_merchant_id_fingerprint_id_for_payout(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,fingerprint_id: &str,) -> StorageResult<Self> {generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }+ /// Returns payment and legacy NULL-namespace fingerprint rows for the resolved profile+ /// and merchant-wide entries.+ pub async fn list_by_processor_merchant_id_profile_id_fingerprint_id_for_payment(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (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())))+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ None,+ None,+ None::<dsl::created_at>,+ )+ .await+ }+ pub async fn list_by_processor_merchant_id_profile_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (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())))+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ None,+ None,+ None::<dsl::created_at>,+ )+ .await+ }+ pub async fn list_all_by_processor_merchant_id_profile_id_fingerprint_id(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(conn,dsl::processor_merchant_id.eq(processor_merchant_id.to_owned())- .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())),+ .or(dsl::processor_merchant_id+ .is_null()+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned())))+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ),+ None,+ None,+ None::<dsl::created_at>,).await}-// Rows written before profile scoping have a NULL profile_id and block the whole merchant,// so they must keep matching every profile.- pub async fn find_by_processor_merchant_id_profile_id_fingerprint_id(++ pub async fn find_by_processor_merchant_id_profile_id_fingerprint_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -102,19 +202,45 @@ impl Blocklist {) -> StorageResult<Self> {generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn,- dsl::processor_merchant_id+ (dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()).and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())).and(dsl::profile_id.eq(profile_id.to_owned()).or(dsl::profile_id.is_null()),- ),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),).await}- pub async fn find_by_processor_merchant_id_profile_id_fingerprint_ids(+ pub async fn find_by_processor_merchant_id_profile_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }++ pub async fn find_by_processor_merchant_id_profile_id_fingerprint_ids_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -122,7 +248,7 @@ impl Blocklist {) -> StorageResult<Option<Self>> {generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(conn,- dsl::processor_merchant_id+ (dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()).or(dsl::processor_merchant_id.is_null()@@ -132,17 +258,45 @@ impl Blocklist {dsl::profile_id.eq(profile_id.to_owned()).or(dsl::profile_id.is_null()),- ),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),).await}+ pub async fn find_by_processor_merchant_id_profile_id_fingerprint_ids_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_ids: Vec<String>,+ ) -> StorageResult<Option<Self>> {+ generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(+ conn,+ (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())))+ .and(dsl::fingerprint_id.eq_any(fingerprint_ids))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }/// Batched BIN-only lookup: all BIN-kind blocklist entries for this merchant/profile whose/// stored BIN is in `card_bins`. PAN-fingerprint entries (`data_kind = payment_method`) are/// excluded — they hold vault HMACs of full card numbers, which cannot be matched from a/// BIN. Uses the same processor-merchant-with-legacy-fallback and profile-or-merchant-wide/// predicates as the single-entry lookups.- pub async fn find_by_processor_merchant_id_profile_id_card_bins(+ pub async fn find_by_processor_merchant_id_profile_id_card_bins_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -150,7 +304,7 @@ impl Blocklist {) -> StorageResult<Vec<Self>> {generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(conn,- dsl::processor_merchant_id+ (dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()).or(dsl::processor_merchant_id.is_null()@@ -163,7 +317,12 @@ impl Blocklist {dsl::profile_id.eq(profile_id.to_owned()).or(dsl::profile_id.is_null()),- ),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),None,None,Some(dsl::created_at.desc()),@@ -171,22 +330,72 @@ impl Blocklist {.await}+ pub async fn find_by_processor_merchant_id_profile_id_card_bins_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ card_bins: Vec<String>,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (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())))+ .and(dsl::data_kind.eq_any(equivalent_data_kinds(+ common_enums::BlocklistDataKind::GenericCardBin,+ )))+ .and(dsl::fingerprint_id.eq_any(card_bins))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ None,+ None,+ Some(dsl::created_at.desc()),+ )+ .await+ }// Fallback function for stagger release - finds by merchant_id when processor_merchant_id is NULL- pub async fn find_by_merchant_id_fingerprint_id(++ pub async fn find_by_merchant_id_fingerprint_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,fingerprint_id: &str,) -> StorageResult<Self> {generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn,- dsl::merchant_id+ (dsl::merchant_id.eq(processor_merchant_id.to_owned())- .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())),+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),).await}- pub async fn find_by_merchant_id_profile_id_fingerprint_id(+ pub async fn find_by_merchant_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }++ pub async fn find_by_merchant_id_profile_id_fingerprint_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -194,19 +403,45 @@ impl Blocklist {) -> StorageResult<Self> {generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn,- dsl::merchant_id+ (dsl::merchant_id.eq(processor_merchant_id.to_owned()).and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())).and(dsl::profile_id.eq(profile_id.to_owned()).or(dsl::profile_id.is_null()),- ),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ )+ .await+ }++ pub async fn find_by_merchant_id_profile_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),).await}- pub async fn list_by_processor_merchant_id_data_kind(+ pub async fn list_by_processor_merchant_id_data_kind_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,data_kind: common_enums::BlocklistDataKind,@@ -216,12 +451,41 @@ impl Blocklist {let data_kinds = equivalent_data_kinds(data_kind);generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(conn,- dsl::processor_merchant_id+ (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())))+ .and(dsl::data_kind.eq_any(data_kinds)))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ Some(limit),+ Some(offset),+ Some(dsl::created_at.desc()),+ )+ .await+ }++ pub async fn list_by_processor_merchant_id_data_kind_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ data_kind: common_enums::BlocklistDataKind,+ limit: i64,+ offset: i64,+ ) -> StorageResult<Vec<Self>> {+ let data_kinds = equivalent_data_kinds(data_kind);+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (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())))- .and(dsl::data_kind.eq_any(data_kinds)),+ .and(dsl::data_kind.eq_any(data_kinds)))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),Some(limit),Some(offset),Some(dsl::created_at.desc()),@@ -229,7 +493,7 @@ impl Blocklist {.await}- pub async fn list_by_processor_merchant_id_profile_id_data_kind(+ pub async fn list_by_processor_merchant_id_profile_id_data_kind_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -240,7 +504,7 @@ impl Blocklist {let data_kinds = equivalent_data_kinds(data_kind);generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(conn,- dsl::processor_merchant_id+ (dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()).or(dsl::processor_merchant_id.is_null()@@ -250,7 +514,12 @@ impl Blocklist {dsl::profile_id.eq(profile_id.to_owned()).or(dsl::profile_id.is_null()),- ),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),Some(limit),Some(offset),Some(dsl::created_at.desc()),@@ -258,12 +527,83 @@ impl Blocklist {.await}- pub async fn get_count_by_processor_merchant_id_data_kind(+ pub async fn list_by_processor_merchant_id_profile_id_data_kind_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ data_kind: common_enums::BlocklistDataKind,+ limit: i64,+ offset: i64,+ ) -> StorageResult<Vec<Self>> {+ let data_kinds = equivalent_data_kinds(data_kind);+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (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())))+ .and(dsl::data_kind.eq_any(data_kinds))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ Some(limit),+ Some(offset),+ Some(dsl::created_at.desc()),+ )+ .await+ }++ pub async fn get_count_by_processor_merchant_id_data_kind_for_payment(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ data_kind: common_enums::BlocklistDataKind,+ ) -> StorageResult<usize> {+ let data_kinds = equivalent_data_kinds(data_kind);+ generics::generic_count::<<Self as HasTable>::Table, _>(+ conn,+ (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())))+ .and(dsl::data_kind.eq_any(data_kinds)))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ )+ .await+ }++ pub async fn get_count_by_processor_merchant_id_data_kind_for_payout(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,data_kind: common_enums::BlocklistDataKind,) -> StorageResult<usize> {let data_kinds = equivalent_data_kinds(data_kind);+ generics::generic_count::<<Self as HasTable>::Table, _>(+ conn,+ (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())))+ .and(dsl::data_kind.eq_any(data_kinds)))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }++ pub async fn get_all_count_by_processor_merchant_id_data_kind(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ data_kind: common_enums::BlocklistDataKind,+ ) -> StorageResult<usize> {generics::generic_count::<<Self as HasTable>::Table, _>(conn,dsl::processor_merchant_id@@ -271,18 +611,17 @@ impl Blocklist {.or(dsl::processor_merchant_id.is_null().and(dsl::merchant_id.eq(processor_merchant_id.to_owned())))- .and(dsl::data_kind.eq_any(data_kinds)),+ .and(dsl::data_kind.eq_any(equivalent_data_kinds(data_kind))),).await}- pub async fn get_count_by_processor_merchant_id_profile_id_data_kind(+ pub async fn get_all_count_by_processor_merchant_id_profile_id_data_kind(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,) -> StorageResult<usize> {- let data_kinds = equivalent_data_kinds(data_kind);generics::generic_count::<<Self as HasTable>::Table, _>(conn,dsl::processor_merchant_id@@ -290,7 +629,7 @@ impl Blocklist {.or(dsl::processor_merchant_id.is_null().and(dsl::merchant_id.eq(processor_merchant_id.to_owned())))- .and(dsl::data_kind.eq_any(data_kinds))+ .and(dsl::data_kind.eq_any(equivalent_data_kinds(data_kind))).and(dsl::profile_id.eq(profile_id.to_owned())@@ -300,13 +639,148 @@ impl Blocklist {.await}- pub async fn count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(+ pub async fn get_count_by_processor_merchant_id_profile_id_data_kind_for_payment(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ data_kind: common_enums::BlocklistDataKind,+ ) -> StorageResult<usize> {+ let data_kinds = equivalent_data_kinds(data_kind);+ generics::generic_count::<<Self as HasTable>::Table, _>(+ conn,+ (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())))+ .and(dsl::data_kind.eq_any(data_kinds))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ )+ .await+ }++ pub async fn get_count_by_processor_merchant_id_profile_id_data_kind_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ data_kind: common_enums::BlocklistDataKind,+ ) -> StorageResult<usize> {+ let data_kinds = equivalent_data_kinds(data_kind);+ generics::generic_count::<<Self as HasTable>::Table, _>(+ conn,+ (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())))+ .and(dsl::data_kind.eq_any(data_kinds))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }++ pub async fn count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,) -> StorageResult<Vec<(i32, i64)>> {let data_kinds = equivalent_data_kinds(data_kind);+ let result = {+ let query = <Self as HasTable>::table()+ .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())))+ .and(dsl::data_kind.eq_any(data_kinds))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ )+ .group_by(fingerprint_length())+ .select((fingerprint_length(), count_star()));+ generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(+ conn.request_id(),+ conn.event_emitter(),+ generics::db_metrics::DatabaseOperation::Count,+ query.get_results_async(conn.raw_connection()),+ )+ .await+ };+ result+ .map_err(|e| error_stack::report!(e))+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Failed to count blocklist entries by fingerprint length")+ }++ pub async fn count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ data_kind: common_enums::BlocklistDataKind,+ ) -> StorageResult<Vec<(i32, i64)>> {+ let data_kinds = equivalent_data_kinds(data_kind);+ let result = {+ let query = <Self as HasTable>::table()+ .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())))+ .and(dsl::data_kind.eq_any(data_kinds))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .group_by(fingerprint_length())+ .select((fingerprint_length(), count_star()));+ generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(+ conn.request_id(),+ conn.event_emitter(),+ generics::db_metrics::DatabaseOperation::Count,+ query.get_results_async(conn.raw_connection()),+ )+ .await+ };+ result+ .map_err(|e| error_stack::report!(e))+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Failed to count blocklist entries by fingerprint length")+ }++ pub async fn count_all_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ data_kind: common_enums::BlocklistDataKind,+ ) -> StorageResult<Vec<(i32, i64)>> {let query = <Self as HasTable>::table().filter(dsl::processor_merchant_id@@ -314,7 +788,7 @@ impl Blocklist {.or(dsl::processor_merchant_id.is_null().and(dsl::merchant_id.eq(processor_merchant_id.to_owned())))- .and(dsl::data_kind.eq_any(data_kinds))+ .and(dsl::data_kind.eq_any(equivalent_data_kinds(data_kind))).and(dsl::profile_id.eq(profile_id.to_owned())@@ -323,7 +797,6 @@ impl Blocklist {).group_by(fingerprint_length()).select((fingerprint_length(), count_star()));-generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(conn.request_id(),conn.event_emitter(),@@ -336,17 +809,22 @@ impl Blocklist {.attach_printable("Failed to count blocklist entries by fingerprint length")}- pub async fn list_by_processor_merchant_id(+ pub async fn list_by_processor_merchant_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,) -> StorageResult<Vec<Self>> {generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(conn,- dsl::processor_merchant_id+ (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()))),+ .and(dsl::merchant_id.eq(processor_merchant_id.to_owned()))))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),None,None,Some(dsl::created_at.desc()),@@ -354,7 +832,85 @@ impl Blocklist {.await}- pub async fn list_after_fingerprint_by_processor_merchant_id_profile_id(+ pub async fn list_by_processor_merchant_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (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()))))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ None,+ None,+ Some(dsl::created_at.desc()),+ )+ .await+ }++ pub async fn list_after_fingerprint_by_processor_merchant_id_profile_id_for_payment(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.gt(after_fingerprint_id))+ .and(dsl::created_at.le(snapshot_at))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ Some(limit),+ None,+ Some(dsl::fingerprint_id.asc()),+ )+ .await+ }++ pub async fn list_after_fingerprint_by_processor_merchant_id_profile_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.gt(after_fingerprint_id))+ .and(dsl::created_at.le(snapshot_at))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ Some(limit),+ None,+ Some(dsl::fingerprint_id.asc()),+ )+ .await+ }++ /// Clones all transaction types; used when no type filter is requested.+ pub async fn list_all_after_fingerprint_by_processor_merchant_id_profile_id(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -380,7 +936,68 @@ impl Blocklist {.await}- pub async fn list_after_fingerprint_by_legacy_merchant_id_profile_id(+ pub async fn list_after_fingerprint_by_legacy_merchant_id_profile_id_for_payment(+ conn: &DatabaseConnectionWithContext<'_>,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::processor_merchant_id.is_null())+ .and(dsl::fingerprint_id.gt(after_fingerprint_id))+ .and(dsl::created_at.le(snapshot_at))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ Some(limit),+ None,+ Some(dsl::fingerprint_id.asc()),+ )+ .await+ }++ pub async fn list_after_fingerprint_by_legacy_merchant_id_profile_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> StorageResult<Vec<Self>> {+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(+ conn,+ (dsl::merchant_id+ .eq(merchant_id.to_owned())+ .and(dsl::processor_merchant_id.is_null())+ .and(dsl::fingerprint_id.gt(after_fingerprint_id))+ .and(dsl::created_at.le(snapshot_at))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ Some(limit),+ None,+ Some(dsl::fingerprint_id.asc()),+ )+ .await+ }++ /// Clones all transaction types from legacy rows; used when no type filter is requested.+ pub async fn list_all_after_fingerprint_by_legacy_merchant_id_profile_id(conn: &DatabaseConnectionWithContext<'_>,merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -407,21 +1024,41 @@ impl Blocklist {.await}- pub async fn delete_by_processor_merchant_id_fingerprint_id(+ pub async fn delete_by_processor_merchant_id_fingerprint_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,fingerprint_id: &str,) -> StorageResult<Self> {generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn,- dsl::processor_merchant_id+ (dsl::processor_merchant_id.eq(processor_merchant_id.to_owned())- .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())),+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),).await}- pub async fn delete_by_processor_merchant_id_profile_id_fingerprint_id(+ pub async fn delete_by_processor_merchant_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }++ pub async fn delete_by_processor_merchant_id_profile_id_fingerprint_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -429,34 +1066,80 @@ impl Blocklist {) -> StorageResult<Self> {generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn,- dsl::processor_merchant_id+ (dsl::processor_merchant_id.eq(processor_merchant_id.to_owned()).and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())).and(dsl::profile_id.eq(profile_id.to_owned()).or(dsl::profile_id.is_null()),- ),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),).await}+ pub async fn delete_by_processor_merchant_id_profile_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::processor_merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }// Fallback function for stagger release - deletes by merchant_id when processor_merchant_id is NULL- pub async fn delete_by_merchant_id_fingerprint_id(++ pub async fn delete_by_merchant_id_fingerprint_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,fingerprint_id: &str,) -> StorageResult<Self> {generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn,- dsl::merchant_id+ (dsl::merchant_id.eq(processor_merchant_id.to_owned())- .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())),+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),).await}- pub async fn delete_by_merchant_id_profile_id_fingerprint_id(+ pub async fn delete_by_merchant_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),+ )+ .await+ }++ pub async fn delete_by_merchant_id_profile_id_fingerprint_id_for_payment(conn: &DatabaseConnectionWithContext<'_>,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -464,14 +1147,40 @@ impl Blocklist {) -> StorageResult<Self> {generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn,- dsl::merchant_id+ (dsl::merchant_id.eq(processor_merchant_id.to_owned()).and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())).and(dsl::profile_id.eq(profile_id.to_owned()).or(dsl::profile_id.is_null()),- ),+ ))+ .and(+ dsl::transaction_type+ .eq(common_enums::BlocklistTransactionType::Payment)+ .or(dsl::transaction_type.is_null()),+ ),+ )+ .await+ }++ pub async fn delete_by_merchant_id_profile_id_fingerprint_id_for_payout(+ conn: &DatabaseConnectionWithContext<'_>,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> StorageResult<Self> {+ generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(+ conn,+ (dsl::merchant_id+ .eq(processor_merchant_id.to_owned())+ .and(dsl::fingerprint_id.eq(fingerprint_id.to_owned()))+ .and(+ dsl::profile_id+ .eq(profile_id.to_owned())+ .or(dsl::profile_id.is_null()),+ ))+ .and(dsl::transaction_type.eq(common_enums::BlocklistTransactionType::Payout)),).await}diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 6a100eeec2..e7e198fe8e 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -234,6 +234,7 @@ diesel::table! {created_by -> Nullable<Varchar>,#[max_length = 64]profile_id -> Nullable<Varchar>,+ transaction_type -> Nullable<Text>,}}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 19d800c5cc..b7bbb0509f 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -1049,6 +1049,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::offer_engine::BrowseOffersResponse,api_models::offer_engine::BrowseOffer,api_models::blocklist::BlocklistRequest,+ api_models::blocklist::BlocklistEntryRequest,api_models::blocklist::BlocklistResponse,api_models::blocklist::ToggleBlocklistResponse,api_models::blocklist::ListBlocklistQuery,@@ -1057,9 +1058,11 @@ Never share your secret api keys. Keep them guarded and secure.api_models::blocklist::BlocklistLookupQuery,api_models::blocklist::BlocklistLookupResponse,api_models::blocklist::BatchBlocklistUploadResponse,+ api_models::blocklist::BatchBlocklistUploadQuery,api_models::blocklist::BatchBlocklistJobStatusResponse,api_models::blocklist::ListBatchBlocklistJobsResponse,api_models::blocklist::BlocklistRowError,+ api_models::blocklist::BlocklistExportQuery,api_models::blocklist::BlocklistExportResponse,api_models::blocklist::CloneBlocklistEntriesRequest,api_models::blocklist::CloneBlocklistEntriesResponse,@@ -1068,6 +1071,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::enums::BatchBlocklistJobStatus,api_models::enums::BatchBlocklistJobType,api_models::enums::BlocklistDataKind,+ api_models::enums::BlocklistTransactionType,api_models::enums::ErrorCategory,api_models::webhook_events::EventListConstraints,api_models::webhook_events::EventListItemResponse,diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rsindex 457afb0c09..8cb791f0a0 100644--- a/crates/openapi/src/openapi_v2.rs+++ b/crates/openapi/src/openapi_v2.rs@@ -939,6 +939,7 @@ Never share your secret api keys. Keep them guarded and secure.api_models::blocklist::ToggleBlocklistResponse,api_models::blocklist::ListBlocklistQuery,api_models::enums::BlocklistDataKind,+ api_models::enums::BlocklistTransactionType,api_models::enums::ErrorCategory,api_models::webhook_events::EventListItemResponse,api_models::webhook_events::EventRetrieveResponse,diff --git a/crates/openapi/src/routes/blocklist.rs b/crates/openapi/src/routes/blocklist.rsindex f6b040c312..f5bbe7e2db 100644--- a/crates/openapi/src/routes/blocklist.rs+++ b/crates/openapi/src/routes/blocklist.rs@@ -3,6 +3,7 @@path = "/blocklist/count",params (("data_kind" = BlocklistDataKind, Query, description = "Kind of blocklist entries to count"),+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Counts only payment or payout when selected. When omitted, counts both, including legacy NULL entries. Legacy NULL entries belong to payment when filtered."),("X-Profile-Id" = Option<String>, Header, description = "Restricts the count to entries \belonging to this business profile, plus entries with no profile. If omitted, the \merchant's default profile is used; merchants with more than one profile have no default \@@ -30,6 +31,7 @@ pub async fn get_blocklist_count() {}path = "/blocklist/lookup",params (("data" = String, Query, description = "The raw value to check against the blocklist, e.g. a card BIN"),+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Looks up only payment or payout when selected. When omitted, both are included. Legacy NULL transaction namespaces belong to payment."),("X-Profile-Id" = Option<String>, Header, description = "Restricts the lookup to entries \belonging to this business profile, plus entries with no profile. If omitted, the \merchant's default profile is used; merchants with more than one profile have no default \@@ -43,7 +45,7 @@ pub async fn get_blocklist_count() {})),responses(- (status = 200, description = "Blocklist lookup result", body = BlocklistLookupResponse),+ (status = 200, description = "All matches within the resolved profile, including merchant-wide entries. transaction_types contains distinct matching payment/payout namespaces, without data kinds or profile IDs.", body = BlocklistLookupResponse),(status = 400, description = "Invalid Data, or no profile could be resolved")),tag = "Blocklist",@@ -78,7 +80,7 @@ pub async fn toggle_blocklist_guard() {}#[utoipa::path(post,path = "/blocklist",- request_body = BlocklistRequest,+ request_body = BlocklistEntryRequest,params (("X-Profile-Id" = Option<String>, Header, description = "The business profile to block this \entry under. Ignored when authenticating with a JWT, which carries its own profile. If \@@ -105,7 +107,7 @@ pub async fn add_entry_to_blocklist() {}#[utoipa::path(delete,path = "/blocklist",- request_body = BlocklistRequest,+ request_body = BlocklistEntryRequest,params (("X-Profile-Id" = Option<String>, Header, description = "The business profile to unblock \this entry from. Only entries belonging to that profile, or entries with no profile, are \@@ -135,6 +137,7 @@ pub async fn remove_entry_from_blocklist() {}path = "/blocklist",params (("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Blocklist flow: payment (default) or payout."),("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to entries \belonging to this business profile, plus entries with no profile. When no profile can be \resolved - as with publishable-key authentication - all of the merchant's entries are \@@ -165,12 +168,15 @@ pub async fn list_blocked_payment_methods() {}content_type = "multipart/form-data",description = "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). \The part's `filename` is recorded on the job and returned as `file_name`. \- The CSV must have a header row: `type,data,metadata`. \- `type`: one of `generic_card_bin` (6 to 10 digits), `fingerprint`. \+ The CSV header is `type,data,metadata,transaction_type`; older headers without `transaction_type` are accepted. \+ `type`: one of `generic_card_bin` (6 to 10 digits), `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. \`metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \+ `transaction_type`: optional, `payment` (default) or `payout`; selection may differ per row. \+ Invalid CSV transaction-type values are rejected even when a query override is selected. \Maximum 100,000 data rows.",),params (+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Overrides every CSV row with payment or payout when selected. When omitted, row selections are used; missing or empty row values default to payment."),("X-Profile-Id" = Option<String>, Header, description = "The business profile every entry \in this upload is blocked under. Resolution follows the same rules as blocking a single \entry."),@@ -252,6 +258,8 @@ pub async fn list_batch_blocklist_jobs() {}post,path = "/blocklist/export",params (+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Exports only \+ `payment` or `payout` entries when selected. Both are exported when omitted."),("X-Profile-Id" = Option<String>, Header, description = "The business profile whose \blocklist is exported. Resolution follows the same rules as blocking a single entry."),(@@ -264,7 +272,7 @@ pub async fn list_batch_blocklist_jobs() {}),responses((status = 202, description = "Blocklist export started", body = BlocklistExportResponse),- (status = 400, description = "No profile could be resolved"),+ (status = 400, description = "Invalid transaction type, or no profile could be resolved"),),tag = "Blocklist",operation_id = "Start a blocklist CSV export",diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rsindex 6759923f2d..5349e66d4f 100644--- a/crates/router/src/core/blocklist.rs+++ b/crates/router/src/core/blocklist.rs@@ -17,9 +17,10 @@ pub async fn add_entry_to_blocklist(state: SessionState,platform: domain::Platform,profile_id: Option<common_utils::id_type::ProfileId>,+ transaction_type: common_enums::BlocklistTransactionType,body: api_blocklist::AddToBlocklistRequest,) -> RouterResponse<api_blocklist::AddToBlocklistResponse> {- utils::insert_entry_into_blocklist(&state, &platform, profile_id, body)+ utils::insert_entry_into_blocklist(&state, &platform, profile_id, transaction_type, body).await.map(services::ApplicationResponse::Json)}@@ -28,9 +29,10 @@ pub async fn remove_entry_from_blocklist(state: SessionState,processor: domain::Processor,profile_id: Option<common_utils::id_type::ProfileId>,+ transaction_type: common_enums::BlocklistTransactionType,body: api_blocklist::DeleteFromBlocklistRequest,) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> {- utils::delete_entry_from_blocklist(&state, &processor, profile_id, body)+ utils::delete_entry_from_blocklist(&state, &processor, profile_id, transaction_type, body).await.map(services::ApplicationResponse::Json)}@@ -89,10 +91,18 @@ pub async fn upload_batch_blocklist(profile_id: Option<common_utils::id_type::ProfileId>,csv_bytes: bytes::Bytes,file_name: Option<String>,+ transaction_type: Option<common_enums::BlocklistTransactionType>,) -> RouterResponse<api_blocklist::BatchBlocklistUploadResponse> {- batch::initiate_batch_blocklist_upload(&state, &platform, profile_id, csv_bytes, file_name)- .await- .map(services::ApplicationResponse::Json)+ batch::initiate_batch_blocklist_upload(+ &state,+ &platform,+ profile_id,+ csv_bytes,+ file_name,+ transaction_type,+ )+ .await+ .map(services::ApplicationResponse::Json)}pub async fn get_batch_blocklist_job_status(@@ -131,8 +141,9 @@ pub async fn create_blocklist_export(state: SessionState,platform: domain::Platform,profile_id: Option<common_utils::id_type::ProfileId>,+ transaction_type: Option<common_enums::BlocklistTransactionType>,) -> RouterResponse<api_blocklist::BlocklistExportResponse> {- export::initiate_blocklist_export(&state, &platform, profile_id)+ export::initiate_blocklist_export(&state, &platform, profile_id, transaction_type).await.map(services::ApplicationResponse::Json)}diff --git a/crates/router/src/core/blocklist/batch.rs b/crates/router/src/core/blocklist/batch.rsindex 07c957b90f..c170d4f658 100644--- a/crates/router/src/core/blocklist/batch.rs+++ b/crates/router/src/core/blocklist/batch.rs@@ -39,10 +39,11 @@ pub(crate) struct BlocklistRow {pub data_kind: common_enums::BlocklistDataKind,pub data: String,pub metadata: Option<serde_json::Value>,+ pub transaction_type: common_enums::BlocklistTransactionType,}/// Column order of the blocklist CSV, shared by import and export.-pub(crate) const CSV_HEADER: [&str; 3] = ["type", "data", "metadata"];+pub(crate) const CSV_HEADER: [&str; 4] = ["type", "data", "metadata", "transaction_type"];/// One row of the blocklist CSV, in both directions.#[derive(Debug, Serialize, Deserialize)]@@ -52,6 +53,8 @@ pub(crate) struct BlocklistCsvRecord {data: String,#[serde(default)]metadata: Option<String>,+ #[serde(default)]+ transaction_type: Option<common_enums::BlocklistTransactionType>,}impl BlocklistCsvRecord {@@ -61,6 +64,7 @@ impl BlocklistCsvRecord {data: row.data.clone(),metadata: Some(metadata_to_csv_field(row.metadata.as_ref())).filter(|metadata| !metadata.is_empty()),+ transaction_type: Some(row.transaction_type),}}@@ -70,6 +74,7 @@ impl BlocklistCsvRecord {data: entry.fingerprint_id.clone(),metadata: Some(metadata_to_csv_field(entry.metadata.as_ref())).filter(|metadata| !metadata.is_empty()),+ transaction_type: Some(entry.transaction_type.unwrap_or_default()),}}}@@ -137,14 +142,18 @@ impl BlocklistRow {)})?;+ let transaction_type = record.transaction_type.unwrap_or_default();+if data.is_empty() {- return Err(Self::build_row_error(+ Err(Self::build_row_error(row_index,parsed_kind,String::new(),"data field must not be empty",- ));- }+ ))+ } else {+ Ok(())+ }?;let is_invalid = super::utils::validate_bin(&data, parsed_kind).is_err();let format_error = match parsed_kind {@@ -161,34 +170,34 @@ impl BlocklistRow {};if let Some(reason) = format_error {- return Err(Self::build_row_error(+ Err(Self::build_row_error(row_index,parsed_kind,data.clone(),reason,- ));- }+ ))+ } else {+ Ok(())+ }?;let metadata_raw = record.metadata.as_deref().filter(|s| !s.is_empty());let metadata = match metadata_raw {None => None,- Some(s) => match parse_metadata(s) {- Some(m) => Some(m),- None => {- return Err(Self::build_row_error(- row_index,- parsed_kind,- data.clone(),- "metadata must be in key=value format, separated by semicolons (e.g. reason=fraud;source=manual)",- ));- }- },+ Some(s) => Some(parse_metadata(s).ok_or_else(|| {+ Self::build_row_error(+ row_index,+ parsed_kind,+ data.clone(),+ "metadata must be in key=value format, separated by semicolons (e.g. reason=fraud;source=manual)",+ )+ })?),};Ok(Self {data_kind: parsed_kind,data,metadata,+ transaction_type,})}}@@ -342,6 +351,7 @@ pub async fn initiate_batch_blocklist_upload(profile_id: Option<id_type::ProfileId>,csv_bytes: bytes::Bytes,file_name: Option<String>,+ transaction_type: Option<common_enums::BlocklistTransactionType>,) -> RouterResult<api_blocklist::BatchBlocklistUploadResponse> {let processor_merchant_id = platform.get_processor().get_account().get_id();let profile_id = core_utils::get_profile_from_business_details(@@ -393,9 +403,13 @@ pub async fn initiate_batch_blocklist_upload(let fs = state.file_storage_client.clone();async move {let key = key?;- let chunk_bytes = records_to_csv_bytes(- chunk_rows.iter().map(BlocklistCsvRecord::from_parsed_row),- )?;+ let chunk_bytes = records_to_csv_bytes(chunk_rows.iter().map(|row| {+ let mut record = BlocklistCsvRecord::from_parsed_row(row);+ if let Some(transaction_type) = transaction_type {+ record.transaction_type = Some(transaction_type);+ }+ record+ }))?;fs.upload_file(&key, chunk_bytes).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -512,6 +526,7 @@ pub(crate) async fn process_chunk(merchant_id: merchant_id.to_owned(),fingerprint_id: row.data.clone(),data_kind: row.data_kind,+ transaction_type: row.transaction_type,metadata: row.metadata.clone(),created_at: now,processor_merchant_id: processor_merchant_id.map(|id| id.to_owned()),@@ -680,3 +695,59 @@ pub async fn list_batch_blocklist_jobs(data,})}++#[cfg(test)]+mod tests {+ use common_enums::BlocklistTransactionType;++ use super::{parse_chunk_csv, parse_csv, records_to_csv_bytes, BlocklistCsvRecord};++ #[test]+ fn legacy_csv_and_in_flight_chunks_remain_payment_uploads() {+ let uploaded =+ parse_csv(b"type,data,metadata\ngeneric_card_bin,424242,reason=fraud\n").unwrap();+ let chunked = parse_chunk_csv(b"generic_card_bin,424242,reason=fraud\n").unwrap();+ for rows in [uploaded, chunked] {+ let row = rows.first().unwrap();+ assert_eq!(row.transaction_type, BlocklistTransactionType::Payment);+ assert_eq!(row.data, "424242");+ assert_eq!(row.metadata, Some(serde_json::json!({"reason": "fraud"})));+ }+ }++ #[test]+ fn mixed_upload_retains_each_flow_through_stored_chunks() {+ let rows = parse_csv(+ b"type,data,metadata,transaction_type\ngeneric_card_bin,424242,,payment\ngeneric_card_bin,424242,,payout\nfingerprint,fp_exact,,payout\n",+ )+ .unwrap();+ let chunks =+ records_to_csv_bytes(rows.iter().map(BlocklistCsvRecord::from_parsed_row)).unwrap();+ let restored = parse_chunk_csv(&chunks).unwrap();+ let identities = restored+ .iter()+ .map(|row| (row.data.as_str(), row.transaction_type))+ .collect::<Vec<_>>();+ assert_eq!(+ identities,+ vec![+ ("424242", BlocklistTransactionType::Payment),+ ("424242", BlocklistTransactionType::Payout),+ ("fp_exact", BlocklistTransactionType::Payout),+ ]+ );+ }++ #[test]+ fn explicit_invalid_flow_is_rejected_without_defaulting_to_payment() {+ for flow in ["three_ds_authentication", "unknown"] {+ let csv =+ format!("type,data,metadata,transaction_type\ngeneric_card_bin,424242,,{flow}\n");+ let error = parse_csv(csv.as_bytes()).unwrap_err();+ assert_eq!(error.row_index, 0);+ assert!(error.reason.contains(flow) || error.reason.contains("payment or payout"));+ let chunk = format!("generic_card_bin,424242,,{flow}\n");+ assert!(parse_chunk_csv(chunk.as_bytes()).is_err());+ }+ }+}diff --git a/crates/router/src/core/blocklist/clone.rs b/crates/router/src/core/blocklist/clone.rsindex 8fbd21ed05..d4fb928193 100644--- a/crates/router/src/core/blocklist/clone.rs+++ b/crates/router/src/core/blocklist/clone.rs@@ -91,7 +91,14 @@ pub async fn clone_blocklist_entries().await?;- let job_id = enqueue_clone_job(state, platform, &source_profile_id, &targets).await?;+ let job_id = enqueue_clone_job(+ state,+ platform,+ &source_profile_id,+ &targets,+ request.transaction_type,+ )+ .await?;Ok(api_blocklist::CloneBlocklistEntriesResponse {source_profile_id,@@ -109,6 +116,7 @@ async fn enqueue_clone_job(platform: &domain::Platform,source_profile_id: &id_type::ProfileId,targets: &[id_type::ProfileId],+ transaction_type: Option<common_enums::BlocklistTransactionType>,) -> RouterResult<String> {let processor_merchant_id = platform.get_processor().get_account().get_id();let job_id = common_utils::generate_id(crate::consts::ID_LENGTH, "blkclone");@@ -157,6 +165,7 @@ async fn enqueue_clone_job(current_target: 0,snapshot_at: now,draining_legacy_rows: false,+ selected_transaction_type: transaction_type,last_fingerprint_id: String::new(),processed_rows: 0,};@@ -232,5 +241,6 @@ pub(crate) fn to_target_entry(processor_merchant_id: entry.processor_merchant_id,created_by: entry.created_by,profile_id: Some(target_profile_id.clone()),+ transaction_type: entry.transaction_type.unwrap_or_default(),}}diff --git a/crates/router/src/core/blocklist/export.rs b/crates/router/src/core/blocklist/export.rsindex 7083914a43..4cdb9a6412 100644--- a/crates/router/src/core/blocklist/export.rs+++ b/crates/router/src/core/blocklist/export.rs@@ -74,6 +74,7 @@ pub async fn initiate_blocklist_export(state: &SessionState,platform: &domain::Platform,profile_id: Option<id_type::ProfileId>,+ transaction_type: Option<common_enums::BlocklistTransactionType>,) -> RouterResult<api_blocklist::BlocklistExportResponse> {let processor_merchant_id = platform.get_processor().get_account().get_id();let profile_id = core_utils::get_profile_from_business_details(@@ -117,6 +118,7 @@ pub async fn initiate_blocklist_export(merchant_id: platform.get_provider().get_account().get_id().clone(),processor_merchant_id: Some(processor_merchant_id.clone()),profile_id,+ transaction_type,snapshot_at: now,upload_id: None,};@@ -209,3 +211,52 @@ pub(crate) async fn presign_export_download(None => None,}}++#[cfg(test)]+mod tests {+ use common_enums::BlocklistTransactionType;+ use serde_json::json;++ use super::{batch, rows_to_csv_bytes, storage};++ #[test]+ fn exported_twins_reimport_into_their_original_blocklists() {+ let entries = [+ ("424242", "generic_card_bin", "payment"),+ ("424242", "generic_card_bin", "payout"),+ ("fp_exact", "payment_method", "payment"),+ ("fp_exact", "payment_method", "payout"),+ ]+ .into_iter()+ .map(|(fingerprint, kind, flow)| {+ serde_json::from_value::<storage::Blocklist>(json!({+ "merchant_id": "merchant_test",+ "fingerprint_id": fingerprint,+ "data_kind": kind,+ "metadata": {"reason": "fraud"},+ "created_at": common_utils::date_time::now(),+ "processor_merchant_id": "merchant_test",+ "created_by": null,+ "profile_id": "pro_source",+ "transaction_type": flow+ }))+ .unwrap()+ })+ .collect::<Vec<_>>();+ let csv = rows_to_csv_bytes(&entries).unwrap();+ let imported = batch::parse_chunk_csv(&csv).unwrap();+ let identities = imported+ .iter()+ .map(|row| (row.data.as_str(), row.transaction_type))+ .collect::<Vec<_>>();+ assert_eq!(+ identities,+ vec![+ ("424242", BlocklistTransactionType::Payment),+ ("424242", BlocklistTransactionType::Payout),+ ("fp_exact", BlocklistTransactionType::Payment),+ ("fp_exact", BlocklistTransactionType::Payout),+ ]+ );+ }+}diff --git a/crates/router/src/core/blocklist/transformers.rs b/crates/router/src/core/blocklist/transformers.rsindex 16617a3c09..1336ed74dc 100644--- a/crates/router/src/core/blocklist/transformers.rs+++ b/crates/router/src/core/blocklist/transformers.rs@@ -19,6 +19,7 @@ impl ForeignFrom<storage::Blocklist> for blocklist::AddToBlocklistResponse {Self {fingerprint_id: from.fingerprint_id,data_kind: from.data_kind,+ transaction_type: from.transaction_type.unwrap_or_default(),created_at: from.created_at,profile_id: from.profile_id,}diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rsindex 1caa4c303b..a1ec935c46 100644--- a/crates/router/src/core/blocklist/utils.rs+++ b/crates/router/src/core/blocklist/utils.rs@@ -26,6 +26,7 @@ pub async fn delete_entry_from_blocklist(state: &SessionState,processor: &domain::Processor,profile_id: Option<common_utils::id_type::ProfileId>,+ transaction_type: common_enums::BlocklistTransactionType,request: api_blocklist::DeleteFromBlocklistRequest,) -> RouterResult<api_blocklist::DeleteFromBlocklistResponse> {let processor_merchant_id = processor.get_account().get_id();@@ -45,13 +46,21 @@ pub async fn delete_entry_from_blocklist(api_blocklist::DeleteFromBlocklistRequest::CardBin(bin)| api_blocklist::DeleteFromBlocklistRequest::ExtendedCardBin(bin)| api_blocklist::DeleteFromBlocklistRequest::GenericCardBin(bin) => {- delete_card_bin_blocklist_entry(state, &bin, processor_merchant_id, &profile_id).await?+ delete_card_bin_blocklist_entry(+ state,+ &bin,+ processor_merchant_id,+ transaction_type,+ &profile_id,+ )+ .await?}api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => state.store.delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ transaction_type,&profile_id,&fingerprint_id,)@@ -118,6 +127,7 @@ pub async fn list_blocklist_entries_for_merchant(.store.list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ query.transaction_type,profile_id,query.data_kind,query.limit.into(),@@ -132,6 +142,7 @@ pub async fn list_blocklist_entries_for_merchant(.store.get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ Some(query.transaction_type),profile_id,query.data_kind,)@@ -203,6 +214,7 @@ pub async fn get_blocklist_count(.store.get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ query.transaction_type,Some(&profile_id),query.data_kind,)@@ -220,6 +232,7 @@ pub async fn get_blocklist_count(.store.count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ query.transaction_type,&profile_id,query.data_kind,)@@ -273,28 +286,30 @@ pub async fn lookup_blocklist_entry(.get_id().to_owned();- let result = state+ let entries = state.store- .find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ .list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ query.transaction_type,&profile_id,query.data.get_string_repr(),)- .await;-- let blocked = match result {- Ok(_) => true,- Err(error) if error.current_context().is_db_not_found() => false,- Err(error) => {- return Err(error- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("failed to look up blocklist entry"));+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("failed to look up blocklist entries")?;++ let mut transaction_types = Vec::with_capacity(entries.len().min(2));+ for entry in entries {+ let transaction_type = entry.transaction_type.unwrap_or_default();+ if !transaction_types.contains(&transaction_type) {+ transaction_types.push(transaction_type);}- };+ }Ok(api_blocklist::BlocklistLookupResponse {data: query.data.get_string_repr().to_string(),- blocked,+ blocked: !transaction_types.is_empty(),+ transaction_types,})}@@ -302,6 +317,7 @@ pub async fn insert_entry_into_blocklist(state: &SessionState,platform: &domain::Platform,profile_id: Option<common_utils::id_type::ProfileId>,+ transaction_type: common_enums::BlocklistTransactionType,to_block: api_blocklist::AddToBlocklistRequest,) -> RouterResult<api_blocklist::AddToBlocklistResponse> {let processor_merchant_id = platform.get_processor().get_account().get_id();@@ -326,6 +342,7 @@ pub async fn insert_entry_into_blocklist(platform,&profile_id,common_enums::BlocklistDataKind::CardBin,+ transaction_type,).await?}@@ -339,6 +356,7 @@ pub async fn insert_entry_into_blocklist(platform,&profile_id,common_enums::BlocklistDataKind::ExtendedCardBin,+ transaction_type,).await?}@@ -351,6 +369,7 @@ pub async fn insert_entry_into_blocklist(platform,&profile_id,common_enums::BlocklistDataKind::GenericCardBin,+ transaction_type,).await?}@@ -360,6 +379,7 @@ pub async fn insert_entry_into_blocklist(.store.find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ transaction_type,&profile_id,fingerprint_id,)@@ -389,6 +409,7 @@ pub async fn insert_entry_into_blocklist(merchant_id: platform.get_provider().get_account().get_id().clone(),fingerprint_id: fingerprint_id.clone(),data_kind: api_models::enums::enums::BlocklistDataKind::PaymentMethod,+ transaction_type,metadata: None,created_at: common_utils::date_time::now(),processor_merchant_id: Some(processor_merchant_id.to_owned()),@@ -430,6 +451,7 @@ async fn duplicate_check_insert_bin(platform: &domain::Platform,profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,+ transaction_type: common_enums::BlocklistTransactionType,) -> RouterResult<storage::Blocklist> {let processor_merchant_id = platform.get_processor().get_account().get_id();@@ -437,6 +459,7 @@ async fn duplicate_check_insert_bin(.store.find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ transaction_type,profile_id,bin,)@@ -465,6 +488,7 @@ async fn duplicate_check_insert_bin(merchant_id: platform.get_provider().get_account().get_id().clone(),fingerprint_id: bin.to_string(),data_kind,+ transaction_type,metadata: None,created_at: common_utils::date_time::now(),processor_merchant_id: Some(processor_merchant_id.to_owned()),@@ -483,12 +507,14 @@ async fn delete_card_bin_blocklist_entry(state: &SessionState,bin: &str,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,) -> RouterResult<storage::Blocklist> {state.store.delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ transaction_type,profile_id,bin,)@@ -501,6 +527,7 @@ async fn delete_card_bin_blocklist_entry(pub async fn check_blocklist(state: &SessionState,processor: &domain::Processor,+ transaction_type: common_enums::BlocklistTransactionType,payment_method_data: &Option<domain::EligibilityPaymentMethodData>,business_profile: &domain::Profile,) -> CustomResult<Option<BlockReason>, errors::ApiErrorResponse> {@@ -563,6 +590,7 @@ pub async fn check_blocklist(match db.find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(processor_merchant_id,+ transaction_type,profile_id,fingerprint_ids,)@@ -597,6 +625,7 @@ pub async fn check_blocklist(pub async fn get_blocked_bins(state: &SessionState,processor: &domain::Processor,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,bins: HashSet<String>,) -> HashSet<String> {@@ -604,6 +633,7 @@ pub async fn get_blocked_bins(.store.list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(processor.get_account().get_id(),+ transaction_type,profile_id,bins.into_iter().collect(),)@@ -635,6 +665,7 @@ wherelet block_reason = check_blocklist(state,processor,+ common_enums::BlocklistTransactionType::Payment,&payment_data.payment_method_data.clone()diff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rsindex 3a876bc86e..2d1b9d2dc9 100644--- a/crates/router/src/core/payment_methods/client.rs+++ b/crates/router/src/core/payment_methods/client.rs@@ -610,7 +610,14 @@ async fn filter_customer_pms_by_blocklist(let blocked_bins = if bins.is_empty() {std::collections::HashSet::new()} else {- blocklist_utils::get_blocked_bins(state, processor, profile_id, bins).await+ blocklist_utils::get_blocked_bins(+ state,+ processor,+ common_enums::BlocklistTransactionType::Payment,+ profile_id,+ bins,+ )+ .await};if blocked_bins.is_empty() {diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex 5f4883dcf4..d48a962581 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -14797,6 +14797,7 @@ impl EligibilityCheck for BlockListCheck {let block_reason = blocklist_utils::check_blocklist(state,platform.get_processor(),+ common_enums::BlocklistTransactionType::Payment,&payment_method_data,business_profile,)diff --git a/crates/router/src/core/payouts/guards.rs b/crates/router/src/core/payouts/guards.rsindex 59d37ccf0e..7a55156e8f 100644--- a/crates/router/src/core/payouts/guards.rs+++ b/crates/router/src/core/payouts/guards.rs@@ -74,6 +74,7 @@ impl PayoutGuard for BlocklistGuard {blocklist_utils::check_blocklist(state,platform.get_processor(),+ common_enums::BlocklistTransactionType::Payout,&Some(payment_method_data),&payout_data.business_profile,)diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rsindex a28cdb562a..e436959aee 100644--- a/crates/router/src/db/blocklist.rs+++ b/crates/router/src/db/blocklist.rs@@ -20,12 +20,24 @@ pub trait BlocklistInterface {async fn find_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError>;+ /// Returns matching fingerprint rows for the resolved profile and merchant-wide entries.+ /// An omitted transaction type includes every namespace; legacy NULL rows match payment.+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;+async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError>;@@ -33,6 +45,7 @@ pub trait BlocklistInterface {async fn find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_ids: Vec<String>,) -> CustomResult<Option<storage::Blocklist>, errors::StorageError>;@@ -42,6 +55,7 @@ pub trait BlocklistInterface {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,card_bins: Vec<String>,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;@@ -49,12 +63,14 @@ pub trait BlocklistInterface {async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError>;async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError>;@@ -66,6 +82,7 @@ pub trait BlocklistInterface {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: Option<&common_utils::id_type::ProfileId>,data_kind: common_enums::BlocklistDataKind,limit: i64,@@ -76,6 +93,7 @@ pub trait BlocklistInterface {async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,after_fingerprint_id: String,snapshot_at: time::PrimitiveDateTime,@@ -84,6 +102,27 @@ pub trait BlocklistInterface {/// The same page over rows written before `processor_merchant_id` existed.async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;++ /// Same scan as above but with no `transaction_type` filter; used when cloning all types.+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;++ /// Same scan as above but with no `transaction_type` filter; used when cloning all types.+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(&self,merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -95,6 +134,7 @@ pub trait BlocklistInterface {async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,profile_id: Option<&common_utils::id_type::ProfileId>,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError>;@@ -104,6 +144,7 @@ pub trait BlocklistInterface {async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<Vec<(i32, i64)>, errors::StorageError>;@@ -111,11 +152,13 @@ pub trait BlocklistInterface {async fn list_blocklist_entries_by_processor_merchant_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;async fn list_blocklist_entries_by_processor_merchant_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,data_kind: common_enums::BlocklistDataKind,limit: i64,offset: i64,@@ -124,6 +167,7 @@ pub trait BlocklistInterface {async fn get_blocklist_entries_count_by_processor_merchant_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError>;@@ -150,21 +194,75 @@ impl BlocklistInterface for Store {.map_err(|error| report!(errors::StorageError::from(error)))}+ #[instrument(skip_all)]+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ let conn = connection::pg_connection_read(self).await?;+ match transaction_type {+ Some(common_enums::BlocklistTransactionType::Payment) => {+ storage::Blocklist::list_by_processor_merchant_id_profile_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ }+ Some(common_enums::BlocklistTransactionType::Payout) => {+ storage::Blocklist::list_by_processor_merchant_id_profile_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ }+ None => {+ storage::Blocklist::list_all_by_processor_merchant_id_profile_id_fingerprint_id(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ }+ }+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[instrument(skip_all)]async fn find_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;// Stagger release fallback: first try processor_merchant_id, if not found fallback to merchant_id// For old records processor_merchant_id is NULL, so we use merchant_id (which has the same value)- let result = storage::Blocklist::find_by_processor_merchant_id_fingerprint_id(- &conn,- processor_merchant_id,- fingerprint_id,- )- .await;+ let result = match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::find_by_processor_merchant_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::find_by_processor_merchant_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ };match result {Ok(blocklist_entry) => Ok(blocklist_entry),@@ -173,12 +271,24 @@ impl BlocklistInterface for Store {error.current_context(),diesel_models::errors::DatabaseError::NotFound) {- storage::Blocklist::find_by_merchant_id_fingerprint_id(- &conn,- processor_merchant_id,- fingerprint_id,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::find_by_merchant_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::find_by_merchant_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ }.map_err(|error| report!(errors::StorageError::from(error)))} else {Err(report!(errors::StorageError::from(error)))@@ -191,17 +301,31 @@ impl BlocklistInterface for Store {async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- let result = storage::Blocklist::find_by_processor_merchant_id_profile_id_fingerprint_id(- &conn,- processor_merchant_id,- profile_id,- fingerprint_id,- )- .await;+ let result = match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::find_by_processor_merchant_id_profile_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::find_by_processor_merchant_id_profile_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ )+ .await+ }+ };match result {Ok(blocklist_entry) => Ok(blocklist_entry),@@ -210,13 +334,24 @@ impl BlocklistInterface for Store {error.current_context(),diesel_models::errors::DatabaseError::NotFound) {- storage::Blocklist::find_by_merchant_id_profile_id_fingerprint_id(- &conn,- processor_merchant_id,- profile_id,- fingerprint_id,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::find_by_merchant_id_profile_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ ).await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::find_by_merchant_id_profile_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ ).await+ }+ }.map_err(|error| report!(errors::StorageError::from(error)))} else {Err(report!(errors::StorageError::from(error)))@@ -229,17 +364,29 @@ impl BlocklistInterface for Store {async fn find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_ids: Vec<String>,) -> CustomResult<Option<storage::Blocklist>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- storage::Blocklist::find_by_processor_merchant_id_profile_id_fingerprint_ids(- &conn,- processor_merchant_id,- profile_id,- fingerprint_ids,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::find_by_processor_merchant_id_profile_id_fingerprint_ids_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_ids,+ ).await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::find_by_processor_merchant_id_profile_id_fingerprint_ids_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_ids,+ ).await+ }+ }.map_err(|error| report!(errors::StorageError::from(error)))}@@ -247,17 +394,31 @@ impl BlocklistInterface for Store {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,card_bins: Vec<String>,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- storage::Blocklist::find_by_processor_merchant_id_profile_id_card_bins(- &conn,- processor_merchant_id,- profile_id,- card_bins,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::find_by_processor_merchant_id_profile_id_card_bins_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ card_bins,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::find_by_processor_merchant_id_profile_id_card_bins_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ card_bins,+ )+ .await+ }+ }.map_err(|error| report!(errors::StorageError::from(error)))}@@ -265,30 +426,60 @@ impl BlocklistInterface for Store {async fn list_blocklist_entries_by_processor_merchant_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- storage::Blocklist::list_by_processor_merchant_id(&conn, processor_merchant_id)- .await- .map_err(|error| report!(errors::StorageError::from(error)))+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::list_by_processor_merchant_id_for_payment(+ &conn,+ processor_merchant_id,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::list_by_processor_merchant_id_for_payout(+ &conn,+ processor_merchant_id,+ )+ .await+ }+ }+ .map_err(|error| report!(errors::StorageError::from(error)))}#[instrument(skip_all)]async fn list_blocklist_entries_by_processor_merchant_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,data_kind: common_enums::BlocklistDataKind,limit: i64,offset: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- storage::Blocklist::list_by_processor_merchant_id_data_kind(- &conn,- processor_merchant_id,- data_kind,- limit,- offset,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::list_by_processor_merchant_id_data_kind_for_payment(+ &conn,+ processor_merchant_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::list_by_processor_merchant_id_data_kind_for_payout(+ &conn,+ processor_merchant_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ }.change_context(errors::StorageError::DatabaseError(report!(diesel_models::errors::DatabaseError::Others)))@@ -298,15 +489,28 @@ impl BlocklistInterface for Store {async fn get_blocklist_entries_count_by_processor_merchant_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- storage::Blocklist::get_count_by_processor_merchant_id_data_kind(- &conn,- processor_merchant_id,- data_kind,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::get_count_by_processor_merchant_id_data_kind_for_payment(+ &conn,+ processor_merchant_id,+ data_kind,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::get_count_by_processor_merchant_id_data_kind_for_payout(+ &conn,+ processor_merchant_id,+ data_kind,+ )+ .await+ }+ }.change_context(errors::StorageError::DatabaseError(report!(diesel_models::errors::DatabaseError::Others)))@@ -316,17 +520,30 @@ impl BlocklistInterface for Store {async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {let conn = connection::pg_connection_write(self).await?;// Stagger release fallback: first try processor_merchant_id, if not found fallback to merchant_id// For old records processor_merchant_id is NULL, so we delete by merchant_id (which has the same value)- let result = storage::Blocklist::delete_by_processor_merchant_id_fingerprint_id(- &conn,- processor_merchant_id,- fingerprint_id,- )- .await;+ let result = match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::delete_by_processor_merchant_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::delete_by_processor_merchant_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ };match result {Ok(blocklist) => Ok(blocklist),@@ -335,12 +552,24 @@ impl BlocklistInterface for Store {error.current_context(),diesel_models::errors::DatabaseError::NotFound) {- storage::Blocklist::delete_by_merchant_id_fingerprint_id(- &conn,- processor_merchant_id,- fingerprint_id,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::delete_by_merchant_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::delete_by_merchant_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ fingerprint_id,+ )+ .await+ }+ }.map_err(|error| report!(errors::StorageError::from(error)))} else {Err(report!(errors::StorageError::from(error)))@@ -353,17 +582,29 @@ impl BlocklistInterface for Store {async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {let conn = connection::pg_connection_write(self).await?;- let result = storage::Blocklist::delete_by_processor_merchant_id_profile_id_fingerprint_id(- &conn,- processor_merchant_id,- profile_id,- fingerprint_id,- )- .await;+ let result = match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::delete_by_processor_merchant_id_profile_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ ).await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::delete_by_processor_merchant_id_profile_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ ).await+ }+ };match result {Ok(blocklist) => Ok(blocklist),@@ -372,13 +613,24 @@ impl BlocklistInterface for Store {error.current_context(),diesel_models::errors::DatabaseError::NotFound) {- storage::Blocklist::delete_by_merchant_id_profile_id_fingerprint_id(- &conn,- processor_merchant_id,- profile_id,- fingerprint_id,- )- .await+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::delete_by_merchant_id_profile_id_fingerprint_id_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ ).await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::delete_by_merchant_id_profile_id_fingerprint_id_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ fingerprint_id,+ ).await+ }+ }.map_err(|error| report!(errors::StorageError::from(error)))} else {Err(report!(errors::StorageError::from(error)))@@ -391,6 +643,7 @@ impl BlocklistInterface for Store {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: Option<&common_utils::id_type::ProfileId>,data_kind: common_enums::BlocklistDataKind,limit: i64,@@ -398,35 +651,134 @@ impl BlocklistInterface for Store {) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;match profile_id {- Some(profile_id) => {- storage::Blocklist::list_by_processor_merchant_id_profile_id_data_kind(+ Some(profile_id) => match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::list_by_processor_merchant_id_profile_id_data_kind_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::list_by_processor_merchant_id_profile_id_data_kind_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ },+ None => match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::list_by_processor_merchant_id_data_kind_for_payment(+ &conn,+ processor_merchant_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::list_by_processor_merchant_id_data_kind_for_payout(+ &conn,+ processor_merchant_id,+ data_kind,+ limit,+ offset,+ )+ .await+ }+ },+ }+ .change_context(errors::StorageError::DatabaseError(report!(+ diesel_models::errors::DatabaseError::Others+ )))+ }++ #[instrument(skip_all)]+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ let conn = pg_connection_read_replica(self).await?;+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::list_after_fingerprint_by_processor_merchant_id_profile_id_for_payment(+ &conn,+ processor_merchant_id,+ profile_id,+ after_fingerprint_id,+ snapshot_at,+ limit,+ ).await+ }+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::list_after_fingerprint_by_processor_merchant_id_profile_id_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ after_fingerprint_id,+ snapshot_at,+ limit,+ ).await+ }+ }+ .map_err(|error| report!(errors::StorageError::from(error)))+ }++ #[instrument(skip_all)]+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ let conn = pg_connection_read_replica(self).await?;+ match transaction_type {+ common_enums::BlocklistTransactionType::Payment => {+ storage::Blocklist::list_after_fingerprint_by_legacy_merchant_id_profile_id_for_payment(&conn,- processor_merchant_id,+ merchant_id,profile_id,- data_kind,+ after_fingerprint_id,+ snapshot_at,limit,- offset,).await}- None => {- storage::Blocklist::list_by_processor_merchant_id_data_kind(+ common_enums::BlocklistTransactionType::Payout => {+ storage::Blocklist::list_after_fingerprint_by_legacy_merchant_id_profile_id_for_payout(&conn,- processor_merchant_id,- data_kind,+ merchant_id,+ profile_id,+ after_fingerprint_id,+ snapshot_at,limit,- offset,).await}}- .change_context(errors::StorageError::DatabaseError(report!(- diesel_models::errors::DatabaseError::Others- )))+ .map_err(|error| report!(errors::StorageError::from(error)))}#[instrument(skip_all)]- async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(&self,processor_merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -435,7 +787,7 @@ impl BlocklistInterface for Store {limit: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {let conn = pg_connection_read_replica(self).await?;- storage::Blocklist::list_after_fingerprint_by_processor_merchant_id_profile_id(+ storage::Blocklist::list_all_after_fingerprint_by_processor_merchant_id_profile_id(&conn,processor_merchant_id,profile_id,@@ -448,7 +800,7 @@ impl BlocklistInterface for Store {}#[instrument(skip_all)]- async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(&self,merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -457,7 +809,7 @@ impl BlocklistInterface for Store {limit: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {let conn = pg_connection_read_replica(self).await?;- storage::Blocklist::list_after_fingerprint_by_legacy_merchant_id_profile_id(+ storage::Blocklist::list_all_after_fingerprint_by_legacy_merchant_id_profile_id(&conn,merchant_id,profile_id,@@ -473,13 +825,14 @@ impl BlocklistInterface for Store {async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,profile_id: Option<&common_utils::id_type::ProfileId>,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- match profile_id {- Some(profile_id) => {- storage::Blocklist::get_count_by_processor_merchant_id_profile_id_data_kind(+ match (profile_id, transaction_type) {+ (Some(profile_id), Some(common_enums::BlocklistTransactionType::Payment)) => {+ storage::Blocklist::get_count_by_processor_merchant_id_profile_id_data_kind_for_payment(&conn,processor_merchant_id,profile_id,@@ -487,8 +840,42 @@ impl BlocklistInterface for Store {).await}- None => {- storage::Blocklist::get_count_by_processor_merchant_id_data_kind(+ (Some(profile_id), Some(common_enums::BlocklistTransactionType::Payout)) => {+ storage::Blocklist::get_count_by_processor_merchant_id_profile_id_data_kind_for_payout(+ &conn,+ processor_merchant_id,+ profile_id,+ data_kind,+ )+ .await+ }+ (Some(profile_id), None) => {+ storage::Blocklist::get_all_count_by_processor_merchant_id_profile_id_data_kind(+ &conn,+ processor_merchant_id,+ profile_id,+ data_kind,+ )+ .await+ }+ (None, Some(common_enums::BlocklistTransactionType::Payment)) => {+ storage::Blocklist::get_count_by_processor_merchant_id_data_kind_for_payment(+ &conn,+ processor_merchant_id,+ data_kind,+ )+ .await+ }+ (None, Some(common_enums::BlocklistTransactionType::Payout)) => {+ storage::Blocklist::get_count_by_processor_merchant_id_data_kind_for_payout(+ &conn,+ processor_merchant_id,+ data_kind,+ )+ .await+ }+ (None, None) => {+ storage::Blocklist::get_all_count_by_processor_merchant_id_data_kind(&conn,processor_merchant_id,data_kind,@@ -505,17 +892,28 @@ impl BlocklistInterface for Store {async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<Vec<(i32, i64)>, errors::StorageError> {let conn = connection::pg_connection_read(self).await?;- storage::Blocklist::count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(- &conn,- processor_merchant_id,- profile_id,- data_kind,- )- .await+ match transaction_type {+ Some(common_enums::BlocklistTransactionType::Payment) => {+ storage::Blocklist::count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind_for_payment(+ &conn, processor_merchant_id, profile_id, data_kind,+ ).await+ }+ Some(common_enums::BlocklistTransactionType::Payout) => {+ storage::Blocklist::count_by_fingerprint_length_processor_merchant_id_profile_id_data_kind_for_payout(+ &conn, processor_merchant_id, profile_id, data_kind,+ ).await+ }+ None => {+ storage::Blocklist::count_all_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(+ &conn, processor_merchant_id, profile_id, data_kind,+ ).await+ }+ }.change_context(errors::StorageError::DatabaseError(report!(diesel_models::errors::DatabaseError::Others)))@@ -543,9 +941,38 @@ impl BlocklistInterface for MockDb {Err(errors::StorageError::MockDbError)?}+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ Ok(self+ .blocklists+ .lock()+ .await+ .iter()+ .filter(|entry| {+ (entry.processor_merchant_id.as_ref() == Some(processor_merchant_id)+ || (entry.processor_merchant_id.is_none()+ && &entry.merchant_id == processor_merchant_id))+ && entry.fingerprint_id == fingerprint_id+ && (entry.profile_id.as_ref() == Some(profile_id) || entry.profile_id.is_none())+ && transaction_type+ .map(|transaction_type| {+ entry.transaction_type.unwrap_or_default() == transaction_type+ })+ .unwrap_or(true)+ })+ .cloned()+ .collect())+ }+async fn find_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {Err(errors::StorageError::MockDbError)?@@ -554,6 +981,7 @@ impl BlocklistInterface for MockDb {async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_profile_id: &common_utils::id_type::ProfileId,_fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {@@ -563,6 +991,7 @@ impl BlocklistInterface for MockDb {async fn find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_profile_id: &common_utils::id_type::ProfileId,_fingerprint_ids: Vec<String>,) -> CustomResult<Option<storage::Blocklist>, errors::StorageError> {@@ -572,6 +1001,7 @@ impl BlocklistInterface for MockDb {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_profile_id: &common_utils::id_type::ProfileId,_card_bins: Vec<String>,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {@@ -581,6 +1011,7 @@ impl BlocklistInterface for MockDb {async fn list_blocklist_entries_by_processor_merchant_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {Err(errors::StorageError::MockDbError)?}@@ -588,6 +1019,7 @@ impl BlocklistInterface for MockDb {async fn list_blocklist_entries_by_processor_merchant_id_data_kind(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_data_kind: common_enums::BlocklistDataKind,_limit: i64,_offset: i64,@@ -598,6 +1030,7 @@ impl BlocklistInterface for MockDb {async fn get_blocklist_entries_count_by_processor_merchant_id_data_kind(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {Err(errors::StorageError::MockDbError)?@@ -606,6 +1039,7 @@ impl BlocklistInterface for MockDb {async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {Err(errors::StorageError::MockDbError)?@@ -614,6 +1048,7 @@ impl BlocklistInterface for MockDb {async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_profile_id: &common_utils::id_type::ProfileId,_fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {@@ -623,6 +1058,7 @@ impl BlocklistInterface for MockDb {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: common_enums::BlocklistTransactionType,_profile_id: Option<&common_utils::id_type::ProfileId>,_data_kind: common_enums::BlocklistDataKind,_limit: i64,@@ -634,6 +1070,7 @@ impl BlocklistInterface for MockDb {async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,after_fingerprint_id: String,snapshot_at: time::PrimitiveDateTime,@@ -646,6 +1083,7 @@ impl BlocklistInterface for MockDb {.iter().filter(|entry| {entry.processor_merchant_id.as_ref() == Some(processor_merchant_id)+ && entry.transaction_type.unwrap_or_default() == transaction_type&& entry.fingerprint_id > after_fingerprint_id&& entry.created_at <= snapshot_at&& (entry.profile_id.as_ref() == Some(profile_id) || entry.profile_id.is_none())@@ -658,6 +1096,61 @@ impl BlocklistInterface for MockDb {}async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ let mut entries = self+ .blocklists+ .lock()+ .await+ .iter()+ .filter(|entry| {+ entry.merchant_id == *merchant_id+ && entry.processor_merchant_id.is_none()+ && entry.transaction_type.unwrap_or_default() == transaction_type+ && entry.fingerprint_id > after_fingerprint_id+ && entry.created_at <= snapshot_at+ && (entry.profile_id.as_ref() == Some(profile_id) || entry.profile_id.is_none())+ })+ .cloned()+ .collect::<Vec<_>>();+ entries.sort_by(|left, right| left.fingerprint_id.cmp(&right.fingerprint_id));+ entries.truncate(usize::try_from(limit).unwrap_or(usize::MAX));+ Ok(entries)+ }++ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ let mut entries = self+ .blocklists+ .lock()+ .await+ .iter()+ .filter(|entry| {+ entry.processor_merchant_id.as_ref() == Some(processor_merchant_id)+ && entry.fingerprint_id > after_fingerprint_id+ && entry.created_at <= snapshot_at+ && (entry.profile_id.as_ref() == Some(profile_id) || entry.profile_id.is_none())+ })+ .cloned()+ .collect::<Vec<_>>();+ entries.sort_by(|left, right| left.fingerprint_id.cmp(&right.fingerprint_id));+ entries.truncate(usize::try_from(limit).unwrap_or(usize::MAX));+ Ok(entries)+ }++ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(&self,merchant_id: &common_utils::id_type::MerchantId,profile_id: &common_utils::id_type::ProfileId,@@ -687,6 +1180,7 @@ impl BlocklistInterface for MockDb {async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: Option<common_enums::BlocklistTransactionType>,_profile_id: Option<&common_utils::id_type::ProfileId>,_data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {@@ -696,6 +1190,7 @@ impl BlocklistInterface for MockDb {async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(&self,_processor_merchant_id: &common_utils::id_type::MerchantId,+ _transaction_type: Option<common_enums::BlocklistTransactionType>,_profile_id: &common_utils::id_type::ProfileId,_data_kind: common_enums::BlocklistDataKind,) -> CustomResult<Vec<(i32, i64)>, errors::StorageError> {@@ -710,9 +1205,12 @@ impl BlocklistInterface for MockDb {let mut inserted = 0usize;for entry in entries {let already_exists = blocklists.iter().any(|b| {- b.processor_merchant_id == entry.processor_merchant_id+ ((b.merchant_id == entry.merchant_id && entry.profile_id.is_some())+ || (entry.processor_merchant_id.is_some()+ && b.processor_merchant_id == entry.processor_merchant_id))&& b.profile_id == entry.profile_id&& b.fingerprint_id == entry.fingerprint_id+ && b.transaction_type == Some(entry.transaction_type)});if !already_exists {blocklists.push(storage::Blocklist {@@ -724,6 +1222,7 @@ impl BlocklistInterface for MockDb {processor_merchant_id: entry.processor_merchant_id,created_by: entry.created_by,profile_id: entry.profile_id,+ transaction_type: Some(entry.transaction_type),});inserted += 1;}@@ -742,15 +1241,35 @@ impl BlocklistInterface for KafkaStore {self.diesel_store.insert_blocklist_entry(pm_blocklist).await}+ #[instrument(skip_all)]+ async fn list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,+ profile_id: &common_utils::id_type::ProfileId,+ fingerprint_id: &str,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ self.diesel_store+ .list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(+ processor_merchant_id,+ transaction_type,+ profile_id,+ fingerprint_id,+ )+ .await+ }+#[instrument(skip_all)]async fn find_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {self.diesel_store.find_blocklist_entry_by_processor_merchant_id_fingerprint_id(processor_merchant_id,+ transaction_type,fingerprint_id,).await@@ -760,12 +1279,14 @@ impl BlocklistInterface for KafkaStore {async fn find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {self.diesel_store.find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ transaction_type,profile_id,fingerprint_id,)@@ -776,12 +1297,14 @@ impl BlocklistInterface for KafkaStore {async fn find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_ids: Vec<String>,) -> CustomResult<Option<storage::Blocklist>, errors::StorageError> {self.diesel_store.find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(processor_merchant_id,+ transaction_type,profile_id,fingerprint_ids,)@@ -792,12 +1315,14 @@ impl BlocklistInterface for KafkaStore {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,card_bins: Vec<String>,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {self.diesel_store.list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(processor_merchant_id,+ transaction_type,profile_id,card_bins,)@@ -808,11 +1333,13 @@ impl BlocklistInterface for KafkaStore {async fn delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {self.diesel_store.delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(processor_merchant_id,+ transaction_type,fingerprint_id,).await@@ -822,6 +1349,7 @@ impl BlocklistInterface for KafkaStore {async fn list_blocklist_entries_by_processor_merchant_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,data_kind: common_enums::BlocklistDataKind,limit: i64,offset: i64,@@ -829,6 +1357,7 @@ impl BlocklistInterface for KafkaStore {self.diesel_store.list_blocklist_entries_by_processor_merchant_id_data_kind(processor_merchant_id,+ transaction_type,data_kind,limit,offset,@@ -840,12 +1369,14 @@ impl BlocklistInterface for KafkaStore {async fn delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {self.diesel_store.delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(processor_merchant_id,+ transaction_type,profile_id,fingerprint_id,)@@ -856,6 +1387,7 @@ impl BlocklistInterface for KafkaStore {async fn list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: Option<&common_utils::id_type::ProfileId>,data_kind: common_enums::BlocklistDataKind,limit: i64,@@ -864,6 +1396,7 @@ impl BlocklistInterface for KafkaStore {self.diesel_store.list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ transaction_type,profile_id,data_kind,limit,@@ -876,6 +1409,7 @@ impl BlocklistInterface for KafkaStore {async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,after_fingerprint_id: String,snapshot_at: time::PrimitiveDateTime,@@ -884,6 +1418,7 @@ impl BlocklistInterface for KafkaStore {self.diesel_store.list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(processor_merchant_id,+ transaction_type,profile_id,after_fingerprint_id,snapshot_at,@@ -896,6 +1431,7 @@ impl BlocklistInterface for KafkaStore {async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(&self,merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,profile_id: &common_utils::id_type::ProfileId,after_fingerprint_id: String,snapshot_at: time::PrimitiveDateTime,@@ -903,6 +1439,47 @@ impl BlocklistInterface for KafkaStore {) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {self.diesel_store.list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ merchant_id,+ transaction_type,+ profile_id,+ after_fingerprint_id,+ snapshot_at,+ limit,+ )+ .await+ }++ #[instrument(skip_all)]+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(+ &self,+ processor_merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ self.diesel_store+ .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(+ processor_merchant_id,+ profile_id,+ after_fingerprint_id,+ snapshot_at,+ limit,+ )+ .await+ }++ #[instrument(skip_all)]+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(+ &self,+ merchant_id: &common_utils::id_type::MerchantId,+ profile_id: &common_utils::id_type::ProfileId,+ after_fingerprint_id: String,+ snapshot_at: time::PrimitiveDateTime,+ limit: i64,+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {+ self.diesel_store+ .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(merchant_id,profile_id,after_fingerprint_id,@@ -916,12 +1493,14 @@ impl BlocklistInterface for KafkaStore {async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,profile_id: Option<&common_utils::id_type::ProfileId>,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {self.diesel_store.get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(processor_merchant_id,+ transaction_type,profile_id,data_kind,)@@ -932,11 +1511,13 @@ impl BlocklistInterface for KafkaStore {async fn get_blocklist_entries_count_by_processor_merchant_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {self.diesel_store.get_blocklist_entries_count_by_processor_merchant_id_data_kind(processor_merchant_id,+ transaction_type,data_kind,).await@@ -946,15 +1527,16 @@ impl BlocklistInterface for KafkaStore {async fn count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: Option<common_enums::BlocklistTransactionType>,profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<Vec<(i32, i64)>, errors::StorageError> {- self.diesel_store- .count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(- processor_merchant_id,- profile_id,- data_kind,- )+ self.diesel_store.count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(+ processor_merchant_id,+ transaction_type,+ profile_id,+ data_kind,+ ).await}@@ -962,9 +1544,13 @@ impl BlocklistInterface for KafkaStore {async fn list_blocklist_entries_by_processor_merchant_id(&self,processor_merchant_id: &common_utils::id_type::MerchantId,+ transaction_type: common_enums::BlocklistTransactionType,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {self.diesel_store- .list_blocklist_entries_by_processor_merchant_id(processor_merchant_id)+ .list_blocklist_entries_by_processor_merchant_id(+ processor_merchant_id,+ transaction_type,+ ).await}diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rsindex 8976d22e5a..781867e622 100644--- a/crates/router/src/routes/blocklist.rs+++ b/crates/router/src/routes/blocklist.rs@@ -13,7 +13,7 @@ use crate::{#[utoipa::path(post,path = "/blocklist",- request_body = BlocklistRequest,+ request_body = BlocklistEntryRequest,params (("X-Profile-Id" = Option<String>, Header, description = "The business profile to block this \entry under. Ignored when authenticating with a JWT, which carries its own profile. If \@@ -31,17 +31,25 @@ use crate::{pub async fn add_entry_to_blocklist(state: web::Data<AppState>,req: HttpRequest,- json_payload: web::Json<api_blocklist::AddToBlocklistRequest>,+ json_payload: web::Json<api_blocklist::BlocklistEntryRequest>,) -> HttpResponse {let flow = Flow::AddToBlocklist;+ let body = json_payload.into_inner();+ let transaction_type = body.transaction_type;Box::pin(api::server_wrap(flow,state,&req,- json_payload.into_inner(),+ body.entry,|state, auth: auth::AuthenticationData, body, _| {let profile_id = auth.profile.map(|profile| profile.get_id().clone());- blocklist::add_entry_to_blocklist(state, auth.platform, profile_id, body)+ blocklist::add_entry_to_blocklist(+ state,+ auth.platform,+ profile_id,+ transaction_type,+ body,+ )},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {@@ -63,7 +71,7 @@ pub async fn add_entry_to_blocklist(#[utoipa::path(delete,path = "/blocklist",- request_body = BlocklistRequest,+ request_body = BlocklistEntryRequest,params (("X-Profile-Id" = Option<String>, Header, description = "The business profile to unblock \this entry from. Only entries belonging to that profile, or entries with no profile, are \@@ -82,20 +90,23 @@ pub async fn add_entry_to_blocklist(pub async fn remove_entry_from_blocklist(state: web::Data<AppState>,req: HttpRequest,- json_payload: web::Json<api_blocklist::DeleteFromBlocklistRequest>,+ json_payload: web::Json<api_blocklist::BlocklistEntryRequest>,) -> HttpResponse {let flow = Flow::DeleteFromBlocklist;+ let body = json_payload.into_inner();+ let transaction_type = body.transaction_type;Box::pin(api::server_wrap(flow,state,&req,- json_payload.into_inner(),+ body.entry,|state, auth: auth::AuthenticationData, body, _| {let profile_id = auth.profile.map(|profile| profile.get_id().clone());blocklist::remove_entry_from_blocklist(state,auth.platform.get_processor().clone(),profile_id,+ transaction_type,body,)},@@ -121,6 +132,7 @@ pub async fn remove_entry_from_blocklist(path = "/blocklist",params (("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Blocklist flow: payment (default) or payout."),("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to entries \belonging to this business profile, plus entries with no profile. When no profile can be \resolved - as with publishable-key authentication - all of the merchant's entries are \@@ -192,6 +204,7 @@ pub async fn list_blocked_payment_methods(path = "/blocklist/count",params (("data_kind" = BlocklistDataKind, Query, description = "Kind of blocklist entries to count"),+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Counts only payment or payout when selected. When omitted, counts both, including legacy NULL entries. Legacy NULL entries belong to payment when filtered."),("X-Profile-Id" = Option<String>, Header, description = "Restricts the count to entries \belonging to this business profile, plus entries with no profile. If omitted, the \merchant's default profile is used; merchants with more than one profile have no default \@@ -247,13 +260,14 @@ pub async fn get_blocklist_count(path = "/blocklist/lookup",params (("data" = String, Query, description = "The raw value to check against the blocklist, e.g. a card BIN"),+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Looks up only payment or payout when selected. When omitted, both are included. Legacy NULL transaction namespaces belong to payment."),("X-Profile-Id" = Option<String>, Header, description = "Restricts the lookup to entries \belonging to this business profile, plus entries with no profile. If omitted, the \merchant's default profile is used; merchants with more than one profile have no default \and will receive an error asking for this header."),),responses(- (status = 200, description = "Blocklist lookup result", body = BlocklistLookupResponse),+ (status = 200, description = "All matches within the resolved profile, including merchant-wide entries. transaction_types contains distinct matching payment/payout namespaces, without data kinds or profile IDs.", body = BlocklistLookupResponse),(status = 400, description = "Invalid Data, or no profile could be resolved")),tag = "Blocklist",@@ -359,12 +373,15 @@ pub struct BatchBlocklistUploadForm {content = String,content_type = "multipart/form-data",description = "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). \- The CSV must have a header row: `type,data,metadata`. \- `type`: one of `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. \+ The CSV header is `type,data,metadata,transaction_type`; older headers without `transaction_type` are accepted. \+ `type`: one of `generic_card_bin` (6 to 10 digits), `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. \`metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \+ `transaction_type`: optional, `payment` (default) or `payout`; selection may differ per row. \+ Invalid CSV transaction-type values are rejected even when a query override is selected. \Maximum 100,000 data rows.",),params (+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Overrides every CSV row with payment or payout when selected. When omitted, row selections are used; missing or empty row values default to payment."),("X-Profile-Id" = Option<String>, Header, description = "The business profile every entry \in this upload is blocked under. Resolution follows the same rules as blocking a single \entry."),@@ -381,6 +398,7 @@ pub async fn upload_batch_blocklist(state: web::Data<AppState>,req: HttpRequest,MultipartForm(form): MultipartForm<BatchBlocklistUploadForm>,+ query_payload: web::Query<api_blocklist::BatchBlocklistUploadQuery>,) -> HttpResponse {let flow = Flow::BatchBlocklistUpload;let csv_bytes = bytes::Bytes::from(form.file.data.to_vec());@@ -390,11 +408,12 @@ pub async fn upload_batch_blocklist(flow,state,&req,- (),- |state, auth: auth::AuthenticationData, _payload, _| {+ query_payload.into_inner(),+ |state, auth: auth::AuthenticationData, query, _| {let csv_bytes = csv_bytes.clone();let file_name = file_name.clone();let profile_id = auth.profile.map(|profile| profile.get_id().clone());+ let transaction_type = query.transaction_type;async move {blocklist::upload_batch_blocklist(state,@@ -402,6 +421,7 @@ pub async fn upload_batch_blocklist(profile_id,csv_bytes,file_name,+ transaction_type,).await}@@ -527,27 +547,38 @@ pub async fn list_batch_blocklist_jobs(post,path = "/blocklist/export",params (+ ("transaction_type" = Option<BlocklistTransactionType>, Query, description = "Exports only \+ `payment` or `payout` entries when selected. Both are exported when omitted."),("X-Profile-Id" = Option<String>, Header, description = "The business profile whose \blocklist is exported. Resolution follows the same rules as blocking a single entry."),),responses((status = 202, description = "Blocklist export started", body = BlocklistExportResponse),- (status = 400, description = "No profile could be resolved"),+ (status = 400, description = "Invalid transaction type, or no profile could be resolved"),),tag = "Blocklist",operation_id = "Start a blocklist CSV export",security(("api_key" = []), ("jwt_key" = [])))]-pub async fn create_blocklist_export(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {+pub async fn create_blocklist_export(+ state: web::Data<AppState>,+ req: HttpRequest,+ query_payload: web::Query<api_blocklist::BlocklistExportQuery>,+) -> HttpResponse {let flow = Flow::CreateBlocklistExport;Box::pin(api::server_wrap(flow,state,&req,- (),- |state, auth: auth::AuthenticationData, _payload, _| {+ query_payload.into_inner(),+ |state, auth: auth::AuthenticationData, query, _| {let profile_id = auth.profile.map(|profile| profile.get_id().clone());- blocklist::create_blocklist_export(state, auth.platform, profile_id)+ blocklist::create_blocklist_export(+ state,+ auth.platform,+ profile_id,+ query.transaction_type,+ )},auth::auth_type(&auth::HeaderAuth(auth::ApiKeyAuth {diff --git a/crates/router/src/types/storage/batch_blocklist_job.rs b/crates/router/src/types/storage/batch_blocklist_job.rsindex 03fe86032f..a2edd81388 100644--- a/crates/router/src/types/storage/batch_blocklist_job.rs+++ b/crates/router/src/types/storage/batch_blocklist_job.rs@@ -20,6 +20,8 @@ pub struct BlocklistExportTrackingData {pub merchant_id: id_type::MerchantId,pub processor_merchant_id: Option<id_type::MerchantId>,pub profile_id: id_type::ProfileId,+ /// `None` exports both transaction namespaces, including trackers created before this field.+ pub transaction_type: Option<common_enums::BlocklistTransactionType>,/// Bounds the scan, so a run spanning minutes still describes one moment.pub snapshot_at: time::PrimitiveDateTime,/// Written once the multipart upload starts, so a retry can discard the abandoned parts.@@ -38,10 +40,12 @@ pub struct BlocklistProfileCloneTrackingData {pub current_target: usize,/// Bounds the scan, so a run spanning minutes still copies one moment of the source.pub snapshot_at: time::PrimitiveDateTime,- /// The source is drained in two passes, the same split the export uses: rows carrying a- /// `processor_merchant_id` first, then the legacy rows without one.+ /// Each flow drains processor-scoped rows, then legacy rows, before advancing to the next flow.pub draining_legacy_rows: bool,- /// Keyset cursor within the current pass. `""` starts the pass from the beginning.+ /// Requested namespace; `None` clones both, including jobs created before this field.+ #[serde(default)]+ pub selected_transaction_type: Option<common_enums::BlocklistTransactionType>,+ /// Keyset cursor within the current flow and merchant pass. `""` starts at the beginning.pub last_fingerprint_id: String,/// Source rows fully handled by this target tracker. This advances with the cursor.pub processed_rows: i32,@@ -118,3 +122,40 @@ impl From<BlocklistProfileCloneTargetMetadata>}}}++#[cfg(test)]+mod tests {+ use common_enums::BlocklistTransactionType;+ use serde_json::json;++ use super::BlocklistExportTrackingData;++ fn old_export_job() -> serde_json::Value {+ json!({+ "job_id": "export_job",+ "merchant_id": "merchant_test",+ "processor_merchant_id": null,+ "profile_id": "pro_source",+ "snapshot_at": common_utils::date_time::now(),+ "upload_id": "previous_upload"+ })+ }++ #[test]+ fn export_retry_payload_preserves_payout_selection() {+ let mut tracking: BlocklistExportTrackingData =+ serde_json::from_value(old_export_job()).unwrap();+ tracking.transaction_type = Some(BlocklistTransactionType::Payout);+ let retry = BlocklistExportTrackingData {+ upload_id: Some("retry_upload".to_owned()),+ ..tracking+ };+ let restored: BlocklistExportTrackingData =+ serde_json::from_value(serde_json::to_value(retry).unwrap()).unwrap();+ assert_eq!(+ restored.transaction_type,+ Some(BlocklistTransactionType::Payout)+ );+ assert_eq!(restored.upload_id.as_deref(), Some("retry_upload"));+ }+}diff --git a/crates/router/src/workflows/blocklist_export.rs b/crates/router/src/workflows/blocklist_export.rsindex 80babbabe0..d104b2d8fd 100644--- a/crates/router/src/workflows/blocklist_export.rs+++ b/crates/router/src/workflows/blocklist_export.rs@@ -32,11 +32,13 @@ struct ExportScope<'a> {merchant_id: &'a id_type::MerchantId,profile_id: &'a id_type::ProfileId,snapshot_at: time::PrimitiveDateTime,+ transaction_type: Option<common_enums::BlocklistTransactionType>,}async fn drain_scope(state: &SessionState,scope: &ExportScope<'_>,+ transaction_type: Option<common_enums::BlocklistTransactionType>,legacy: bool,progress: &mut ExportProgress,) -> RouterResult<()> {@@ -44,33 +46,52 @@ async fn drain_scope(let mut cursor = String::new();loop {- let page =- match legacy {- false => state- .store- .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(- scope.merchant_id,- scope.profile_id,- cursor.clone(),- scope.snapshot_at,- export::EXPORT_PAGE_SIZE,- )- .await,- true => {- state- .store- .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(- scope.merchant_id,- scope.profile_id,- cursor.clone(),- scope.snapshot_at,- export::EXPORT_PAGE_SIZE,- )- .await- }- }- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to read a blocklist page for export")?;+ let page = match (legacy, transaction_type) {+ (false, Some(transaction_type)) => state+ .store+ .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(+ scope.merchant_id,+ transaction_type,+ scope.profile_id,+ cursor.clone(),+ scope.snapshot_at,+ export::EXPORT_PAGE_SIZE,+ )+ .await,+ (false, None) => state+ .store+ .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(+ scope.merchant_id,+ scope.profile_id,+ cursor.clone(),+ scope.snapshot_at,+ export::EXPORT_PAGE_SIZE,+ )+ .await,+ (true, Some(transaction_type)) => state+ .store+ .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ scope.merchant_id,+ transaction_type,+ scope.profile_id,+ cursor.clone(),+ scope.snapshot_at,+ export::EXPORT_PAGE_SIZE,+ )+ .await,+ (true, None) => state+ .store+ .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(+ scope.merchant_id,+ scope.profile_id,+ cursor.clone(),+ scope.snapshot_at,+ export::EXPORT_PAGE_SIZE,+ )+ .await,+ }+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to read a blocklist page for export")?;let next_cursor = page.last().map(|row| row.fingerprint_id.clone());@@ -163,6 +184,7 @@ async fn run_export_job(merchant_id,profile_id: &tracking_data.profile_id,snapshot_at: tracking_data.snapshot_at,+ transaction_type: tracking_data.transaction_type,};let result = collect_and_complete(state, &scope).await;@@ -196,8 +218,8 @@ async fn collect_and_complete(parts: Vec::new(),};- drain_scope(state, scope, false, &mut progress).await?;- drain_scope(state, scope, true, &mut progress).await?;+ drain_scope(state, scope, scope.transaction_type, false, &mut progress).await?;+ drain_scope(state, scope, scope.transaction_type, true, &mut progress).await?;// The final part is the only one allowed below the minimum size.if !progress.buffer.is_empty() {diff --git a/crates/router/src/workflows/blocklist_profile_clone.rs b/crates/router/src/workflows/blocklist_profile_clone.rsindex 7edf282b2f..485448dc7d 100644--- a/crates/router/src/workflows/blocklist_profile_clone.rs+++ b/crates/router/src/workflows/blocklist_profile_clone.rs@@ -30,9 +30,20 @@ async fn run_clone_job(let merchant_id_str = merchant_id_obj.get_string_repr();loop {- let page = match tracking_data.draining_legacy_rows {- false => {+ let page = match (tracking_data.draining_legacy_rows, tracking_data.selected_transaction_type) {+ (false, Some(transaction_type)) => {db.list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(+ merchant_id_obj,+ transaction_type,+ &tracking_data.source_profile_id,+ tracking_data.last_fingerprint_id.clone(),+ tracking_data.snapshot_at,+ clone::CLONE_PAGE_SIZE,+ )+ .await+ }+ (false, None) => {+ db.list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(merchant_id_obj,&tracking_data.source_profile_id,tracking_data.last_fingerprint_id.clone(),@@ -41,8 +52,19 @@ async fn run_clone_job().await}- true => {+ (true, Some(transaction_type)) => {db.list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ merchant_id_obj,+ transaction_type,+ &tracking_data.source_profile_id,+ tracking_data.last_fingerprint_id.clone(),+ tracking_data.snapshot_at,+ clone::CLONE_PAGE_SIZE,+ )+ .await+ }+ (true, None) => {+ db.list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(merchant_id_obj,&tracking_data.source_profile_id,tracking_data.last_fingerprint_id.clone(),@@ -56,15 +78,13 @@ async fn run_clone_job(.attach_printable_lazy(|| format!("Failed to read a source page for clone job {job_id}"))?;match page.last().map(|entry| entry.fingerprint_id.clone()) {- // End of a pass: switch to the legacy rows, or stop if that pass is already done.- None => match tracking_data.draining_legacy_rows {- true => break,- false => {- tracking_data.draining_legacy_rows = true;- tracking_data.last_fingerprint_id = String::new();- persist_cursor(state, process_id, tracking_data).await?;+ // Empty page: advance to legacy pass, or finish this target if both passes are done.+ None => {+ if !move_to_next_scope(tracking_data) {+ break;}- },+ persist_cursor(state, process_id, tracking_data).await?;+ }Some(cursor) => {let page_len = page.len();let now = common_utils::date_time::now();@@ -123,6 +143,17 @@ async fn run_clone_job(Ok(tracking_data.processed_rows)}+/// Advances the draining pass; each target has two passes (processor rows, then legacy rows).+fn move_to_next_scope(tracking_data: &mut storage::BlocklistProfileCloneTrackingData) -> bool {+ if !tracking_data.draining_legacy_rows {+ tracking_data.draining_legacy_rows = true;+ tracking_data.last_fingerprint_id = String::new();+ true+ } else {+ false+ }+}+/// Rewrites the process's tracking data so a retry picks up where this run left off.async fn persist_cursor(state: &SessionState,@@ -454,3 +485,86 @@ impl ProcessTrackerWorkflow<SessionState> for BlocklistProfileCloneWorkflow {}}}++#[cfg(test)]+mod tests {+ use common_enums::BlocklistTransactionType;+ use serde_json::json;++ use super::{move_to_next_scope, move_to_next_target, storage};++ fn legacy_tracking() -> storage::BlocklistProfileCloneTrackingData {+ serde_json::from_value(json!({+ "job_id": "clone_job",+ "merchant_id": "merchant_test",+ "processor_merchant_id": null,+ "source_profile_id": "pro_source",+ "target_profile_ids": ["pro_target_one", "pro_target_two"],+ "current_target": 0,+ "snapshot_at": common_utils::date_time::now(),+ "draining_legacy_rows": true,+ "last_fingerprint_id": "424242",+ "processed_rows": 7+ }))+ .unwrap()+ }++ #[test]+ fn legacy_clone_resume_drains_legacy_then_stops() {+ // Old tracker with no selected_transaction_type: resumes mid-legacy pass,+ // advances once (processor→legacy already done here), then exhausts.+ let mut tracking = legacy_tracking();+ assert!(tracking.draining_legacy_rows);+ assert_eq!(tracking.last_fingerprint_id, "424242");+ assert_eq!(tracking.processed_rows, 7);+ // Already draining legacy rows → scope is exhausted.+ assert!(!move_to_next_scope(&mut tracking));+ }++ #[test]+ fn scope_advances_processor_to_legacy_then_stops() {+ let mut tracking = legacy_tracking();+ tracking.draining_legacy_rows = false;+ tracking.last_fingerprint_id = String::new();+ // Processor pass done → advance to legacy.+ assert!(move_to_next_scope(&mut tracking));+ assert!(tracking.draining_legacy_rows);+ assert_eq!(tracking.last_fingerprint_id, "");+ // Legacy pass done → no more scopes.+ assert!(!move_to_next_scope(&mut tracking));+ }++ #[test]+ fn selected_clone_retry_stops_after_its_legacy_pass() {+ for selected in [+ BlocklistTransactionType::Payment,+ BlocklistTransactionType::Payout,+ ] {+ let mut tracking = legacy_tracking(); // starts draining_legacy_rows = true+ tracking.selected_transaction_type = Some(selected);+ // Already in legacy pass → exhausted.+ assert!(!move_to_next_scope(&mut tracking));+ // Advance to next target: cursor resets cleanly.+ assert!(move_to_next_target(&mut tracking));+ assert_eq!(tracking.current_target, 1);+ assert!(!tracking.draining_legacy_rows);+ assert_eq!(tracking.last_fingerprint_id, "");+ assert_eq!(tracking.processed_rows, 0);+ // New target starts with processor pass, then legacy, then stops.+ assert!(move_to_next_scope(&mut tracking));+ assert!(tracking.draining_legacy_rows);+ assert!(!move_to_next_scope(&mut tracking));+ }+ }++ #[test]+ fn next_target_resets_cursor_and_advances_index() {+ let mut tracking = legacy_tracking();+ assert!(move_to_next_target(&mut tracking));+ assert_eq!(tracking.current_target, 1);+ assert!(!tracking.draining_legacy_rows);+ assert_eq!(tracking.last_fingerprint_id, "");+ assert_eq!(tracking.processed_rows, 0);+ assert!(!move_to_next_target(&mut tracking));+ }+}diff --git a/migrations/2026-10-10-100000_scope_blocklist_by_transaction_type/down.sql b/migrations/2026-10-10-100000_scope_blocklist_by_transaction_type/down.sqlnew file mode 100644index 0000000000..386a3d0339--- /dev/null+++ b/migrations/2026-10-10-100000_scope_blocklist_by_transaction_type/down.sql@@ -0,0 +1 @@+ALTER TABLE blocklist DROP COLUMN transaction_type;diff --git a/migrations/2026-10-10-100000_scope_blocklist_by_transaction_type/up.sql b/migrations/2026-10-10-100000_scope_blocklist_by_transaction_type/up.sqlnew file mode 100644index 0000000000..1ad9c175e7--- /dev/null+++ b/migrations/2026-10-10-100000_scope_blocklist_by_transaction_type/up.sql@@ -0,0 +1,2 @@+-- Commit the column addition before the following migration backfills rows.+ALTER TABLE blocklist ADD COLUMN transaction_type TEXT;diff --git a/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/down.sql b/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/down.sqlnew file mode 100644index 0000000000..bef90570ef--- /dev/null+++ b/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/down.sql@@ -0,0 +1,3 @@+-- Keep payment values intact; the preceding schema migration drops the+-- transaction_type column when the full change is rolled back.+SELECT 1;diff --git a/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/metadata.toml b/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/up.sql b/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/up.sqlnew file mode 100644index 0000000000..1e09e9d0cc--- /dev/null+++ b/migrations/2026-10-10-100050_backfill_blocklist_transaction_type/up.sql@@ -0,0 +1,31 @@+-- Existing rows are payment-scoped. The preceding migration commits the+-- column addition first, releasing its ALTER TABLE lock before this backfill.+-- Keep this file as one DO statement; metadata.toml allows per-batch commits.+DO $$+DECLARE+ rows_updated BIGINT;+BEGIN+ LOOP+ WITH batch AS (+ SELECT ctid+ FROM blocklist+ WHERE transaction_type IS NULL+ LIMIT 5000+ FOR UPDATE+ )+ UPDATE blocklist AS b+ SET transaction_type = 'payment'+ FROM batch+ WHERE b.ctid = batch.ctid;++ GET DIAGNOSTICS rows_updated = ROW_COUNT;++ COMMIT;++ RAISE NOTICE 'Updated % rows', rows_updated;+ EXIT WHEN rows_updated = 0;++ PERFORM pg_sleep(1);+ END LOOP;+END;+$$;diff --git a/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/down.sql b/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/down.sqlnew file mode 100644index 0000000000..5c836c7274--- /dev/null+++ b/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_pm_fingerprint_profile_transaction_type_index;diff --git a/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/metadata.toml b/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/up.sql b/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/up.sqlnew file mode 100644index 0000000000..c9c4917945--- /dev/null+++ b/migrations/2026-10-10-100100_add_blocklist_pm_profile_transaction_index/up.sql@@ -0,0 +1,3 @@+-- Build the replacement before removing the existing uniqueness indexes.+CREATE UNIQUE INDEX CONCURRENTLY blocklist_pm_fingerprint_profile_transaction_type_index+ ON blocklist (processor_merchant_id, fingerprint_id, profile_id, transaction_type);diff --git a/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/down.sql b/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/down.sqlnew file mode 100644index 0000000000..d0e87e690d--- /dev/null+++ b/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_pm_fingerprint_null_profile_transaction_type_index;diff --git a/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/metadata.toml b/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/up.sql b/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/up.sqlnew file mode 100644index 0000000000..c719874393--- /dev/null+++ b/migrations/2026-10-10-100200_add_blocklist_pm_null_profile_transaction_index/up.sql@@ -0,0 +1,4 @@+-- Build the replacement before removing the existing uniqueness indexes.+CREATE UNIQUE INDEX CONCURRENTLY blocklist_pm_fingerprint_null_profile_transaction_type_index+ ON blocklist (processor_merchant_id, fingerprint_id, transaction_type)+ WHERE profile_id IS NULL;diff --git a/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/down.sql b/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/down.sqlnew file mode 100644index 0000000000..dc4c7c33db--- /dev/null+++ b/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_merchant_fingerprint_profile_transaction_type_index;diff --git a/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/metadata.toml b/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/up.sql b/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/up.sqlnew file mode 100644index 0000000000..c90e8e7381--- /dev/null+++ b/migrations/2026-10-10-100300_add_blocklist_merchant_profile_transaction_index/up.sql@@ -0,0 +1,3 @@+-- Build the replacement before removing the existing uniqueness indexes.+CREATE UNIQUE INDEX CONCURRENTLY blocklist_merchant_fingerprint_profile_transaction_type_index+ ON blocklist (merchant_id, fingerprint_id, profile_id, transaction_type);diff --git a/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/down.sql b/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/down.sqlnew file mode 100644index 0000000000..5d1f127eb2--- /dev/null+++ b/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/down.sql@@ -0,0 +1,3 @@+-- Resolve conflicting payment/payout rows before restoring the old uniqueness rule.+CREATE UNIQUE INDEX CONCURRENTLY blocklist_processor_merchant_id_fingerprint_id_profile_id_index+ ON blocklist (processor_merchant_id, fingerprint_id, profile_id);diff --git a/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/metadata.toml b/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/up.sql b/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/up.sqlnew file mode 100644index 0000000000..0b59c1b42d--- /dev/null+++ b/migrations/2026-10-10-100400_drop_blocklist_pm_profile_index/up.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_processor_merchant_id_fingerprint_id_profile_id_index;diff --git a/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/down.sql b/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/down.sqlnew file mode 100644index 0000000000..12c23998e7--- /dev/null+++ b/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/down.sql@@ -0,0 +1,4 @@+-- Resolve conflicting payment/payout rows before restoring the old uniqueness rule.+CREATE UNIQUE INDEX CONCURRENTLY blocklist_pm_fingerprint_null_profile_index+ ON blocklist (processor_merchant_id, fingerprint_id)+ WHERE profile_id IS NULL;diff --git a/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/metadata.toml b/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/up.sql b/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/up.sqlnew file mode 100644index 0000000000..4d6ec2ed05--- /dev/null+++ b/migrations/2026-10-10-100500_drop_blocklist_pm_null_profile_index/up.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_pm_fingerprint_null_profile_index;diff --git a/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/down.sql b/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/down.sqlnew file mode 100644index 0000000000..5d53ebbbd9--- /dev/null+++ b/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/down.sql@@ -0,0 +1,3 @@+-- Resolve conflicting payment/payout rows before restoring the old uniqueness rule.+CREATE UNIQUE INDEX CONCURRENTLY blocklist_merchant_id_fingerprint_id_profile_id_index+ ON blocklist (merchant_id, fingerprint_id, profile_id);diff --git a/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/metadata.toml b/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/metadata.tomlnew file mode 100644index 0000000000..79e9221c1f--- /dev/null+++ b/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/metadata.toml@@ -0,0 +1 @@+run_in_transaction = falsediff --git a/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/up.sql b/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/up.sqlnew file mode 100644index 0000000000..a8662bddc2--- /dev/null+++ b/migrations/2026-10-10-100600_drop_blocklist_merchant_profile_index/up.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS blocklist_merchant_id_fingerprint_id_profile_id_index;