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(soup): add crm_company entity type to soup feed (#3523)

Evan Hutnik59a34fff7780
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts b/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts
index 27874153cc..6074dc4cc9 100644
--- a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts
+++ b/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts
@@ -24,6 +24,7 @@ type QueryTarget =
| 'pf'
| 'callf'
| 'fef'
+ | 'ccf'
| 'propf';
export type TargetAstMap = {
@@ -111,6 +112,7 @@ const FIELD_CONFIG: Record<
callSpeakerId: { target: 'callf', field: 'Speaker' },
callAttended: { target: 'callf', field: 'Attended' },
foreignEntityRecordId: { target: 'fef', field: 'id' },
+ crmCompanyId: { target: 'ccf', field: 'id' },
};
const DATE_RANGE_FIELDS: Record<
@@ -161,6 +163,7 @@ export function compileToAst(state: QueryState): TargetAstMap {
pf: [],
callf: [],
fef: [],
+ ccf: [],
propf: [],
};
@@ -284,6 +287,11 @@ export function compileToAst(state: QueryState): TargetAstMap {
result.emailView = state.emailView;
}
+ // crm companies are opt-in: excluded unless a view sets `crmCompanyId`.
+ if (!result.ccf) {
+ result.ccf = AST.literal('id', NIL_UUID);
+ }
+
return result;
}
@@ -295,6 +303,7 @@ const ID_FIELD_NAMES: Partial<Record<QueryTarget, FieldName>> = {
pf: 'folderId',
callf: 'callId',
fef: 'foreignEntityRecordId',
+ ccf: 'crmCompanyId',
};
type DefineQueryFiltersOptions = {
diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts b/js/app/packages/app/component/next-soup/filters/filter-store/types.ts
index 280552469c..6f287c9c8c 100644
--- a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts
+++ b/js/app/packages/app/component/next-soup/filters/filter-store/types.ts
@@ -35,6 +35,7 @@ export type ArrayFieldFilters = {
callChannelId?: string[];
callSpeakerId?: string[];
foreignEntityRecordId?: string[];
+ crmCompanyId?: string[];
properties?: PropertyFilter[];
};
diff --git a/js/app/packages/app/component/next-soup/filters/query-filters.ts b/js/app/packages/app/component/next-soup/filters/query-filters.ts
index 4c935135cb..0658aa2fd5 100644
--- a/js/app/packages/app/component/next-soup/filters/query-filters.ts
+++ b/js/app/packages/app/component/next-soup/filters/query-filters.ts
@@ -11,6 +11,7 @@ export const QUERY_FILTERS_BASE: SoupItemsQueryFilters = {
call_filters: { call_ids: EXCLUDE },
channel_filters: { channel_ids: EXCLUDE },
chat_filters: { chat_ids: EXCLUDE },
+ crm_company_filters: { company_ids: EXCLUDE },
document_filters: { document_ids: EXCLUDE },
email_filters: { email_thread_ids: EXCLUDE },
foreign_entity_filters: { ids: EXCLUDE },
@@ -79,6 +80,11 @@ export function filterSoupItemByRequestBody(
!isIdFilteredOut(body.call_filters?.call_ids, data.callId) &&
!isAttendedFilteredOut(body.call_filters?.attended, data.attended)
)
+ .with(
+ { tag: 'crmCompany' },
+ ({ data }) =>
+ !isIdFilteredOut(body.crm_company_filters?.company_ids, data.id)
+ )
.with(
{ tag: 'foreignEntity' },
({ data }) =>
diff --git a/js/app/packages/channel/Attachments/attachment-utils.ts b/js/app/packages/channel/Attachments/attachment-utils.ts
index e3a235033c..db0b85e1b5 100644
--- a/js/app/packages/channel/Attachments/attachment-utils.ts
+++ b/js/app/packages/channel/Attachments/attachment-utils.ts
@@ -76,6 +76,8 @@ export function buildAttachmentEntityFilters(
call_filters: {
call_ids: callIds.length > 0 ? callIds : [NIL_ID],
},
+ // Attachments are never crm companies; exclude them.
+ crm_company_filters: { company_ids: [NIL_ID] },
};
}
diff --git a/js/app/packages/queries/notification/user-notifications.ts b/js/app/packages/queries/notification/user-notifications.ts
index 4badbe3e39..8ba6d2b6df 100644
--- a/js/app/packages/queries/notification/user-notifications.ts
+++ b/js/app/packages/queries/notification/user-notifications.ts
@@ -539,7 +539,10 @@ function notificationEntityTypeToSoupTag(
.with('project', () => 'project' as const)
.with('email_thread', () => 'emailThread' as const)
.with('foreign_entity', () => 'foreignEntity' as const)
- .with(P.union('user', 'team', 'call', 'static_file'), () => null)
+ .with(
+ P.union('user', 'team', 'call', 'static_file', 'crm_company'),
+ () => null
+ )
.exhaustive();
}
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
index 51bbb023d0..b0a30e688a 100644
--- a/js/app/packages/queries/properties/entity.ts
+++ b/js/app/packages/queries/properties/entity.ts
@@ -82,10 +82,12 @@ function optimisticUpdateSoupEntityProperty(
value: SoupPropertyValue
): SoupTransaction | undefined {
const current = getSoupEntityById(entityId);
+ // crmCompany has no properties; channel / call are also property-less.
if (
!current ||
current.tag === 'channel' ||
current.tag === 'call' ||
+ current.tag === 'crmCompany' ||
current.tag === 'foreignEntity' ||
!current.data.properties
) {
diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.ts
index 6fcf3f2306..2350380adf 100644
--- a/js/app/packages/queries/soup/normalized-cache/operations.ts
+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts
@@ -295,6 +295,10 @@ export function buildSingleEntityFilter(
...base,
call_filters: { call_ids: [entityId] },
}))
+ .with('crmCompany', () => ({
+ ...base,
+ crm_company_filters: { company_ids: [entityId] },
+ }))
.with('foreignEntity', () => ({
...base,
foreign_entity_filters: { ids: [entityId] },
diff --git a/js/app/packages/queries/soup/recently-viewed.ts b/js/app/packages/queries/soup/recently-viewed.ts
index 4e4d699b2f..85332bf778 100644
--- a/js/app/packages/queries/soup/recently-viewed.ts
+++ b/js/app/packages/queries/soup/recently-viewed.ts
@@ -19,9 +19,13 @@ const RECENTLY_VIEWED_GC_TIME = 10 * 60 * 1000; // 10 minutes
const recentlyViewedArgs: SoupItemsQueryArgs = {
params: { sort_method: 'viewed_at', limit: RECENTLY_VIEWED_LIMIT },
body: {
+ // No viewed_at signal on calls or crm_companies — exclude both.
call_filters: {
call_ids: ['00000000-0000-0000-0000-000000000000'],
},
+ crm_company_filters: {
+ company_ids: ['00000000-0000-0000-0000-000000000000'],
+ },
},
};
@@ -42,7 +46,13 @@ export function useRecentlyViewedSoupQuery() {
})
);
return page.items.flatMap((item): RecentlyViewedItem[] => {
- if (item.tag === 'call' || item.tag === 'foreignEntity') return [];
+ if (
+ item.tag === 'call' ||
+ item.tag === 'crmCompany' ||
+ item.tag === 'foreignEntity'
+ ) {
+ return [];
+ }
return [
{
diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.ts
index 3c882d4190..9ab40e0a1f 100644
--- a/js/app/packages/queries/soup/transform-utils.ts
+++ b/js/app/packages/queries/soup/transform-utils.ts
@@ -49,7 +49,7 @@ type InnerSearchResult =
type DisplayableSoupItem = Exclude<
SoupPage['items'][number],
- { tag: 'foreignEntity' }
+ { tag: 'foreignEntity' } | { tag: 'crmCompany' }
>;
type TypedInnerSearchResult =
@@ -465,6 +465,7 @@ export const mapSoupPageToEntityList: (
.filter(
(item): item is DisplayableSoupItem =>
item.tag !== 'foreignEntity' &&
+ item.tag !== 'crmCompany' &&
(item.tag !== 'document' ||
!options.instructionsIdQuery.isSuccess ||
item.data.id !== options.instructionsIdQuery.data)
diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts
index 25e7f80a20..806baedf2a 100644
--- a/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/entityType.ts
@@ -22,4 +22,5 @@ export const EntityType = {
call: 'call',
foreign_entity: 'foreign_entity',
static_file: 'static_file',
+ crm_company: 'crm_company',
} as const;
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index b70784cada..1ff5b625a0 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -2396,7 +2396,8 @@
"team",
"call",
"foreign_entity",
- "static_file"
+ "static_file",
+ "crm_company"
]
},
"ErrorResponse": {
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts
index d853b81635..ba77b13a7e 100644
--- a/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/entityType.ts
@@ -22,4 +22,5 @@ export const EntityType = {
call: 'call',
foreign_entity: 'foreign_entity',
static_file: 'static_file',
+ crm_company: 'crm_company',
} as const;
diff --git a/js/app/packages/service-clients/service-connection/openapi.json b/js/app/packages/service-clients/service-connection/openapi.json
index e25a098ee0..a2e6738914 100644
--- a/js/app/packages/service-clients/service-connection/openapi.json
+++ b/js/app/packages/service-clients/service-connection/openapi.json
@@ -239,7 +239,8 @@
"team",
"call",
"foreign_entity",
- "static_file"
+ "static_file",
+ "crm_company"
]
},
"GenericErrorResponse": {
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts
index 6f8fd0bf4b..2588cf4759 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/entityType.ts
@@ -22,4 +22,5 @@ export const EntityType = {
call: 'call',
foreign_entity: 'foreign_entity',
static_file: 'static_file',
+ crm_company: 'crm_company',
} as const;
diff --git a/js/app/packages/service-clients/service-notification/generated/zod.ts b/js/app/packages/service-clients/service-notification/generated/zod.ts
index 24bc910286..ee41e3b2b5 100644
--- a/js/app/packages/service-clients/service-notification/generated/zod.ts
+++ b/js/app/packages/service-clients/service-notification/generated/zod.ts
@@ -118,6 +118,7 @@ export const listTypedNotificationsResponse = zod
'call',
'foreign_entity',
'static_file',
+ 'crm_company',
])
.describe('The type of an entity in Macro'),
})
@@ -635,6 +636,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
'call',
'foreign_entity',
'static_file',
+ 'crm_company',
])
.describe('The type of an entity in Macro'),
})
@@ -1146,6 +1148,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod
'call',
'foreign_entity',
'static_file',
+ 'crm_company',
])
.describe('The type of an entity in Macro'),
})
@@ -1668,6 +1671,7 @@ export const getTypedNotificationByIdResponse = zod
'call',
'foreign_entity',
'static_file',
+ 'crm_company',
])
.describe('The type of an entity in Macro'),
})
diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.json
index df2c78a270..ddb4bf6534 100644
--- a/js/app/packages/service-clients/service-notification/openapi.json
+++ b/js/app/packages/service-clients/service-notification/openapi.json
@@ -1474,7 +1474,8 @@
"team",
"call",
"foreign_entity",
- "static_file"
+ "static_file",
+ "crm_company"
]
},
"ErrorResponse": {
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
new file mode 100644
index 0000000000..10c74196b9
--- /dev/null
+++ b/js/app/packages/service-clients/service-search/generated/models/crmCompanyFilters.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The crm company filters used to narrow which CRM companies appear in soup.
+ */
+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[];
+}
diff --git a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts b/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts
index febec78bd6..039ed259cf 100644
--- a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts
@@ -7,6 +7,7 @@
import type { CallFilters } from './callFilters';
import type { ChannelFilters } from './channelFilters';
import type { ChatFilters } from './chatFilters';
+import type { CrmCompanyFilters } from './crmCompanyFilters';
import type { DocumentFilters } from './documentFilters';
import type { EmailFilters } from './emailFilters';
import type { ForeignEntityFilters } from './foreignEntityFilters';
@@ -23,6 +24,8 @@ export interface EntityFilters {
channel_filters?: ChannelFilters;
/** the bundled [ChatFilters] */
chat_filters?: ChatFilters;
+ /** the bundled [CrmCompanyFilters] */
+ crm_company_filters?: CrmCompanyFilters;
/** the bundled [DocumentFilters] */
document_filters?: DocumentFilters;
/** the bundled [EmailFilters] */
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 a689f918f8..accaea1983 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
@@ -71,6 +71,7 @@ export * from './chatSearchResponseItem';
export * from './chatSearchResponseItemWithMetadata';
export * from './chatSearchResponseItemWithMetadataAllOf';
export * from './chatSearchResponseItemWithMetadataAllOfMetadata';
+export * from './crmCompanyFilters';
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 075b9a40d0..6c9a6eadf6 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -819,6 +819,19 @@
],
"description": "ChatSearchResponse object with channel metadata we fetch from macrodb. we don't store these\ntimestamps in opensearch as they would require us to update each chat message record for the chat\nevery time the chat updates (specifically for updated_at and viewed_at)"
},
+ "CrmCompanyFilters": {
+ "type": "object",
+ "description": "The crm company filters used to narrow which CRM companies appear in soup.",
+ "properties": {
+ "company_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM company ids to filter by. Examples: ['11111111-...']. Empty to\ninclude all of the team's visible CRM companies."
+ }
+ }
+ },
"DataType": {
"type": "string",
"description": "Data type for property values, determining storage and validation.",
@@ -1444,6 +1457,10 @@
"$ref": "#/components/schemas/ChatFilters",
"description": "the bundled [ChatFilters]"
},
+ "crm_company_filters": {
+ "$ref": "#/components/schemas/CrmCompanyFilters",
+ "description": "the bundled [CrmCompanyFilters]"
+ },
"document_filters": {
"$ref": "#/components/schemas/DocumentFilters",
"description": "the bundled [DocumentFilters]"
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
index eeed1530cf..13aab72073 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
@@ -8,6 +8,9 @@
export interface ApiEntityFilterAst {
/** the filters that should be applied to the call entity */
callf?: unknown;
+ /** Filters applied to the crm_company entity (wire key `ccf`).
+Empty/omitted = team's full visible list. */
+ ccf?: unknown;
/** the filters that should be applied to the chat entity */
cf?: unknown;
/** the filters that should be applied to the channel entity */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createCrmCommentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createCrmCommentRequest.ts
new file mode 100644
index 0000000000..9aa4432ea9
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createCrmCommentRequest.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateCrmCommentRequestThreadId } from './createCrmCommentRequestThreadId';
+
+/**
+ * Request body for `POST /crm/comments/{entity_type}/{entity_id}`.
+ */
+export interface CreateCrmCommentRequest {
+ /** Arbitrary client metadata for the comment. */
+ metadata?: unknown;
+ /** The comment body (markdown). */
+ text: string;
+ /** Existing thread to append to. Omit to start a new thread on the
+addressed entity. */
+ threadId?: CreateCrmCommentRequestThreadId;
+ /** Metadata to set on a newly created thread (ignored when replying
+without a value). */
+ threadMetadata?: unknown;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createCrmCommentRequestThreadId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createCrmCommentRequestThreadId.ts
new file mode 100644
index 0000000000..4bbe4edd4e
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createCrmCommentRequestThreadId.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Existing thread to append to. Omit to start a new thread on the
+addressed entity.
+ */
+export type CreateCrmCommentRequestThreadId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmComment.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmComment.ts
new file mode 100644
index 0000000000..6ad9d97035
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmComment.ts
@@ -0,0 +1,36 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CrmCommentDeletedAt } from './crmCommentDeletedAt';
+import type { CrmCommentOrder } from './crmCommentOrder';
+import type { CrmCommentSender } from './crmCommentSender';
+
+/**
+ * A single comment within a [`CrmThread`].
+ */
+export interface CrmComment {
+ /** The comment id. */
+ commentId: string;
+ /** When the comment was created. */
+ createdAt: string;
+ /** When the comment was soft-deleted, if ever. */
+ deletedAt?: CrmCommentDeletedAt;
+ /** Arbitrary client metadata. */
+ metadata?: unknown;
+ /** Optional explicit ordering within the thread; the frontend falls
+back to `createdAt` when absent. */
+ order?: CrmCommentOrder;
+ /** Macro user id of the comment author. */
+ owner: string;
+ /** Macro user id of the actual sender, when distinct from `owner`. */
+ sender?: CrmCommentSender;
+ /** The comment body (markdown). */
+ text: string;
+ /** The id of the thread this comment belongs to. */
+ threadId: string;
+ /** When the comment was last updated. */
+ updatedAt: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentDeletedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentDeletedAt.ts
new file mode 100644
index 0000000000..ba77180894
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentDeletedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When the comment was soft-deleted, if ever.
+ */
+export type CrmCommentDeletedAt = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentEntityType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentEntityType.ts
new file mode 100644
index 0000000000..6de395c97a
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentEntityType.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Which CRM entity a comment thread is attached to. Serializes to
+`crm_company` / `crm_contact` — matching the `entityType` the frontend
+uses elsewhere when building entity URLs — and is parsed from the
+`{entity_type}` path segment on the comment routes.
+ */
+export type CrmCommentEntityType =
+ (typeof CrmCommentEntityType)[keyof typeof CrmCommentEntityType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const CrmCommentEntityType = {
+ crm_company: 'crm_company',
+ crm_contact: 'crm_contact',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentOrder.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentOrder.ts
new file mode 100644
index 0000000000..5cebb086af
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentOrder.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional explicit ordering within the thread; the frontend falls
+back to `createdAt` when absent.
+ */
+export type CrmCommentOrder = number | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentSender.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentSender.ts
new file mode 100644
index 0000000000..b4447f5a1e
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentSender.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Macro user id of the actual sender, when distinct from `owner`.
+ */
+export type CrmCommentSender = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentThread.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentThread.ts
new file mode 100644
index 0000000000..527f299200
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCommentThread.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CrmComment } from './crmComment';
+import type { CrmThread } from './crmThread';
+
+/**
+ * A [`CrmThread`] with its comments nested under it — the unit the
+frontend renders.
+ */
+export interface CrmCommentThread {
+ /** The thread's comments, oldest first. */
+ comments: CrmComment[];
+ /** The thread. */
+ thread: CrmThread;
+}
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
new file mode 100644
index 0000000000..6f1cf3546b
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmCompanyFilters.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The crm company filters used to narrow which CRM companies appear in soup.
+ */
+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[];
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponse.ts
new file mode 100644
index 0000000000..b1406ce95b
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponse.ts
@@ -0,0 +1,29 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CrmContactResponseName } from './crmContactResponseName';
+
+/**
+ * A CRM contact as returned by `GET /crm/companies/{company_id}/contacts`.
+ */
+export interface CrmContactResponse {
+ /** The id of the company the contact belongs to. */
+ companyId: string;
+ /** When the contact record was created. */
+ createdAt: string;
+ /** The contact's email address. */
+ email: string;
+ /** Earliest known interaction with this contact. */
+ firstInteraction: string;
+ /** The id of the contact record. */
+ id: string;
+ /** Most recent known interaction with this contact. */
+ lastInteraction: string;
+ /** Display name observed for the contact, if any. */
+ name?: CrmContactResponseName;
+ /** When the contact record was last updated. */
+ updatedAt: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponseName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponseName.ts
new file mode 100644
index 0000000000..9c5d763bb4
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponseName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name observed for the contact, if any.
+ */
+export type CrmContactResponseName = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmThread.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmThread.ts
new file mode 100644
index 0000000000..50df008413
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmThread.ts
@@ -0,0 +1,33 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { CrmCommentEntityType } from './crmCommentEntityType';
+import type { CrmThreadDeletedAt } from './crmThreadDeletedAt';
+
+/**
+ * A CRM comment thread: the parent record one or more comments hang off.
+ */
+export interface CrmThread {
+ /** When the thread was created. */
+ createdAt: string;
+ /** When the thread was soft-deleted, if ever. */
+ deletedAt?: CrmThreadDeletedAt;
+ /** The id of the CRM company or contact this thread belongs to. */
+ entityId: string;
+ /** Which CRM entity kind this thread belongs to. */
+ entityType: CrmCommentEntityType;
+ /** Arbitrary client metadata. */
+ metadata?: unknown;
+ /** Macro user id of the thread creator. */
+ owner: string;
+ /** Whether the thread is resolved. */
+ resolved: boolean;
+ /** The thread id. */
+ threadId: string;
+ /** When the thread was last updated. */
+ updatedAt: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/crmThreadDeletedAt.ts b/js/app/packages/service-clients/service-storage/generated/schemas/crmThreadDeletedAt.ts
new file mode 100644
index 0000000000..b0c18f92cf
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmThreadDeletedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When the thread was soft-deleted, if ever.
+ */
+export type CrmThreadDeletedAt = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/deleteCrmCommentResult.ts b/js/app/packages/service-clients/service-storage/generated/schemas/deleteCrmCommentResult.ts
new file mode 100644
index 0000000000..0efc0b079f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/deleteCrmCommentResult.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Outcome of soft-deleting a CRM comment: reports whether the parent thread
+was soft-deleted too (it is when the deleted comment was its last live one).
+ */
+export interface DeleteCrmCommentResult {
+ /** The deleted comment's id. */
+ commentId: string;
+ /** Whether the thread itself was soft-deleted because no live comments
+remained. */
+ threadDeleted: boolean;
+ /** The thread the comment belonged to. */
+ threadId: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/editCrmCommentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/editCrmCommentRequest.ts
new file mode 100644
index 0000000000..1b231dcba7
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/editCrmCommentRequest.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for `PATCH /crm/comments/comment/{comment_id}`.
+ */
+export interface EditCrmCommentRequest {
+ /** The new comment body (markdown). */
+ text: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
index a9ef5fd6ed..2a16fc0307 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
@@ -7,6 +7,7 @@
import type { CallFilters } from './callFilters';
import type { ChannelFilters } from './channelFilters';
import type { ChatFilters } from './chatFilters';
+import type { CrmCompanyFilters } from './crmCompanyFilters';
import type { DocumentFilters } from './documentFilters';
import type { EmailFilters } from './emailFilters';
import type { ForeignEntityFilters } from './foreignEntityFilters';
@@ -23,6 +24,8 @@ export interface EntityFilters {
channel_filters?: ChannelFilters;
/** the bundled [ChatFilters] */
chat_filters?: ChatFilters;
+ /** the bundled [CrmCompanyFilters] */
+ crm_company_filters?: CrmCompanyFilters;
/** the bundled [DocumentFilters] */
document_filters?: DocumentFilters;
/** the bundled [EmailFilters] */
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 8ede092e09..760e27a989 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
@@ -204,6 +204,8 @@ export * from './createCommentRequestThreadId';
export * from './createCommentResponse';
export * from './createCommentResponseAllOf';
export * from './createCommentResponseAllOfAnchor';
+export * from './createCrmCommentRequest';
+export * from './createCrmCommentRequestThreadId';
export * from './createDocument200';
export * from './createDocument200DataOneOf';
export * from './createDocument200DataOneOfAllOf';
@@ -257,6 +259,17 @@ export * from './createUnthreadedPdfAnchorRequestOneOf';
export * from './createUnthreadedPdfAnchorRequestOneOfAllOf';
export * from './createUnthreadedPdfAnchorRequestOneOfAllOfAnchorType';
export * from './createViewRequest';
+export * from './crmComment';
+export * from './crmCommentDeletedAt';
+export * from './crmCommentEntityType';
+export * from './crmCommentOrder';
+export * from './crmCommentSender';
+export * from './crmCommentThread';
+export * from './crmCompanyFilters';
+export * from './crmContactResponse';
+export * from './crmContactResponseName';
+export * from './crmThread';
+export * from './crmThreadDeletedAt';
export * from './customSpeakerAssignment';
export * from './dataType';
export * from './deleteAnchorInfo';
@@ -265,6 +278,7 @@ export * from './deleteCommentRequest';
export * from './deleteCommentRequestRemoveAnchorThreadOnly';
export * from './deleteCommentResponse';
export * from './deleteCommentResponseAnchor';
+export * from './deleteCrmCommentResult';
export * from './deleteEntityMentionResponse';
export * from './deleteMessageParams';
export * from './deleteMessageQuery';
@@ -371,6 +385,7 @@ export * from './editCommentResponse';
export * from './editCommentResponseAllOf';
export * from './editCommentResponseAllOfFileType';
export * from './editCommentResponseAllOfSubType';
+export * from './editCrmCommentRequest';
export * from './editDocumentResponse';
export * from './editDocumentServiceArgs';
export * from './editDocumentServiceArgsDocumentName';
@@ -727,6 +742,10 @@ export * from './soupContact';
export * from './soupContactEmailAddress';
export * from './soupContactName';
export * from './soupContactSfsPhotoUrl';
+export * from './soupCrmCompany';
+export * from './soupCrmCompanyDescription';
+export * from './soupCrmCompanyName';
+export * from './soupCrmDomain';
export * from './soupDocument';
export * from './soupDocumentBranchedFromId';
export * from './soupDocumentBranchedFromVersionId';
@@ -759,6 +778,8 @@ export * from './soupItemOneOfFive';
export * from './soupItemOneOfFiveTag';
export * from './soupItemOneOfNine';
export * from './soupItemOneOfNineTag';
+export * from './soupItemOneOfOnefive';
+export * from './soupItemOneOfOnefiveTag';
export * from './soupItemOneOfOneone';
export * from './soupItemOneOfOneoneTag';
export * from './soupItemOneOfOnethree';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompany.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompany.ts
new file mode 100644
index 0000000000..3c0821650a
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompany.ts
@@ -0,0 +1,38 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SoupCrmCompanyDescription } from './soupCrmCompanyDescription';
+import type { SoupCrmCompanyName } from './soupCrmCompanyName';
+import type { SoupCrmDomain } from './soupCrmDomain';
+
+/**
+ * A CRM company as displayed in Soup. Carries the core company
+fields plus display metadata resolved from `crm_domain_directory`
+against the primary (earliest-created) domain.
+ */
+export interface SoupCrmCompany {
+ /** When the company was created. */
+ createdAt: string;
+ /** Display description from the primary domain's directory entry. */
+ description?: SoupCrmCompanyDescription;
+ /** Domains associated with this company, ordered by creation time
+ascending (primary first). */
+ domains: SoupCrmDomain[];
+ /** Whether email sync is enabled for this company. */
+ emailSync: boolean;
+ /** Whether the company is hidden from CRM listings. Soup filters
+these out by default. */
+ hidden: boolean;
+ /** The id of the company. */
+ id: string;
+ /** Display name from the primary domain's directory entry, or
+`None` when unresolved. */
+ name?: SoupCrmCompanyName;
+ /** The id of the team that owns this company record. */
+ teamId: string;
+ /** When the company was last updated. */
+ updatedAt: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyDescription.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyDescription.ts
new file mode 100644
index 0000000000..1cc232bd46
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyDescription.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display description from the primary domain's directory entry.
+ */
+export type SoupCrmCompanyDescription = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyName.ts
new file mode 100644
index 0000000000..c3206846e8
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmCompanyName.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name from the primary domain's directory entry, or
+`None` when unresolved.
+ */
+export type SoupCrmCompanyName = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmDomain.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmDomain.ts
new file mode 100644
index 0000000000..00493e4c6f
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupCrmDomain.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A CRM domain as displayed in Soup. Mirrors the crm crate's
+[`CrmDomain`] with a stable wire shape that the FE can rely on.
+ */
+export interface SoupCrmDomain {
+ /** The id of the company the domain belongs to. */
+ companyId: string;
+ /** When the domain record was created. */
+ createdAt: string;
+ /** The domain (lowercased, e.g. "acme.com"). */
+ domain: string;
+ /** The id of the domain record. */
+ id: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts
index eb64aced21..fcb2e013d4 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItem.ts
@@ -7,6 +7,7 @@
import type { SoupItemOneOf } from './soupItemOneOf';
import type { SoupItemOneOfFive } from './soupItemOneOfFive';
import type { SoupItemOneOfNine } from './soupItemOneOfNine';
+import type { SoupItemOneOfOnefive } from './soupItemOneOfOnefive';
import type { SoupItemOneOfOneone } from './soupItemOneOfOneone';
import type { SoupItemOneOfOnethree } from './soupItemOneOfOnethree';
import type { SoupItemOneOfSeven } from './soupItemOneOfSeven';
@@ -19,4 +20,5 @@ export type SoupItem =
| SoupItemOneOfSeven
| SoupItemOneOfNine
| SoupItemOneOfOneone
- | SoupItemOneOfOnethree;
+ | SoupItemOneOfOnethree
+ | SoupItemOneOfOnefive;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnefive.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnefive.ts
new file mode 100644
index 0000000000..c4738c5974
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnefive.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { SoupForeignEntity } from './soupForeignEntity';
+import type { SoupItemOneOfOnefiveTag } from './soupItemOneOfOnefiveTag';
+
+export type SoupItemOneOfOnefive = {
+ data: SoupForeignEntity;
+ tag: SoupItemOneOfOnefiveTag;
+};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnefiveTag.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnefiveTag.ts
new file mode 100644
index 0000000000..506aac0ba3
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnefiveTag.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type SoupItemOneOfOnefiveTag =
+ (typeof SoupItemOneOfOnefiveTag)[keyof typeof SoupItemOneOfOnefiveTag];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const SoupItemOneOfOnefiveTag = {
+ foreignEntity: 'foreignEntity',
+} as const;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethree.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethree.ts
index 21ae77a21d..72b2063945 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethree.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethree.ts
@@ -4,10 +4,10 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { SoupForeignEntity } from './soupForeignEntity';
+import type { SoupCrmCompany } from './soupCrmCompany';
import type { SoupItemOneOfOnethreeTag } from './soupItemOneOfOnethreeTag';
export type SoupItemOneOfOnethree = {
- data: SoupForeignEntity;
+ data: SoupCrmCompany;
tag: SoupItemOneOfOnethreeTag;
};
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethreeTag.ts b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethreeTag.ts
index 4380bddfd2..b1f1c5bb62 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethreeTag.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/soupItemOneOfOnethreeTag.ts
@@ -10,5 +10,5 @@ export type SoupItemOneOfOnethreeTag =
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const SoupItemOneOfOnethreeTag = {
- foreignEntity: 'foreignEntity',
+ crmCompany: 'crmCompany',
} as const;
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 1c9eb17df5..d82a6c6af7 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -2367,6 +2367,330 @@ export const postTypingBody = zod
})
.describe('Request to emit a typing event.');
+/**
+ * @summary Soft-delete a CRM comment, scoped to the requesting user's team. When it
+was the thread's last live comment, the thread is soft-deleted too
+(reported via `threadDeleted`).
+ */
+export const deleteCrmCommentParams = zod.object({
+ comment_id: zod.uuid().describe('The CRM comment to delete'),
+});
+
+export const deleteCrmCommentResponse = zod
+ .object({
+ commentId: zod.uuid().describe("The deleted comment's id."),
+ threadDeleted: zod
+ .boolean()
+ .describe(
+ 'Whether the thread itself was soft-deleted because no live comments\nremained.'
+ ),
+ threadId: zod.uuid().describe('The thread the comment belonged to.'),
+ })
+ .describe(
+ 'Outcome of soft-deleting a CRM comment: reports whether the parent thread\nwas soft-deleted too (it is when the deleted comment was its last live one).'
+ );
+
+/**
+ * @summary Edit a CRM comment's text, scoped to the requesting user's team via the
+comment's thread → entity → company. Returns the updated comment.
+ */
+export const editCrmCommentParams = zod.object({
+ comment_id: zod.uuid().describe('The CRM comment to edit'),
+});
+
+export const editCrmCommentBody = zod
+ .object({
+ text: zod.string().describe('The new comment body (markdown).'),
+ })
+ .describe('Request body for `PATCH \/crm\/comments\/comment\/{comment_id}`.');
+
+export const editCrmCommentResponse = zod
+ .object({
+ commentId: zod.uuid().describe('The comment id.'),
+ createdAt: zod.iso.datetime({}).describe('When the comment was created.'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('When the comment was soft-deleted, if ever.'),
+ metadata: zod.unknown().optional().describe('Arbitrary client metadata.'),
+ order: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Optional explicit ordering within the thread; the frontend falls\nback to `createdAt` when absent.'
+ ),
+ owner: zod.string().describe('Macro user id of the comment author.'),
+ sender: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Macro user id of the actual sender, when distinct from `owner`.'
+ ),
+ text: zod.string().describe('The comment body (markdown).'),
+ threadId: zod
+ .uuid()
+ .describe('The id of the thread this comment belongs to.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the comment was last updated.'),
+ })
+ .describe('A single comment within a [`CrmThread`].');
+
+/**
+ * @summary List the comment threads on a CRM company or contact, scoped to the
+requesting user's team. Returns 404 when the entity isn't owned by the
+team; an owned entity with no threads returns `200 []`.
+ */
+export const listCrmCommentsParams = zod.object({
+ entity_type: zod
+ .enum(['crm_company', 'crm_contact'])
+ .describe('Which CRM entity kind the threads hang off'),
+ entity_id: zod.uuid().describe('The CRM company or contact id'),
+});
+
+export const listCrmCommentsResponseItem = zod
+ .object({
+ comments: zod
+ .array(
+ zod
+ .object({
+ commentId: zod.uuid().describe('The comment id.'),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the comment was created.'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('When the comment was soft-deleted, if ever.'),
+ metadata: zod
+ .unknown()
+ .optional()
+ .describe('Arbitrary client metadata.'),
+ order: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Optional explicit ordering within the thread; the frontend falls\nback to `createdAt` when absent.'
+ ),
+ owner: zod
+ .string()
+ .describe('Macro user id of the comment author.'),
+ sender: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Macro user id of the actual sender, when distinct from `owner`.'
+ ),
+ text: zod.string().describe('The comment body (markdown).'),
+ threadId: zod
+ .uuid()
+ .describe('The id of the thread this comment belongs to.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the comment was last updated.'),
+ })
+ .describe('A single comment within a [`CrmThread`].')
+ )
+ .describe("The thread's comments, oldest first."),
+ thread: zod
+ .object({
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the thread was created.'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('When the thread was soft-deleted, if ever.'),
+ entityId: zod
+ .uuid()
+ .describe(
+ 'The id of the CRM company or contact this thread belongs to.'
+ ),
+ entityType: zod
+ .enum(['crm_company', 'crm_contact'])
+ .describe(
+ 'Which CRM entity a comment thread is attached to. Serializes to\n`crm_company` \/ `crm_contact` — matching the `entityType` the frontend\nuses elsewhere when building entity URLs — and is parsed from the\n`{entity_type}` path segment on the comment routes.'
+ ),
+ metadata: zod
+ .unknown()
+ .optional()
+ .describe('Arbitrary client metadata.'),
+ owner: zod.string().describe('Macro user id of the thread creator.'),
+ resolved: zod.boolean().describe('Whether the thread is resolved.'),
+ threadId: zod.uuid().describe('The thread id.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the thread was last updated.'),
+ })
+ .describe(
+ 'A CRM comment thread: the parent record one or more comments hang off.'
+ ),
+ })
+ .describe(
+ 'A [`CrmThread`] with its comments nested under it — the unit the\nfrontend renders.'
+ );
+export const listCrmCommentsResponse = zod.array(listCrmCommentsResponseItem);
+
+/**
+ * @summary Create a comment on a CRM company or contact — a new thread, or a reply
+when `threadId` is supplied. Returns the full thread (with all comments)
+after the insert. Team-scoped; 404 when the entity isn't owned by the
+team or `threadId` doesn't belong to it.
+ */
+export const createCrmCommentParams = zod.object({
+ entity_type: zod
+ .enum(['crm_company', 'crm_contact'])
+ .describe('Which CRM entity kind the thread hangs off'),
+ entity_id: zod.uuid().describe('The CRM company or contact id'),
+});
+
+export const createCrmCommentBody = zod
+ .object({
+ metadata: zod
+ .unknown()
+ .optional()
+ .describe('Arbitrary client metadata for the comment.'),
+ text: zod.string().describe('The comment body (markdown).'),
+ threadId: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'Existing thread to append to. Omit to start a new thread on the\naddressed entity.'
+ ),
+ threadMetadata: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Metadata to set on a newly created thread (ignored when replying\nwithout a value).'
+ ),
+ })
+ .describe(
+ 'Request body for `POST \/crm\/comments\/{entity_type}\/{entity_id}`.'
+ );
+
+export const createCrmCommentResponse = zod
+ .object({
+ comments: zod
+ .array(
+ zod
+ .object({
+ commentId: zod.uuid().describe('The comment id.'),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the comment was created.'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('When the comment was soft-deleted, if ever.'),
+ metadata: zod
+ .unknown()
+ .optional()
+ .describe('Arbitrary client metadata.'),
+ order: zod
+ .number()
+ .nullish()
+ .describe(
+ 'Optional explicit ordering within the thread; the frontend falls\nback to `createdAt` when absent.'
+ ),
+ owner: zod
+ .string()
+ .describe('Macro user id of the comment author.'),
+ sender: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Macro user id of the actual sender, when distinct from `owner`.'
+ ),
+ text: zod.string().describe('The comment body (markdown).'),
+ threadId: zod
+ .uuid()
+ .describe('The id of the thread this comment belongs to.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the comment was last updated.'),
+ })
+ .describe('A single comment within a [`CrmThread`].')
+ )
+ .describe("The thread's comments, oldest first."),
+ thread: zod
+ .object({
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the thread was created.'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('When the thread was soft-deleted, if ever.'),
+ entityId: zod
+ .uuid()
+ .describe(
+ 'The id of the CRM company or contact this thread belongs to.'
+ ),
+ entityType: zod
+ .enum(['crm_company', 'crm_contact'])
+ .describe(
+ 'Which CRM entity a comment thread is attached to. Serializes to\n`crm_company` \/ `crm_contact` — matching the `entityType` the frontend\nuses elsewhere when building entity URLs — and is parsed from the\n`{entity_type}` path segment on the comment routes.'
+ ),
+ metadata: zod
+ .unknown()
+ .optional()
+ .describe('Arbitrary client metadata.'),
+ owner: zod.string().describe('Macro user id of the thread creator.'),
+ resolved: zod.boolean().describe('Whether the thread is resolved.'),
+ threadId: zod.uuid().describe('The thread id.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the thread was last updated.'),
+ })
+ .describe(
+ 'A CRM comment thread: the parent record one or more comments hang off.'
+ ),
+ })
+ .describe(
+ 'A [`CrmThread`] with its comments nested under it — the unit the\nfrontend renders.'
+ );
+
+/**
+ * @summary List the non-hidden contacts of a CRM company, scoped to the
+requesting user's team. Returns 404 when the company isn't owned by
+the team (so existence doesn't leak across teams); an owned company
+with no visible contacts returns `200 []`.
+ */
+export const listCompanyContactsParams = zod.object({
+ company_id: zod.uuid().describe('The CRM company whose contacts to list'),
+});
+
+export const listCompanyContactsResponseItem = zod
+ .object({
+ companyId: zod
+ .uuid()
+ .describe('The id of the company the contact belongs to.'),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the contact record was created.'),
+ email: zod.string().describe("The contact's email address."),
+ firstInteraction: zod.iso
+ .datetime({})
+ .describe('Earliest known interaction with this contact.'),
+ id: zod.uuid().describe('The id of the contact record.'),
+ lastInteraction: zod.iso
+ .datetime({})
+ .describe('Most recent known interaction with this contact.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name observed for the contact, if any.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the contact record was last updated.'),
+ })
+ .describe(
+ 'A CRM contact as returned by `GET \/crm\/companies\/{company_id}\/contacts`.'
+ );
+export const listCompanyContactsResponse = zod.array(
+ listCompanyContactsResponseItem
+);
+
/**
* @summary Toggle `email_sync` on a CRM company. `false` disables CRM email
sharing for the company and permanently removes its existing CRM
@@ -6303,6 +6627,71 @@ export const getItemsSoupResponse = zod.object({
),
tag: zod.enum(['call']),
}),
+ zod.object({
+ data: zod
+ .object({
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the company was created.'),
+ description: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display description from the primary domain's directory entry."
+ ),
+ domains: zod
+ .array(
+ zod
+ .object({
+ companyId: zod
+ .uuid()
+ .describe(
+ 'The id of the company the domain belongs to.'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the domain record was created.'),
+ domain: zod
+ .string()
+ .describe(
+ 'The domain (lowercased, e.g. \"acme.com\").'
+ ),
+ id: zod.uuid().describe('The id of the domain record.'),
+ })
+ .describe(
+ "A CRM domain as displayed in Soup. Mirrors the crm crate's\n[`CrmDomain`] with a stable wire shape that the FE can rely on."
+ )
+ )
+ .describe(
+ 'Domains associated with this company, ordered by creation time\nascending (primary first).'
+ ),
+ emailSync: zod
+ .boolean()
+ .describe('Whether email sync is enabled for this company.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the company is hidden from CRM listings. Soup filters\nthese out by default.'
+ ),
+ id: zod.uuid().describe('The id of the company.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display name from the primary domain's directory entry, or\n`None` when unresolved."
+ ),
+ teamId: zod
+ .uuid()
+ .describe('The id of the team that owns this company record.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the company was last updated.'),
+ })
+ .describe(
+ 'A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'
+ ),
+ tag: zod.enum(['crmCompany']),
+ }),
zod.object({
data: zod
.object({
@@ -6514,6 +6903,19 @@ export const postItemsSoupBody = zod
.describe(
'The chat filters used to filter down what chats you search over.'
),
+ crm_company_filters: zod
+ .object({
+ company_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "CRM company ids to filter by. Examples: ['11111111-...']. Empty to\ninclude all of the team's visible CRM companies."
+ ),
+ })
+ .optional()
+ .describe(
+ 'The crm company filters used to narrow which CRM companies appear in soup.'
+ ),
document_filters: zod
.object({
document_ids: zod
@@ -8066,6 +8468,71 @@ export const postItemsSoupResponse = zod.object({
),
tag: zod.enum(['call']),
}),
+ zod.object({
+ data: zod
+ .object({
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the company was created.'),
+ description: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display description from the primary domain's directory entry."
+ ),
+ domains: zod
+ .array(
+ zod
+ .object({
+ companyId: zod
+ .uuid()
+ .describe(
+ 'The id of the company the domain belongs to.'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the domain record was created.'),
+ domain: zod
+ .string()
+ .describe(
+ 'The domain (lowercased, e.g. \"acme.com\").'
+ ),
+ id: zod.uuid().describe('The id of the domain record.'),
+ })
+ .describe(
+ "A CRM domain as displayed in Soup. Mirrors the crm crate's\n[`CrmDomain`] with a stable wire shape that the FE can rely on."
+ )
+ )
+ .describe(
+ 'Domains associated with this company, ordered by creation time\nascending (primary first).'
+ ),
+ emailSync: zod
+ .boolean()
+ .describe('Whether email sync is enabled for this company.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the company is hidden from CRM listings. Soup filters\nthese out by default.'
+ ),
+ id: zod.uuid().describe('The id of the company.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display name from the primary domain's directory entry, or\n`None` when unresolved."
+ ),
+ teamId: zod
+ .uuid()
+ .describe('The id of the team that owns this company record.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the company was last updated.'),
+ })
+ .describe(
+ 'A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'
+ ),
+ tag: zod.enum(['crmCompany']),
+ }),
zod.object({
data: zod
.object({
@@ -8128,6 +8595,12 @@ export const postItemsSoupAstBody = zod
.unknown()
.optional()
.describe('the filters that should be applied to the call entity'),
+ ccf: zod
+ .unknown()
+ .optional()
+ .describe(
+ "Filters applied to the crm_company entity (wire key `ccf`).\nEmpty\/omitted = team's full visible list."
+ ),
cf: zod
.unknown()
.optional()
@@ -9441,6 +9914,71 @@ export const postItemsSoupAstResponse = zod.object({
),
tag: zod.enum(['call']),
}),
+ zod.object({
+ data: zod
+ .object({
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the company was created.'),
+ description: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display description from the primary domain's directory entry."
+ ),
+ domains: zod
+ .array(
+ zod
+ .object({
+ companyId: zod
+ .uuid()
+ .describe(
+ 'The id of the company the domain belongs to.'
+ ),
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When the domain record was created.'),
+ domain: zod
+ .string()
+ .describe(
+ 'The domain (lowercased, e.g. \"acme.com\").'
+ ),
+ id: zod.uuid().describe('The id of the domain record.'),
+ })
+ .describe(
+ "A CRM domain as displayed in Soup. Mirrors the crm crate's\n[`CrmDomain`] with a stable wire shape that the FE can rely on."
+ )
+ )
+ .describe(
+ 'Domains associated with this company, ordered by creation time\nascending (primary first).'
+ ),
+ emailSync: zod
+ .boolean()
+ .describe('Whether email sync is enabled for this company.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the company is hidden from CRM listings. Soup filters\nthese out by default.'
+ ),
+ id: zod.uuid().describe('The id of the company.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe(
+ "Display name from the primary domain's directory entry, or\n`None` when unresolved."
+ ),
+ teamId: zod
+ .uuid()
+ .describe('The id of the team that owns this company record.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When the company was last updated.'),
+ })
+ .describe(
+ 'A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.'
+ ),
+ tag: zod.enum(['crmCompany']),
+ }),
zod.object({
data: zod
.object({
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 8392478f1f..b38a9c6ab9 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -3382,6 +3382,351 @@
}
}
},
+ "/crm/comment/{comment_id}": {
+ "delete": {
+ "tags": ["crm::inbound::axum_router::comments"],
+ "summary": "Soft-delete a CRM comment, scoped to the requesting user's team. When it\nwas the thread's last live comment, the thread is soft-deleted too\n(reported via `threadDeleted`).",
+ "operationId": "delete_crm_comment",
+ "parameters": [
+ {
+ "name": "comment_id",
+ "in": "path",
+ "description": "The CRM comment to delete",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/DeleteCrmCommentResult"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "patch": {
+ "tags": ["crm::inbound::axum_router::comments"],
+ "summary": "Edit a CRM comment's text, scoped to the requesting user's team via the\ncomment's thread → entity → company. Returns the updated comment.",
+ "operationId": "edit_crm_comment",
+ "parameters": [
+ {
+ "name": "comment_id",
+ "in": "path",
+ "description": "The CRM comment to edit",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/EditCrmCommentRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CrmComment"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/comments/{entity_type}/{entity_id}": {
+ "get": {
+ "tags": ["crm::inbound::axum_router::comments"],
+ "summary": "List the comment threads on a CRM company or contact, scoped to the\nrequesting user's team. Returns 404 when the entity isn't owned by the\nteam; an owned entity with no threads returns `200 []`.",
+ "operationId": "list_crm_comments",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "description": "Which CRM entity kind the threads hang off",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/CrmCommentEntityType"
+ }
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "description": "The CRM company or contact id",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CrmCommentThread"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["crm::inbound::axum_router::comments"],
+ "summary": "Create a comment on a CRM company or contact — a new thread, or a reply\nwhen `threadId` is supplied. Returns the full thread (with all comments)\nafter the insert. Team-scoped; 404 when the entity isn't owned by the\nteam or `threadId` doesn't belong to it.",
+ "operationId": "create_crm_comment",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "description": "Which CRM entity kind the thread hangs off",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/CrmCommentEntityType"
+ }
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "description": "The CRM company or contact id",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCrmCommentRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CrmCommentThread"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/companies/{company_id}/contacts": {
+ "get": {
+ "tags": ["crm::inbound::axum_router::list_company_contacts"],
+ "summary": "List the non-hidden contacts of a CRM company, scoped to the\nrequesting user's team. Returns 404 when the company isn't owned by\nthe team (so existence doesn't leak across teams); an owned company\nwith no visible contacts returns `200 []`.",
+ "operationId": "list_company_contacts",
+ "parameters": [
+ {
+ "name": "company_id",
+ "in": "path",
+ "description": "The CRM company whose contacts to list",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CrmContactResponse"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/crm/companies/{company_id}/email-sync": {
"put": {
"tags": ["crm::inbound::axum_router::set_email_sync"],
@@ -8448,6 +8793,9 @@
"callf": {
"description": "the filters that should be applied to the call entity"
},
+ "ccf": {
+ "description": "Filters applied to the crm_company entity (wire key `ccf`).\nEmpty/omitted = team's full visible list."
+ },
"cf": {
"description": "the filters that should be applied to the chat entity"
},
@@ -9793,6 +10141,28 @@
}
]
},
+ "CreateCrmCommentRequest": {
+ "type": "object",
+ "description": "Request body for `POST /crm/comments/{entity_type}/{entity_id}`.",
+ "required": ["text"],
+ "properties": {
+ "metadata": {
+ "description": "Arbitrary client metadata for the comment."
+ },
+ "text": {
+ "type": "string",
+ "description": "The comment body (markdown)."
+ },
+ "threadId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Existing thread to append to. Omit to start a new thread on the\naddressed entity."
+ },
+ "threadMetadata": {
+ "description": "Metadata to set on a newly created thread (ignored when replying\nwithout a value)."
+ }
+ }
+ },
"CreateDocumentRequest": {
"type": "object",
"required": ["sha", "documentName"],
@@ -10155,6 +10525,209 @@
}
}
},
+ "CrmComment": {
+ "type": "object",
+ "description": "A single comment within a [`CrmThread`].",
+ "required": [
+ "commentId",
+ "threadId",
+ "owner",
+ "text",
+ "createdAt",
+ "updatedAt"
+ ],
+ "properties": {
+ "commentId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The comment id."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the comment was created."
+ },
+ "deletedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the comment was soft-deleted, if ever."
+ },
+ "metadata": {
+ "description": "Arbitrary client metadata."
+ },
+ "order": {
+ "type": ["integer", "null"],
+ "format": "int32",
+ "description": "Optional explicit ordering within the thread; the frontend falls\nback to `createdAt` when absent."
+ },
+ "owner": {
+ "type": "string",
+ "description": "Macro user id of the comment author."
+ },
+ "sender": {
+ "type": ["string", "null"],
+ "description": "Macro user id of the actual sender, when distinct from `owner`."
+ },
+ "text": {
+ "type": "string",
+ "description": "The comment body (markdown)."
+ },
+ "threadId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the thread this comment belongs to."
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the comment was last updated."
+ }
+ }
+ },
+ "CrmCommentEntityType": {
+ "type": "string",
+ "description": "Which CRM entity a comment thread is attached to. Serializes to\n`crm_company` / `crm_contact` — matching the `entityType` the frontend\nuses elsewhere when building entity URLs — and is parsed from the\n`{entity_type}` path segment on the comment routes.",
+ "enum": ["crm_company", "crm_contact"]
+ },
+ "CrmCommentThread": {
+ "type": "object",
+ "description": "A [`CrmThread`] with its comments nested under it — the unit the\nfrontend renders.",
+ "required": ["thread", "comments"],
+ "properties": {
+ "comments": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CrmComment"
+ },
+ "description": "The thread's comments, oldest first."
+ },
+ "thread": {
+ "$ref": "#/components/schemas/CrmThread",
+ "description": "The thread."
+ }
+ }
+ },
+ "CrmCompanyFilters": {
+ "type": "object",
+ "description": "The crm company filters used to narrow which CRM companies appear in soup.",
+ "properties": {
+ "company_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "CRM company ids to filter by. Examples: ['11111111-...']. Empty to\ninclude all of the team's visible CRM companies."
+ }
+ }
+ },
+ "CrmContactResponse": {
+ "type": "object",
+ "description": "A CRM contact as returned by `GET /crm/companies/{company_id}/contacts`.",
+ "required": [
+ "id",
+ "companyId",
+ "email",
+ "firstInteraction",
+ "lastInteraction",
+ "createdAt",
+ "updatedAt"
+ ],
+ "properties": {
+ "companyId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the company the contact belongs to."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the contact record was created."
+ },
+ "email": {
+ "type": "string",
+ "description": "The contact's email address."
+ },
+ "firstInteraction": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Earliest known interaction with this contact."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the contact record."
+ },
+ "lastInteraction": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Most recent known interaction with this contact."
+ },
+ "name": {
+ "type": ["string", "null"],
+ "description": "Display name observed for the contact, if any."
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the contact record was last updated."
+ }
+ }
+ },
+ "CrmThread": {
+ "type": "object",
+ "description": "A CRM comment thread: the parent record one or more comments hang off.",
+ "required": [
+ "threadId",
+ "entityType",
+ "entityId",
+ "owner",
+ "resolved",
+ "createdAt",
+ "updatedAt"
+ ],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the thread was created."
+ },
+ "deletedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the thread was soft-deleted, if ever."
+ },
+ "entityId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the CRM company or contact this thread belongs to."
+ },
+ "entityType": {
+ "$ref": "#/components/schemas/CrmCommentEntityType",
+ "description": "Which CRM entity kind this thread belongs to."
+ },
+ "metadata": {
+ "description": "Arbitrary client metadata."
+ },
+ "owner": {
+ "type": "string",
+ "description": "Macro user id of the thread creator."
+ },
+ "resolved": {
+ "type": "boolean",
+ "description": "Whether the thread is resolved."
+ },
+ "threadId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The thread id."
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the thread was last updated."
+ }
+ }
+ },
"CustomSpeakerAssignment": {
"type": "object",
"description": "One per-diarized-speaker override, used in [`EditCallTranscriptRequest`].\n\n`custom_speaker = None` clears any existing override for this\n`diarized_speaker_id`; `Some(macro_user_id)` sets it. The string is\nexpected to parse as a `MacroUserId` (e.g. `macro|[email protected]`);\nthe service layer rejects malformed values with `400 Bad Request`.",
@@ -10235,6 +10808,27 @@
}
}
},
+ "DeleteCrmCommentResult": {
+ "type": "object",
+ "description": "Outcome of soft-deleting a CRM comment: reports whether the parent thread\nwas soft-deleted too (it is when the deleted comment was its last live one).",
+ "required": ["commentId", "threadId", "threadDeleted"],
+ "properties": {
+ "commentId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The deleted comment's id."
+ },
+ "threadDeleted": {
+ "type": "boolean",
+ "description": "Whether the thread itself was soft-deleted because no live comments\nremained."
+ },
+ "threadId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The thread the comment belonged to."
+ }
+ }
+ },
"DeleteEntityMentionResponse": {
"type": "object",
"description": "Response body for `DELETE /channels/mentions/{mention_id}`.",
@@ -11022,6 +11616,17 @@
}
]
},
+ "EditCrmCommentRequest": {
+ "type": "object",
+ "description": "Request body for `PATCH /crm/comments/comment/{comment_id}`.",
+ "required": ["text"],
+ "properties": {
+ "text": {
+ "type": "string",
+ "description": "The new comment body (markdown)."
+ }
+ }
+ },
"EditDocumentResponse": {
"type": "object",
"description": "Edit document response.",
@@ -11258,6 +11863,10 @@
"$ref": "#/components/schemas/ChatFilters",
"description": "the bundled [ChatFilters]"
},
+ "crm_company_filters": {
+ "$ref": "#/components/schemas/CrmCompanyFilters",
+ "description": "the bundled [CrmCompanyFilters]"
+ },
"document_filters": {
"$ref": "#/components/schemas/DocumentFilters",
"description": "the bundled [DocumentFilters]"
@@ -14815,6 +15424,90 @@
}
}
},
+ "SoupCrmCompany": {
+ "type": "object",
+ "description": "A CRM company as displayed in Soup. Carries the core company\nfields plus display metadata resolved from `crm_domain_directory`\nagainst the primary (earliest-created) domain.",
+ "required": [
+ "id",
+ "teamId",
+ "emailSync",
+ "hidden",
+ "createdAt",
+ "updatedAt",
+ "domains"
+ ],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the company was created."
+ },
+ "description": {
+ "type": ["string", "null"],
+ "description": "Display description from the primary domain's directory entry."
+ },
+ "domains": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/SoupCrmDomain"
+ },
+ "description": "Domains associated with this company, ordered by creation time\nascending (primary first)."
+ },
+ "emailSync": {
+ "type": "boolean",
+ "description": "Whether email sync is enabled for this company."
+ },
+ "hidden": {
+ "type": "boolean",
+ "description": "Whether the company is hidden from CRM listings. Soup filters\nthese out by default."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the company."
+ },
+ "name": {
+ "type": ["string", "null"],
+ "description": "Display name from the primary domain's directory entry, or\n`None` when unresolved."
+ },
+ "teamId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the team that owns this company record."
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the company was last updated."
+ }
+ }
+ },
+ "SoupCrmDomain": {
+ "type": "object",
+ "description": "A CRM domain as displayed in Soup. Mirrors the crm crate's\n[`CrmDomain`] with a stable wire shape that the FE can rely on.",
+ "required": ["id", "companyId", "domain", "createdAt"],
+ "properties": {
+ "companyId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the company the domain belongs to."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the domain record was created."
+ },
+ "domain": {
+ "type": "string",
+ "description": "The domain (lowercased, e.g. \"acme.com\")."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The id of the domain record."
+ }
+ }
+ },
"SoupDocument": {
"type": "object",
"required": [
@@ -15173,6 +15866,19 @@
}
}
},
+ {
+ "type": "object",
+ "required": ["data", "tag"],
+ "properties": {
+ "data": {
+ "$ref": "#/components/schemas/SoupCrmCompany"
+ },
+ "tag": {
+ "type": "string",
+ "enum": ["crmCompany"]
+ }
+ }
+ },
{
"type": "object",
"required": ["data", "tag"],
diff --git a/rust/cloud-storage/.sqlx/query-0e241930c0e8b940ac3f513f8081270a0b93e88f5b7f7f7fc36276b3718b8297.json b/rust/cloud-storage/.sqlx/query-0e241930c0e8b940ac3f513f8081270a0b93e88f5b7f7f7fc36276b3718b8297.json
new file mode 100644
index 0000000000..84c6ebbc4b
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-0e241930c0e8b940ac3f513f8081270a0b93e88f5b7f7f7fc36276b3718b8297.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO crm_thread (company_id, contact_id, owner, metadata)\n VALUES ($1, $2, $3, $4)\n RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "0e241930c0e8b940ac3f513f8081270a0b93e88f5b7f7f7fc36276b3718b8297"
+}
diff --git a/rust/cloud-storage/.sqlx/query-30d2fd821db0a5161001069fa193d3fc449e51d833bb5b5b4df5904007bdd6a0.json b/rust/cloud-storage/.sqlx/query-30d2fd821db0a5161001069fa193d3fc449e51d833bb5b5b4df5904007bdd6a0.json
new file mode 100644
index 0000000000..bffb5c1c7a
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-30d2fd821db0a5161001069fa193d3fc449e51d833bb5b5b4df5904007bdd6a0.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT t.id\n FROM crm_comment c\n JOIN crm_thread t ON t.id = c.thread_id\n WHERE c.id = $1\n AND c.deleted_at IS NULL\n AND (\n EXISTS (\n SELECT 1 FROM crm_companies co\n WHERE co.id = t.company_id AND co.team_id = $2\n )\n OR EXISTS (\n SELECT 1 FROM crm_contacts ct\n JOIN crm_companies co2 ON co2.id = ct.company_id\n WHERE ct.id = t.contact_id AND co2.team_id = $2\n )\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "30d2fd821db0a5161001069fa193d3fc449e51d833bb5b5b4df5904007bdd6a0"
+}
diff --git a/rust/cloud-storage/.sqlx/query-30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51.json b/rust/cloud-storage/.sqlx/query-30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51.json
new file mode 100644
index 0000000000..8d99aa7295
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM crm_contacts c\n JOIN crm_companies co ON co.id = c.company_id\n WHERE c.id = $1 AND co.team_id = $2\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51"
+}
diff --git a/rust/cloud-storage/.sqlx/query-ea7e68915b34bffb086e716622e7dc82d140c0c566761fdae5309215de4ef41d.json b/rust/cloud-storage/.sqlx/query-33f91fe23f4aa503e8eea88cb0b14de49b5a047222518939169ac8b36170df61.json
similarity index 52%
rename from rust/cloud-storage/.sqlx/query-ea7e68915b34bffb086e716622e7dc82d140c0c566761fdae5309215de4ef41d.json
rename to rust/cloud-storage/.sqlx/query-33f91fe23f4aa503e8eea88cb0b14de49b5a047222518939169ac8b36170df61.json
index 91d6736071..1755ed40d0 100644
--- a/rust/cloud-storage/.sqlx/query-ea7e68915b34bffb086e716622e7dc82d140c0c566761fdae5309215de4ef41d.json
+++ b/rust/cloud-storage/.sqlx/query-33f91fe23f4aa503e8eea88cb0b14de49b5a047222518939169ac8b36170df61.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH thread_owner AS (\n SELECT el.macro_id\n FROM email_threads t\n JOIN email_links el ON el.id = t.link_id\n WHERE t.id = $1::uuid\n ),\n shared_teams AS (\n -- Teams the requester shares with the owner that have CRM enabled.\n SELECT tcs.team_id\n FROM team_user requester\n JOIN team_user owner_member ON owner_member.team_id = requester.team_id\n JOIN thread_owner o ON o.macro_id = owner_member.user_id\n JOIN team_crm_settings tcs ON tcs.team_id = requester.team_id\n WHERE requester.user_id = $2\n AND tcs.crm_enabled\n ),\n participants AS (\n -- Distinct addresses across from + to/cc/bcc on the thread.\n SELECT DISTINCT LOWER(ec.email_address) AS email\n FROM email_messages m\n JOIN email_contacts ec ON ec.id = m.from_contact_id\n WHERE m.thread_id = $1::uuid\n UNION\n SELECT DISTINCT LOWER(ec.email_address)\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts ec ON ec.id = r.contact_id\n WHERE m.thread_id = $1::uuid\n )\n SELECT EXISTS (\n SELECT 1\n FROM shared_teams st\n WHERE EXISTS (SELECT 1 FROM participants)\n AND NOT EXISTS (\n -- A participant with no qualifying contact in this team.\n SELECT 1\n FROM participants p\n WHERE NOT EXISTS (\n SELECT 1\n FROM crm_contacts ct\n JOIN crm_companies c ON c.id = ct.company_id\n WHERE c.team_id = st.team_id\n AND ct.email = p.email\n AND c.email_sync\n AND NOT c.hidden\n AND NOT ct.hidden\n )\n )\n ) AS \"granted!\"\n ",
+ "query": "\n WITH thread_owner AS (\n SELECT el.macro_id\n FROM email_threads t\n JOIN email_links el ON el.id = t.link_id\n WHERE t.id = $1::uuid\n ),\n shared_teams AS (\n -- Teams the requester shares with the owner that have CRM enabled.\n SELECT tcs.team_id\n FROM team_user requester\n JOIN team_user owner_member ON owner_member.team_id = requester.team_id\n JOIN thread_owner o ON o.macro_id = owner_member.user_id\n JOIN team_crm_settings tcs ON tcs.team_id = requester.team_id\n WHERE requester.user_id = $2\n AND tcs.crm_enabled\n ),\n participants AS (\n -- Distinct addresses across from + to/cc/bcc on the thread.\n SELECT DISTINCT LOWER(ec.email_address) AS email\n FROM email_messages m\n JOIN email_contacts ec ON ec.id = m.from_contact_id\n WHERE m.thread_id = $1::uuid\n UNION\n SELECT DISTINCT LOWER(ec.email_address)\n FROM email_messages m\n JOIN email_message_recipients r ON r.message_id = m.id\n JOIN email_contacts ec ON ec.id = r.contact_id\n WHERE m.thread_id = $1::uuid\n )\n SELECT EXISTS (\n SELECT 1\n FROM shared_teams st\n -- Require at least one *external* participant (outside the\n -- requester's own email domain). Internal colleagues don't\n -- need to be tracked CRM contacts, but a purely-internal\n -- thread shouldn't grant CRM access either.\n WHERE EXISTS (\n SELECT 1\n FROM participants p\n WHERE split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)\n )\n AND NOT EXISTS (\n -- An external participant with no qualifying contact in\n -- this team. Participants on the requester's own domain\n -- are skipped (they're internal, not CRM contacts).\n SELECT 1\n FROM participants p\n WHERE split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)\n AND NOT EXISTS (\n SELECT 1\n FROM crm_contacts ct\n JOIN crm_companies c ON c.id = ct.company_id\n WHERE c.team_id = st.team_id\n AND ct.email = p.email\n AND c.email_sync\n AND NOT c.hidden\n AND NOT ct.hidden\n )\n )\n ) AS \"granted!\"\n ",
"describe": {
"columns": [
{
@@ -19,5 +19,5 @@
null
]
},
- "hash": "ea7e68915b34bffb086e716622e7dc82d140c0c566761fdae5309215de4ef41d"
+ "hash": "33f91fe23f4aa503e8eea88cb0b14de49b5a047222518939169ac8b36170df61"
}
diff --git a/rust/cloud-storage/.sqlx/query-504e516996c2c65d7b2d7c47bdc5fbab6644ddd99a4913bc05ffd713f0c4ad5b.json b/rust/cloud-storage/.sqlx/query-504e516996c2c65d7b2d7c47bdc5fbab6644ddd99a4913bc05ffd713f0c4ad5b.json
new file mode 100644
index 0000000000..59020de757
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-504e516996c2c65d7b2d7c47bdc5fbab6644ddd99a4913bc05ffd713f0c4ad5b.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE crm_thread\n SET updated_at = now(), metadata = COALESCE($2, metadata)\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "504e516996c2c65d7b2d7c47bdc5fbab6644ddd99a4913bc05ffd713f0c4ad5b"
+}
diff --git a/rust/cloud-storage/.sqlx/query-582f4f2d5a5e9c72835d0a043f743a94d927a08a81b8687714a96bd52a94cfcf.json b/rust/cloud-storage/.sqlx/query-582f4f2d5a5e9c72835d0a043f743a94d927a08a81b8687714a96bd52a94cfcf.json
new file mode 100644
index 0000000000..3c62d246ab
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-582f4f2d5a5e9c72835d0a043f743a94d927a08a81b8687714a96bd52a94cfcf.json
@@ -0,0 +1,76 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, thread_id, \"order\", owner, sender, text, metadata,\n created_at, updated_at, deleted_at\n FROM crm_comment\n WHERE thread_id = ANY($1) AND deleted_at IS NULL\n ORDER BY created_at ASC, id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "order",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "sender",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "metadata",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "582f4f2d5a5e9c72835d0a043f743a94d927a08a81b8687714a96bd52a94cfcf"
+}
diff --git a/rust/cloud-storage/.sqlx/query-6dd441191ae20b764a7b3e66633b9f9e666235381e20631e0ed08d095a29507e.json b/rust/cloud-storage/.sqlx/query-6dd441191ae20b764a7b3e66633b9f9e666235381e20631e0ed08d095a29507e.json
new file mode 100644
index 0000000000..da7a35be6f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-6dd441191ae20b764a7b3e66633b9f9e666235381e20631e0ed08d095a29507e.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM crm_comment\n WHERE thread_id = $1 AND deleted_at IS NULL\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "6dd441191ae20b764a7b3e66633b9f9e666235381e20631e0ed08d095a29507e"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e.json b/rust/cloud-storage/.sqlx/query-9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e.json
new file mode 100644
index 0000000000..4bae9fea4c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM crm_companies\n WHERE id = $1 AND team_id = $2\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e"
+}
diff --git a/rust/cloud-storage/.sqlx/query-aa9ca547f8128f5f2a4418b6ccf252d9726565fbef858cf484ca86ab0625c6ec.json b/rust/cloud-storage/.sqlx/query-aa9ca547f8128f5f2a4418b6ccf252d9726565fbef858cf484ca86ab0625c6ec.json
new file mode 100644
index 0000000000..d9fc6443bf
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-aa9ca547f8128f5f2a4418b6ccf252d9726565fbef858cf484ca86ab0625c6ec.json
@@ -0,0 +1,70 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, company_id, contact_id, owner, resolved, metadata,\n created_at, updated_at, deleted_at\n FROM crm_thread\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "company_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "contact_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 3,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "resolved",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "metadata",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ false,
+ false,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "aa9ca547f8128f5f2a4418b6ccf252d9726565fbef858cf484ca86ab0625c6ec"
+}
diff --git a/rust/cloud-storage/.sqlx/query-ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8.json b/rust/cloud-storage/.sqlx/query-ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8.json
new file mode 100644
index 0000000000..48d35a1bb7
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8.json
@@ -0,0 +1,78 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE crm_comment c\n SET text = $3, updated_at = now()\n FROM crm_thread t\n WHERE c.id = $1\n AND c.thread_id = t.id\n AND c.deleted_at IS NULL\n AND (\n EXISTS (\n SELECT 1 FROM crm_companies co\n WHERE co.id = t.company_id AND co.team_id = $2\n )\n OR EXISTS (\n SELECT 1 FROM crm_contacts ct\n JOIN crm_companies co2 ON co2.id = ct.company_id\n WHERE ct.id = t.contact_id AND co2.team_id = $2\n )\n )\n RETURNING c.id, c.thread_id, c.\"order\", c.owner, c.sender, c.text,\n c.metadata, c.created_at, c.updated_at, c.deleted_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "order",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "sender",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "metadata",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true,
+ false,
+ true,
+ false,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b14f90ed1d2e7f0121f95af1b0d364f1a7feee942c2a3785bf39c6f110aa70ba.json b/rust/cloud-storage/.sqlx/query-b14f90ed1d2e7f0121f95af1b0d364f1a7feee942c2a3785bf39c6f110aa70ba.json
new file mode 100644
index 0000000000..2868a9715f
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b14f90ed1d2e7f0121f95af1b0d364f1a7feee942c2a3785bf39c6f110aa70ba.json
@@ -0,0 +1,59 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, owner, resolved, metadata, created_at, updated_at, deleted_at\n FROM crm_thread\n WHERE (company_id = $1 OR contact_id = $2)\n AND deleted_at IS NULL\n ORDER BY created_at ASC, id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "resolved",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 3,
+ "name": "metadata",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "b14f90ed1d2e7f0121f95af1b0d364f1a7feee942c2a3785bf39c6f110aa70ba"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b3d476868aa3b19eb8407112f0cabdce0882403268c35f6a4acf62c1212183fb.json b/rust/cloud-storage/.sqlx/query-b3d476868aa3b19eb8407112f0cabdce0882403268c35f6a4acf62c1212183fb.json
new file mode 100644
index 0000000000..08a280e9fc
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b3d476868aa3b19eb8407112f0cabdce0882403268c35f6a4acf62c1212183fb.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_comment SET deleted_at = now(), updated_at = now() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b3d476868aa3b19eb8407112f0cabdce0882403268c35f6a4acf62c1212183fb"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b73077f2df6391baeaf31c0f136503cea1c346685d29795e26caab50e3654d22.json b/rust/cloud-storage/.sqlx/query-b73077f2df6391baeaf31c0f136503cea1c346685d29795e26caab50e3654d22.json
new file mode 100644
index 0000000000..d13590b7e5
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b73077f2df6391baeaf31c0f136503cea1c346685d29795e26caab50e3654d22.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_thread SET deleted_at = now(), updated_at = now() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b73077f2df6391baeaf31c0f136503cea1c346685d29795e26caab50e3654d22"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c3381d086690011cad23f03e78a79a08ac84dde454e716e5d21dd52cd9b75ec6.json b/rust/cloud-storage/.sqlx/query-c3381d086690011cad23f03e78a79a08ac84dde454e716e5d21dd52cd9b75ec6.json
new file mode 100644
index 0000000000..31b865c178
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-c3381d086690011cad23f03e78a79a08ac84dde454e716e5d21dd52cd9b75ec6.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM crm_companies WHERE id = $1 AND team_id = $2\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "c3381d086690011cad23f03e78a79a08ac84dde454e716e5d21dd52cd9b75ec6"
+}
diff --git a/rust/cloud-storage/.sqlx/query-cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a.json b/rust/cloud-storage/.sqlx/query-cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a.json
new file mode 100644
index 0000000000..e54333bbe3
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n company_id,\n email,\n name,\n first_interaction,\n last_interaction,\n created_at,\n updated_at\n FROM crm_contacts\n WHERE company_id = $1\n AND hidden = FALSE\n ORDER BY LOWER(COALESCE(name, email)) ASC, id DESC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "company_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "email",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "first_interaction",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 5,
+ "name": "last_interaction",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a"
+}
diff --git a/rust/cloud-storage/.sqlx/query-d13e90d3f2bda80111ac9849f14099b08f372bf4606405d18d8c465d241b5781.json b/rust/cloud-storage/.sqlx/query-d13e90d3f2bda80111ac9849f14099b08f372bf4606405d18d8c465d241b5781.json
new file mode 100644
index 0000000000..279e89e180
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-d13e90d3f2bda80111ac9849f14099b08f372bf4606405d18d8c465d241b5781.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO crm_comment (thread_id, owner, text, metadata)\n VALUES ($1, $2, $3, $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "d13e90d3f2bda80111ac9849f14099b08f372bf4606405d18d8c465d241b5781"
+}
diff --git a/rust/cloud-storage/.sqlx/query-e1661b2dd9feaf90960460b587fb5639ae2ea1210a6eef750d607ed54c245616.json b/rust/cloud-storage/.sqlx/query-e1661b2dd9feaf90960460b587fb5639ae2ea1210a6eef750d607ed54c245616.json
new file mode 100644
index 0000000000..43e5288ec3
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-e1661b2dd9feaf90960460b587fb5639ae2ea1210a6eef750d607ed54c245616.json
@@ -0,0 +1,85 @@
+{
+ "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 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"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true
+ ]
+ },
+ "hash": "e1661b2dd9feaf90960460b587fb5639ae2ea1210a6eef750d607ed54c245616"
+}
diff --git a/rust/cloud-storage/.sqlx/query-ef656114c7f86aa883e6360df927ea16b18efcff635cbb4d8146ff4f3ba67416.json b/rust/cloud-storage/.sqlx/query-ef656114c7f86aa883e6360df927ea16b18efcff635cbb4d8146ff4f3ba67416.json
new file mode 100644
index 0000000000..82ec51214d
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-ef656114c7f86aa883e6360df927ea16b18efcff635cbb4d8146ff4f3ba67416.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM crm_thread\n WHERE id = $1\n AND deleted_at IS NULL\n AND (company_id = $2 OR contact_id = $3)\n ) AS \"exists!\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "ef656114c7f86aa883e6360df927ea16b18efcff635cbb4d8146ff4f3ba67416"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 20e5aa0434..f0acbda2af 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2699,6 +2699,7 @@ dependencies = [
"macro_uuid",
"model-error-response",
"serde",
+ "serde_json",
"sqlx",
"thiserror 2.0.18",
"tokio",
@@ -7284,6 +7285,7 @@ dependencies = [
"call",
"chrono",
"comms",
+ "crm",
"document_sub_type",
"doppleganger",
"email",
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 41d091ba17..5e12a8d2bb 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -180,6 +180,7 @@ pub async fn build_tool_service_context_from_env(
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
call::domain::ports::NoOpCallRecordQueryService,
+ crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 8d325b86ed..d48834d14e 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -442,6 +442,7 @@ pub type ToolSoupService = SoupImpl<
email::domain::ports::ReadonlyEmailPreviewAdapter<ToolEmailService>,
ToolCommsService,
call::domain::ports::NoOpCallRecordQueryService,
+ crm::domain::service::NoOpCrmService,
ToolForeignEntityService,
>;
diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.toml
index 3ef7bb6d9e..0664deeda4 100644
--- a/rust/cloud-storage/crm/Cargo.toml
+++ b/rust/cloud-storage/crm/Cargo.toml
@@ -23,6 +23,7 @@ ports = []
anyhow = { workspace = true }
chrono = { workspace = true }
serde = { workspace = true }
+serde_json = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
diff --git a/rust/cloud-storage/crm/src/domain.rs b/rust/cloud-storage/crm/src/domain.rs
index 39ba44445f..9931a67484 100644
--- a/rust/cloud-storage/crm/src/domain.rs
+++ b/rust/cloud-storage/crm/src/domain.rs
@@ -1,6 +1,9 @@
/// Domain models for CRM records
pub mod model;
+/// Domain and wire models for CRM comment threads
+pub mod comment;
+
/// Static list of generic/personal email-provider domains to exclude
/// from CRM populate
#[cfg(feature = "ports")]
diff --git a/rust/cloud-storage/crm/src/domain/comment.rs b/rust/cloud-storage/crm/src/domain/comment.rs
new file mode 100644
index 0000000000..b7ea9c58f7
--- /dev/null
+++ b/rust/cloud-storage/crm/src/domain/comment.rs
@@ -0,0 +1,105 @@
+//! Domain (and wire) models for CRM comment threads.
+//!
+//! A CRM comment thread mirrors the document `Thread`/`Comment` shape closely
+//! enough that the frontend reuses its thread-assembly and rendering logic,
+//! but threads hang off a CRM company or contact (not a document) and use
+//! uuid ids. `entityType` + `entityId` replace the document `documentId`.
+
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use uuid::Uuid;
+
+/// Which CRM entity a comment thread is attached to. Serializes to
+/// `crm_company` / `crm_contact` — matching the `entityType` the frontend
+/// uses elsewhere when building entity URLs — and is parsed from the
+/// `{entity_type}` path segment on the comment routes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum CrmCommentEntityType {
+ /// Thread attached to a `crm_companies` row.
+ CrmCompany,
+ /// Thread attached to a `crm_contacts` row.
+ CrmContact,
+}
+
+/// A CRM comment thread: the parent record one or more comments hang off.
+#[derive(Debug, Clone, Serialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CrmThread {
+ /// The thread id.
+ pub thread_id: Uuid,
+ /// Which CRM entity kind this thread belongs to.
+ pub entity_type: CrmCommentEntityType,
+ /// The id of the CRM company or contact this thread belongs to.
+ pub entity_id: Uuid,
+ /// Macro user id of the thread creator.
+ pub owner: String,
+ /// Whether the thread is resolved.
+ pub resolved: bool,
+ /// Arbitrary client metadata.
+ pub metadata: Option<Value>,
+ /// When the thread was created.
+ pub created_at: DateTime<Utc>,
+ /// When the thread was last updated.
+ pub updated_at: DateTime<Utc>,
+ /// When the thread was soft-deleted, if ever.
+ pub deleted_at: Option<DateTime<Utc>>,
+}
+
+/// A single comment within a [`CrmThread`].
+#[derive(Debug, Clone, Serialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CrmComment {
+ /// The comment id.
+ pub comment_id: Uuid,
+ /// The id of the thread this comment belongs to.
+ pub thread_id: Uuid,
+ /// Optional explicit ordering within the thread; the frontend falls
+ /// back to `createdAt` when absent.
+ pub order: Option<i32>,
+ /// Macro user id of the comment author.
+ pub owner: String,
+ /// Macro user id of the actual sender, when distinct from `owner`.
+ pub sender: Option<String>,
+ /// The comment body (markdown).
+ pub text: String,
+ /// Arbitrary client metadata.
+ pub metadata: Option<Value>,
+ /// When the comment was created.
+ pub created_at: DateTime<Utc>,
+ /// When the comment was last updated.
+ pub updated_at: DateTime<Utc>,
+ /// When the comment was soft-deleted, if ever.
+ pub deleted_at: Option<DateTime<Utc>>,
+}
+
+/// A [`CrmThread`] with its comments nested under it — the unit the
+/// frontend renders.
+#[derive(Debug, Clone, Serialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CrmCommentThread {
+ /// The thread.
+ pub thread: CrmThread,
+ /// The thread's comments, oldest first.
+ pub comments: Vec<CrmComment>,
+}
+
+/// Outcome of soft-deleting a CRM comment: reports whether the parent thread
+/// was soft-deleted too (it is when the deleted comment was its last live one).
+#[derive(Debug, Clone, Serialize)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteCrmCommentResult {
+ /// The deleted comment's id.
+ pub comment_id: Uuid,
+ /// The thread the comment belonged to.
+ pub thread_id: Uuid,
+ /// Whether the thread itself was soft-deleted because no live comments
+ /// remained.
+ pub thread_deleted: bool,
+}
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index 0bf25ee30b..42a1445294 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -1,7 +1,23 @@
//! Port for persistence operations on CRM companies.
-use crate::domain::model::{CrmCompany, CrmError, CrmScopePrecheck, DomainMetadata};
+use crate::domain::comment::{
+ CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult,
+};
+use crate::domain::model::{
+ CrmCompany, CrmCompanyForSoup, CrmContact, CrmError, CrmScopePrecheck, DomainMetadata,
+};
use chrono::{DateTime, Utc};
+use serde_json::Value;
+
+/// Sort order for [`CompaniesRepository::list_companies_for_soup`].
+/// Both variants tiebreak on `id DESC` for deterministic pagination.
+#[derive(Debug, Clone, Copy)]
+pub enum CrmCompanyListSort {
+ /// Sort by `crm_companies.last_interaction` DESC.
+ UpdatedAt,
+ /// Sort by `crm_companies.first_interaction` DESC.
+ CreatedAt,
+}
/// The CompaniesRepository defines persistence operations for CRM
/// companies and their associated domains.
@@ -267,4 +283,91 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
domains: &[String],
addresses: &[String],
) -> impl Future<Output = Result<CrmScopePrecheck, CrmError>> + Send;
+
+ /// 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`.
+ fn list_companies_for_soup(
+ &self,
+ team_id: &uuid::Uuid,
+ company_ids: &[uuid::Uuid],
+ sort: CrmCompanyListSort,
+ limit: i64,
+ ) -> impl Future<Output = Result<Vec<CrmCompanyForSoup>, CrmError>> + Send;
+
+ /// Lists the non-hidden contacts of `company_id`, scoped to
+ /// `team_id` via the contact's company. Returns
+ /// [`CrmError::CompanyNotFoundForTeam`] when the company doesn't
+ /// exist or isn't owned by the team (so existence doesn't leak
+ /// across teams); an owned company with no visible contacts
+ /// returns `Ok(vec![])`. Ordered alphabetically (case-insensitive)
+ /// by display name, falling back to email when the contact has no
+ /// name; ties break on `id DESC`.
+ fn list_contacts_for_company(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Vec<CrmContact>, CrmError>> + Send;
+
+ /// Create a CRM comment. With `thread_id = None` a new thread is opened
+ /// on `(entity_type, entity_id)` and the comment becomes its root; with
+ /// `Some`, the comment is appended to that existing thread (whose
+ /// `updated_at` is bumped). Scoped to `team_id` via the entity's
+ /// company: returns [`CrmError::CompanyNotFoundForTeam`] /
+ /// [`CrmError::ContactNotFoundForTeam`] when the entity isn't owned by
+ /// the team, or [`CrmError::ThreadNotFound`] when a supplied `thread_id`
+ /// is deleted or doesn't belong to that entity. Returns the full thread
+ /// (with all its comments) after the insert.
+ #[allow(clippy::too_many_arguments)]
+ fn create_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ owner: &str,
+ thread_id: Option<uuid::Uuid>,
+ thread_metadata: Option<Value>,
+ text: &str,
+ metadata: Option<Value>,
+ ) -> impl Future<Output = Result<CrmCommentThread, CrmError>> + Send;
+
+ /// List the non-deleted comment threads on `(entity_type, entity_id)`,
+ /// each with its comments nested oldest-first; threads are ordered
+ /// oldest-first by creation. Scoped to `team_id` via the entity's
+ /// company — returns [`CrmError::CompanyNotFoundForTeam`] /
+ /// [`CrmError::ContactNotFoundForTeam`] when the entity isn't owned by
+ /// the team (so existence doesn't leak across teams); an owned entity
+ /// with no threads returns `Ok(vec![])`.
+ fn get_crm_comment_threads(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Vec<CrmCommentThread>, CrmError>> + Send;
+
+ /// Edit a CRM comment's `text`, scoped to `team_id` via the comment's
+ /// thread → entity → company. Returns the updated comment, or
+ /// [`CrmError::CommentNotFound`] when it doesn't exist or isn't owned by
+ /// the team.
+ fn edit_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ text: &str,
+ ) -> impl Future<Output = Result<CrmComment, CrmError>> + Send;
+
+ /// Soft-delete a CRM comment (sets `deleted_at`), scoped to `team_id`.
+ /// When it was the thread's last live comment, the thread is
+ /// soft-deleted too (reported via
+ /// [`DeleteCrmCommentResult::thread_deleted`]). Returns
+ /// [`CrmError::CommentNotFound`] when the comment doesn't exist, is
+ /// already deleted, or isn't owned by the team.
+ fn delete_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<DeleteCrmCommentResult, CrmError>> + Send;
}
diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rs
index c846e6ab7c..88bc1fcf56 100644
--- a/rust/cloud-storage/crm/src/domain/model.rs
+++ b/rust/cloud-storage/crm/src/domain/model.rs
@@ -2,6 +2,20 @@
use chrono::{DateTime, Utc};
+/// A [`CrmCompany`] bundled with display metadata resolved from
+/// `crm_domain_directory` against the primary (earliest-created) domain.
+/// `name` / `description` are `None` when no directory row exists or
+/// the row is in negative-cache state (NULL fields).
+#[derive(Debug, Clone)]
+pub struct CrmCompanyForSoup {
+ /// The underlying company record.
+ pub company: CrmCompany,
+ /// Display name from the primary domain's directory entry.
+ pub name: Option<String>,
+ /// Display description from the primary domain's directory entry.
+ pub description: Option<String>,
+}
+
/// A known external company tracked by a team (CRM-style record). A company
/// aggregates one or more email domains and individual contacts that are
/// considered to belong to the same external party.
@@ -64,6 +78,29 @@ pub struct CrmDomain {
pub created_at: DateTime<Utc>,
}
+/// A contact (individual external party) belonging to a [`CrmCompany`].
+/// Tracked per `(company_id, email)`; `name` is the first non-NULL display
+/// name observed across the team's populates.
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct CrmContact {
+ /// The id of the contact record
+ pub id: uuid::Uuid,
+ /// The id of the company the contact belongs to
+ pub company_id: uuid::Uuid,
+ /// The contact's email address
+ pub email: String,
+ /// Display name observed for the contact, if any
+ pub name: Option<String>,
+ /// Earliest known interaction with this contact
+ pub first_interaction: DateTime<Utc>,
+ /// Most recent known interaction with this contact
+ pub last_interaction: DateTime<Utc>,
+ /// When the contact record was created
+ pub created_at: DateTime<Utc>,
+ /// When the contact record was last updated
+ pub updated_at: DateTime<Utc>,
+}
+
/// Result of [`crate::domain::companies_repo::CompaniesRepository::crm_scope_precheck`].
///
/// Carries the per-input authorization status the caller (`EmailService`)
@@ -131,6 +168,16 @@ pub enum CrmError {
/// Contact id is not owned by the requesting team.
#[error("crm contact not found for team")]
ContactNotFoundForTeam,
+ /// Comment thread id does not exist, is deleted, or does not belong
+ /// to the addressed entity / team.
+ #[error("crm comment thread not found")]
+ ThreadNotFound,
+ /// Comment id does not exist or does not belong to the team.
+ #[error("crm comment not found for team")]
+ CommentNotFound,
+ /// Request rejected for a client-side reason (e.g. blank comment text).
+ #[error("{0}")]
+ InvalidRequest(String),
/// Tried to mutate a CRM company in a way that contradicts its
/// `hidden = true` state — currently raised when attempting to
/// re-enable `email_sync` on a hidden company.
diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rs
index 4cab422c85..326cbb2c46 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -1,12 +1,14 @@
//! The CrmService trait and its default implementation.
use crate::domain::{
- companies_repo::CompaniesRepository,
+ comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult},
+ companies_repo::{CompaniesRepository, CrmCompanyListSort},
company_metadata_resolver::CompanyMetadataResolver,
generic_email_domains::is_generic_email_domain,
- model::{CrmCompany, CrmError, CrmScopePrecheck},
+ model::{CrmCompany, CrmCompanyForSoup, CrmContact, CrmError, CrmScopePrecheck},
};
use chrono::{DateTime, Utc};
+use serde_json::Value;
/// The CrmService exposes operations over CRM records (companies, their
/// domains and contacts).
@@ -176,6 +178,68 @@ pub trait CrmService: Clone + Send + Sync + 'static {
domains: &[String],
addresses: &[String],
) -> impl Future<Output = Result<CrmScopePrecheck, CrmError>> + Send;
+
+ /// List the team's CRM companies for the soup feed. See
+ /// [`CompaniesRepository::list_companies_for_soup`].
+ fn list_companies_for_soup(
+ &self,
+ team_id: &uuid::Uuid,
+ company_ids: &[uuid::Uuid],
+ sort: CrmCompanyListSort,
+ limit: i64,
+ ) -> impl Future<Output = Result<Vec<CrmCompanyForSoup>, CrmError>> + Send;
+
+ /// List a company's non-hidden contacts, scoped to `team_id`. See
+ /// [`CompaniesRepository::list_contacts_for_company`].
+ fn list_contacts_for_company(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Vec<CrmContact>, CrmError>> + Send;
+
+ /// Create a comment on a CRM company or contact, optionally as a reply
+ /// to an existing thread. See
+ /// [`CompaniesRepository::create_crm_comment`]. Authorization (team
+ /// membership) is the caller's responsibility; the entity-ownership
+ /// scoping is enforced in the repository.
+ #[allow(clippy::too_many_arguments)]
+ fn create_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ owner: &str,
+ thread_id: Option<uuid::Uuid>,
+ thread_metadata: Option<Value>,
+ text: &str,
+ metadata: Option<Value>,
+ ) -> impl Future<Output = Result<CrmCommentThread, CrmError>> + Send;
+
+ /// List a CRM entity's comment threads. See
+ /// [`CompaniesRepository::get_crm_comment_threads`].
+ fn get_crm_comment_threads(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<Vec<CrmCommentThread>, CrmError>> + Send;
+
+ /// Edit a CRM comment's text, scoped to `team_id`. See
+ /// [`CompaniesRepository::edit_crm_comment`].
+ fn edit_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ text: &str,
+ ) -> impl Future<Output = Result<CrmComment, CrmError>> + Send;
+
+ /// Soft-delete a CRM comment, scoped to `team_id`. See
+ /// [`CompaniesRepository::delete_crm_comment`].
+ fn delete_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ ) -> impl Future<Output = Result<DeleteCrmCommentResult, CrmError>> + Send;
}
/// Implementation of [`CrmService`] backed by a [`CompaniesRepository`]
@@ -422,4 +486,237 @@ where
.crm_scope_precheck(team_id, domains, addresses)
.await
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn list_companies_for_soup(
+ &self,
+ team_id: &uuid::Uuid,
+ company_ids: &[uuid::Uuid],
+ sort: CrmCompanyListSort,
+ limit: i64,
+ ) -> Result<Vec<CrmCompanyForSoup>, CrmError> {
+ self.companies_repository
+ .list_companies_for_soup(team_id, company_ids, sort, limit)
+ .await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn list_contacts_for_company(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ ) -> Result<Vec<CrmContact>, CrmError> {
+ self.companies_repository
+ .list_contacts_for_company(team_id, company_id)
+ .await
+ }
+
+ #[tracing::instrument(skip(self, thread_metadata, text, metadata), err)]
+ #[allow(clippy::too_many_arguments)]
+ async fn create_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ owner: &str,
+ thread_id: Option<uuid::Uuid>,
+ thread_metadata: Option<Value>,
+ text: &str,
+ metadata: Option<Value>,
+ ) -> Result<CrmCommentThread, CrmError> {
+ self.companies_repository
+ .create_crm_comment(
+ team_id,
+ entity_type,
+ entity_id,
+ owner,
+ thread_id,
+ thread_metadata,
+ text,
+ metadata,
+ )
+ .await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_crm_comment_threads(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ ) -> Result<Vec<CrmCommentThread>, CrmError> {
+ self.companies_repository
+ .get_crm_comment_threads(team_id, entity_type, entity_id)
+ .await
+ }
+
+ #[tracing::instrument(skip(self, text), err)]
+ async fn edit_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ text: &str,
+ ) -> Result<CrmComment, CrmError> {
+ self.companies_repository
+ .edit_crm_comment(team_id, comment_id, text)
+ .await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn delete_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ ) -> Result<DeleteCrmCommentResult, CrmError> {
+ self.companies_repository
+ .delete_crm_comment(team_id, comment_id)
+ .await
+ }
+}
+
+/// No-op [`CrmService`] for binaries that need to satisfy the bound
+/// but never call CRM. `list_companies_for_soup` returns empty; every
+/// other method panics — swap for [`CrmServiceImpl`] if you actually
+/// need CRM functionality.
+#[derive(Clone, Debug)]
+pub struct NoOpCrmService;
+
+impl CrmService for NoOpCrmService {
+ async fn get_company_by_domain(
+ &self,
+ _team_id: &uuid::Uuid,
+ _domain: &str,
+ ) -> Result<Option<CrmCompany>, CrmError> {
+ unimplemented!("NoOpCrmService.get_company_by_domain")
+ }
+
+ async fn populate_contact(
+ &self,
+ _team_id: &uuid::Uuid,
+ _link_id: &uuid::Uuid,
+ _user_email: &str,
+ _email: &str,
+ _name: Option<&str>,
+ _first_at: DateTime<Utc>,
+ _last_at: DateTime<Utc>,
+ _is_sent: bool,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.populate_contact")
+ }
+
+ async fn depopulate_contact(
+ &self,
+ _team_id: &uuid::Uuid,
+ _link_id: &uuid::Uuid,
+ _email: &str,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.depopulate_contact")
+ }
+
+ async fn depopulate_link_in_team(
+ &self,
+ _team_id: &uuid::Uuid,
+ _link_id: &uuid::Uuid,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.depopulate_link_in_team")
+ }
+
+ async fn get_team_id_for_user(&self, _macro_id: &str) -> Result<Option<uuid::Uuid>, CrmError> {
+ unimplemented!("NoOpCrmService.get_team_id_for_user")
+ }
+
+ async fn set_email_sync(
+ &self,
+ _team_id: &uuid::Uuid,
+ _company_id: &uuid::Uuid,
+ _email_sync: bool,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.set_email_sync")
+ }
+
+ async fn set_company_hidden(
+ &self,
+ _team_id: &uuid::Uuid,
+ _company_id: &uuid::Uuid,
+ _hidden: bool,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.set_company_hidden")
+ }
+
+ async fn set_contact_hidden(
+ &self,
+ _team_id: &uuid::Uuid,
+ _contact_id: &uuid::Uuid,
+ _hidden: bool,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.set_contact_hidden")
+ }
+
+ async fn crm_scope_precheck(
+ &self,
+ _team_id: &uuid::Uuid,
+ _domains: &[String],
+ _addresses: &[String],
+ ) -> Result<CrmScopePrecheck, CrmError> {
+ unimplemented!("NoOpCrmService.crm_scope_precheck")
+ }
+
+ async fn list_companies_for_soup(
+ &self,
+ _team_id: &uuid::Uuid,
+ _company_ids: &[uuid::Uuid],
+ _sort: CrmCompanyListSort,
+ _limit: i64,
+ ) -> Result<Vec<CrmCompanyForSoup>, CrmError> {
+ Ok(Vec::new())
+ }
+
+ async fn list_contacts_for_company(
+ &self,
+ _team_id: &uuid::Uuid,
+ _company_id: &uuid::Uuid,
+ ) -> Result<Vec<CrmContact>, CrmError> {
+ Ok(Vec::new())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ async fn create_crm_comment(
+ &self,
+ _team_id: &uuid::Uuid,
+ _entity_type: CrmCommentEntityType,
+ _entity_id: &uuid::Uuid,
+ _owner: &str,
+ _thread_id: Option<uuid::Uuid>,
+ _thread_metadata: Option<Value>,
+ _text: &str,
+ _metadata: Option<Value>,
+ ) -> Result<CrmCommentThread, CrmError> {
+ unimplemented!("NoOpCrmService.create_crm_comment")
+ }
+
+ async fn get_crm_comment_threads(
+ &self,
+ _team_id: &uuid::Uuid,
+ _entity_type: CrmCommentEntityType,
+ _entity_id: &uuid::Uuid,
+ ) -> Result<Vec<CrmCommentThread>, CrmError> {
+ Ok(Vec::new())
+ }
+
+ async fn edit_crm_comment(
+ &self,
+ _team_id: &uuid::Uuid,
+ _comment_id: &uuid::Uuid,
+ _text: &str,
+ ) -> Result<CrmComment, CrmError> {
+ unimplemented!("NoOpCrmService.edit_crm_comment")
+ }
+
+ async fn delete_crm_comment(
+ &self,
+ _team_id: &uuid::Uuid,
+ _comment_id: &uuid::Uuid,
+ ) -> Result<DeleteCrmCommentResult, CrmError> {
+ unimplemented!("NoOpCrmService.delete_crm_comment")
+ }
}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs b/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
new file mode 100644
index 0000000000..5dd52e827d
--- /dev/null
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
@@ -0,0 +1,221 @@
+//! Handlers for CRM comment threads.
+//!
+//! Threads and comments hang off a CRM company or contact and mirror the
+//! document comment shape so the frontend reuses its thread assembly /
+//! rendering. All routes are team-scoped via [`MacroUserTeamExtractor`];
+//! entity ownership is enforced in the repository.
+
+use axum::{
+ Json,
+ extract::{Path, State},
+};
+use entity_access::{
+ domain::{models::MemberTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
+use model_error_response::ErrorResponse;
+use serde::Deserialize;
+use serde_json::Value;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::{
+ comment::{CrmComment, CrmCommentEntityType, CrmCommentThread, DeleteCrmCommentResult},
+ model::CrmError,
+ service::CrmService,
+};
+
+use super::CrmRouterState;
+
+/// Request body for `POST /crm/comments/{entity_type}/{entity_id}`.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateCrmCommentRequest {
+ /// Existing thread to append to. Omit to start a new thread on the
+ /// addressed entity.
+ pub thread_id: Option<Uuid>,
+ /// Metadata to set on a newly created thread (ignored when replying
+ /// without a value).
+ pub thread_metadata: Option<Value>,
+ /// The comment body (markdown).
+ pub text: String,
+ /// Arbitrary client metadata for the comment.
+ pub metadata: Option<Value>,
+}
+
+/// Request body for `PATCH /crm/comments/comment/{comment_id}`.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct EditCrmCommentRequest {
+ /// The new comment body (markdown).
+ pub text: String,
+}
+
+/// List the comment threads on a CRM company or contact, scoped to the
+/// requesting user's team. Returns 404 when the entity isn't owned by the
+/// team; an owned entity with no threads returns `200 []`.
+#[utoipa::path(
+ get,
+ path = "/crm/comments/{entity_type}/{entity_id}",
+ operation_id = "list_crm_comments",
+ params(
+ ("entity_type" = CrmCommentEntityType, Path, description = "Which CRM entity kind the threads hang off"),
+ ("entity_id" = Uuid, Path, description = "The CRM company or contact id"),
+ ),
+ responses(
+ (status = 200, body = [CrmCommentThread]),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
+pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ State(state): State<CrmRouterState<C, Eas>>,
+ Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
+) -> Result<Json<Vec<CrmCommentThread>>, CrmError> {
+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidTeamId)?;
+
+ let threads = state
+ .service
+ .get_crm_comment_threads(&team_id, entity_type, &entity_id)
+ .await?;
+
+ Ok(Json(threads))
+}
+
+/// Create a comment on a CRM company or contact — a new thread, or a reply
+/// when `threadId` is supplied. Returns the full thread (with all comments)
+/// after the insert. Team-scoped; 404 when the entity isn't owned by the
+/// team or `threadId` doesn't belong to it.
+#[utoipa::path(
+ post,
+ path = "/crm/comments/{entity_type}/{entity_id}",
+ operation_id = "create_crm_comment",
+ params(
+ ("entity_type" = CrmCommentEntityType, Path, description = "Which CRM entity kind the thread hangs off"),
+ ("entity_id" = Uuid, Path, description = "The CRM company or contact id"),
+ ),
+ request_body = CreateCrmCommentRequest,
+ responses(
+ (status = 200, body = CrmCommentThread),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
+pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ State(state): State<CrmRouterState<C, Eas>>,
+ Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
+ Json(req): Json<CreateCrmCommentRequest>,
+) -> Result<Json<CrmCommentThread>, CrmError> {
+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidTeamId)?;
+ let owner = access
+ .entity_access_receipt
+ .get_authenticated_user()
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let text = req.text.trim();
+ if text.is_empty() {
+ return Err(CrmError::InvalidRequest(
+ "comment text cannot be empty".into(),
+ ));
+ }
+
+ let thread = state
+ .service
+ .create_crm_comment(
+ &team_id,
+ entity_type,
+ &entity_id,
+ owner.as_ref(),
+ req.thread_id,
+ req.thread_metadata,
+ text,
+ req.metadata,
+ )
+ .await?;
+
+ Ok(Json(thread))
+}
+
+/// Edit a CRM comment's text, scoped to the requesting user's team via the
+/// comment's thread → entity → company. Returns the updated comment.
+#[utoipa::path(
+ patch,
+ path = "/crm/comment/{comment_id}",
+ operation_id = "edit_crm_comment",
+ params(
+ ("comment_id" = Uuid, Path, description = "The CRM comment to edit"),
+ ),
+ request_body = EditCrmCommentRequest,
+ responses(
+ (status = 200, body = CrmComment),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
+pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ State(state): State<CrmRouterState<C, Eas>>,
+ Path(comment_id): Path<Uuid>,
+ Json(req): Json<EditCrmCommentRequest>,
+) -> Result<Json<CrmComment>, CrmError> {
+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidTeamId)?;
+
+ let text = req.text.trim();
+ if text.is_empty() {
+ return Err(CrmError::InvalidRequest(
+ "comment text cannot be empty".into(),
+ ));
+ }
+
+ let comment = state
+ .service
+ .edit_crm_comment(&team_id, &comment_id, text)
+ .await?;
+
+ Ok(Json(comment))
+}
+
+/// Soft-delete a CRM comment, scoped to the requesting user's team. When it
+/// was the thread's last live comment, the thread is soft-deleted too
+/// (reported via `threadDeleted`).
+#[utoipa::path(
+ delete,
+ path = "/crm/comment/{comment_id}",
+ operation_id = "delete_crm_comment",
+ params(
+ ("comment_id" = Uuid, Path, description = "The CRM comment to delete"),
+ ),
+ responses(
+ (status = 200, body = DeleteCrmCommentResult),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
+pub async fn delete_handler<C: CrmService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ State(state): State<CrmRouterState<C, Eas>>,
+ Path(comment_id): Path<Uuid>,
+) -> Result<Json<DeleteCrmCommentResult>, CrmError> {
+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidTeamId)?;
+
+ let result = state
+ .service
+ .delete_crm_comment(&team_id, &comment_id)
+ .await?;
+
+ Ok(Json(result))
+}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/list_company_contacts.rs b/rust/cloud-storage/crm/src/inbound/axum_router/list_company_contacts.rs
new file mode 100644
index 0000000000..885add7d45
--- /dev/null
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/list_company_contacts.rs
@@ -0,0 +1,92 @@
+use axum::{
+ Json,
+ extract::{Path, State},
+};
+use chrono::{DateTime, Utc};
+use entity_access::{
+ domain::{models::MemberTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
+use model_error_response::ErrorResponse;
+use serde::Serialize;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::{
+ model::{CrmContact, CrmError},
+ service::CrmService,
+};
+
+use super::CrmRouterState;
+
+/// A CRM contact as returned by `GET /crm/companies/{company_id}/contacts`.
+#[derive(Debug, Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CrmContactResponse {
+ /// The id of the contact record.
+ pub id: Uuid,
+ /// The id of the company the contact belongs to.
+ pub company_id: Uuid,
+ /// The contact's email address.
+ pub email: String,
+ /// Display name observed for the contact, if any.
+ pub name: Option<String>,
+ /// Earliest known interaction with this contact.
+ pub first_interaction: DateTime<Utc>,
+ /// Most recent known interaction with this contact.
+ pub last_interaction: DateTime<Utc>,
+ /// When the contact record was created.
+ pub created_at: DateTime<Utc>,
+ /// When the contact record was last updated.
+ pub updated_at: DateTime<Utc>,
+}
+
+impl From<CrmContact> for CrmContactResponse {
+ fn from(c: CrmContact) -> Self {
+ Self {
+ id: c.id,
+ company_id: c.company_id,
+ email: c.email,
+ name: c.name,
+ first_interaction: c.first_interaction,
+ last_interaction: c.last_interaction,
+ created_at: c.created_at,
+ updated_at: c.updated_at,
+ }
+ }
+}
+
+/// List the non-hidden contacts of a CRM company, scoped to the
+/// requesting user's team. Returns 404 when the company isn't owned by
+/// the team (so existence doesn't leak across teams); an owned company
+/// with no visible contacts returns `200 []`.
+#[utoipa::path(
+ get,
+ path = "/crm/companies/{company_id}/contacts",
+ operation_id = "list_company_contacts",
+ params(
+ ("company_id" = Uuid, Path, description = "The CRM company whose contacts to list"),
+ ),
+ responses(
+ (status = 200, body = [CrmContactResponse]),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
+pub async fn handler<C: CrmService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ State(state): State<CrmRouterState<C, Eas>>,
+ Path(company_id): Path<Uuid>,
+) -> Result<Json<Vec<CrmContactResponse>>, CrmError> {
+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidTeamId)?;
+
+ let contacts = state
+ .service
+ .list_contacts_for_company(&team_id, &company_id)
+ .await?;
+
+ Ok(Json(contacts.into_iter().map(Into::into).collect()))
+}
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
index 49919a7d1d..e36bb7ca0a 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
@@ -9,6 +9,12 @@ pub mod set_company_hidden;
/// Toggle the `hidden` flag on a `crm_contacts` row.
pub mod set_contact_hidden;
+/// List the non-hidden contacts of a `crm_companies` row.
+pub mod list_company_contacts;
+
+/// Comment threads on a `crm_companies` / `crm_contacts` row.
+pub mod comments;
+
use std::sync::Arc;
use axum::{
@@ -16,7 +22,7 @@ use axum::{
extract::FromRef,
http::StatusCode,
response::{IntoResponse, Response},
- routing::put,
+ routing::{get, patch, put},
};
use entity_access::domain::ports::EntityAccessService;
use model_error_response::ErrorResponse;
@@ -63,10 +69,22 @@ where
"/companies/{company_id}/hidden",
put(set_company_hidden::handler::<C, Eas>),
)
+ .route(
+ "/companies/{company_id}/contacts",
+ get(list_company_contacts::handler::<C, Eas>),
+ )
.route(
"/contacts/{contact_id}/hidden",
put(set_contact_hidden::handler::<C, Eas>),
)
+ .route(
+ "/comments/{entity_type}/{entity_id}",
+ get(comments::list_handler::<C, Eas>).post(comments::create_handler::<C, Eas>),
+ )
+ .route(
+ "/comment/{comment_id}",
+ patch(comments::edit_handler::<C, Eas>).delete(comments::delete_handler::<C, Eas>),
+ )
.with_state(state)
}
@@ -85,6 +103,24 @@ impl IntoResponse for CrmError {
message: "crm contact not found for team".into(),
}),
),
+ CrmError::ThreadNotFound => (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "crm comment thread not found".into(),
+ }),
+ ),
+ CrmError::CommentNotFound => (
+ StatusCode::NOT_FOUND,
+ Json(ErrorResponse {
+ message: "crm comment not found".into(),
+ }),
+ ),
+ CrmError::InvalidRequest(message) => (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ ),
CrmError::CompanyHidden => (
StatusCode::CONFLICT,
Json(ErrorResponse {
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index a3f57f7f50..ed2618817e 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -4,14 +4,20 @@
mod test;
use crate::domain::{
- companies_repo::CompaniesRepository,
+ comment::{
+ CrmComment, CrmCommentEntityType, CrmCommentThread, CrmThread, DeleteCrmCommentResult,
+ },
+ companies_repo::{CompaniesRepository, CrmCompanyListSort},
model::{
- CrmAddressStatus, CrmCompany, CrmDomain, CrmDomainStatus, CrmError, CrmScopePrecheck,
- DomainMetadata,
+ CrmAddressStatus, CrmCompany, CrmCompanyForSoup, CrmContact, CrmDomain, CrmDomainStatus,
+ CrmError, CrmScopePrecheck, DomainMetadata,
},
};
use chrono::{DateTime, Utc};
+use serde_json::Value;
use sqlx::PgPool;
+use std::collections::HashMap;
+use uuid::Uuid;
/// PostgreSQL-backed [`CompaniesRepository`].
#[derive(Clone)]
@@ -963,4 +969,620 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
addresses: address_statuses,
})
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn list_companies_for_soup(
+ &self,
+ team_id: &uuid::Uuid,
+ company_ids: &[uuid::Uuid],
+ sort: CrmCompanyListSort,
+ limit: i64,
+ ) -> Result<Vec<CrmCompanyForSoup>, CrmError> {
+ let sort_method_str = match sort {
+ CrmCompanyListSort::UpdatedAt => "updated_at",
+ CrmCompanyListSort::CreatedAt => "created_at",
+ };
+
+ // CTE limits companies before the domain/directory joins; the
+ // outer ORDER BY repeats the CTE's sort + `d.created_at ASC`
+ // so rows arrive contiguous per company with the primary
+ // domain first. Sort columns are `first_interaction` /
+ // `last_interaction` from populate_contact (both NOT NULL —
+ // see the `crm_interaction_timestamps` migration).
+ let rows = sqlx::query!(
+ r#"
+ WITH limited_companies AS (
+ SELECT
+ c.id,
+ c.team_id,
+ c.email_sync,
+ c.hidden,
+ c.first_interaction,
+ c.last_interaction
+ FROM crm_companies c
+ WHERE c.team_id = $1
+ AND c.hidden = FALSE
+ AND EXISTS (
+ SELECT 1 FROM team_crm_settings tcs
+ WHERE tcs.team_id = $1 AND tcs.crm_enabled
+ )
+ AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))
+ ORDER BY
+ CASE $4
+ WHEN 'created_at' THEN c.first_interaction
+ ELSE c.last_interaction
+ END DESC,
+ c.id DESC
+ LIMIT $3
+ )
+ SELECT
+ lc.id AS "company_id!",
+ lc.team_id AS "company_team_id!",
+ lc.email_sync AS "company_email_sync!",
+ lc.hidden AS "company_hidden!",
+ lc.first_interaction AS "company_created_at!",
+ lc.last_interaction AS "company_updated_at!",
+ d.id AS "domain_id?",
+ d.domain AS "domain?",
+ d.created_at AS "domain_created_at?",
+ dd.name AS "dir_name?",
+ dd.description AS "dir_description?"
+ FROM limited_companies lc
+ LEFT JOIN crm_domains d ON d.company_id = lc.id
+ LEFT JOIN crm_domain_directory dd
+ ON LOWER(dd.domain) = LOWER(d.domain)
+ ORDER BY
+ CASE $4
+ WHEN 'created_at' THEN lc.first_interaction
+ ELSE lc.last_interaction
+ END DESC,
+ lc.id DESC,
+ d.created_at ASC NULLS LAST
+ "#,
+ team_id,
+ company_ids,
+ limit,
+ sort_method_str,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ // First row per company carries the primary domain's directory
+ // metadata; remaining rows only contribute to `domains`.
+ let mut result: Vec<CrmCompanyForSoup> = Vec::new();
+ for row in rows {
+ let cid = row.company_id;
+ if result.last().is_none_or(|c| c.company.id != cid) {
+ result.push(CrmCompanyForSoup {
+ company: CrmCompany {
+ id: cid,
+ team_id: row.company_team_id,
+ email_sync: row.company_email_sync,
+ hidden: row.company_hidden,
+ created_at: row.company_created_at,
+ updated_at: row.company_updated_at,
+ domains: Vec::new(),
+ },
+ name: row.dir_name,
+ description: row.dir_description,
+ });
+ }
+ // LEFT JOIN gives an all-NULL domain row for companies with
+ // zero domains — skip the push then.
+ if let (Some(did), Some(domain), Some(created_at)) =
+ (row.domain_id, row.domain, row.domain_created_at)
+ {
+ result.last_mut().unwrap().company.domains.push(CrmDomain {
+ id: did,
+ company_id: cid,
+ domain,
+ created_at,
+ });
+ }
+ }
+
+ Ok(result)
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn list_contacts_for_company(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ ) -> Result<Vec<CrmContact>, CrmError> {
+ // Authorize first: a company id that isn't the team's must be
+ // indistinguishable from one that doesn't exist, so we 404
+ // rather than returning an empty list (which would confirm the
+ // id belongs to another team).
+ let owns_company = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM crm_companies
+ WHERE id = $1 AND team_id = $2
+ ) AS "exists!"
+ "#,
+ company_id,
+ team_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ if !owns_company {
+ return Err(CrmError::CompanyNotFoundForTeam);
+ }
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ id,
+ company_id,
+ email,
+ name,
+ first_interaction,
+ last_interaction,
+ created_at,
+ updated_at
+ FROM crm_contacts
+ WHERE company_id = $1
+ AND hidden = FALSE
+ ORDER BY LOWER(COALESCE(name, email)) ASC, id DESC
+ "#,
+ company_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| CrmContact {
+ id: row.id,
+ company_id: row.company_id,
+ email: row.email,
+ name: row.name,
+ first_interaction: row.first_interaction,
+ last_interaction: row.last_interaction,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ })
+ .collect())
+ }
+
+ #[tracing::instrument(skip(self, thread_metadata, text, metadata), err, fields(entity_id = %entity_id))]
+ async fn create_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ owner: &str,
+ thread_id: Option<uuid::Uuid>,
+ thread_metadata: Option<Value>,
+ text: &str,
+ metadata: Option<Value>,
+ ) -> Result<CrmCommentThread, CrmError> {
+ // Exactly one parent column is set; the CHECK constraint enforces it.
+ let (company_id, contact_id) = match entity_type {
+ CrmCommentEntityType::CrmCompany => (Some(*entity_id), None),
+ CrmCommentEntityType::CrmContact => (None, Some(*entity_id)),
+ };
+
+ let mut tx = self
+ .pool
+ .begin()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ // Authorize: the entity must belong to the requesting team. Done
+ // in-tx so a concurrent teardown can't slip a delete past us.
+ if !entity_owned_by_team(&mut *tx, team_id, entity_type, entity_id).await? {
+ return Err(entity_not_found_err(entity_type));
+ }
+
+ // Resolve the target thread: reuse the supplied one (after checking
+ // it belongs to this entity and isn't deleted) or open a new one.
+ let thread_id = match thread_id {
+ Some(tid) => {
+ let belongs = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM crm_thread
+ WHERE id = $1
+ AND deleted_at IS NULL
+ AND (company_id = $2 OR contact_id = $3)
+ ) AS "exists!"
+ "#,
+ tid,
+ company_id,
+ contact_id,
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ if !belongs {
+ return Err(CrmError::ThreadNotFound);
+ }
+ // Bump updated_at; replace metadata only when one is supplied.
+ sqlx::query!(
+ r#"
+ UPDATE crm_thread
+ SET updated_at = now(), metadata = COALESCE($2, metadata)
+ WHERE id = $1
+ "#,
+ tid,
+ thread_metadata,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ tid
+ }
+ None => sqlx::query_scalar!(
+ r#"
+ INSERT INTO crm_thread (company_id, contact_id, owner, metadata)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id
+ "#,
+ company_id,
+ contact_id,
+ owner,
+ thread_metadata,
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?,
+ };
+
+ sqlx::query!(
+ r#"
+ INSERT INTO crm_comment (thread_id, owner, text, metadata)
+ VALUES ($1, $2, $3, $4)
+ "#,
+ thread_id,
+ owner,
+ text,
+ metadata,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ tx.commit()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ // Re-read the full thread (with all comments) to return.
+ let row = sqlx::query!(
+ r#"
+ SELECT id, company_id, contact_id, owner, resolved, metadata,
+ created_at, updated_at, deleted_at
+ FROM crm_thread
+ WHERE id = $1
+ "#,
+ thread_id,
+ )
+ .fetch_one(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let thread = CrmThread {
+ thread_id: row.id,
+ entity_type,
+ entity_id: *entity_id,
+ owner: row.owner,
+ resolved: row.resolved,
+ metadata: row.metadata,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: row.deleted_at,
+ };
+ let comments = fetch_comments_for_threads(&self.pool, &[thread_id]).await?;
+ Ok(CrmCommentThread { thread, comments })
+ }
+
+ #[tracing::instrument(skip(self), err, fields(entity_id = %entity_id))]
+ async fn get_crm_comment_threads(
+ &self,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+ ) -> Result<Vec<CrmCommentThread>, CrmError> {
+ if !entity_owned_by_team(&self.pool, team_id, entity_type, entity_id).await? {
+ return Err(entity_not_found_err(entity_type));
+ }
+
+ let (company_id, contact_id) = match entity_type {
+ CrmCommentEntityType::CrmCompany => (Some(*entity_id), None),
+ CrmCommentEntityType::CrmContact => (None, Some(*entity_id)),
+ };
+
+ let thread_rows = sqlx::query!(
+ r#"
+ SELECT id, owner, resolved, metadata, created_at, updated_at, deleted_at
+ FROM crm_thread
+ WHERE (company_id = $1 OR contact_id = $2)
+ AND deleted_at IS NULL
+ ORDER BY created_at ASC, id ASC
+ "#,
+ company_id,
+ contact_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let threads: Vec<CrmThread> = thread_rows
+ .into_iter()
+ .map(|row| CrmThread {
+ thread_id: row.id,
+ entity_type,
+ entity_id: *entity_id,
+ owner: row.owner,
+ resolved: row.resolved,
+ metadata: row.metadata,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: row.deleted_at,
+ })
+ .collect();
+
+ let thread_ids: Vec<Uuid> = threads.iter().map(|t| t.thread_id).collect();
+ let comments = fetch_comments_for_threads(&self.pool, &thread_ids).await?;
+
+ let mut by_thread: HashMap<Uuid, Vec<CrmComment>> = HashMap::new();
+ for comment in comments {
+ by_thread
+ .entry(comment.thread_id)
+ .or_default()
+ .push(comment);
+ }
+
+ Ok(threads
+ .into_iter()
+ .map(|thread| {
+ let comments = by_thread.remove(&thread.thread_id).unwrap_or_default();
+ CrmCommentThread { thread, comments }
+ })
+ .collect())
+ }
+
+ #[tracing::instrument(skip(self, text), err, fields(comment_id = %comment_id))]
+ async fn edit_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ text: &str,
+ ) -> Result<CrmComment, CrmError> {
+ // Update only when the comment's thread resolves to a company or
+ // contact owned by the team, so cross-team edits 404.
+ let row = sqlx::query!(
+ r#"
+ UPDATE crm_comment c
+ SET text = $3, updated_at = now()
+ FROM crm_thread t
+ WHERE c.id = $1
+ AND c.thread_id = t.id
+ AND c.deleted_at IS NULL
+ AND (
+ EXISTS (
+ SELECT 1 FROM crm_companies co
+ WHERE co.id = t.company_id AND co.team_id = $2
+ )
+ OR EXISTS (
+ SELECT 1 FROM crm_contacts ct
+ JOIN crm_companies co2 ON co2.id = ct.company_id
+ WHERE ct.id = t.contact_id AND co2.team_id = $2
+ )
+ )
+ RETURNING c.id, c.thread_id, c."order", c.owner, c.sender, c.text,
+ c.metadata, c.created_at, c.updated_at, c.deleted_at
+ "#,
+ comment_id,
+ team_id,
+ text,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ match row {
+ Some(row) => Ok(CrmComment {
+ comment_id: row.id,
+ thread_id: row.thread_id,
+ order: row.order,
+ owner: row.owner,
+ sender: row.sender,
+ text: row.text,
+ metadata: row.metadata,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: row.deleted_at,
+ }),
+ None => Err(CrmError::CommentNotFound),
+ }
+ }
+
+ #[tracing::instrument(skip(self), err, fields(comment_id = %comment_id))]
+ async fn delete_crm_comment(
+ &self,
+ team_id: &uuid::Uuid,
+ comment_id: &uuid::Uuid,
+ ) -> Result<DeleteCrmCommentResult, CrmError> {
+ let mut tx = self
+ .pool
+ .begin()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ // Resolve the thread and authorize in one shot; absent / cross-team
+ // comments are reported as not found.
+ let thread_id = sqlx::query_scalar!(
+ r#"
+ SELECT t.id
+ FROM crm_comment c
+ JOIN crm_thread t ON t.id = c.thread_id
+ WHERE c.id = $1
+ AND c.deleted_at IS NULL
+ AND (
+ EXISTS (
+ SELECT 1 FROM crm_companies co
+ WHERE co.id = t.company_id AND co.team_id = $2
+ )
+ OR EXISTS (
+ SELECT 1 FROM crm_contacts ct
+ JOIN crm_companies co2 ON co2.id = ct.company_id
+ WHERE ct.id = t.contact_id AND co2.team_id = $2
+ )
+ )
+ "#,
+ comment_id,
+ team_id,
+ )
+ .fetch_optional(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let Some(thread_id) = thread_id else {
+ return Err(CrmError::CommentNotFound);
+ };
+
+ sqlx::query!(
+ r#"UPDATE crm_comment SET deleted_at = now(), updated_at = now() WHERE id = $1"#,
+ comment_id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ // If that was the thread's last live comment, soft-delete the now-empty thread.
+ let has_remaining = sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM crm_comment
+ WHERE thread_id = $1 AND deleted_at IS NULL
+ ) AS "exists!"
+ "#,
+ thread_id,
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ let thread_deleted = !has_remaining;
+ if thread_deleted {
+ sqlx::query!(
+ r#"UPDATE crm_thread SET deleted_at = now(), updated_at = now() WHERE id = $1"#,
+ thread_id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ }
+
+ tx.commit()
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ Ok(DeleteCrmCommentResult {
+ comment_id: *comment_id,
+ thread_id,
+ thread_deleted,
+ })
+ }
+}
+
+/// Maps a CRM entity type to the team-scoped not-found error used when the
+/// entity isn't owned by the requesting team.
+fn entity_not_found_err(entity_type: CrmCommentEntityType) -> CrmError {
+ match entity_type {
+ CrmCommentEntityType::CrmCompany => CrmError::CompanyNotFoundForTeam,
+ CrmCommentEntityType::CrmContact => CrmError::ContactNotFoundForTeam,
+ }
+}
+
+/// Returns whether `(entity_type, entity_id)` is owned by `team_id` — for a
+/// contact, ownership is resolved through its company. Generic over the
+/// executor so callers can check inside or outside a transaction.
+async fn entity_owned_by_team<'e, E>(
+ executor: E,
+ team_id: &uuid::Uuid,
+ entity_type: CrmCommentEntityType,
+ entity_id: &uuid::Uuid,
+) -> Result<bool, CrmError>
+where
+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,
+{
+ let owned = match entity_type {
+ CrmCommentEntityType::CrmCompany => {
+ sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM crm_companies WHERE id = $1 AND team_id = $2
+ ) AS "exists!"
+ "#,
+ entity_id,
+ team_id,
+ )
+ .fetch_one(executor)
+ .await
+ }
+ CrmCommentEntityType::CrmContact => {
+ sqlx::query_scalar!(
+ r#"
+ SELECT EXISTS (
+ SELECT 1 FROM crm_contacts c
+ JOIN crm_companies co ON co.id = c.company_id
+ WHERE c.id = $1 AND co.team_id = $2
+ ) AS "exists!"
+ "#,
+ entity_id,
+ team_id,
+ )
+ .fetch_one(executor)
+ .await
+ }
+ }
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ Ok(owned)
+}
+
+/// Fetches all non-deleted comments for the given threads, oldest-first,
+/// for grouping under their threads by the caller.
+async fn fetch_comments_for_threads(
+ pool: &PgPool,
+ thread_ids: &[Uuid],
+) -> Result<Vec<CrmComment>, CrmError> {
+ if thread_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let rows = sqlx::query!(
+ r#"
+ SELECT id, thread_id, "order", owner, sender, text, metadata,
+ created_at, updated_at, deleted_at
+ FROM crm_comment
+ WHERE thread_id = ANY($1) AND deleted_at IS NULL
+ ORDER BY created_at ASC, id ASC
+ "#,
+ thread_ids,
+ )
+ .fetch_all(pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| CrmComment {
+ comment_id: row.id,
+ thread_id: row.thread_id,
+ order: row.order,
+ owner: row.owner,
+ sender: row.sender,
+ text: row.text,
+ metadata: row.metadata,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: row.deleted_at,
+ })
+ .collect())
}
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 2ea133157b..9cd5fc2bb2 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::domain::comment::CrmCommentEntityType;
use crate::domain::service::{CrmService, CrmServiceImpl};
use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
@@ -1547,3 +1548,750 @@ async fn populate_contact_seed_style_range_merges_into_existing(
assert_eq!(contact_last, seed_last);
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_returns_empty_when_killswitch_missing(pool: PgPool) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ // No team_crm_settings row → killswitch defaults to off.
+ insert_company(&pool, team, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, 100)
+ .await?;
+ assert!(
+ result.is_empty(),
+ "killswitch missing must short-circuit to empty list even when companies exist"
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_returns_empty_when_killswitch_off(pool: PgPool) -> anyhow::Result<()> {
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ sqlx::query(r#"INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, FALSE)"#)
+ .bind(team)
+ .execute(&pool)
+ .await?;
+ insert_company(&pool, team, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, 100)
+ .await?;
+ assert!(result.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_excludes_hidden_rows(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 result = repo
+ .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, 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");
+ // The visible row must have its domains hydrated.
+ assert_eq!(result[0].company.domains.len(), 1);
+ assert_eq!(result[0].company.domains[0].domain, "acme.com");
+ // No directory row for acme.com — both display fields should be None.
+ assert_eq!(result[0].name, None);
+ assert_eq!(result[0].description, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_hydrates_name_and_description_from_directory(
+ 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?;
+ insert_company(&pool, team, true, &["acme.com", "acmecorp.com"]).await?;
+ // Directory row only on the primary — secondary must not be picked.
+ sqlx::query(
+ r#"INSERT INTO crm_domain_directory (domain, name, description)
+ VALUES ($1, $2, $3)"#,
+ )
+ .bind("acme.com")
+ .bind("Acme Inc.")
+ .bind("Maker of rocket-powered roller skates.")
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, 100)
+ .await?;
+ assert_eq!(result.len(), 1);
+ assert_eq!(result[0].name.as_deref(), Some("Acme Inc."));
+ assert_eq!(
+ result[0].description.as_deref(),
+ Some("Maker of rocket-powered roller skates.")
+ );
+ // Domain order is by created_at ASC; both should be present.
+ assert_eq!(result[0].company.domains.len(), 2);
+ assert_eq!(result[0].company.domains[0].domain, "acme.com");
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_returns_none_for_negative_cache_directory_row(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // Negative-cache directory row (NULL name/description) → soup
+ // surfaces as None, not Some("").
+ let team = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team, owner).await?;
+ enable_crm_for_team(&pool, team).await?;
+ insert_company(&pool, team, true, &["acme.com"]).await?;
+ sqlx::query(
+ r#"INSERT INTO crm_domain_directory (domain, name, description)
+ VALUES ($1, NULL, NULL)"#,
+ )
+ .bind("acme.com")
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .list_companies_for_soup(&team, &[], CrmCompanyListSort::UpdatedAt, 100)
+ .await?;
+ assert_eq!(result.len(), 1);
+ assert_eq!(result[0].name, None);
+ assert_eq!(result[0].description, None);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_filters_by_company_ids_when_non_empty(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 wanted = insert_company(&pool, team, true, &["acme.com"]).await?;
+ let _other = insert_company(&pool, team, true, &["zeta.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .list_companies_for_soup(&team, &[wanted], CrmCompanyListSort::UpdatedAt, 100)
+ .await?;
+ let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();
+ assert_eq!(ids, vec![wanted]);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_for_soup_does_not_leak_other_team_rows(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ seed_team(&pool, team_a, "macro|[email protected]").await?;
+ seed_team(&pool, team_b, "macro|[email protected]").await?;
+ enable_crm_for_team(&pool, team_a).await?;
+ enable_crm_for_team(&pool, team_b).await?;
+ insert_company(&pool, team_a, true, &["acme.com"]).await?;
+ let b_only = insert_company(&pool, team_b, true, &["zeta.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .list_companies_for_soup(&team_b, &[], CrmCompanyListSort::UpdatedAt, 100)
+ .await?;
+ let ids: Vec<Uuid> = result.iter().map(|c| c.company.id).collect();
+ assert_eq!(ids, vec![b_only]);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_contacts_returns_visible_ordered_alphabetically(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ // Named contacts sort by name; a name-less contact sorts by email.
+ // `anna smith` is lowercased to confirm the sort is case-insensitive.
+ let zoe = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ let mike = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ let carol = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ sqlx::query(r#"UPDATE crm_contacts SET name = 'Zoe Adams' WHERE id = $1"#)
+ .bind(zoe)
+ .execute(&pool)
+ .await?;
+ sqlx::query(r#"UPDATE crm_contacts SET name = 'anna smith' WHERE id = $1"#)
+ .bind(carol)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let contacts = repo
+ .list_contacts_for_company(&team_id, &company_id)
+ .await?;
+ let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();
+ // "anna smith" (carol) < "[email protected]" (mike) < "zoe adams" (zoe)
+ assert_eq!(ids, vec![carol, mike, zoe]);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_contacts_excludes_hidden(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+ let visible = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ let hidden = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)
+ .bind(hidden)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let contacts = repo
+ .list_contacts_for_company(&team_id, &company_id)
+ .await?;
+ let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();
+ assert_eq!(ids, vec![visible]);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_contacts_owned_company_with_no_contacts_returns_empty(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let contacts = repo
+ .list_contacts_for_company(&team_id, &company_id)
+ .await?;
+ assert!(contacts.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_contacts_unknown_company_returns_not_found(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .list_contacts_for_company(&team_id, &Uuid::now_v7())
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_contacts_does_not_leak_across_teams(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ seed_team(&pool, team_a, "macro|[email protected]").await?;
+ seed_team(&pool, team_b, "macro|[email protected]").await?;
+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;
+ let link_a = insert_email_link(&pool, "macro|[email protected]", "[email protected]").await?;
+ insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;
+
+ // Team B asking for team A's company must 404, not see an empty list.
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo.list_contacts_for_company(&team_b, &company_a).await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// CRM comment threads
+// ---------------------------------------------------------------------------
+
+/// Inserts a bare contact under `company_id` (no source row needed for the
+/// comment tests).
+async fn insert_contact(pool: &PgPool, company_id: Uuid, email: &str) -> sqlx::Result<Uuid> {
+ let contact_id = Uuid::now_v7();
+ sqlx::query(
+ r#"INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction)
+ VALUES ($1, $2, $3, now(), now())"#,
+ )
+ .bind(contact_id)
+ .bind(company_id)
+ .bind(email)
+ .execute(pool)
+ .await?;
+ Ok(contact_id)
+}
+
+/// Counts live (non-soft-deleted) threads.
+async fn count_threads(pool: &PgPool) -> sqlx::Result<i64> {
+ let (count,): (i64,) =
+ sqlx::query_as(r#"SELECT COUNT(*) FROM crm_thread WHERE deleted_at IS NULL"#)
+ .fetch_one(pool)
+ .await?;
+ Ok(count)
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_crm_comment_opens_thread_on_company(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let ct = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "first comment",
+ None,
+ )
+ .await?;
+
+ assert_eq!(ct.thread.entity_type, CrmCommentEntityType::CrmCompany);
+ assert_eq!(ct.thread.entity_id, company_id);
+ assert_eq!(ct.thread.owner, owner);
+ assert_eq!(ct.comments.len(), 1);
+ assert_eq!(ct.comments[0].text, "first comment");
+ assert_eq!(ct.comments[0].owner, owner);
+ assert_eq!(ct.comments[0].thread_id, ct.thread.thread_id);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_crm_comment_opens_thread_on_contact(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let ct = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmContact,
+ &contact_id,
+ owner,
+ None,
+ None,
+ "hi alice",
+ None,
+ )
+ .await?;
+
+ assert_eq!(ct.thread.entity_type, CrmCommentEntityType::CrmContact);
+ assert_eq!(ct.thread.entity_id, contact_id);
+ assert_eq!(ct.comments.len(), 1);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_crm_comment_reply_appends_to_thread(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let root = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "root",
+ None,
+ )
+ .await?;
+ let thread_id = root.thread.thread_id;
+
+ repo.create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ Some(thread_id),
+ None,
+ "reply",
+ None,
+ )
+ .await?;
+
+ // One thread, two comments, oldest-first.
+ let threads = repo
+ .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .await?;
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].thread.thread_id, thread_id);
+ assert_eq!(threads[0].comments.len(), 2);
+ assert_eq!(threads[0].comments[0].text, "root");
+ assert_eq!(threads[0].comments[1].text, "reply");
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_crm_comment_unknown_company_404(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &Uuid::now_v7(),
+ owner,
+ None,
+ None,
+ "x",
+ None,
+ )
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ seed_team(&pool, team_a, "macro|[email protected]").await?;
+ seed_team(&pool, team_b, "macro|[email protected]").await?;
+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;
+
+ // Team B cannot comment on team A's company.
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .create_crm_comment(
+ &team_b,
+ CrmCommentEntityType::CrmCompany,
+ &company_a,
+ None,
+ None,
+ "x",
+ None,
+ )
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_crm_comment_reply_to_foreign_thread_404(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_1 = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let company_2 = insert_company(&pool, team_id, true, &["beta.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let root = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_1,
+ owner,
+ None,
+ None,
+ "root",
+ None,
+ )
+ .await?;
+
+ // Replying with company_1's thread id but addressing company_2 must 404.
+ let result = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_2,
+ owner,
+ Some(root.thread.thread_id),
+ None,
+ "reply",
+ None,
+ )
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::ThreadNotFound)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_crm_comment_threads_empty_for_owned_company(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let threads = repo
+ .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .await?;
+ assert!(threads.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_crm_comment_threads_unknown_company_404(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &Uuid::now_v7())
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn edit_crm_comment_updates_text(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let ct = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "before",
+ None,
+ )
+ .await?;
+ let comment_id = ct.comments[0].comment_id;
+
+ let updated = repo
+ .edit_crm_comment(&team_id, &comment_id, "after")
+ .await?;
+ assert_eq!(updated.text, "after");
+
+ let threads = repo
+ .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .await?;
+ assert_eq!(threads[0].comments[0].text, "after");
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn edit_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ seed_team(&pool, team_a, "macro|[email protected]").await?;
+ seed_team(&pool, team_b, "macro|[email protected]").await?;
+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let ct = repo
+ .create_crm_comment(
+ &team_a,
+ CrmCommentEntityType::CrmCompany,
+ &company_a,
+ None,
+ None,
+ "secret",
+ None,
+ )
+ .await?;
+
+ let result = repo
+ .edit_crm_comment(&team_b, &ct.comments[0].comment_id, "hacked")
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CommentNotFound)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn delete_crm_comment_removes_empty_thread(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let ct = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "only comment",
+ None,
+ )
+ .await?;
+
+ let result = repo
+ .delete_crm_comment(&team_id, &ct.comments[0].comment_id)
+ .await?;
+ assert!(result.thread_deleted);
+ assert_eq!(result.thread_id, ct.thread.thread_id);
+ assert_eq!(count_threads(&pool).await?, 0);
+
+ let threads = repo
+ .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .await?;
+ assert!(threads.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn delete_crm_comment_keeps_thread_with_remaining(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let root = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "root",
+ None,
+ )
+ .await?;
+ repo.create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ Some(root.thread.thread_id),
+ None,
+ "reply",
+ None,
+ )
+ .await?;
+
+ // Deleting the root leaves the thread alive with the reply.
+ let result = repo
+ .delete_crm_comment(&team_id, &root.comments[0].comment_id)
+ .await?;
+ assert!(!result.thread_deleted);
+
+ let threads = repo
+ .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .await?;
+ assert_eq!(threads.len(), 1);
+ assert_eq!(threads[0].comments.len(), 1);
+ assert_eq!(threads[0].comments[0].text, "reply");
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn delete_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
+ let team_a = Uuid::now_v7();
+ let team_b = Uuid::now_v7();
+ seed_team(&pool, team_a, "macro|[email protected]").await?;
+ seed_team(&pool, team_b, "macro|[email protected]").await?;
+ let company_a = insert_company(&pool, team_a, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let ct = repo
+ .create_crm_comment(
+ &team_a,
+ CrmCommentEntityType::CrmCompany,
+ &company_a,
+ None,
+ None,
+ "secret",
+ None,
+ )
+ .await?;
+
+ let result = repo
+ .delete_crm_comment(&team_b, &ct.comments[0].comment_id)
+ .await;
+ assert!(matches!(
+ result,
+ Err(crate::domain::model::CrmError::CommentNotFound)
+ ));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn deleting_company_cascades_to_threads(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ let owner = "macro|[email protected]";
+ seed_team(&pool, team_id, owner).await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "doomed",
+ None,
+ )
+ .await?;
+ assert_eq!(count_threads(&pool).await?, 1);
+
+ // Hard-deleting the company cascades to its threads (and their comments).
+ sqlx::query(r#"DELETE FROM crm_companies WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+ assert_eq!(count_threads(&pool).await?, 0);
+ Ok(())
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 6cd5ae4c24..fbea69d3e1 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -189,6 +189,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
call::domain::ports::NoOpCallRecordQueryService,
+ crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index be2d82624d..4bee6c3940 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -229,6 +229,7 @@ async fn main() -> anyhow::Result<()> {
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
call::domain::ports::NoOpCallRecordQueryService,
+ crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index 3f39fb1e66..0dee6c6fed 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -111,6 +111,7 @@ type DssSoupState = SoupRouterState<
ReadonlyEmailPreviewAdapter<DssEmailService>,
CommsChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>,
call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,
+ DssCrmService,
ForeignEntityServiceType,
>,
DssEmailService,
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index 28cb209be5..5e158214f0 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -283,6 +283,11 @@ use utoipa::OpenApi;
crm::inbound::axum_router::set_email_sync::handler,
crm::inbound::axum_router::set_company_hidden::handler,
crm::inbound::axum_router::set_contact_hidden::handler,
+ crm::inbound::axum_router::list_company_contacts::handler,
+ crm::inbound::axum_router::comments::list_handler,
+ crm::inbound::axum_router::comments::create_handler,
+ crm::inbound::axum_router::comments::edit_handler,
+ crm::inbound::axum_router::comments::delete_handler,
),
components(
schemas(
@@ -509,6 +514,14 @@ use utoipa::OpenApi;
crm::inbound::axum_router::set_email_sync::SetEmailSyncRequest,
crm::inbound::axum_router::set_company_hidden::SetCompanyHiddenRequest,
crm::inbound::axum_router::set_contact_hidden::SetContactHiddenRequest,
+ crm::inbound::axum_router::list_company_contacts::CrmContactResponse,
+ crm::inbound::axum_router::comments::CreateCrmCommentRequest,
+ crm::inbound::axum_router::comments::EditCrmCommentRequest,
+ crm::domain::comment::CrmCommentEntityType,
+ crm::domain::comment::CrmThread,
+ crm::domain::comment::CrmComment,
+ crm::domain::comment::CrmCommentThread,
+ crm::domain::comment::DeleteCrmCommentResult,
),
),
tags(
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 0569cf4587..57de74a723 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -586,6 +586,7 @@ async fn main() -> anyhow::Result<()> {
readonly_email_service,
channel_service_for_soup,
call_record_query_service,
+ crm_service.clone(),
foreign_entity_service_for_soup,
),
email_service,
diff --git a/rust/cloud-storage/entity_access/src/domain/service.rs b/rust/cloud-storage/entity_access/src/domain/service.rs
index 4574a65c81..2490f2a97f 100644
--- a/rust/cloud-storage/entity_access/src/domain/service.rs
+++ b/rust/cloud-storage/entity_access/src/domain/service.rs
@@ -164,6 +164,8 @@ where
EntityType::StaticFile => Ok(Some(AccessLevel::View)),
// These entity types don't have access checks implemented yet.
EntityType::Team | EntityType::User => Ok(None),
+ // CRM companies are gated by team membership, not entity_access.
+ EntityType::CrmCompany => Ok(None),
}
}
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
index 40f3933f5a..95d329bdcd 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs
@@ -134,12 +134,23 @@ pub async fn get_thread_access(
SELECT EXISTS (
SELECT 1
FROM shared_teams st
- WHERE EXISTS (SELECT 1 FROM participants)
+ -- Require at least one *external* participant (outside the
+ -- requester's own email domain). Internal colleagues don't
+ -- need to be tracked CRM contacts, but a purely-internal
+ -- thread shouldn't grant CRM access either.
+ WHERE EXISTS (
+ SELECT 1
+ FROM participants p
+ WHERE split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)
+ )
AND NOT EXISTS (
- -- A participant with no qualifying contact in this team.
+ -- An external participant with no qualifying contact in
+ -- this team. Participants on the requester's own domain
+ -- are skipped (they're internal, not CRM contacts).
SELECT 1
FROM participants p
- WHERE NOT EXISTS (
+ WHERE split_part(p.email, '@', 2) <> split_part(LOWER($2), '@', 2)
+ AND NOT EXISTS (
SELECT 1
FROM crm_contacts ct
JOIN crm_companies c ON c.id = ct.company_id
diff --git a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs
index 938d146dc1..eee7f57929 100644
--- a/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs
+++ b/rust/cloud-storage/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs
@@ -714,3 +714,57 @@ async fn denies_when_unsynced_participant_in_a_later_message(pool: PgPool) -> an
assert_eq!(access_as_requester(&pool, &thread_id).await, None);
Ok(())
}
+
+// ---------------------------------------------------------------------------
+// Requester's own domain is exempt from the CRM-contact requirement
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn grants_when_only_unsynced_participant_is_on_requesters_domain(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // A colleague on the requester's own domain (corp.test) is a participant but
+ // has no CRM contact. Internal addresses are exempt, so the external
+ // participant (alice) being synced is enough to grant.
+ let team_id = setup_shared_team(&pool, true).await;
+ let thread_id = create_thread(
+ &pool,
+ OWNER,
+ &[("[email protected]", "TO")],
+ )
+ .await;
+
+ let company = insert_crm_company(&pool, team_id, true, false).await;
+ insert_crm_contact(&pool, company, "[email protected]", false).await;
+ // [email protected] intentionally has no CRM contact.
+
+ assert_eq!(
+ access_as_requester(&pool, &thread_id).await,
+ Some(AccessLevel::Comment)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn denies_when_every_participant_is_on_requesters_domain(pool: PgPool) -> anyhow::Result<()> {
+ // Purely-internal thread: all participants share the requester's domain, so
+ // there's no external participant to anchor CRM access. Deny even though the
+ // internal addresses would be exempt from the contact check.
+ let team_id = setup_shared_team(&pool, true).await;
+ let thread_id = create_thread(
+ &pool,
+ OWNER,
+ &[("[email protected]", "TO")],
+ )
+ .await;
+
+ // Even with a qualifying contact for an internal address, the absence of any
+ // external participant must deny.
+ let company = insert_crm_company(&pool, team_id, true, false).await;
+ insert_crm_contact(&pool, company, "[email protected]", false).await;
+
+ assert_eq!(access_as_requester(&pool, &thread_id).await, None);
+ Ok(())
+}
diff --git a/rust/cloud-storage/entity_access_db_utils/src/lib.rs b/rust/cloud-storage/entity_access_db_utils/src/lib.rs
index dd50071810..24dd57c8eb 100644
--- a/rust/cloud-storage/entity_access_db_utils/src/lib.rs
+++ b/rust/cloud-storage/entity_access_db_utils/src/lib.rs
@@ -224,9 +224,8 @@ pub async fn update_entity_access_channel_share_permissions(
| EntityType::Team
| EntityType::Channel
| EntityType::StaticFile
- | EntityType::ForeignEntity => {
- unreachable!()
- }
+ | EntityType::CrmCompany
+ | EntityType::ForeignEntity => unreachable!(),
EntityType::Project => {
// Get all items in project
let project_items = get_nested_project_entities(transaction, entity_id).await?;
@@ -283,9 +282,8 @@ pub async fn update_entity_access_channel_share_permissions(
| EntityType::Team
| EntityType::Channel
| EntityType::StaticFile
- | EntityType::ForeignEntity => {
- unreachable!()
- }
+ | EntityType::CrmCompany
+ | EntityType::ForeignEntity => unreachable!(),
EntityType::Project => {
// (a) Direct grant on the project itself (granted_from_project_id IS NULL)
let mut qb: QueryBuilder<Postgres> = QueryBuilder::new(
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
index f2d24101d2..4c521c82e4 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
@@ -959,6 +959,7 @@ async fn test_dynamic_filter_document_date_created_at_gt(pool: PgPool) {
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
+ crm_company_filter: None,
foreign_entity_filter: None,
properties_filter: None,
};
@@ -1051,6 +1052,7 @@ async fn test_dynamic_filter_document_date_created_at_lt(pool: PgPool) {
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
+ crm_company_filter: None,
foreign_entity_filter: None,
properties_filter: None,
};
@@ -1139,6 +1141,7 @@ async fn test_dynamic_filter_document_date_updated_at_gt(pool: PgPool) {
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
+ crm_company_filter: None,
foreign_entity_filter: None,
properties_filter: None,
};
@@ -1232,6 +1235,7 @@ async fn test_dynamic_filter_document_date_updated_at_lt(pool: PgPool) {
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
+ crm_company_filter: None,
foreign_entity_filter: None,
properties_filter: None,
};
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 51d5b74cc7..787e3e2849 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -2,12 +2,13 @@
//! This is used to construct a strictly typed ast for the input filters, allowing consumers to have a logical represenation of the required operations
use crate::{
- CallFilters, ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, EntityFilters,
- ForeignEntityFilters, ProjectFilters, PropertyFilter,
+ CallFilters, ChannelFilters, ChatFilters, CrmCompanyFilters, DocumentFilters, EmailFilters,
+ EntityFilters, ForeignEntityFilters, ProjectFilters, PropertyFilter,
ast::{
call::CallLiteral,
channel::{ChannelLiteral, ChannelTypeFilter},
chat::{ChatLiteral, ChatRole},
+ crm_company::CrmCompanyLiteral,
email::EmailLiteral,
foreign_entity::ForeignEntityLiteral,
project::ProjectLiteral,
@@ -27,6 +28,8 @@ pub mod call;
pub mod channel;
/// contains the ast literal value for chat
pub mod chat;
+/// contains the ast literal value for crm companies
+pub mod crm_company;
/// contains the date comparison literal type
pub mod date;
/// contains the ast literal value for documents
@@ -196,6 +199,10 @@ pub struct EntityFilterAst {
#[serde(default, rename = "callf")]
#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub call_filter: LiteralTree<CallLiteral>,
+ /// the filters that should be applied to the crm_company entity
+ #[serde(default, rename = "ccf")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
+ pub crm_company_filter: LiteralTree<CrmCompanyLiteral>,
/// the filters that should be applied to foreign entity records
#[serde(default, rename = "fef")]
#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
@@ -235,6 +242,8 @@ impl EntityFilterAst {
channel_filter: ChannelFilters::expand_ast(entity_filter.channel_filters)?
.map(Arc::new),
call_filter: CallFilters::expand_ast(entity_filter.call_filters)?.map(Arc::new),
+ crm_company_filter: CrmCompanyFilters::expand_ast(entity_filter.crm_company_filters)?
+ .map(Arc::new),
foreign_entity_filter: ForeignEntityFilters::expand_ast(
entity_filter.foreign_entity_filters,
)?
@@ -254,6 +263,7 @@ impl EntityFilterAst {
email_filter: EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
+ crm_company_filter: None,
foreign_entity_filter: None,
properties_filter: None,
}
@@ -269,6 +279,7 @@ impl IsEmpty for EntityFilterAst {
email_filter,
channel_filter,
call_filter,
+ crm_company_filter,
foreign_entity_filter,
properties_filter,
} = self;
@@ -278,6 +289,7 @@ impl IsEmpty for EntityFilterAst {
&& email_filter.is_empty()
&& channel_filter.is_none()
&& call_filter.is_none()
+ && crm_company_filter.is_none()
&& foreign_entity_filter.is_none()
&& properties_filter.is_none()
}
diff --git a/rust/cloud-storage/item_filters/src/ast/crm_company.rs b/rust/cloud-storage/item_filters/src/ast/crm_company.rs
new file mode 100644
index 0000000000..df19e85f6b
--- /dev/null
+++ b/rust/cloud-storage/item_filters/src/ast/crm_company.rs
@@ -0,0 +1,26 @@
+use filter_ast::{ExpandFrame, Expr, TryExpandNode};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::{CrmCompanyFilters, ast::ExpandErr};
+
+/// the literal ast types for a crm company
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub enum CrmCompanyLiteral {
+ /// matches a single crm_company by id
+ #[serde(rename = "id")]
+ Id(Uuid),
+}
+
+impl ExpandFrame<CrmCompanyLiteral> for CrmCompanyFilters {
+ type Err = ExpandErr;
+
+ fn expand_ast(input: Self) -> Result<Option<Expr<CrmCompanyLiteral>>, Self::Err> {
+ let CrmCompanyFilters { company_ids } = input;
+
+ Ok(company_ids
+ .iter()
+ .map(|s| Uuid::parse_str(s))
+ .try_expand(|r| r.map(CrmCompanyLiteral::Id), Expr::or)?)
+ }
+}
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index 5ebb4c5f3e..0203bdee1b 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -458,6 +458,23 @@ impl IsEmpty for PropertyFilter {
}
}
+/// The crm company filters used to narrow which CRM companies appear in soup.
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
+pub struct CrmCompanyFilters {
+ /// CRM company ids to filter by. Examples: ['11111111-...']. Empty to
+ /// include all of the team's visible CRM companies.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub company_ids: Vec<String>,
+}
+
+impl IsEmpty for CrmCompanyFilters {
+ fn is_empty(&self) -> bool {
+ let CrmCompanyFilters { company_ids } = self;
+ company_ids.is_empty()
+ }
+}
+
/// The project filters used to filter down what projects you search over.
#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
@@ -522,6 +539,9 @@ pub struct EntityFilters {
/// the bundled [EmailFilters]
#[serde(default)]
pub email_filters: EmailFilters,
+ /// the bundled [CrmCompanyFilters]
+ #[serde(default)]
+ pub crm_company_filters: CrmCompanyFilters,
/// the bundled [ForeignEntityFilters]
#[serde(default)]
pub foreign_entity_filters: ForeignEntityFilters,
@@ -539,6 +559,7 @@ impl IsEmpty for EntityFilters {
channel_filters,
call_filters,
email_filters,
+ crm_company_filters,
foreign_entity_filters,
property_filters,
} = self;
@@ -548,6 +569,7 @@ impl IsEmpty for EntityFilters {
&& channel_filters.is_empty()
&& call_filters.is_empty()
&& email_filters.is_empty()
+ && crm_company_filters.is_empty()
&& foreign_entity_filters.is_empty()
&& property_filters.iter().all(IsEmpty::is_empty)
}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260527194808_create_crm_comments.sql b/rust/cloud-storage/macro_db_client/migrations/20260527194808_create_crm_comments.sql
new file mode 100644
index 0000000000..5f31671655
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260527194808_create_crm_comments.sql
@@ -0,0 +1,47 @@
+-- CRM comment threads. A thread hangs off exactly one CRM entity (a company
+-- or a contact) and carries one or more comments. Mirrors the document
+-- "Thread"/"Comment" shape closely enough that the frontend reuses the same
+-- assembly/rendering logic, but with uuid PKs and team-scoped CRM parents.
+
+CREATE TABLE IF NOT EXISTS crm_thread (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ -- Exactly one of company_id / contact_id is set (enforced below). Both
+ -- cascade-delete so a thread never outlives its CRM parent (companies and
+ -- contacts are hard-deleted on email-sync disable / hide / depopulate).
+ company_id uuid REFERENCES crm_companies(id) ON DELETE CASCADE,
+ contact_id uuid REFERENCES crm_contacts(id) ON DELETE CASCADE,
+ owner text NOT NULL REFERENCES "User"(id) ON UPDATE CASCADE ON DELETE CASCADE,
+ resolved boolean NOT NULL DEFAULT false,
+ metadata jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ deleted_at timestamptz,
+
+ CONSTRAINT crm_thread_one_parent CHECK (num_nonnulls(company_id, contact_id) = 1)
+);
+
+CREATE TABLE IF NOT EXISTS crm_comment (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ thread_id uuid NOT NULL REFERENCES crm_thread(id) ON DELETE CASCADE,
+ owner text NOT NULL REFERENCES "User"(id) ON UPDATE CASCADE ON DELETE CASCADE,
+ sender text,
+ text text NOT NULL,
+ "order" integer,
+ metadata jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ deleted_at timestamptz
+);
+
+-- Look up a CRM entity's threads (the GET path).
+CREATE INDEX IF NOT EXISTS crm_thread_company_id_idx ON crm_thread (company_id) WHERE company_id IS NOT NULL;
+CREATE INDEX IF NOT EXISTS crm_thread_contact_id_idx ON crm_thread (contact_id) WHERE contact_id IS NOT NULL;
+-- Assemble a thread's comments in order (the nesting step).
+CREATE INDEX IF NOT EXISTS crm_comment_thread_id_created_at_idx ON crm_comment (thread_id, created_at);
+
+-- Reuse the shared CRM updated_at trigger (same one crm_companies uses).
+-- CREATE TRIGGER has no IF NOT EXISTS, so drop-then-create for idempotency.
+DROP TRIGGER IF EXISTS crm_thread_set_updated_at ON crm_thread;
+CREATE TRIGGER crm_thread_set_updated_at BEFORE UPDATE ON crm_thread FOR EACH ROW EXECUTE FUNCTION set_crm_updated_at();
+DROP TRIGGER IF EXISTS crm_comment_set_updated_at ON crm_comment;
+CREATE TRIGGER crm_comment_set_updated_at BEFORE UPDATE ON crm_comment FOR EACH ROW EXECUTE FUNCTION set_crm_updated_at();
diff --git a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs b/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
index b13f11e868..ba43ce9f3e 100644
--- a/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
+++ b/rust/cloud-storage/macro_db_client/src/item_access/delete.rs
@@ -37,6 +37,7 @@ pub async fn delete_user_entity_access_bulk(
| EntityType::Team
| EntityType::Channel
| EntityType::StaticFile
+ | EntityType::CrmCompany
| EntityType::ForeignEntity => {
anyhow::bail!("invalid entity type")
}
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 979e963fa5..729234ad3a 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -190,6 +190,7 @@ async fn build_tool_context(
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
call::domain::ports::NoOpCallRecordQueryService,
+ crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 00c7da9a06..7e9a3f7dc0 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -95,6 +95,7 @@ pub async fn build_tool_service_context(
ReadonlyEmailPreviewAdapter(email_service),
channels_service,
call::domain::ports::NoOpCallRecordQueryService,
+ crm::domain::service::NoOpCrmService,
foreign_entity_service,
));
diff --git a/rust/cloud-storage/model-entity/src/lib.rs b/rust/cloud-storage/model-entity/src/lib.rs
index 4dd1729a57..b1923b65ec 100644
--- a/rust/cloud-storage/model-entity/src/lib.rs
+++ b/rust/cloud-storage/model-entity/src/lib.rs
@@ -52,6 +52,8 @@ pub enum EntityType {
ForeignEntity,
/// A public file in the static file service
StaticFile,
+ /// The entity is a CRM company tracked by a team
+ CrmCompany,
}
impl EntityType {
@@ -71,6 +73,8 @@ impl EntityType {
EntityType::Call => true,
EntityType::ForeignEntity => false,
EntityType::StaticFile => false,
+ // CRM companies are gated by team membership, not entity_access.
+ EntityType::CrmCompany => false,
}
}
/// provide an entity string slice to upgrade this type into an [Entity]
diff --git a/rust/cloud-storage/models_soup/Cargo.toml b/rust/cloud-storage/models_soup/Cargo.toml
index b7d5a38b00..1b5138e89a 100644
--- a/rust/cloud-storage/models_soup/Cargo.toml
+++ b/rust/cloud-storage/models_soup/Cargo.toml
@@ -13,6 +13,7 @@ anyhow = { workspace = true }
call = { path = "../call", default-features = false }
chrono = { workspace = true }
comms = { path = "../comms" }
+crm = { path = "../crm", default-features = false }
document_sub_type = { path = "../document_sub_type" }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
email = { path = "../email" }
diff --git a/rust/cloud-storage/models_soup/src/crm_company.rs b/rust/cloud-storage/models_soup/src/crm_company.rs
new file mode 100644
index 0000000000..b46daba53f
--- /dev/null
+++ b/rust/cloud-storage/models_soup/src/crm_company.rs
@@ -0,0 +1,86 @@
+use chrono::{DateTime, Utc};
+use crm::domain::model::{CrmCompanyForSoup, CrmDomain};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// A CRM domain as displayed in Soup. Mirrors the crm crate's
+/// [`CrmDomain`] with a stable wire shape that the FE can rely on.
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct SoupCrmDomain {
+ /// The id of the domain record.
+ pub id: Uuid,
+ /// The id of the company the domain belongs to.
+ pub company_id: Uuid,
+ /// The domain (lowercased, e.g. "acme.com").
+ pub domain: String,
+ /// When the domain record was created.
+ pub created_at: DateTime<Utc>,
+}
+
+impl From<CrmDomain> for SoupCrmDomain {
+ fn from(d: CrmDomain) -> Self {
+ SoupCrmDomain {
+ id: d.id,
+ company_id: d.company_id,
+ domain: d.domain,
+ created_at: d.created_at,
+ }
+ }
+}
+
+/// A CRM company as displayed in Soup. Carries the core company
+/// fields plus display metadata resolved from `crm_domain_directory`
+/// against the primary (earliest-created) domain.
+#[derive(Debug, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct SoupCrmCompany {
+ /// The id of the company.
+ pub id: Uuid,
+ /// The id of the team that owns this company record.
+ pub team_id: Uuid,
+ /// Display name from the primary domain's directory entry, or
+ /// `None` when unresolved.
+ pub name: Option<String>,
+ /// Display description from the primary domain's directory entry.
+ pub description: Option<String>,
+ /// Whether email sync is enabled for this company.
+ pub email_sync: bool,
+ /// Whether the company is hidden from CRM listings. Soup filters
+ /// these out by default.
+ pub hidden: bool,
+ /// When the company was created.
+ pub created_at: DateTime<Utc>,
+ /// When the company was last updated.
+ pub updated_at: DateTime<Utc>,
+ /// Domains associated with this company, ordered by creation time
+ /// ascending (primary first).
+ pub domains: Vec<SoupCrmDomain>,
+}
+
+impl From<CrmCompanyForSoup> for SoupCrmCompany {
+ fn from(c: CrmCompanyForSoup) -> Self {
+ let CrmCompanyForSoup {
+ company,
+ name,
+ description,
+ } = c;
+ SoupCrmCompany {
+ id: company.id,
+ team_id: company.team_id,
+ name,
+ description,
+ email_sync: company.email_sync,
+ hidden: company.hidden,
+ created_at: company.created_at,
+ updated_at: company.updated_at,
+ domains: company
+ .domains
+ .into_iter()
+ .map(SoupCrmDomain::from)
+ .collect(),
+ }
+ }
+}
diff --git a/rust/cloud-storage/models_soup/src/item.rs b/rust/cloud-storage/models_soup/src/item.rs
index 85867cd435..1ac21e990b 100644
--- a/rust/cloud-storage/models_soup/src/item.rs
+++ b/rust/cloud-storage/models_soup/src/item.rs
@@ -1,4 +1,5 @@
use crate::call_record::SoupCallRecord;
+use crate::crm_company::SoupCrmCompany;
use crate::document::SoupDocument;
use crate::email_thread::SoupEnrichedEmailThreadPreview;
use crate::foreign_entity::SoupForeignEntity;
@@ -21,6 +22,7 @@ pub enum SoupItem {
EmailThread(SoupEnrichedEmailThreadPreview),
Channel(SoupChannel),
Call(SoupCallRecord),
+ CrmCompany(SoupCrmCompany),
ForeignEntity(SoupForeignEntity),
}
@@ -46,6 +48,9 @@ impl SoupItem {
SoupItem::Call(record) => {
EntityType::Call.with_entity_string(record.call_id.to_string())
}
+ SoupItem::CrmCompany(company) => {
+ EntityType::CrmCompany.with_entity_string(company.id.to_string())
+ }
SoupItem::ForeignEntity(foreign_entity) => {
EntityType::ForeignEntity.with_entity_string(foreign_entity.id.to_string())
}
@@ -60,6 +65,7 @@ impl SoupItem {
SoupItem::EmailThread(soup_thread) => soup_thread.thread.updated_at,
SoupItem::Channel(soup_channel) => soup_channel.channel.channel.updated_at,
SoupItem::Call(record) => record.ended_at.unwrap_or(record.started_at),
+ SoupItem::CrmCompany(company) => company.updated_at,
SoupItem::ForeignEntity(foreign_entity) => foreign_entity.updated_at,
}
}
@@ -120,6 +126,9 @@ impl SoupItem {
.unwrap_or(soup_channel.channel.channel.updated_at),
(SoupItem::Call(record), SimpleSortMethod::CreatedAt) => record.started_at,
(SoupItem::Call(record), _) => record.ended_at.unwrap_or(record.started_at),
+ // No viewed_at signal for CrmCompany yet — fall back to updated_at.
+ (SoupItem::CrmCompany(company), SimpleSortMethod::CreatedAt) => company.created_at,
+ (SoupItem::CrmCompany(company), _) => company.updated_at,
(SoupItem::ForeignEntity(foreign_entity), SimpleSortMethod::CreatedAt) => {
foreign_entity.created_at
}
@@ -139,6 +148,7 @@ impl Identify for SoupItem {
SoupItem::EmailThread(thread) => thread.thread.id,
SoupItem::Channel(soup_channel) => soup_channel.channel.channel.id.0,
SoupItem::Call(record) => record.call_id,
+ SoupItem::CrmCompany(company) => company.id,
SoupItem::ForeignEntity(foreign_entity) => foreign_entity.id,
}
}
@@ -182,6 +192,8 @@ impl SoupItem {
)),
SoupItem::Channel(_) => None,
SoupItem::Call(_) => None,
+ // CRM companies are not in entity_properties.
+ SoupItem::CrmCompany(_) => None,
SoupItem::ForeignEntity(_) => None,
}
}
diff --git a/rust/cloud-storage/models_soup/src/lib.rs b/rust/cloud-storage/models_soup/src/lib.rs
index 121c5d5b25..2d7812d998 100644
--- a/rust/cloud-storage/models_soup/src/lib.rs
+++ b/rust/cloud-storage/models_soup/src/lib.rs
@@ -1,6 +1,7 @@
pub mod call_record;
pub mod chat;
pub mod comms;
+pub mod crm_company;
pub mod document;
pub mod email_thread;
pub mod foreign_entity;
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index eebe04ee12..7475037d72 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -32,7 +32,7 @@ axum = [
]
inbound = ["email/inbound", "entity_access/inbound", "ports"]
outbound = ["crm/outbound", "dep:readonly_pool", "dep:sqlx", "ports"]
-ports = ["dep:tokio", "frecency/ports"]
+ports = ["crm/ports", "dep:tokio", "frecency/ports"]
[dependencies]
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 66035928cc..3513032539 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -7,8 +7,10 @@ pub use grouping::{
use call::domain::models::GetCallRecordsRequest;
use comms::domain::models::GetChannelsRequest;
+use crm::domain::companies_repo::CrmCompanyListSort;
use email::domain::models::{GetEmailsRequest, PreviewView};
use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};
+use filter_ast::Expr;
use foreign_entity::domain::{
models::{ForeignEntityError, SourceId},
ports::ForeignEntityListQuery,
@@ -16,7 +18,7 @@ use foreign_entity::domain::{
use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};
use item_filters::{
EntityFilters,
- ast::{EntityFilterAst, ExpandErr},
+ ast::{EntityFilterAst, ExpandErr, crm_company::CrmCompanyLiteral},
};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
@@ -349,6 +351,61 @@ impl SoupRequest<Option<EntityFilterAst>> {
})
}
+ /// Returns `None` (skipping the CRM sub-request) for no-team users,
+ /// Frecency cursors, or a malformed team-receipt uuid.
+ pub(crate) fn build_crm_company_request(
+ &self,
+ team_receipt: &Option<EntityAccessReceipt<MemberTeamRole>>,
+ ) -> Option<GetCrmCompaniesRequest> {
+ let receipt = team_receipt.as_ref()?;
+ let team_id = Uuid::parse_str(&receipt.entity().entity_id)
+ .inspect_err(|e| {
+ tracing::warn!(
+ error=?e,
+ "team_receipt entity_id is not a valid uuid; skipping crm_company sub-request"
+ );
+ })
+ .ok()?;
+
+ let (sort_method, filter_ast): (SimpleSortMethod, Option<&EntityFilterAst>) =
+ match &self.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(t, f))) => (*t, f.as_ref()),
+ SoupQuery::Simple(SimpleQueryInner(Query::Cursor(CursorWithValAndFilter {
+ val,
+ filter,
+ ..
+ }))) => (val.sort_type, filter.as_ref()),
+ SoupQuery::Frecency(_) => return None,
+ };
+
+ // No viewed_at signal for crm_company yet — ViewedAt/ViewedUpdated
+ // fall back to updated_at.
+ let sort = match sort_method {
+ SimpleSortMethod::CreatedAt => CrmCompanyListSort::CreatedAt,
+ SimpleSortMethod::UpdatedAt
+ | SimpleSortMethod::ViewedAt
+ | SimpleSortMethod::ViewedUpdated => CrmCompanyListSort::UpdatedAt,
+ };
+
+ let mut company_ids = Vec::new();
+ if let Some(tree) = filter_ast.and_then(|a| a.crm_company_filter.as_ref())
+ && !collect_crm_company_ids(tree, &mut company_ids)
+ {
+ // Fail closed: unsupported AST shape would widen the result
+ // set. Skip the CRM sub-request rather than over-include.
+ return None;
+ }
+
+ Some(GetCrmCompaniesRequest {
+ team_id,
+ company_ids,
+ sort,
+ // Match the soup paginator's bounds so the CRM layer doesn't
+ // overfetch on an oversized client limit.
+ limit: self.limit.clamp(20, 500) as i64,
+ })
+ }
+
pub(crate) fn build_comms_request(&self) -> Option<GetChannelsRequest> {
Some(GetChannelsRequest {
macro_id: self.user.clone(),
@@ -414,6 +471,36 @@ impl SoupRequest<Option<EntityFilterAst>> {
}
}
+/// Parameters for fetching CRM companies to fold into the soup feed.
+#[derive(Debug)]
+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).
+ pub company_ids: Vec<Uuid>,
+ /// Which timestamp column to sort by.
+ pub sort: CrmCompanyListSort,
+ /// Upper bound on rows returned — the soup paginator re-slices.
+ 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 {
+ 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);
+ true
+ }
+ Expr::And(_, _) | Expr::Not(_) => false,
+ }
+}
+
/// a [SoupItem] with an associated frecency score
#[derive(Debug)]
#[non_exhaustive]
@@ -492,6 +579,8 @@ pub enum SoupErr {
CommsErr,
#[error("A call error has occurred, see logs for more details")]
CallErr,
+ #[error("A CRM error has occurred, see logs for more details")]
+ CrmErr,
#[error(transparent)]
ForeignEntityErr(#[from] ForeignEntityError),
#[error(transparent)]
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 5b3bd03531..d437be846a 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -1,14 +1,15 @@
use crate::domain::{
models::{
- AdvancedSortParams, FrecencyQueryInner, FrecencySoupItem, GroupedSortRequest,
- GroupedSoupItem, IntoSoupReqAst, SimpleQueryInner, SimpleSortQuery, SimpleSortRequest,
- SoupErr, SoupQuery, SoupRequest, SoupType,
+ AdvancedSortParams, FrecencyQueryInner, FrecencySoupItem, GetCrmCompaniesRequest,
+ GroupedSortRequest, GroupedSoupItem, IntoSoupReqAst, SimpleQueryInner, SimpleSortQuery,
+ SimpleSortRequest, SoupErr, SoupQuery, SoupRequest, SoupType,
},
ports::{SoupOutput, SoupRepo, SoupService},
};
use call::domain::{models::GetCallRecordsRequest, ports::CallRecordQueryService};
use comms::domain::{models::GetChannelsRequest, ports::ChannelsService};
use cowlike::CowLike;
+use crm::domain::service::CrmService;
use doppleganger::Mirror;
use either::Either;
use email::domain::{
@@ -32,6 +33,7 @@ use models_pagination::{
use models_soup::{
call_record::SoupCallRecord,
comms::SoupChannel,
+ crm_company::SoupCrmCompany,
email_thread::{
SoupAttachment, SoupContact, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreview,
SoupLabel,
@@ -60,7 +62,7 @@ fn foreign_entity_to_soup_item(entity: ForeignEntity) -> SoupItem {
}
/// struct which handles the actual implementation of soup with abstracted interfaces for mocking
-pub struct SoupImpl<T, U, V, C, K, F> {
+pub struct SoupImpl<T, U, V, C, K, Crm, F> {
/// the interface for interacting with the db
soup_storage: T,
/// the interface for interacting with frecency
@@ -71,11 +73,13 @@ pub struct SoupImpl<T, U, V, C, K, F> {
comms_service: C,
/// the interface for interacting with call records
call_record_service: K,
+ /// the interface for interacting with CRM (companies)
+ crm_service: Crm,
/// the interface for interacting with foreign entities
foreign_entity_service: F,
}
-impl<T, U, V, C, K, F> SoupImpl<T, U, V, C, K, F>
+impl<T, U, V, C, K, Crm, F> SoupImpl<T, U, V, C, K, Crm, F>
where
T: SoupRepo,
anyhow::Error: From<T::Err>,
@@ -83,6 +87,7 @@ where
V: EmailPreviewServiceReadOnly,
C: ChannelsService,
K: CallRecordQueryService,
+ Crm: CrmService,
F: ForeignEntityService,
{
pub fn new(
@@ -91,6 +96,7 @@ where
email_service: V,
comms_service: C,
call_record_service: K,
+ crm_service: Crm,
foreign_entity_service: F,
) -> Self {
SoupImpl {
@@ -99,6 +105,7 @@ where
email_service,
comms_service,
call_record_service,
+ crm_service,
foreign_entity_service,
}
}
@@ -392,6 +399,35 @@ where
))
}
+ #[tracing::instrument(err, skip(self, req))]
+ async fn handle_crm_company_request(
+ &self,
+ req: Option<GetCrmCompaniesRequest>,
+ ) -> Result<impl Iterator<Item = FrecencySoupItem>, SoupErr> {
+ let Some(req) = req else {
+ return Ok(Either::Left(None.into_iter()));
+ };
+
+ let GetCrmCompaniesRequest {
+ team_id,
+ company_ids,
+ sort,
+ limit,
+ } = req;
+
+ Ok(Either::Right(
+ self.crm_service
+ .list_companies_for_soup(&team_id, &company_ids, sort, limit)
+ .await
+ .map_err(|_| SoupErr::CrmErr)?
+ .into_iter()
+ .map(|company| FrecencySoupItem {
+ item: SoupItem::CrmCompany(SoupCrmCompany::from(company)),
+ frecency_score: None,
+ }),
+ ))
+ }
+
#[tracing::instrument(err, skip(self, req))]
async fn handle_call_request(
&self,
@@ -444,7 +480,7 @@ where
}
}
-impl<T, U, V, C, K, F> SoupService for SoupImpl<T, U, V, C, K, F>
+impl<T, U, V, C, K, Crm, F> SoupService for SoupImpl<T, U, V, C, K, Crm, F>
where
T: SoupRepo,
anyhow::Error: From<T::Err>,
@@ -452,6 +488,7 @@ where
V: EmailPreviewServiceReadOnly,
C: ChannelsService,
K: CallRecordQueryService,
+ Crm: CrmService,
F: ForeignEntityService,
{
#[tracing::instrument(err, skip(self, req, team_receipt))]
@@ -468,6 +505,8 @@ where
let req = req.into_ast()?;
let limit = req.limit.clamp(20, 500);
+ // Borrow before email's builder consumes team_receipt.
+ let crm_company_request = req.build_crm_company_request(&team_receipt);
let foreign_entity_source_ids = req.build_foreign_entity_source_ids(team_receipt.as_ref());
let foreign_entity_query = req.build_foreign_entity_query();
let email_request = req.build_email_request(team_receipt);
@@ -493,17 +532,27 @@ where
let call_soup_fut = self.handle_call_request(call_request);
+ let crm_company_soup_fut = self.handle_crm_company_request(crm_company_request);
+
let foreign_entity_soup_fut = self.handle_foreign_entity_request(
foreign_entity_source_ids,
limit as u32,
foreign_entity_query,
);
- let (main_soup, email_soup, comms_soup, call_soup, foreign_entity_soup) = tokio::join!(
+ let (
+ main_soup,
+ email_soup,
+ comms_soup,
+ call_soup,
+ crm_company_soup,
+ foreign_entity_soup,
+ ) = tokio::join!(
main_soup_fut,
email_soup_fut,
comms_soup_fut,
call_soup_fut,
+ crm_company_soup_fut,
foreign_entity_soup_fut,
);
@@ -511,6 +560,7 @@ where
.chain(email_soup?)
.chain(comms_soup?)
.chain(call_soup?)
+ .chain(crm_company_soup?)
.chain(foreign_entity_soup?)
.paginate_on(limit.into(), sort_method)
.filter_on(entity_filter.clone())
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index c557f00980..2e95f66b3c 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -85,6 +85,8 @@ impl CallRecordQueryService for NoopCallRecordQueryService {
}
}
+use crm::domain::service::NoOpCrmService;
+
#[derive(Clone)]
struct NoopForeignEntityService;
@@ -394,6 +396,7 @@ async fn simple_soup_includes_foreign_entities() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
foreign_entity_service.clone(),
)
.get_user_soup(
@@ -474,6 +477,7 @@ async fn frecency_soup_does_not_query_foreign_entities() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
foreign_entity_service.clone(),
)
.get_user_soup(
@@ -519,6 +523,7 @@ async fn team_receipt_contributes_team_foreign_entity_source_id() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
foreign_entity_service.clone(),
)
.get_user_soup(
@@ -574,6 +579,7 @@ async fn foreign_entity_filter_suppresses_non_matching_foreign_entities() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
foreign_entity_service.clone(),
)
.get_user_soup(
@@ -646,6 +652,7 @@ async fn it_should_not_query_frecency() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -732,6 +739,7 @@ async fn it_should_query_frecency() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -815,6 +823,7 @@ async fn it_should_sort_frecency_descending() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -912,6 +921,7 @@ async fn frecency_should_fallback() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -993,6 +1003,7 @@ async fn frecency_should_paginate() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1076,6 +1087,7 @@ async fn frecency_should_resume_cursor() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1175,6 +1187,7 @@ async fn frecency_fallback_cursor_should_resume() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1250,6 +1263,7 @@ async fn cursor_should_return_simple_sort() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1321,6 +1335,7 @@ async fn cursor_should_return_frecency() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1382,6 +1397,7 @@ async fn it_should_return_is_completed_true_for_completed_tasks() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1433,6 +1449,7 @@ async fn it_should_return_is_completed_false_for_incomplete_tasks() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1484,6 +1501,7 @@ async fn it_should_return_is_completed_none_for_non_tasks() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1547,6 +1565,7 @@ async fn it_should_preserve_is_completed_for_mixed_items() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
@@ -1629,6 +1648,7 @@ async fn it_should_preserve_is_completed_in_by_ids_queries() {
NoopEmailPreviewService,
NoopCommsService,
NoopCallRecordQueryService,
+ NoOpCrmService,
NoopForeignEntityService,
)
.get_user_soup(
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index 887ba6362d..9a8eb8960d 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -38,6 +38,7 @@ use item_filters::{
call::CallLiteral,
channel::ChannelLiteral,
chat::ChatLiteral,
+ crm_company::CrmCompanyLiteral,
document::DocumentLiteral,
email::EmailLiteral,
foreign_entity::ForeignEntityLiteral,
@@ -851,6 +852,11 @@ pub struct ApiEntityFilterAst {
#[serde(default, rename = "callf")]
#[schema(value_type = serde_json::Value)]
pub call_filter: LiteralTree<CallLiteral>,
+ /// Filters applied to the crm_company entity (wire key `ccf`).
+ /// Empty/omitted = team's full visible list.
+ #[serde(default, rename = "ccf")]
+ #[schema(value_type = serde_json::Value)]
+ pub crm_company_filter: LiteralTree<CrmCompanyLiteral>,
/// the filters that should be applied based on entity properties
#[serde(default, rename = "propf")]
#[schema(value_type = serde_json::Value)]
@@ -933,6 +939,7 @@ impl ApiEntityFilterAst {
channel_filter,
foreign_entity_filter,
call_filter,
+ crm_company_filter,
properties_filter,
email_crm_domains,
email_crm_addresses,
@@ -997,6 +1004,7 @@ impl ApiEntityFilterAst {
},
channel_filter,
call_filter,
+ crm_company_filter,
foreign_entity_filter,
properties_filter,
})
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
index 2690cbde22..bc3ace6dd8 100644
--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
@@ -12,8 +12,8 @@ use item_filters::{
SharedEmailFilter,
ast::{
EntityFilterAst, LiteralTree, call::CallLiteral, channel::ChannelLiteral,
- chat::ChatLiteral, document::DocumentLiteral, email::EmailLiteral,
- foreign_entity::ForeignEntityLiteral, project::ProjectLiteral,
+ chat::ChatLiteral, crm_company::CrmCompanyLiteral, document::DocumentLiteral,
+ email::EmailLiteral, foreign_entity::ForeignEntityLiteral, project::ProjectLiteral,
properties::PropertiesLiteral,
},
};
@@ -131,6 +131,11 @@ impl From<SoupItem> for EntityItem {
id: record.call_id,
created_by: record.created_by,
},
+ // `entity_filter_ast` force-filters CrmCompany out — kept
+ // loud here so a contract break is obvious, not silent.
+ SoupItem::CrmCompany(_) => {
+ unreachable!("ListEntities tool does not surface CrmCompany rows")
+ }
SoupItem::ForeignEntity(foreign_entity) => EntityItem::ForeignEntity {
id: foreign_entity.id,
foreign_entity_id: foreign_entity.foreign_entity_id,
@@ -262,6 +267,9 @@ impl ListEntities {
},
channel_filter: self.channel_filter.clone(),
call_filter: self.call_filter.clone(),
+ // CrmCompany not in the tool surface — force-filter so the
+ // AI never sees one.
+ crm_company_filter: Some(Arc::new(Expr::val(CrmCompanyLiteral::Id(Uuid::nil())))),
foreign_entity_filter: self.foreign_entity_filter.clone(),
properties_filter: self.properties_filter.clone(),
};
@@ -311,6 +319,9 @@ impl ListEntities {
} else {
Some(Arc::new(Expr::val(CallLiteral::CallId(Uuid::nil()))))
},
+ // Preserve the upstream nil filter — no ItemType::CrmCompany
+ // to toggle against.
+ crm_company_filter: ast.crm_company_filter,
foreign_entity_filter: if include_types.contains(&ItemType::ForeignEntity) {
ast.foreign_entity_filter
} else {
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
index 5e7c78d416..862cda3ff0 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
@@ -198,7 +198,11 @@ pub(crate) async fn populate_properties(
SoupItem::Project(x) => properties_map.get(&x.id.to_string()),
SoupItem::EmailThread(x) => properties_map.get(&x.thread.id.to_string()),
SoupItem::Chat(x) => properties_map.get(&x.id.to_string()),
- SoupItem::Channel(_) | SoupItem::Call(_) | SoupItem::ForeignEntity(_) => None,
+ // Channels, calls, CRM companies, and foreign entities are not in entity_properties.
+ SoupItem::Channel(_)
+ | SoupItem::Call(_)
+ | SoupItem::CrmCompany(_)
+ | SoupItem::ForeignEntity(_) => None,
};
if let Some(props) = props {
let soup_props: Vec<SoupProperty> =
@@ -208,7 +212,10 @@ pub(crate) async fn populate_properties(
SoupItem::Project(x) => x.properties = soup_props,
SoupItem::EmailThread(x) => x.properties = soup_props,
SoupItem::Chat(x) => x.properties = soup_props,
- SoupItem::Channel(_) | SoupItem::Call(_) | SoupItem::ForeignEntity(_) => {}
+ SoupItem::Channel(_)
+ | SoupItem::Call(_)
+ | SoupItem::CrmCompany(_)
+ | SoupItem::ForeignEntity(_) => {}
}
}
}
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index e80d6198bf..af019a0917 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -366,6 +366,7 @@ async fn test_expanded_soup_by_ids(pool: Pool<Postgres>) {
| SoupItem::EmailThread(_)
| SoupItem::Channel(_)
| SoupItem::Call(_)
+ | SoupItem::CrmCompany(_)
| SoupItem::ForeignEntity(_) => None,
})
.expect("The document should exist");
@@ -5455,6 +5456,7 @@ fn mock_empty_ast() -> EntityFilterAst {
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
call_filter: None,
+ crm_company_filter: None,
foreign_entity_filter: None,
properties_filter: None,
}
diff --git a/rust/sync-service/Cargo.lock b/rust/sync-service/Cargo.lock
index f98b4be7a9..83557a9d9d 100644
--- a/rust/sync-service/Cargo.lock
+++ b/rust/sync-service/Cargo.lock
@@ -909,9 +909,9 @@ checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "js-sys"
-version = "0.3.95"
+version = "0.3.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"
+checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11"
dependencies = [
"cfg-if",
"futures-util",
@@ -2260,9 +2260,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
-version = "0.2.118"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"
+checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409"
dependencies = [
"cfg-if",
"once_cell",
@@ -2273,9 +2273,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
-version = "0.4.68"
+version = "0.4.72"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8"
+checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -2283,9 +2283,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.118"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"
+checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -2293,9 +2293,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.118"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"
+checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e"
dependencies = [
"bumpalo",
"proc-macro2",
@@ -2306,9 +2306,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.118"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"
+checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437"
dependencies = [
"unicode-ident",
]
@@ -2328,9 +2328,9 @@ dependencies = [
[[package]]
name = "web-sys"
-version = "0.3.95"
+version = "0.3.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d"
+checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436"
dependencies = [
"js-sys",
"wasm-bindgen",