Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(crm): filter companies by hidden, admin-gated in soup (#3657)

Evan Hutnik57c301423c9c
diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts
index 10c74196b9..99ae429381 100644
--- a/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts
@@ -4,6 +4,7 @@
* search_service
* OpenAPI spec version: 0.1.0
*/
+import type { CrmCompanyFiltersHidden } from './crmCompanyFiltersHidden';
/**
* The crm company filters used to narrow which CRM companies appear in soup.
@@ -12,4 +13,9 @@ export interface CrmCompanyFilters {
/** CRM company ids to filter by. Examples: ['11111111-...']. Empty to
include all of the team's visible CRM companies. */
company_ids?: string[];
+ /** Optional `crm_companies.hidden` filter. `None` = visible only
+(default for back-compat with non-admin callers). `Some(false)` =
+visible only (explicit). `Some(true)` = hidden only — requires
+admin/owner team role; enforced upstream in soup's axum router. */
+ hidden?: CrmCompanyFiltersHidden;
}
diff --git a/js/app/packages/service-clients/service-search/generated/models/crmCompanyFiltersHidden.ts b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFiltersHidden.ts
new file mode 100644
index 0000000000..a8d81bb3f3
--- /dev/null
+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFiltersHidden.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional `crm_companies.hidden` filter. `None` = visible only
+(default for back-compat with non-admin callers). `Some(false)` =
+visible only (explicit). `Some(true)` = hidden only — requires
+admin/owner team role; enforced upstream in soup's axum router.
+ */
+export type CrmCompanyFiltersHidden = boolean | null;
diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.ts
index accaea1983..4fdaeb2539 100644
--- a/js/app/packages/service-clients/service-search/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts
@@ -72,6 +72,7 @@ export * from './chatSearchResponseItemWithMetadata';
export * from './chatSearchResponseItemWithMetadataAllOf';
export * from './chatSearchResponseItemWithMetadataAllOfMetadata';
export * from './crmCompanyFilters';
+export * from './crmCompanyFiltersHidden';
export * from './dataType';
export * from './documentFilters';
export * from './documentFiltersImportance';
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index 6c9a6eadf6..0540cd2e85 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -829,6 +829,10 @@
"type": "string"
},
"description": "CRM company ids to filter by. Examples: ['11111111-...']. Empty to\ninclude all of the team's visible CRM companies."
+ },
+ "hidden": {
+ "type": ["boolean", "null"],
+ "description": "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin/owner team role; enforced upstream in soup's axum router."
}
}
},
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts
index 6f1cf3546b..07a4b3e2f1 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { CrmCompanyFiltersHidden } from './crmCompanyFiltersHidden';
/**
* The crm company filters used to narrow which CRM companies appear in soup.
@@ -12,4 +13,9 @@ export interface CrmCompanyFilters {
/** CRM company ids to filter by. Examples: ['11111111-...']. Empty to
include all of the team's visible CRM companies. */
company_ids?: string[];
+ /** Optional `crm_companies.hidden` filter. `None` = visible only
+(default for back-compat with non-admin callers). `Some(false)` =
+visible only (explicit). `Some(true)` = hidden only — requires
+admin/owner team role; enforced upstream in soup's axum router. */
+ hidden?: CrmCompanyFiltersHidden;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFiltersHidden.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFiltersHidden.ts
new file mode 100644
index 0000000000..5baf4a0229
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFiltersHidden.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional `crm_companies.hidden` filter. `None` = visible only
+(default for back-compat with non-admin callers). `Some(false)` =
+visible only (explicit). `Some(true)` = hidden only — requires
+admin/owner team role; enforced upstream in soup's axum router.
+ */
+export type CrmCompanyFiltersHidden = boolean | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index a90627f476..27202f888d 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -269,6 +269,7 @@ export * from './crmCommentOrder';
export * from './crmCommentSender';
export * from './crmCommentThread';
export * from './crmCompanyFilters';
+export * from './crmCompanyFiltersHidden';
export * from './crmContactResponse';
export * from './crmContactResponseName';
export * from './crmThread';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index cd9622f606..fa091f58bd 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -7314,6 +7314,12 @@ export const postItemsSoupBody = zod
.describe(
"CRM company ids to filter by. Examples: ['11111111-...']. Empty to\ninclude all of the team's visible CRM companies."
),
+ hidden: zod
+ .boolean()
+ .nullish()
+ .describe(
+ "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin\/owner team role; enforced upstream in soup's axum router."
+ ),
})
.optional()
.describe(
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 30ca8171e8..f52b055715 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6417,6 +6417,16 @@
}
}
},
+ "403": {
+ "description": "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -6465,6 +6475,16 @@
}
}
},
+ "403": {
+ "description": "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -6515,6 +6535,16 @@
}
}
},
+ "403": {
+ "description": "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
"500": {
"description": "",
"content": {
@@ -10833,6 +10863,10 @@
"type": "string"
},
"description": "CRM company ids to filter by. Examples: ['11111111-...']. Empty to\ninclude all of the team's visible CRM companies."
+ },
+ "hidden": {
+ "type": ["boolean", "null"],
+ "description": "Optional `crm_companies.hidden` filter. `None` = visible only\n(default for back-compat with non-admin callers). `Some(false)` =\nvisible only (explicit). `Some(true)` = hidden only — requires\nadmin/owner team role; enforced upstream in soup's axum router."
}
}
},
diff --git a/rust/cloud-storage/.sqlx/query-32d69c4b151395989d7d00d594b1bd7161f5cc97b63616e9062feef7a335321c.json b/rust/cloud-storage/.sqlx/query-32d69c4b151395989d7d00d594b1bd7161f5cc97b63616e9062feef7a335321c.json
deleted file mode 100644
index 06db0f26c9..0000000000
--- a/rust/cloud-storage/.sqlx/query-32d69c4b151395989d7d00d594b1bd7161f5cc97b63616e9062feef7a335321c.json
+++ /dev/null
@@ -1,60 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO comms_activity (\n id,\n user_id,\n channel_id,\n viewed_at\n )\n VALUES (\n $1, $2, $3, NOW()\n )\n ON CONFLICT (user_id, channel_id) DO UPDATE \n SET \n viewed_at = NOW(),\n updated_at = NOW()\n RETURNING \n id as \"id!: Uuid\",\n user_id as \"user_id!: String\",\n channel_id as \"channel_id!: Uuid\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\",\n viewed_at as \"viewed_at?: DateTime<Utc>\",\n interacted_at as \"interacted_at?: DateTime<Utc>\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id!: Uuid",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "user_id!: String",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "channel_id!: Uuid",
- "type_info": "Uuid"
- },
- {
- "ordinal": 3,
- "name": "created_at!: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 4,
- "name": "updated_at!: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 5,
- "name": "viewed_at?: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 6,
- "name": "interacted_at?: DateTime<Utc>",
- "type_info": "Timestamp"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- true,
- true
- ]
- },
- "hash": "32d69c4b151395989d7d00d594b1bd7161f5cc97b63616e9062feef7a335321c"
-}
diff --git a/rust/cloud-storage/.sqlx/query-68ce38278462b5328c5444aadd3f309c9fbe4f4a2883ee55e7247c65a911ee80.json b/rust/cloud-storage/.sqlx/query-68ce38278462b5328c5444aadd3f309c9fbe4f4a2883ee55e7247c65a911ee80.json
deleted file mode 100644
index d682fd6e7c..0000000000
--- a/rust/cloud-storage/.sqlx/query-68ce38278462b5328c5444aadd3f309c9fbe4f4a2883ee55e7247c65a911ee80.json
+++ /dev/null
@@ -1,60 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO comms_activity (\n id,\n user_id,\n channel_id,\n interacted_at\n )\n VALUES (\n $1, $2, $3, NOW()\n )\n ON CONFLICT (user_id, channel_id) DO UPDATE \n SET \n interacted_at = NOW(),\n updated_at = NOW()\n RETURNING \n id as \"id!: Uuid\",\n user_id as \"user_id!: String\",\n channel_id as \"channel_id!: Uuid\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\",\n viewed_at as \"viewed_at?: DateTime<Utc>\",\n interacted_at as \"interacted_at?: DateTime<Utc>\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id!: Uuid",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "user_id!: String",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "channel_id!: Uuid",
- "type_info": "Uuid"
- },
- {
- "ordinal": 3,
- "name": "created_at!: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 4,
- "name": "updated_at!: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 5,
- "name": "viewed_at?: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 6,
- "name": "interacted_at?: DateTime<Utc>",
- "type_info": "Timestamp"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Uuid"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- true,
- true
- ]
- },
- "hash": "68ce38278462b5328c5444aadd3f309c9fbe4f4a2883ee55e7247c65a911ee80"
-}
diff --git a/rust/cloud-storage/.sqlx/query-694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad.json b/rust/cloud-storage/.sqlx/query-694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad.json
new file mode 100644
index 0000000000..fa83ca1fa5
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad.json
@@ -0,0 +1,88 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH limited_companies AS (\n SELECT\n c.id,\n c.team_id,\n c.email_sync,\n c.hidden,\n c.first_interaction,\n c.last_interaction\n FROM crm_companies c\n WHERE c.team_id = $1\n AND c.hidden = COALESCE($5::bool, FALSE)\n AND EXISTS (\n SELECT 1 FROM team_crm_settings tcs\n WHERE tcs.team_id = $1 AND tcs.crm_enabled\n )\n AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))\n -- Keyset seek (NULL = first page): keep only rows that\n -- sort strictly after the cursor.\n AND (\n $6::timestamptz IS NULL\n OR (\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n ELSE c.last_interaction\n END,\n c.id::text\n ) < ($6, $7)\n )\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n ELSE c.last_interaction\n END DESC,\n c.id DESC\n LIMIT $3\n )\n SELECT\n lc.id AS \"company_id!\",\n lc.team_id AS \"company_team_id!\",\n lc.email_sync AS \"company_email_sync!\",\n lc.hidden AS \"company_hidden!\",\n lc.first_interaction AS \"company_created_at!\",\n lc.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\"\n FROM limited_companies lc\n LEFT JOIN crm_domains d ON d.company_id = lc.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN lc.first_interaction\n ELSE lc.last_interaction\n END DESC,\n lc.id DESC,\n d.created_at ASC NULLS LAST\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "company_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "company_team_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "company_email_sync!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "company_hidden!",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "company_created_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "company_updated_at!",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "domain_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "domain?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "domain_created_at?",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "dir_name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "dir_description?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray",
+ "Int8",
+ "Text",
+ "Bool",
+ "Timestamptz",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "694440e1141a1afea892f03c2397da3f899bd4ca4ad3adc60c1c7babcd39faad"
+}
diff --git a/rust/cloud-storage/.sqlx/query-fc567a15d9fdb4dd36547a34b9b3d43ef5cb4e898a074e2655d84efcad25dc4d.json b/rust/cloud-storage/.sqlx/query-fc567a15d9fdb4dd36547a34b9b3d43ef5cb4e898a074e2655d84efcad25dc4d.json
deleted file mode 100644
index 4389f1a7d0..0000000000
--- a/rust/cloud-storage/.sqlx/query-fc567a15d9fdb4dd36547a34b9b3d43ef5cb4e898a074e2655d84efcad25dc4d.json
+++ /dev/null
@@ -1,87 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH limited_companies AS (\n SELECT\n c.id,\n c.team_id,\n c.email_sync,\n c.hidden,\n c.first_interaction,\n c.last_interaction\n FROM crm_companies c\n WHERE c.team_id = $1\n AND c.hidden = FALSE\n AND EXISTS (\n SELECT 1 FROM team_crm_settings tcs\n WHERE tcs.team_id = $1 AND tcs.crm_enabled\n )\n AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))\n -- Keyset seek (NULL = first page): keep only rows that\n -- sort strictly after the cursor.\n AND (\n $5::timestamptz IS NULL\n OR (\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n ELSE c.last_interaction\n END,\n c.id::text\n ) < ($5, $6)\n )\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN c.first_interaction\n ELSE c.last_interaction\n END DESC,\n c.id DESC\n LIMIT $3\n )\n SELECT\n lc.id AS \"company_id!\",\n lc.team_id AS \"company_team_id!\",\n lc.email_sync AS \"company_email_sync!\",\n lc.hidden AS \"company_hidden!\",\n lc.first_interaction AS \"company_created_at!\",\n lc.last_interaction AS \"company_updated_at!\",\n d.id AS \"domain_id?\",\n d.domain AS \"domain?\",\n d.created_at AS \"domain_created_at?\",\n dd.name AS \"dir_name?\",\n dd.description AS \"dir_description?\"\n FROM limited_companies lc\n LEFT JOIN crm_domains d ON d.company_id = lc.id\n LEFT JOIN crm_domain_directory dd\n ON LOWER(dd.domain) = LOWER(d.domain)\n ORDER BY\n CASE $4\n WHEN 'created_at' THEN lc.first_interaction\n ELSE lc.last_interaction\n END DESC,\n lc.id DESC,\n d.created_at ASC NULLS LAST\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "company_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "company_team_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "company_email_sync!",
- "type_info": "Bool"
- },
- {
- "ordinal": 3,
- "name": "company_hidden!",
- "type_info": "Bool"
- },
- {
- "ordinal": 4,
- "name": "company_created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 5,
- "name": "company_updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "domain_id?",
- "type_info": "Uuid"
- },
- {
- "ordinal": 7,
- "name": "domain?",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "domain_created_at?",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 9,
- "name": "dir_name?",
- "type_info": "Text"
- },
- {
- "ordinal": 10,
- "name": "dir_description?",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "UuidArray",
- "Int8",
- "Text",
- "Timestamptz",
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- false,
- true,
- true
- ]
- },
- "hash": "fc567a15d9fdb4dd36547a34b9b3d43ef5cb4e898a074e2655d84efcad25dc4d"
-}
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index 70699690d6..31ad6d0e6d 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -299,14 +299,18 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// Lists a team's CRM companies for the soup feed, hydrated with
/// domains and primary-domain directory metadata. Honors the
/// team-level killswitch (missing or `crm_enabled = false` →
- /// empty) and excludes `hidden = true` rows. Empty `company_ids`
- /// = all non-hidden companies; non-empty = whitelist. Both sort
- /// orders tiebreak on `id DESC`. `cursor` seeks strictly past the
- /// previous soup page's last row (`None` = first page).
+ /// empty). `hidden = None` or `Some(false)` returns visible
+ /// companies; `Some(true)` returns hidden companies — the caller
+ /// is responsible for enforcing admin/owner role before reaching
+ /// this method (soup's axum router does this). Empty `company_ids`
+ /// = all rows matching the `hidden` filter; non-empty = whitelist.
+ /// `cursor` seeks strictly past the previous soup page's last row
+ /// (`None` = first page). Both sort orders tiebreak on `id DESC`.
fn list_companies_for_soup(
&self,
team_id: &uuid::Uuid,
company_ids: &[uuid::Uuid],
+ hidden: Option<bool>,
sort: CrmCompanyListSort,
cursor: Option<CrmCompanySoupCursor>,
limit: i64,
diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rs
index 989146e736..5ceeec2537 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -185,6 +185,7 @@ pub trait CrmService: Clone + Send + Sync + 'static {
&self,
team_id: &uuid::Uuid,
company_ids: &[uuid::Uuid],
+ hidden: Option<bool>,
sort: CrmCompanyListSort,
cursor: Option<CrmCompanySoupCursor>,
limit: i64,
@@ -493,12 +494,13 @@ where
&self,
team_id: &uuid::Uuid,
company_ids: &[uuid::Uuid],
+ hidden: Option<bool>,
sort: CrmCompanyListSort,
cursor: Option<CrmCompanySoupCursor>,
limit: i64,
) -> Result<Vec<CrmCompanyForSoup>, CrmError> {
self.companies_repository
- .list_companies_for_soup(team_id, company_ids, sort, cursor, limit)
+ .list_companies_for_soup(team_id, company_ids, hidden, sort, cursor, limit)
.await
}
@@ -667,6 +669,7 @@ impl CrmService for NoOpCrmService {
&self,
_team_id: &uuid::Uuid,
_company_ids: &[uuid::Uuid],
+ _hidden: Option<bool>,
_sort: CrmCompanyListSort,
_cursor: Option<CrmCompanySoupCursor>,
_limit: i64,
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index 7363ebbfd6..4e572cbc75 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -975,6 +975,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
&self,
team_id: &uuid::Uuid,
company_ids: &[uuid::Uuid],
+ hidden: Option<bool>,
sort: CrmCompanyListSort,
cursor: Option<CrmCompanySoupCursor>,
limit: i64,
@@ -995,6 +996,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// domain first. Sort columns are `first_interaction` /
// `last_interaction` from populate_contact (both NOT NULL —
// see the `crm_interaction_timestamps` migration).
+ //
+ // `$5` (`hidden`) defaults to visible-only when `NULL`; the
+ // admin/owner role check for `Some(true)` is enforced upstream
+ // in soup's axum router.
let rows = sqlx::query!(
r#"
WITH limited_companies AS (
@@ -1007,7 +1012,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
c.last_interaction
FROM crm_companies c
WHERE c.team_id = $1
- AND c.hidden = FALSE
+ AND c.hidden = COALESCE($5::bool, FALSE)
AND EXISTS (
SELECT 1 FROM team_crm_settings tcs
WHERE tcs.team_id = $1 AND tcs.crm_enabled
@@ -1016,14 +1021,14 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
-- Keyset seek (NULL = first page): keep only rows that
-- sort strictly after the cursor.
AND (
- $5::timestamptz IS NULL
+ $6::timestamptz IS NULL
OR (
CASE $4
WHEN 'created_at' THEN c.first_interaction
ELSE c.last_interaction
END,
c.id::text
- ) < ($5, $6)
+ ) < ($6, $7)
)
ORDER BY
CASE $4
@@ -1061,6 +1066,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
company_ids,
limit,
sort_method_str,
+ hidden,
cursor_ts,
cursor_id,
)
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
index ccd4d22534..52fd3ea29b 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
@@ -1559,7 +1559,7 @@ async fn list_for_soup_returns_empty_when_killswitch_missing(pool: PgPool) -> an
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, None, 100)
+ .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)
.await?;
assert!(
result.is_empty(),
@@ -1581,7 +1581,7 @@ async fn list_for_soup_returns_empty_when_killswitch_off(pool: PgPool) -> anyhow
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, None, 100)
+ .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)
.await?;
assert!(result.is_empty());
Ok(())
@@ -1602,7 +1602,7 @@ async fn list_for_soup_excludes_hidden_rows(pool: PgPool) -> anyhow::Result<()>
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, None, 100)
+ .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)
.await?;
let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();
assert_eq!(ids, vec![visible], "hidden = TRUE rows must not appear");
@@ -1615,6 +1615,57 @@ async fn list_for_soup_excludes_hidden_rows(pool: PgPool) -> anyhow::Result<()>
Ok(())
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_returns_hidden_when_hidden_true(pool: PgPool) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ enable_crm_for_team(&pool, team).await?;
+ let visible = insert_company(&pool, team, true, &["acme.com"]).await?;
+ let hidden = insert_company(&pool, team, true, &["zeta.com"]).await?;
+ sqlx::query("UPDATE crm_companies SET hidden = TRUE WHERE id = $1")
+ .bind(hidden)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+
+ let hidden_only = repo
+ .list_companies_for_soup(
+ &team,
+ &[],
+ Some(true),
+ CrmCompanyListSort::UpdatedAt,
+ None,
+ 100,
+ )
+ .await?;
+ let ids: Vec<Uuid> = hidden_only.iter().map(|c| c.company.id).collect();
+ assert_eq!(
+ ids,
+ vec![hidden],
+ "hidden=Some(true) must return only hidden rows"
+ );
+
+ let visible_only_explicit = repo
+ .list_companies_for_soup(
+ &team,
+ &[],
+ Some(false),
+ CrmCompanyListSort::UpdatedAt,
+ None,
+ 100,
+ )
+ .await?;
+ let ids: Vec<Uuid> = visible_only_explicit.iter().map(|c| c.company.id).collect();
+ assert_eq!(
+ ids,
+ vec![visible],
+ "hidden=Some(false) must behave the same as None (visible only)",
+ );
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn list_for_soup_hydrates_name_and_description_from_directory(
pool: PgPool,
@@ -1637,7 +1688,7 @@ async fn list_for_soup_hydrates_name_and_description_from_directory(
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, None, 100)
+ .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)
.await?;
assert_eq!(result.len(), 1);
assert_eq!(result[0].name.as_deref(), Some("Acme Inc."));
@@ -1672,7 +1723,7 @@ async fn list_for_soup_returns_none_for_negative_cache_directory_row(
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, None, 100)
+ .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)
.await?;
assert_eq!(result.len(), 1);
assert_eq!(result[0].name, None);
@@ -1691,7 +1742,14 @@ async fn list_for_soup_filters_by_company_ids_when_non_empty(pool: PgPool) -> an
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_companies_for_soup(&team, &[wanted], CrmCompanyListSort::UpdatedAt, None, 100)
+ .list_companies_for_soup(
+ &team,
+ &[wanted],
+ None,
+ CrmCompanyListSort::UpdatedAt,
+ None,
+ 100,
+ )
.await?;
let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();
assert_eq!(ids, vec![wanted]);
@@ -1711,7 +1769,7 @@ async fn list_for_soup_does_not_leak_other_team_rows(pool: PgPool) -> anyhow::Re
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_companies_for_soup(&team_b, &[], CrmCompanyListSort::UpdatedAt, None, 100)
+ .list_companies_for_soup(&team_b, &[], None, CrmCompanyListSort::UpdatedAt, None, 100)
.await?;
let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();
assert_eq!(ids, vec![b_only]);
@@ -1755,7 +1813,7 @@ async fn list_for_soup_paginates_past_cursor(pool: PgPool) -> anyhow::Result<()>
let mut first_page: Vec<Uuid> = Vec::new();
for page_idx in 0..10 {
let page = repo
- .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, cursor, 2)
+ .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, cursor, 2)
.await?;
if page.is_empty() {
break;
@@ -1831,7 +1889,7 @@ async fn list_for_soup_pagination_breaks_ties_on_id(pool: PgPool) -> anyhow::Res
let mut cursor: Option<CrmCompanySoupCursor> = None;
for _ in 0..10 {
let page = repo
- .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, cursor, 2)
+ .list_companies_for_soup(&team, &[], None, CrmCompanyListSort::UpdatedAt, cursor, 2)
.await?;
if page.is_empty() {
break;
diff --git a/rust/cloud-storage/item_filters/src/ast/crm_company.rs b/rust/cloud-storage/item_filters/src/ast/crm_company.rs
index df19e85f6b..274ac866b2 100644
--- a/rust/cloud-storage/item_filters/src/ast/crm_company.rs
+++ b/rust/cloud-storage/item_filters/src/ast/crm_company.rs
@@ -10,17 +10,32 @@ pub enum CrmCompanyLiteral {
/// matches a single crm_company by id
#[serde(rename = "id")]
Id(Uuid),
+ /// matches companies by `crm_companies.hidden` — `true` requires
+ /// admin/owner team role (enforced upstream in soup's axum router)
+ #[serde(rename = "hidden")]
+ Hidden(bool),
}
impl ExpandFrame<CrmCompanyLiteral> for CrmCompanyFilters {
type Err = ExpandErr;
fn expand_ast(input: Self) -> Result<Option<Expr<CrmCompanyLiteral>>, Self::Err> {
- let CrmCompanyFilters { company_ids } = input;
+ let CrmCompanyFilters {
+ company_ids,
+ hidden,
+ } = input;
- Ok(company_ids
+ let ids_expr = company_ids
.iter()
.map(|s| Uuid::parse_str(s))
- .try_expand(|r| r.map(CrmCompanyLiteral::Id), Expr::or)?)
+ .try_expand(|r| r.map(CrmCompanyLiteral::Id), Expr::or)?;
+
+ let hidden_expr = hidden.map(|b| Expr::val(CrmCompanyLiteral::Hidden(b)));
+
+ Ok(match (ids_expr, hidden_expr) {
+ (None, None) => None,
+ (Some(e), None) | (None, Some(e)) => Some(e),
+ (Some(ids), Some(h)) => Some(Expr::and(ids, h)),
+ })
}
}
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index 0203bdee1b..0ce9108e4b 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -466,12 +466,21 @@ pub struct CrmCompanyFilters {
/// include all of the team's visible CRM companies.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub company_ids: Vec<String>,
+ /// Optional `crm_companies.hidden` filter. `None` = visible only
+ /// (default for back-compat with non-admin callers). `Some(false)` =
+ /// visible only (explicit). `Some(true)` = hidden only — requires
+ /// admin/owner team role; enforced upstream in soup's axum router.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub hidden: Option<bool>,
}
impl IsEmpty for CrmCompanyFilters {
fn is_empty(&self) -> bool {
- let CrmCompanyFilters { company_ids } = self;
- company_ids.is_empty()
+ let CrmCompanyFilters {
+ company_ids,
+ hidden,
+ } = self;
+ company_ids.is_empty() && hidden.is_none()
}
}
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 9c789bb479..93f644fd3c 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -402,9 +402,9 @@ impl SoupRequest<Option<EntityFilterAst>> {
| SimpleSortMethod::ViewedUpdated => CrmCompanyListSort::UpdatedAt,
};
- let mut company_ids = Vec::new();
+ let mut extract = CrmCompanyFilterExtract::default();
if let Some(tree) = filter_ast.and_then(|a| a.crm_company_filter.as_ref())
- && !collect_crm_company_ids(tree, &mut company_ids)
+ && !extract_crm_company_filter(tree, &mut extract)
{
// Fail closed: unsupported AST shape would widen the result
// set. Skip the CRM sub-request rather than over-include.
@@ -413,7 +413,8 @@ impl SoupRequest<Option<EntityFilterAst>> {
Some(GetCrmCompaniesRequest {
team_id,
- company_ids,
+ company_ids: extract.ids,
+ hidden: extract.hidden,
sort,
cursor,
// Match the soup paginator's bounds so the CRM layer doesn't
@@ -493,8 +494,13 @@ pub struct GetCrmCompaniesRequest {
/// Team whose CRM companies to list. Derived from the team receipt.
pub team_id: Uuid,
/// Filter to specific company ids. Empty = all of the team's
- /// non-hidden companies (subject to the killswitch).
+ /// companies matching `hidden` (subject to the killswitch).
pub company_ids: Vec<Uuid>,
+ /// Optional `crm_companies.hidden` filter. `None` = visible only
+ /// (default); `Some(false)` = visible only (explicit); `Some(true)`
+ /// = hidden only. The admin/owner role check is enforced upstream
+ /// in soup's axum router before reaching this request.
+ pub hidden: Option<bool>,
/// Which timestamp column to sort by.
pub sort: CrmCompanyListSort,
/// Keyset cursor to seek past the previous page (`None` = first page).
@@ -503,19 +509,59 @@ pub struct GetCrmCompaniesRequest {
pub limit: i64,
}
-/// Walks a `CrmCompanyLiteral` AST collecting every `Id(uuid)` literal.
-/// Returns `false` when the AST contains `And` or `Not` — both shapes
-/// would change set semantics (`And` would intersect, `Not` would
-/// invert) but a flat collector can't represent that, so the caller
-/// fails closed rather than widening the result.
-fn collect_crm_company_ids(expr: &Expr<CrmCompanyLiteral>, out: &mut Vec<Uuid>) -> bool {
+/// Outcome of walking a `CrmCompanyLiteral` AST: the ids and the
+/// optional `hidden` constraint pulled out of the tree.
+#[derive(Debug, Default)]
+pub(crate) struct CrmCompanyFilterExtract {
+ pub ids: Vec<Uuid>,
+ pub hidden: Option<bool>,
+}
+
+/// Walks a `CrmCompanyLiteral` AST collecting `Id(uuid)` literals into
+/// `out.ids` and a single `Hidden(bool)` constraint into `out.hidden`.
+/// Returns `false` (fail closed) when:
+/// - `Not(_)` appears (would invert set semantics),
+/// - two `Hidden(_)` literals conflict (e.g. `Hidden(true) AND Hidden(false)`),
+/// - an `Or(_, _)` branch mixes ids and a hidden literal (would change
+/// set semantics in ways the simple extractor can't represent).
+fn extract_crm_company_filter(
+ expr: &Expr<CrmCompanyLiteral>,
+ out: &mut CrmCompanyFilterExtract,
+) -> bool {
+ match expr {
+ Expr::Literal(CrmCompanyLiteral::Id(id)) => {
+ out.ids.push(*id);
+ true
+ }
+ Expr::Literal(CrmCompanyLiteral::Hidden(b)) => match out.hidden {
+ Some(prev) if prev != *b => false,
+ _ => {
+ out.hidden = Some(*b);
+ true
+ }
+ },
+ // `And` of arbitrary sub-trees: each side contributes independently
+ // (e.g. id-OR AND Hidden).
+ Expr::And(a, b) => extract_crm_company_filter(a, out) && extract_crm_company_filter(b, out),
+ // `Or` is only safe over ids — mixing a Hidden literal under an Or
+ // would change semantics ("these ids OR all hidden") that the flat
+ // extract can't represent.
+ Expr::Or(a, b) => or_is_ids_only(a, out) && or_is_ids_only(b, out),
+ Expr::Not(_) => false,
+ }
+}
+
+/// Helper for [`extract_crm_company_filter`]: an `Or` branch must be a
+/// pure id sub-tree (nested `Or` of `Id` literals) — any `Hidden`, `And`,
+/// or `Not` inside fails closed.
+fn or_is_ids_only(expr: &Expr<CrmCompanyLiteral>, out: &mut CrmCompanyFilterExtract) -> bool {
match expr {
- Expr::Or(a, b) => collect_crm_company_ids(a, out) && collect_crm_company_ids(b, out),
Expr::Literal(CrmCompanyLiteral::Id(id)) => {
- out.push(*id);
+ out.ids.push(*id);
true
}
- Expr::And(_, _) | Expr::Not(_) => false,
+ Expr::Or(a, b) => or_is_ids_only(a, out) && or_is_ids_only(b, out),
+ _ => false,
}
}
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 177fe97841..a84196149b 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -411,6 +411,7 @@ where
let GetCrmCompaniesRequest {
team_id,
company_ids,
+ hidden,
sort,
cursor,
limit,
@@ -418,7 +419,7 @@ where
Ok(Either::Right(
self.crm_service
- .list_companies_for_soup(&team_id, &company_ids, sort, cursor, limit)
+ .list_companies_for_soup(&team_id, &company_ids, hidden, sort, cursor, limit)
.await
.map_err(|_| SoupErr::CrmErr)?
.into_iter()
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index 9a8eb8960d..3eac2a8827 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -25,7 +25,7 @@ use email::{
};
use entity_access::{
domain::{
- models::{EntityAccessReceipt, MemberTeamRole},
+ models::{AdminTeamRole, EntityAccessReceipt, MemberTeamRole},
ports::EntityAccessService,
},
inbound::axum_extractors::OptionalMacroUserTeamExtractor,
@@ -324,7 +324,7 @@ where
) -> Result<Json<PaginatedOpaqueCursor<SoupApiItem>>, SoupHandlerErr>
where
SoupRequest<R>: IntoSoupReqAst,
- R: Clone + Serialize + Send + RequestsCrmScope,
+ R: Clone + Serialize + Send + RequestsCrmScope + RequestsCrmAdmin,
{
let create_fallback = move || -> SoupQuery<R> {
let params_sort = params
@@ -355,6 +355,7 @@ where
// miss CRM scope on follow-up pages.
let team_receipt =
resolve_crm_team_receipt(cursor.filter().requests_crm_scope(), team_receipt_option)?;
+ require_crm_admin_role(cursor.filter().requests_crm_admin(), &team_receipt)?;
let res = self
.service
@@ -464,6 +465,45 @@ impl RequestsCrmScope for ApiEntityFilterAst {
}
}
+/// Filter bodies that may opt into admin-only CRM data (currently:
+/// hidden CRM companies) implement this so the soup handler can gate
+/// the request on an admin/owner team role.
+pub trait RequestsCrmAdmin {
+ /// True when this filter asks for data only admin/owner team
+ /// members may see — e.g. `crm_company_filters.hidden = Some(true)`.
+ fn requests_crm_admin(&self) -> bool;
+}
+
+impl RequestsCrmAdmin for EntityFilters {
+ fn requests_crm_admin(&self) -> bool {
+ matches!(self.crm_company_filters.hidden, Some(true))
+ }
+}
+
+impl RequestsCrmAdmin for ApiEntityFilterAst {
+ fn requests_crm_admin(&self) -> bool {
+ self.crm_company_filter
+ .as_deref()
+ .is_some_and(ast_requests_crm_admin)
+ }
+}
+
+/// Walks a `CrmCompanyLiteral` AST checking for any `Hidden(true)`
+/// literal. Mirrors the conservative shape the request-time extractor
+/// in `models::extract_crm_company_filter` allows: `And`/`Or` recurse;
+/// `Not` would invert and fail closed downstream, but for the *role
+/// gate* we still must inspect under `Not` to avoid a `Not(Hidden(false))`
+/// sneaking past — treat any path reaching a `Hidden(true)` literal as
+/// admin-required.
+fn ast_requests_crm_admin(expr: &Expr<CrmCompanyLiteral>) -> bool {
+ match expr {
+ Expr::Literal(CrmCompanyLiteral::Hidden(true)) => true,
+ Expr::Literal(_) => false,
+ Expr::And(a, b) | Expr::Or(a, b) => ast_requests_crm_admin(a) || ast_requests_crm_admin(b),
+ Expr::Not(a) => ast_requests_crm_admin(a),
+ }
+}
+
pub fn soup_router<T, U, EAS, S>(state: SoupRouterState<T, U, EAS>) -> Router<S>
where
T: SoupService,
@@ -513,6 +553,8 @@ pub enum SoupHandlerErr {
Expand,
#[error("CRM-scoped queries require team membership")]
CrmScopeForbidden,
+ #[error("Querying hidden CRM companies requires admin/owner team role")]
+ CrmAdminRequired,
}
impl From<SoupErr> for SoupHandlerErr {
@@ -528,7 +570,9 @@ impl IntoResponse for SoupHandlerErr {
fn into_response(self) -> axum::response::Response {
let status_code = match &self {
SoupHandlerErr::ExpandErr(_) | SoupHandlerErr::Expand => StatusCode::BAD_REQUEST,
- SoupHandlerErr::CrmScopeForbidden => StatusCode::FORBIDDEN,
+ SoupHandlerErr::CrmScopeForbidden | SoupHandlerErr::CrmAdminRequired => {
+ StatusCode::FORBIDDEN
+ }
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(
@@ -552,6 +596,7 @@ impl IntoResponse for SoupHandlerErr {
),
responses(
(status = 200, body=SoupPage),
+ (status = 403, description = "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role", body=ErrorResponse),
(status = 500, body=ErrorResponse),
)
)]
@@ -625,6 +670,7 @@ type SoupCursor<R> = axum_extra::either::Either<
),
responses(
(status = 200, body=SoupPage),
+ (status = 403, description = "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role", body=ErrorResponse),
(status = 500, body=ErrorResponse),
)
)]
@@ -693,6 +739,7 @@ pub struct PostSoupAstRequest {
request_body = PostSoupAstRequest,
responses(
(status = 200, body=SoupPage),
+ (status = 403, description = "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role", body=ErrorResponse),
(status = 500, body=ErrorResponse),
)
)]
@@ -760,6 +807,7 @@ pub struct PostGroupedSoupAstRequest {
request_body = PostGroupedSoupAstRequest,
responses(
(status = 200, body=GroupedSoupPage),
+ (status = 403, description = "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role", body=ErrorResponse),
(status = 500, body=ErrorResponse),
)
)]
@@ -819,6 +867,28 @@ fn resolve_crm_team_receipt(
Ok(receipt)
}
+/// Companion to [`resolve_crm_team_receipt`] for the admin-only CRM
+/// data path (currently: hidden CRM companies). `admin_requested` is
+/// the result of [`RequestsCrmAdmin::requests_crm_admin`] on the
+/// effective filter. Returns `Err(CrmAdminRequired)` when the request
+/// asks for admin-only data but the receipt is missing or the user's
+/// actual team role doesn't satisfy [`AdminTeamRole`].
+fn require_crm_admin_role(
+ admin_requested: bool,
+ receipt: &Option<EntityAccessReceipt<MemberTeamRole>>,
+) -> Result<(), SoupHandlerErr> {
+ if !admin_requested {
+ return Ok(());
+ }
+ let Some(receipt) = receipt else {
+ return Err(SoupHandlerErr::CrmAdminRequired);
+ };
+ if !receipt.entity_permission().satisfies::<AdminTeamRole>() {
+ return Err(SoupHandlerErr::CrmAdminRequired);
+ }
+ Ok(())
+}
+
#[derive(Debug, Default, Serialize, Deserialize, Clone, ToSchema)]
pub struct ApiEntityFilterAst {
/// the filters that should be applied to the document entity