Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(crm): serve crm comment routes from the message store and import legacy comments (#7025)
gbirman172c2228c6fa
diff --git a/.sqlx/query-1135a9b12335dbcf6feaa871d478efff6395e63361552cceca5ca30c9faf3f2d.json b/.sqlx/query-1135a9b12335dbcf6feaa871d478efff6395e63361552cceca5ca30c9faf3f2d.jsonnew file mode 100644index 0000000000..ca67d44f61--- /dev/null+++ b/.sqlx/query-1135a9b12335dbcf6feaa871d478efff6395e63361552cceca5ca30c9faf3f2d.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_messages (\n id, parent_entity_type, parent_entity_id, thread_id, sender_id, content,\n created_at, updated_at, edited_at, deleted_at, import_metadata\n )\n SELECT c.id,\n CASE WHEN t.contact_id IS NULL THEN 'crm_company' ELSE 'crm_contact' END,\n COALESCE(t.contact_id, t.company_id)::text,\n NULLIF(first_value(c.id) OVER (PARTITION BY c.thread_id ORDER BY c.created_at, c.id), c.id),\n c.owner, c.text, c.created_at, c.updated_at,\n CASE WHEN c.updated_at > c.created_at THEN c.updated_at AT TIME ZONE 'UTC' END,\n COALESCE(c.deleted_at, t.deleted_at) AT TIME ZONE 'UTC',\n jsonb_build_object('source', 'crm_comment', 'legacy_thread_id', c.thread_id)\n FROM crm_comment c\n JOIN crm_thread t ON t.id = c.thread_id\n ON CONFLICT (id) DO UPDATE SET\n content = EXCLUDED.content,\n updated_at = EXCLUDED.updated_at,\n edited_at = EXCLUDED.edited_at,\n deleted_at = EXCLUDED.deleted_at\n WHERE comms_messages.import_metadata->>'source' = 'crm_comment'\n AND comms_messages.updated_at <= EXCLUDED.updated_at\n AND (comms_messages.content, comms_messages.updated_at, comms_messages.edited_at,\n comms_messages.deleted_at)\n IS DISTINCT FROM\n (EXCLUDED.content, EXCLUDED.updated_at, EXCLUDED.edited_at, EXCLUDED.deleted_at)\n RETURNING (xmax = 0) AS \"inserted!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "inserted!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "1135a9b12335dbcf6feaa871d478efff6395e63361552cceca5ca30c9faf3f2d"+}diff --git a/.sqlx/query-165b5f553dcfe46dfc36a49121d1cfb90f6124b44dbdace772e4d606ffa4fb60.json b/.sqlx/query-165b5f553dcfe46dfc36a49121d1cfb90f6124b44dbdace772e4d606ffa4fb60.jsonnew file mode 100644index 0000000000..399f5ff10f--- /dev/null+++ b/.sqlx/query-165b5f553dcfe46dfc36a49121d1cfb90f6124b44dbdace772e4d606ffa4fb60.json@@ -0,0 +1,56 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT\n (SELECT count(*) FROM crm_thread WHERE metadata IS NOT NULL)\n + (SELECT count(*) FROM crm_comment WHERE metadata IS NOT NULL) AS \"metadata!\",\n (SELECT count(*) FROM crm_comment WHERE sender IS NOT NULL AND sender <> owner) AS \"foreign_senders!\",\n (SELECT count(*) FROM crm_comment WHERE \"order\" IS NOT NULL) AS \"explicit_order!\",\n (SELECT count(*) FROM crm_comment c JOIN comms_messages m ON m.id = c.id\n WHERE m.import_metadata->>'source' IS DISTINCT FROM 'crm_comment') AS \"id_collisions!\",\n (SELECT count(*) FROM crm_comment c\n WHERE NOT EXISTS (SELECT 1 FROM comms_messages m WHERE m.id = c.id)) AS \"pending_comments!\",\n (SELECT count(*) FROM crm_comment c\n JOIN crm_thread t ON t.id = c.thread_id\n JOIN comms_messages m ON m.id = c.id\n WHERE m.import_metadata->>'source' = 'crm_comment'\n AND m.updated_at <= c.updated_at\n AND (m.content, m.updated_at, m.deleted_at)\n IS DISTINCT FROM\n (c.text, c.updated_at, COALESCE(c.deleted_at, t.deleted_at) AT TIME ZONE 'UTC')) AS \"stale_comments!\",\n (SELECT count(*) FROM crm_thread t\n WHERE NOT EXISTS (SELECT 1 FROM crm_comment c WHERE c.thread_id = t.id)) AS \"empty_threads!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "metadata!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "foreign_senders!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "explicit_order!",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "id_collisions!",+ "type_info": "Int8"+ },+ {+ "ordinal": 4,+ "name": "pending_comments!",+ "type_info": "Int8"+ },+ {+ "ordinal": 5,+ "name": "stale_comments!",+ "type_info": "Int8"+ },+ {+ "ordinal": 6,+ "name": "empty_threads!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null,+ null,+ null,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "165b5f553dcfe46dfc36a49121d1cfb90f6124b44dbdace772e4d606ffa4fb60"+}diff --git a/.sqlx/query-370764911f1740f87020c23f75698124a953a3ee175b20eafbb522bf7cf8d1bf.json b/.sqlx/query-370764911f1740f87020c23f75698124a953a3ee175b20eafbb522bf7cf8d1bf.jsonnew file mode 100644index 0000000000..d24dbdcc50--- /dev/null+++ b/.sqlx/query-370764911f1740f87020c23f75698124a953a3ee175b20eafbb522bf7cf8d1bf.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT pg_try_advisory_xact_lock($1) AS \"acquired!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "acquired!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Int8"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "370764911f1740f87020c23f75698124a953a3ee175b20eafbb522bf7cf8d1bf"+}diff --git a/.sqlx/query-4a4b8aa2e73460d5d6d5b0842f5c22a351d68ed22a1f166712a9942b4b9612a3.json b/.sqlx/query-4a4b8aa2e73460d5d6d5b0842f5c22a351d68ed22a1f166712a9942b4b9612a3.jsonnew file mode 100644index 0000000000..3b4c977cc5--- /dev/null+++ b/.sqlx/query-4a4b8aa2e73460d5d6d5b0842f5c22a351d68ed22a1f166712a9942b4b9612a3.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT parent_entity_type, parent_entity_id FROM comms_messages\n WHERE id = $1 AND deleted_at IS NULL",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "parent_entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "parent_entity_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "4a4b8aa2e73460d5d6d5b0842f5c22a351d68ed22a1f166712a9942b4b9612a3"+}diff --git a/.sqlx/query-5129cecb18a6c6df1164cd462b24b27d8edef4a122d47c5e014494cd32853cae.json b/.sqlx/query-5129cecb18a6c6df1164cd462b24b27d8edef4a122d47c5e014494cd32853cae.jsonnew file mode 100644index 0000000000..e2e00e75b8--- /dev/null+++ b/.sqlx/query-5129cecb18a6c6df1164cd462b24b27d8edef4a122d47c5e014494cd32853cae.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT c.id\n FROM crm_comment c\n JOIN crm_thread t ON t.id = c.thread_id\n WHERE t.id = $1\n AND (t.company_id = $2 OR t.contact_id = $2)\n ORDER BY c.created_at ASC, c.id ASC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "5129cecb18a6c6df1164cd462b24b27d8edef4a122d47c5e014494cd32853cae"+}diff --git a/.sqlx/query-5e56844164b2f53aab67022cb6141c25b3c78d4e19eef674cfef968816559980.json b/.sqlx/query-5e56844164b2f53aab67022cb6141c25b3c78d4e19eef674cfef968816559980.jsonnew file mode 100644index 0000000000..cf3ce2e710--- /dev/null+++ b/.sqlx/query-5e56844164b2f53aab67022cb6141c25b3c78d4e19eef674cfef968816559980.json@@ -0,0 +1,38 @@+{+ "db_name": "PostgreSQL",+ "query": "WITH legacy AS (\n SELECT c.id, c.text, c.owner, c.created_at, c.updated_at,\n COALESCE(c.deleted_at, t.deleted_at) AT TIME ZONE 'UTC' AS deleted_at,\n CASE WHEN t.contact_id IS NULL THEN 'crm_company' ELSE 'crm_contact' END AS parent_type,\n COALESCE(t.contact_id, t.company_id)::text AS parent_id,\n NULLIF(first_value(c.id) OVER (PARTITION BY c.thread_id ORDER BY c.created_at, c.id), c.id) AS root_id\n FROM crm_comment c\n JOIN crm_thread t ON t.id = c.thread_id\n )\n SELECT\n count(*) FILTER (WHERE m.id IS NULL) AS \"missing_messages!\",\n count(*) FILTER (\n WHERE m.id IS NOT NULL\n AND (m.parent_entity_type, m.parent_entity_id, m.thread_id)\n IS DISTINCT FROM (l.parent_type, l.parent_id, l.root_id)\n ) AS \"misplaced_messages!\",\n count(*) FILTER (\n WHERE m.id IS NOT NULL AND l.root_id IS NULL\n AND NOT EXISTS (SELECT 1 FROM comms_message_threads th WHERE th.root_id = m.id)\n ) AS \"roots_without_threads!\",\n count(*) FILTER (\n WHERE m.updated_at <= l.updated_at\n AND (m.content, m.sender_id, m.created_at, m.deleted_at)\n IS DISTINCT FROM (l.text, l.owner, l.created_at, l.deleted_at)\n ) AS \"content_mismatches!\"\n FROM legacy l\n LEFT JOIN comms_messages m ON m.id = l.id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "missing_messages!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "misplaced_messages!",+ "type_info": "Int8"+ },+ {+ "ordinal": 2,+ "name": "roots_without_threads!",+ "type_info": "Int8"+ },+ {+ "ordinal": 3,+ "name": "content_mismatches!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null,+ null,+ null,+ null+ ]+ },+ "hash": "5e56844164b2f53aab67022cb6141c25b3c78d4e19eef674cfef968816559980"+}diff --git a/.sqlx/query-d801f390a1cb9d8e8d6c49da272a054a99561c94177134a23a31bf9149571b0a.json b/.sqlx/query-d801f390a1cb9d8e8d6c49da272a054a99561c94177134a23a31bf9149571b0a.jsonnew file mode 100644index 0000000000..293f2e99d1--- /dev/null+++ b/.sqlx/query-d801f390a1cb9d8e8d6c49da272a054a99561c94177134a23a31bf9149571b0a.json@@ -0,0 +1,12 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_message_threads (\n root_id, parent_entity_type, parent_entity_id, user_id, resolved,\n import_metadata, created_at, updated_at, deleted_at\n )\n SELECT root.id,\n CASE WHEN t.contact_id IS NULL THEN 'crm_company' ELSE 'crm_contact' END,\n COALESCE(t.contact_id, t.company_id)::text,\n t.owner, t.resolved,\n jsonb_build_object('source', 'crm_thread', 'legacy_thread_id', t.id),\n t.created_at, t.updated_at, t.deleted_at\n FROM crm_thread t\n CROSS JOIN LATERAL (\n SELECT c.id FROM crm_comment c\n WHERE c.thread_id = t.id\n ORDER BY c.created_at, c.id\n LIMIT 1\n ) root\n ON CONFLICT (root_id) DO UPDATE SET\n user_id = EXCLUDED.user_id,\n resolved = EXCLUDED.resolved,\n import_metadata = EXCLUDED.import_metadata,\n created_at = EXCLUDED.created_at,\n updated_at = EXCLUDED.updated_at,\n deleted_at = EXCLUDED.deleted_at\n WHERE (comms_message_threads.import_metadata IS NULL\n OR (comms_message_threads.import_metadata->>'source' = 'crm_thread'\n AND comms_message_threads.updated_at <= EXCLUDED.updated_at))\n AND (comms_message_threads.import_metadata,\n comms_message_threads.user_id, comms_message_threads.resolved,\n comms_message_threads.created_at, comms_message_threads.updated_at,\n comms_message_threads.deleted_at)\n IS DISTINCT FROM\n (EXCLUDED.import_metadata, EXCLUDED.user_id, EXCLUDED.resolved,\n EXCLUDED.created_at, EXCLUDED.updated_at, EXCLUDED.deleted_at)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": []+ },+ "nullable": []+ },+ "hash": "d801f390a1cb9d8e8d6c49da272a054a99561c94177134a23a31bf9149571b0a"+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCommentRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCommentRequest.tsindex 9aa4432ea9..8fa09f38a2 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCommentRequest.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createCrmCommentRequest.ts@@ -10,14 +10,13 @@ import type { CreateCrmCommentRequestThreadId } from './createCrmCommentRequestT* Request body for `POST /crm/comments/{entity_type}/{entity_id}`.*/export interface CreateCrmCommentRequest {- /** Arbitrary client metadata for the comment. */+ /** Ignored: messages keep no client metadata. */metadata?: unknown;/** The comment body (markdown). */text: string;/** Existing thread to append to. Omit to start a new thread on theaddressed entity. */threadId?: CreateCrmCommentRequestThreadId;- /** Metadata to set on a newly created thread (ignored when replying-without a value). */+ /** Ignored: discussions keep no thread metadata. */threadMetadata?: unknown;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/deleteCrmCommentResult.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/deleteCrmCommentResult.tsindex 0efc0b079f..e2824bb5ad 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/deleteCrmCommentResult.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/deleteCrmCommentResult.ts@@ -6,14 +6,14 @@*//**- * 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).+ * Outcome of deleting a CRM comment: reports whether its discussion went with+it (it does when the deleted comment was the discussion's first).*/export interface DeleteCrmCommentResult {/** The deleted comment's id. */commentId: string;- /** Whether the thread itself was soft-deleted because no live comments-remained. */+ /** Whether the whole discussion was deleted because the comment was its+first. */threadDeleted: boolean;/** The thread the comment belonged to. */threadId: string;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex fbb15205ca..a36cd8c5ab 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -5256,8 +5256,8 @@ export const getChannelsResponse = zod.describe('A cursor-paginated channel list response.');/**- * @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+ * @summary Delete a CRM comment, scoped to the requesting user's team. Deleting a+thread's first comment deletes the whole discussion, as on documents(reported via `threadDeleted`).*/export const deleteCrmCommentParams = zod.object({@@ -5270,12 +5270,12 @@ export const deleteCrmCommentResponse = zodthreadDeleted: zod.boolean().describe(- 'Whether the thread itself was soft-deleted because no live comments\nremained.'+ 'Whether the whole discussion was deleted because the comment was its\nfirst.'),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).'+ "Outcome of deleting a CRM comment: reports whether its discussion went with\nit (it does when the deleted comment was the discussion's first).");/**@@ -5439,7 +5439,7 @@ export const createCrmCommentBody = zodmetadata: zod.unknown().optional()- .describe('Arbitrary client metadata for the comment.'),+ .describe('Ignored: messages keep no client metadata.'),text: zod.string().describe('The comment body (markdown).'),threadId: zod.uuid()@@ -5450,9 +5450,7 @@ export const createCrmCommentBody = zodthreadMetadata: zod.unknown().optional()- .describe(- 'Metadata to set on a newly created thread (ignored when replying\nwithout a value).'- ),+ .describe('Ignored: discussions keep no thread metadata.'),}).describe('Request body for `POST \/crm\/comments\/{entity_type}\/{entity_id}`.'diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 2470085cb8..b78a547f99 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -6270,7 +6270,7 @@"/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`).",+ "summary": "Delete a CRM comment, scoped to the requesting user's team. Deleting a\nthread's first comment deletes the whole discussion, as on documents\n(reported via `threadDeleted`).","operationId": "delete_crm_comment","parameters": [{@@ -20487,7 +20487,7 @@"required": ["text"],"properties": {"metadata": {- "description": "Arbitrary client metadata for the comment."+ "description": "Ignored: messages keep no client metadata."},"text": {"type": "string",@@ -20499,7 +20499,7 @@"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)."+ "description": "Ignored: discussions keep no thread metadata."}}},@@ -21795,7 +21795,7 @@},"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).",+ "description": "Outcome of deleting a CRM comment: reports whether its discussion went with\nit (it does when the deleted comment was the discussion's first).","required": ["commentId", "threadId", "threadDeleted"],"properties": {"commentId": {@@ -21805,7 +21805,7 @@},"threadDeleted": {"type": "boolean",- "description": "Whether the thread itself was soft-deleted because no live comments\nremained."+ "description": "Whether the whole discussion was deleted because the comment was its\nfirst."},"threadId": {"type": "string",diff --git a/crates/crm/Cargo.toml b/crates/crm/Cargo.tomlindex 61668c7d8d..5ba8ff9102 100644--- a/crates/crm/Cargo.toml+++ b/crates/crm/Cargo.toml@@ -17,6 +17,7 @@ ai_tools = []axum = ["dep:axum",+ "dep:messages","dep:macro_authorization","dep:macro_uuid","dep:model-error-response",@@ -83,7 +84,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]macro_db_migrator = { path = "../macro_db_migrator" }-messages = { path = "../messages", default-features = false, features = ["outbound"] }+messages = { path = "../messages", default-features = false, features = ["outbound", "test-utils"] }macro_user_id = { path = "../macro_user_id" }properties = { path = "../properties", default-features = false, features = ["outbound",diff --git a/crates/crm/src/domain/comment.rs b/crates/crm/src/domain/comment.rsindex b7ea9c58f7..4f7a05a7f1 100644--- a/crates/crm/src/domain/comment.rs+++ b/crates/crm/src/domain/comment.rs@@ -89,8 +89,8 @@ pub struct CrmCommentThread {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).+/// Outcome of deleting a CRM comment: reports whether its discussion went with+/// it (it does when the deleted comment was the discussion's first).#[derive(Debug, Clone, Serialize)]#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]@@ -99,7 +99,7 @@ pub struct DeleteCrmCommentResult {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.+ /// Whether the whole discussion was deleted because the comment was its+ /// first.pub thread_deleted: bool,}diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rsindex e5373f0a7b..0b2c108c09 100644--- a/crates/crm/src/domain/companies_repo.rs+++ b/crates/crm/src/domain/companies_repo.rs@@ -651,6 +651,17 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {comment_id: &uuid::Uuid,) -> impl Future<Output = Result<Option<(CrmCommentEntityType, uuid::Uuid)>, CrmError>> + Send;+ /// The first comment of a legacy `crm_thread` on the record, which is the+ /// id its imported discussion root carries. Lets a client that still holds+ /// a legacy thread id reply to the imported discussion.+ fn legacy_thread_root(+ &self,+ _entity_id: &uuid::Uuid,+ _thread_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send {+ async { Ok(None) }+ }+/// Read the team's CRM configuration from `team_crm_settings`./// A missing row yields [`CrmTeamSettings::default`].fn get_team_settings(diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rsindex d61f716e22..a5398b4285 100644--- a/crates/crm/src/domain/service.rs+++ b/crates/crm/src/domain/service.rs@@ -401,6 +401,16 @@ pub trait CrmService: Clone + Send + Sync + 'static {comment_id: &uuid::Uuid,) -> impl Future<Output = Result<Option<(CrmCommentEntityType, uuid::Uuid)>, CrmError>> + Send;+ /// The discussion root a legacy thread id maps to on the record addressed+ /// by `access`. See [`CompaniesRepository::legacy_thread_root`].+ fn legacy_thread_root(+ &self,+ _access: &CrmCommentReceipt<AnyEntityPermission>,+ _thread_id: &uuid::Uuid,+ ) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send {+ async { Ok(None) }+ }+/// Read the team's CRM configuration. Any team member may read;/// a team without a settings row gets the defaults. See/// [`CompaniesRepository::get_team_settings`].@@ -1013,6 +1023,18 @@ where.await}+ #[tracing::instrument(skip(self, access), err)]+ async fn legacy_thread_root(+ &self,+ access: &CrmCommentReceipt<AnyEntityPermission>,+ thread_id: &uuid::Uuid,+ ) -> Result<Option<uuid::Uuid>, CrmError> {+ let (_, entity_id) = access.comment_entity()?;+ self.companies_repository+ .legacy_thread_root(&entity_id, thread_id)+ .await+ }+#[tracing::instrument(skip(self, access), err)]async fn get_team_settings(&self,diff --git a/crates/crm/src/inbound/axum_extractors.rs b/crates/crm/src/inbound/axum_extractors.rsindex b578996007..cde267eba6 100644--- a/crates/crm/src/inbound/axum_extractors.rs+++ b/crates/crm/src/inbound/axum_extractors.rs@@ -29,15 +29,15 @@ use entity_access::{use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,};+use messages::domain::models::MessageParent;use uuid::Uuid;use crate::{domain::{auth::{CrmCommentReceipt, CrmCompanyReceipt, CrmContactReceipt},- comment::CrmCommentEntityType,service::CrmService,},- inbound::axum_router::CrmServiceRef,+ inbound::axum_router::CrmMessagesRef,};/// Validates that the user satisfies the required permission for a CRM@@ -198,14 +198,14 @@ where/// Validates that the user satisfies the required permission for the CRM/// entity (company or contact) a given comment belongs to and mints a/// [`CrmCommentReceipt`]. Reads `comment_id` from the path and resolves-/// the owning entity via `CrmService::get_comment_entity`. The acting user+/// the owning entity from the comment's message parent. The acting user/// is authenticated through the authorization service in router state for/// both direct credentials and internal service access. The same/// role-to-AccessLevel mapping as the company / contact extractors applies;/// hidden parents are invisible to plain members.///-/// Returns `NotFound` when the comment doesn't exist or is soft-deleted,-/// so cross-team callers can't probe for comment existence.+/// Returns `NotFound` when the comment doesn't exist, is deleted, or isn't on+/// a CRM record, so cross-team callers can't probe for comment existence.#[derive(Debug)]pub struct CrmCommentAccessLevelExtractor<T: RequiredPermission, C, Eas, Auth> {/// Capability token authorizing CRM comment service calls.@@ -216,7 +216,7 @@ pub struct CrmCommentAccessLevelExtractor<T: RequiredPermission, C, Eas, Auth> {impl<T, S, C, Eas, Auth> FromRequestParts<S> for CrmCommentAccessLevelExtractor<T, C, Eas, Auth>whereT: RequiredPermission,- CrmServiceRef<C>: FromRef<S>,+ CrmMessagesRef: FromRef<S>,Arc<Eas>: FromRef<S>,MacroAuthorizationState<Auth>: FromRef<S>,C: CrmService,@@ -228,7 +228,7 @@ where#[tracing::instrument(err, skip(state, parts))]async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {- let CrmServiceRef(crm_service) = <CrmServiceRef<C>>::from_ref(state);+ let CrmMessagesRef(messages) = CrmMessagesRef::from_ref(state);let access_service = <Arc<Eas>>::from_ref(state);let Path(path_params): Path<HashMap<String, String>> = parts@@ -243,13 +243,15 @@ where.map_err(ExtractorError::from)?;let macro_user_id = authorization.authorization.user.macro_user_id.clone();- let (crm_entity_type, entity_id) = crm_service- .get_comment_entity(&comment_id)+ let (entity_type, entity_id) = match messages+ .parent_of(comment_id).await.map_err(|_| ExtractorError::Internal)?- .ok_or(ExtractorError::NotFound("CRM comment not found"))?;-- let entity_type = entity_type_for(crm_entity_type);+ {+ Some(MessageParent::CrmCompany(id)) => (EntityType::CrmCompany, id),+ Some(MessageParent::CrmContact(id)) => (EntityType::CrmContact, id),+ _ => return Err(ExtractorError::NotFound("CRM comment not found")),+ };let entity_id_str = entity_id.to_string();// Map an "access denied" outcome to NotFound so a cross-team caller@@ -318,10 +320,3 @@ fn extract_comment_id(path_params: &HashMap<String, String>) -> Result<Uuid, Ext))?;Uuid::parse_str(raw_id).map_err(|_| ExtractorError::BadRequest("invalid comment ID format"))}--fn entity_type_for(t: CrmCommentEntityType) -> EntityType {- match t {- CrmCommentEntityType::CrmCompany => EntityType::CrmCompany,- CrmCommentEntityType::CrmContact => EntityType::CrmContact,- }-}diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rsindex ec34c52d8c..855ad115fc 100644--- a/crates/crm/src/inbound/axum_extractors/test.rs+++ b/crates/crm/src/inbound/axum_extractors/test.rs@@ -526,6 +526,16 @@ fn test_router(comment_entity: Option<(CrmCommentEntityType, Uuid)>,) -> (Router, FakeEntityAccessService, FakeCrmService) {let crm_service = FakeCrmService::new(comment_entity);+ let mut messages = messages::domain::api::MockMessageServiceApi::new();+ let calls = crm_service.comment_calls.clone();+ let parent = comment_entity.map(|(kind, id)| match kind {+ CrmCommentEntityType::CrmCompany => messages::domain::models::MessageParent::CrmCompany(id),+ CrmCommentEntityType::CrmContact => messages::domain::models::MessageParent::CrmContact(id),+ });+ messages.expect_parent_of().returning(move |id| {+ calls.lock().expect("comment calls lock poisoned").push(id);+ Ok(parent.clone())+ });let authorization_service = MacroAuthorizationServiceImpl::new(FakeJwtValidator,InternalAuthConfig {@@ -545,6 +555,7 @@ fn test_router(stage_service: Arc::new(()),entity_access_service: Arc::new(entity_access.clone()),authorization_state: MacroAuthorizationState::new(Arc::new(authorization_service)),+ messages: Arc::new(messages),};let router = Router::new().route("/companies/{company_id}", get(company_handler))diff --git a/crates/crm/src/inbound/axum_router.rs b/crates/crm/src/inbound/axum_router.rsindex fb1be54185..152c72e58b 100644--- a/crates/crm/src/inbound/axum_router.rs+++ b/crates/crm/src/inbound/axum_router.rs@@ -73,6 +73,8 @@ pub struct CrmRouterState<C, St, Eas, Auth> {pub entity_access_service: Arc<Eas>,/// State used to authorize direct users and internal service callers.pub authorization_state: MacroAuthorizationState<Auth>,+ /// Shared message service that stores CRM discussions.+ pub messages: Arc<dyn messages::domain::api::MessageServiceApi>,}impl<C, St, Eas, Auth> FromRef<CrmRouterState<C, St, Eas, Auth>> for Arc<Eas> {@@ -108,6 +110,17 @@ impl<C, St, Eas, Auth> FromRef<CrmRouterState<C, St, Eas, Auth>> for CrmServiceR}}+/// The shared message service, pulled from [`CrmRouterState`] by the comment+/// extractor to find which record a comment belongs to.+#[derive(Clone)]+pub struct CrmMessagesRef(pub Arc<dyn messages::domain::api::MessageServiceApi>);++impl<C, St, Eas, Auth> FromRef<CrmRouterState<C, St, Eas, Auth>> for CrmMessagesRef {+ fn from_ref(state: &CrmRouterState<C, St, Eas, Auth>) -> Self {+ CrmMessagesRef(state.messages.clone())+ }+}+// Manual Clone so C, St, Eas, and Auth don't need Clone.impl<C, St, Eas, Auth> Clone for CrmRouterState<C, St, Eas, Auth> {fn clone(&self) -> Self {@@ -116,6 +129,7 @@ impl<C, St, Eas, Auth> Clone for CrmRouterState<C, St, Eas, Auth> {stage_service: self.stage_service.clone(),entity_access_service: self.entity_access_service.clone(),authorization_state: self.authorization_state.clone(),+ messages: self.messages.clone(),}}}diff --git a/crates/crm/src/inbound/axum_router/comments.rs b/crates/crm/src/inbound/axum_router/comments.rsindex 8e87b0ce14..cf96699a8f 100644--- a/crates/crm/src/inbound/axum_router/comments.rs+++ b/crates/crm/src/inbound/axum_router/comments.rs@@ -1,13 +1,15 @@-//! Handlers for CRM comment threads.+//! Handlers for CRM comment threads, served from the shared message store.//!-//! Threads and comments hang off a CRM company or contact and mirror the-//! document comment shape so the frontend reuses its thread assembly /-//! rendering. List/create routes use [`EntityPermissionExtractor`] over-//! the path's `crm_company`/`crm_contact` entity type. Edit/delete are-//! keyed by `comment_id` only and use [`CrmCommentAccessLevelExtractor`],-//! which resolves the comment's owning entity before checking access. In-//! every case the extractor enforces the team-membership rule, so-//! members can't reach hidden parents.+//! CRM discussions live in `comms_messages` with `crm_company` / `crm_contact`+//! parents; these routes keep the legacy request and response shapes for+//! clients that still use them (see [`adapter`]). List/create routes use+//! [`EntityPermissionExtractor`] over the path's `crm_company`/`crm_contact`+//! entity type. Edit/delete are keyed by `comment_id` only and use+//! [`CrmCommentAccessLevelExtractor`], which resolves the comment's parent+//! before checking access. In every case the team-membership rule applies,+//! so members can't reach hidden parents.++mod adapter;use axum::{Json,@@ -15,7 +17,7 @@ use axum::{};use entity_access::{domain::{- models::{TeamRole, ViewAccessLevel},+ models::{EntityAccessReceipt, RequiredPermission, TeamRole, ViewAccessLevel},ports::EntityAccessService,},inbound::axum_extractors::EntityPermissionExtractor,@@ -37,6 +39,8 @@ use crate::{inbound::axum_extractors::CrmCommentAccessLevelExtractor,};+pub use adapter::CrmCommentAdapter;+use super::CrmRouterState;/// Request body for `POST /crm/comments/{entity_type}/{entity_id}`.@@ -46,12 +50,11 @@ 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).+ /// Ignored: discussions keep no thread metadata.pub thread_metadata: Option<Value>,/// The comment body (markdown).pub text: String,- /// Arbitrary client metadata for the comment.+ /// Ignored: messages keep no client metadata.pub metadata: Option<Value>,}@@ -92,13 +95,12 @@ pub async fn list_handler<>(access: EntityPermissionExtractor<Eas, Auth>,State(state): State<CrmRouterState<C, St, Eas, Auth>>,- Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,+ Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,) -> Result<Json<Vec<CrmCommentThread>>, CrmError> {- let (team_id, team_role) = owning_team_for_entity(&state, &access).await?;- let receipt = CrmCommentReceipt::new(access.entity_access_receipt, team_id, team_role)?;-- let threads = state.service.get_crm_comment_threads(&receipt).await?;-+ let view = message_receipt(&access.entity_access_receipt, CrmError::ThreadNotFound)?;+ let threads = CrmCommentAdapter::new(state.messages.as_ref())+ .list(view, entity_type, entity_id)+ .await?;Ok(Json(threads))}@@ -131,36 +133,27 @@ pub async fn create_handler<>(access: EntityPermissionExtractor<Eas, Auth>,State(state): State<CrmRouterState<C, St, Eas, Auth>>,- Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,+ Path((entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,Json(req): Json<CreateCrmCommentRequest>,) -> Result<Json<CrmCommentThread>, CrmError> {- let (team_id, team_role) = owning_team_for_entity(&state, &access).await?;-let text = req.text.trim();if text.is_empty() {return Err(CrmError::InvalidRequest("comment text cannot be empty".into(),));}-- let receipt = CrmCommentReceipt::new(access.entity_access_receipt, team_id, team_role)?;- let owner = receipt- .receipt()- .get_authenticated_user()- .map_err(|e| CrmError::StorageLayerError(e.into()))?;-- let thread = state- .service- .create_crm_comment(- &receipt,- owner.as_ref(),- req.thread_id,- req.thread_metadata,- text,- req.metadata,- )+ let view = message_receipt(&access.entity_access_receipt, CrmError::ThreadNotFound)?;+ let write = message_receipt(&access.entity_access_receipt, CrmError::ThreadNotFound)?;+ let adapter = CrmCommentAdapter::new(state.messages.as_ref());+ let root = match req.thread_id {+ None => None,+ Some(thread_id) => {+ Some(resolve_root(&state, &access, &adapter, view.clone(), thread_id).await?)+ }+ };+ let thread = adapter+ .create(write, view, entity_type, entity_id, root, text).await?;-Ok(Json(thread))}@@ -199,17 +192,15 @@ pub async fn edit_handler<"comment text cannot be empty".into(),));}-- let comment = state- .service- .edit_crm_comment(&access.receipt, &comment_id, text)+ let write = message_receipt(access.receipt.receipt(), CrmError::CommentNotFound)?;+ let comment = CrmCommentAdapter::new(state.messages.as_ref())+ .edit(write, 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+/// Delete a CRM comment, scoped to the requesting user's team. Deleting a+/// thread's first comment deletes the whole discussion, as on documents/// (reported via `threadDeleted`).#[utoipa::path(delete,@@ -236,14 +227,49 @@ pub async fn delete_handler<State(state): State<CrmRouterState<C, St, Eas, Auth>>,Path(comment_id): Path<Uuid>,) -> Result<Json<DeleteCrmCommentResult>, CrmError> {- let result = state- .service- .delete_crm_comment(&access.receipt, &comment_id)+ let write = message_receipt(access.receipt.receipt(), CrmError::CommentNotFound)?;+ let result = CrmCommentAdapter::new(state.messages.as_ref())+ .delete(write, comment_id).await?;-Ok(Json(result))}+/// Narrow a verified CRM receipt to the message capability a store call+/// needs. A caller who can see the record but not comment on it gets+/// `missing`, a 404, so the routes do not reveal what exists.+fn message_receipt<P: RequiredPermission, T: RequiredPermission + Clone>(+ receipt: &EntityAccessReceipt<T>,+ missing: CrmError,+) -> Result<EntityAccessReceipt<P>, CrmError> {+ receipt.clone().try_into_requirement().map_err(|_| missing)+}++/// The discussion root a client's `threadId` names: a root message id, or a+/// legacy `crm_thread` id that clients loaded before the import still hold.+async fn resolve_root<+ C: CrmService,+ St,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+>(+ state: &CrmRouterState<C, St, Eas, Auth>,+ access: &EntityPermissionExtractor<Eas, Auth>,+ adapter: &CrmCommentAdapter<'_>,+ view: EntityAccessReceipt<messages::domain::service::MessageView>,+ thread_id: Uuid,+) -> Result<Uuid, CrmError> {+ if adapter.is_root(view, thread_id).await? {+ return Ok(thread_id);+ }+ let (team_id, team_role) = owning_team_for_entity(state, access).await?;+ let legacy = CrmCommentReceipt::new(access.entity_access_receipt.clone(), team_id, team_role)?;+ state+ .service+ .legacy_thread_root(&legacy, &thread_id)+ .await?+ .ok_or(CrmError::ThreadNotFound)+}+/// Resolve the owning team of the entity the comment hangs off — and the/// caller's role on it — derived from the same ownership lookup that grants/// access, not the caller's default team, so the bundled team can't driftdiff --git a/crates/crm/src/inbound/axum_router/comments/adapter.rs b/crates/crm/src/inbound/axum_router/comments/adapter.rsnew file mode 100644index 0000000000..4be52fce95--- /dev/null+++ b/crates/crm/src/inbound/axum_router/comments/adapter.rs@@ -0,0 +1,249 @@+//! The legacy CRM comment API served from the shared message store.+//!+//! CRM discussions live in `comms_messages` with `crm_company` / `crm_contact`+//! parents. These routes keep their request and response shapes for clients+//! that still speak them: a thread is a discussion root, identified by the+//! root message id, and a comment is a message. Imported comments keep their+//! `crm_comment` ids, so ids a client already holds stay valid.++use entity_access::domain::models::EntityAccessReceipt;+use messages::domain::{+ api::MessageServiceApi,+ models::{Message, MessageAttribution, MessageThread, PostMessage},+ ports::{MessageError, MessagePatch, MessageTimelineQuery},+ service::{MessageView, MessageWrite},+};+use uuid::Uuid;++use crate::domain::{+ comment::{+ CrmComment, CrmCommentEntityType, CrmCommentThread, CrmThread, DeleteCrmCommentResult,+ },+ model::CrmError,+};++#[cfg(test)]+mod test;++/// Page size for reading a record's discussions; CRM records carry few.+const TIMELINE_PAGE: u16 = 100;++/// Legacy CRM comment operations over the shared message service.+pub struct CrmCommentAdapter<'a> {+ messages: &'a dyn MessageServiceApi,+}++impl<'a> CrmCommentAdapter<'a> {+ /// Serve the legacy shapes from `messages`.+ pub fn new(messages: &'a dyn MessageServiceApi) -> Self {+ Self { messages }+ }++ /// Live discussions on the record, oldest first, each with its live+ /// comments oldest first, as the legacy list returned them.+ pub async fn list(+ &self,+ access: EntityAccessReceipt<MessageView>,+ entity_type: CrmCommentEntityType,+ entity_id: Uuid,+ ) -> Result<Vec<CrmCommentThread>, CrmError> {+ let mut roots = Vec::new();+ let mut cursor = None;+ loop {+ let page = self+ .messages+ .timeline(+ access.clone(),+ MessageTimelineQuery {+ cursor,+ limit: Some(TIMELINE_PAGE),+ ..Default::default()+ },+ )+ .await+ .map_err(thread_error)?;+ roots.extend(page.items.into_iter().map(|item| item.message.id));+ match page.next_cursor {+ Some(next) => cursor = Some(next),+ None => break,+ }+ }+ let mut threads = Vec::with_capacity(roots.len());+ for root in roots {+ let thread = self+ .messages+ .get_thread(access.clone(), root)+ .await+ .map_err(thread_error)?;+ if let Some(thread) = legacy_thread(thread, entity_type, entity_id) {+ threads.push(thread);+ }+ }+ threads.sort_by(|a, b| {+ (a.thread.created_at, a.thread.thread_id)+ .cmp(&(b.thread.created_at, b.thread.thread_id))+ });+ Ok(threads)+ }++ /// Whether `id` is a live discussion root on the record.+ pub async fn is_root(+ &self,+ access: EntityAccessReceipt<MessageView>,+ id: Uuid,+ ) -> Result<bool, CrmError> {+ match self.messages.get_thread(access, id).await {+ Ok(thread) => Ok(thread.state.deleted_at.is_none()),+ Err(MessageError::NotFound) => Ok(false),+ Err(error) => Err(thread_error(error)),+ }+ }++ /// Post a new discussion, or a reply when `root` names one, and return the+ /// whole thread afterwards.+ pub async fn create(+ &self,+ write: EntityAccessReceipt<MessageWrite>,+ view: EntityAccessReceipt<MessageView>,+ entity_type: CrmCommentEntityType,+ entity_id: Uuid,+ root: Option<Uuid>,+ text: &str,+ ) -> Result<CrmCommentThread, CrmError> {+ let message = self+ .messages+ .post(+ write,+ PostMessage {+ id: None,+ attribution: MessageAttribution::default(),+ notification_policy: Default::default(),+ content: text.to_owned(),+ thread_id: root,+ anchor: None,+ mentions: vec![],+ attachments: vec![],+ nonce: None,+ },+ )+ .await+ .map_err(thread_error)?;+ let thread = self+ .messages+ .get_thread(view, message.root_id())+ .await+ .map_err(thread_error)?;+ legacy_thread(thread, entity_type, entity_id).ok_or(CrmError::ThreadNotFound)+ }++ /// Replace a comment's text; only its author may.+ pub async fn edit(+ &self,+ write: EntityAccessReceipt<MessageWrite>,+ comment_id: Uuid,+ text: &str,+ ) -> Result<CrmComment, CrmError> {+ let message = self+ .messages+ .patch(+ write,+ comment_id,+ MessagePatch {+ content: Some(text.to_owned()),+ ..Default::default()+ },+ )+ .await+ .map_err(comment_error)?;+ Ok(legacy_comment(message))+ }++ /// Delete a comment. Deleting a discussion's first comment deletes the+ /// discussion, which the result reports as `threadDeleted`.+ pub async fn delete(+ &self,+ write: EntityAccessReceipt<MessageWrite>,+ comment_id: Uuid,+ ) -> Result<DeleteCrmCommentResult, CrmError> {+ let message = self+ .messages+ .delete(write, comment_id, None)+ .await+ .map_err(comment_error)?;+ Ok(DeleteCrmCommentResult {+ comment_id: message.id,+ thread_id: message.root_id(),+ thread_deleted: message.thread_id.is_none(),+ })+ }+}++fn legacy_thread(+ thread: MessageThread,+ entity_type: CrmCommentEntityType,+ entity_id: Uuid,+) -> Option<CrmCommentThread> {+ if thread.state.deleted_at.is_some() {+ return None;+ }+ let comments: Vec<CrmComment> = std::iter::once(thread.root)+ .chain(thread.replies)+ .filter(|message| message.deleted_at.is_none())+ .map(legacy_comment)+ .collect();+ if comments.is_empty() {+ return None;+ }+ let state = thread.state;+ Some(CrmCommentThread {+ thread: CrmThread {+ thread_id: state.root_id,+ entity_type,+ entity_id,+ owner: state.user_id,+ resolved: state.resolved,+ metadata: None,+ created_at: state.created_at,+ updated_at: state.updated_at,+ deleted_at: state.deleted_at,+ },+ comments,+ })+}++fn legacy_comment(message: Message) -> CrmComment {+ CrmComment {+ comment_id: message.id,+ thread_id: message.root_id(),+ order: None,+ owner: String::from(message.sender_id.clone()),+ sender: None,+ text: message.content,+ metadata: None,+ created_at: message.created_at,+ updated_at: message.updated_at,+ deleted_at: message.deleted_at,+ }+}++fn thread_error(error: MessageError) -> CrmError {+ match error {+ MessageError::NotFound => CrmError::ThreadNotFound,+ other => common_error(other),+ }+}++fn comment_error(error: MessageError) -> CrmError {+ match error {+ MessageError::NotFound => CrmError::CommentNotFound,+ MessageError::Forbidden => CrmError::CommentNotOwned,+ other => common_error(other),+ }+}++fn common_error(error: MessageError) -> CrmError {+ match error {+ MessageError::Invalid(reason) => CrmError::InvalidRequest(reason.to_owned()),+ other => CrmError::StorageLayerError(anyhow::anyhow!(other.to_string())),+ }+}diff --git a/crates/crm/src/inbound/axum_router/comments/adapter/test.rs b/crates/crm/src/inbound/axum_router/comments/adapter/test.rsnew file mode 100644index 0000000000..b884330203--- /dev/null+++ b/crates/crm/src/inbound/axum_router/comments/adapter/test.rs@@ -0,0 +1,164 @@+use entity_access::domain::models::{+ AccessLevel, Entity, EntityAccessReceipt, EntityPermission, EntityType, RequiredPermission,+};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use messages::{+ domain::{+ ports::NoMessageEventPublisher,+ service::{MessageService, MessageView, MessageWrite},+ },+ outbound::pg_message_repo::PgMessageRepository,+};+use sqlx::PgPool;+use uuid::Uuid;++use super::CrmCommentAdapter;+use crate::{+ domain::{comment::CrmCommentEntityType, model::CrmError},+ outbound::lookup::PgCrmParentReader,+};++const AUTHOR: &str = "macro|[email protected]";+const OTHER: &str = "macro|[email protected]";++async fn seed_user(pool: &PgPool, id: &str) {+ let macro_user_id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $3)",+ )+ .bind(macro_user_id)+ .bind(id)+ .bind(format!("stripe_{macro_user_id}"))+ .execute(pool)+ .await+ .unwrap();+ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#)+ .bind(id)+ .bind(macro_user_id)+ .execute(pool)+ .await+ .unwrap();+}++async fn seed_company(pool: &PgPool) -> Uuid {+ seed_user(pool, AUTHOR).await;+ seed_user(pool, OTHER).await;+ let team = Uuid::now_v7();+ sqlx::query("INSERT INTO team (id, name, owner_id) VALUES ($1, 'CRM team', $2)")+ .bind(team)+ .bind(AUTHOR)+ .execute(pool)+ .await+ .unwrap();+ let company = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO crm_companies (id, team_id, first_interaction, last_interaction)+ VALUES ($1, $2, now(), now())",+ )+ .bind(company)+ .bind(team)+ .execute(pool)+ .await+ .unwrap();+ company+}++fn receipt<P: RequiredPermission>(user: &str, company: Uuid) -> EntityAccessReceipt<P> {+ EntityAccessReceipt::try_new_authenticated_user(+ user.to_owned().try_into().unwrap(),+ Entity {+ entity_type: EntityType::CrmCompany,+ entity_id: company.to_string(),+ },+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Edit,+ },+ )+ .unwrap()+}++fn service(pool: &PgPool) -> MessageService<PgMessageRepository, NoMessageEventPublisher> {+ MessageService::new(+ PgMessageRepository::new(pool.clone()).with_crm(PgCrmParentReader::new(pool.clone())),+ NoMessageEventPublisher,+ )+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn legacy_shapes_round_trip_through_the_message_store(pool: PgPool) {+ let company = seed_company(&pool).await;+ let service = service(&pool);+ let adapter = CrmCommentAdapter::new(&service);+ let kind = CrmCommentEntityType::CrmCompany;+ let view = || receipt::<MessageView>(AUTHOR, company);+ let write = |user| receipt::<MessageWrite>(user, company);++ let created = adapter+ .create(+ write(AUTHOR),+ view(),+ kind,+ company,+ None,+ "Renewal call went well",+ )+ .await+ .unwrap();+ let root = created.thread.thread_id;+ assert_eq!(created.thread.entity_id, company);+ assert_eq!(created.thread.owner, AUTHOR);+ assert_eq!(created.comments.len(), 1);+ assert_eq!(created.comments[0].comment_id, root);+ assert_eq!(created.comments[0].thread_id, root);+ assert_eq!(created.comments[0].owner, AUTHOR);++ let replied = adapter+ .create(+ write(OTHER),+ view(),+ kind,+ company,+ Some(root),+ "Following up",+ )+ .await+ .unwrap();+ assert_eq!(replied.thread.thread_id, root);+ let texts: Vec<_> = replied.comments.iter().map(|c| c.text.as_str()).collect();+ assert_eq!(texts, ["Renewal call went well", "Following up"]);+ let reply = replied.comments[1].comment_id;+ assert!(adapter.is_root(view(), root).await.unwrap());+ assert!(!adapter.is_root(view(), reply).await.unwrap());+ assert!(!adapter.is_root(view(), Uuid::now_v7()).await.unwrap());++ let second = adapter+ .create(write(AUTHOR), view(), kind, company, None, "Second thread")+ .await+ .unwrap();+ let listed = adapter.list(view(), kind, company).await.unwrap();+ let roots: Vec<_> = listed.iter().map(|t| t.thread.thread_id).collect();+ assert_eq!(roots, [root, second.thread.thread_id]);++ let edited = adapter.edit(write(OTHER), reply, "Edited").await.unwrap();+ assert_eq!(edited.text, "Edited");+ assert!(matches!(+ adapter.edit(write(OTHER), root, "Not mine").await,+ Err(CrmError::CommentNotOwned)+ ));++ let deleted_reply = adapter.delete(write(OTHER), reply).await.unwrap();+ assert_eq!(deleted_reply.thread_id, root);+ assert!(!deleted_reply.thread_deleted);+ let listed = adapter.list(view(), kind, company).await.unwrap();+ assert_eq!(listed[0].comments.len(), 1);++ let deleted_root = adapter.delete(write(AUTHOR), root).await.unwrap();+ assert!(deleted_root.thread_deleted);+ let listed = adapter.list(view(), kind, company).await.unwrap();+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].thread.thread_id, second.thread.thread_id);+ assert!(matches!(+ adapter.edit(write(AUTHOR), root, "Gone").await,+ Err(CrmError::CommentNotFound)+ ));+}diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rsindex 903e7f6b06..d9983277ba 100644--- a/crates/crm/src/outbound/companies_repo.rs+++ b/crates/crm/src/outbound/companies_repo.rs@@ -2293,6 +2293,30 @@ impl CompaniesRepository for CompaniesRepositoryImpl {}))}+ #[tracing::instrument(skip(self), err)]+ async fn legacy_thread_root(+ &self,+ entity_id: &Uuid,+ thread_id: &Uuid,+ ) -> Result<Option<Uuid>, CrmError> {+ sqlx::query_scalar!(+ r#"+ SELECT c.id+ FROM crm_comment c+ JOIN crm_thread t ON t.id = c.thread_id+ WHERE t.id = $1+ AND (t.company_id = $2 OR t.contact_id = $2)+ ORDER BY c.created_at ASC, c.id ASC+ LIMIT 1+ "#,+ thread_id,+ entity_id,+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))+ }+#[tracing::instrument(skip(self), err)]async fn get_team_settings(&self, team_id: &Uuid) -> Result<CrmTeamSettings, CrmError> {let row = sqlx::query!(diff --git a/crates/crm/src/outbound/companies_repo/test/comments.rs b/crates/crm/src/outbound/companies_repo/test/comments.rsindex 5d89dc4e3b..1885f14454 100644--- a/crates/crm/src/outbound/companies_repo/test/comments.rs+++ b/crates/crm/src/outbound/companies_repo/test/comments.rs@@ -870,3 +870,61 @@ async fn delete_crm_comment_non_owner_forbidden(pool: PgPool) -> anyhow::Result<assert_eq!(threads[0].comments.len(), 1);Ok(())}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn legacy_thread_root_is_the_first_comment_on_the_record(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 other_company = insert_company(&pool, team_id, true, &["other.com"]).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let thread = repo+ .create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ None,+ None,+ "first",+ None,+ false,+ )+ .await?;+ let thread_id = thread.thread.thread_id;+ let first = thread.comments[0].comment_id;+ repo.create_crm_comment(+ &team_id,+ CrmCommentEntityType::CrmCompany,+ &company_id,+ owner,+ Some(thread_id),+ None,+ "second",+ None,+ false,+ )+ .await?;+ // A deleted first comment still names the imported root.+ sqlx::query("UPDATE crm_comment SET deleted_at = now() WHERE id = $1")+ .bind(first)+ .execute(&pool)+ .await?;++ assert_eq!(+ repo.legacy_thread_root(&company_id, &thread_id).await?,+ Some(first)+ );+ assert_eq!(+ repo.legacy_thread_root(&other_company, &thread_id).await?,+ None+ );+ assert_eq!(+ repo.legacy_thread_root(&company_id, &Uuid::now_v7())+ .await?,+ None+ );+ Ok(())+}diff --git a/crates/documents/src/inbound/toolset/comment_test.rs b/crates/documents/src/inbound/toolset/comment_test.rsindex 01eae698c5..ba8118f894 100644--- a/crates/documents/src/inbound/toolset/comment_test.rs+++ b/crates/documents/src/inbound/toolset/comment_test.rs@@ -94,6 +94,9 @@ impl MessageReader for FakeMessages {) -> Result<Message, MessageError> {panic!("unexpected resolve_legacy call")}+ async fn parent_of(&self, _id: Uuid) -> Result<Option<MessageParent>, MessageError> {+ panic!("unexpected parent_of call")+ }}#[async_trait::async_trait]diff --git a/crates/macro_db_migrator/Cargo.toml b/crates/macro_db_migrator/Cargo.tomlindex 6d827198e5..b314e84285 100644--- a/crates/macro_db_migrator/Cargo.toml+++ b/crates/macro_db_migrator/Cargo.toml@@ -17,10 +17,25 @@ comment-import = ["dep:tracing",]+crm-comment-import = [+ "dep:clap",+ "dep:database_env_vars",+ "dep:macro_entrypoint",+ "dep:macro_env",+ "dep:macro_uuid",+ "dep:rootcause",+ "dep:serde_json",+ "dep:tokio",+]+[[bin]]name = "comment_import"required-features = ["comment-import"]+[[bin]]+name = "crm_comment_import"+required-features = ["crm-comment-import"]+[dependencies]clap = { workspace = true, optional = true }database_env_vars = { path = "../database_env_vars", optional = true }diff --git a/crates/macro_db_migrator/src/bin/crm_comment_import.rs b/crates/macro_db_migrator/src/bin/crm_comment_import.rsnew file mode 100644index 0000000000..4acec505f2--- /dev/null+++ b/crates/macro_db_migrator/src/bin/crm_comment_import.rs@@ -0,0 +1,38 @@+//! Idempotent import of legacy CRM company and contact comments into the shared+//! message store. Safe to rerun while the application keeps serving requests.++#[path = "crm_comment_import/runner.rs"]+mod runner;++use clap::Parser;+use database_env_vars::DatabaseUrl;+use macro_entrypoint::MacroEntrypoint;+use macro_env::Environment;+use sqlx::{Connection, PgConnection};++#[derive(Debug, Parser)]+#[command(+ about = "Import legacy CRM comments into comms_messages while the application stays live"+)]+struct Args {+ /// Run the preflight and invariants and report pending work without writing.+ #[arg(long)]+ check: bool,+}++#[tokio::main]+async fn main() -> Result<(), rootcause::Report> {+ let args = Args::parse();+ let entrypoint = MacroEntrypoint::new(Environment::Local).init();+ let database_url = DatabaseUrl::new()?;+ let mut connection = PgConnection::connect(database_url.as_ref()).await?;+ let report = if args.check {+ runner::check(&mut connection).await?+ } else {+ runner::run(&mut connection).await?+ };+ println!("{report}");+ connection.close().await?;+ entrypoint.shutdown();+ Ok(())+}diff --git a/crates/macro_db_migrator/src/bin/crm_comment_import/runner.rs b/crates/macro_db_migrator/src/bin/crm_comment_import/runner.rsnew file mode 100644index 0000000000..6ca3c1f8f4--- /dev/null+++ b/crates/macro_db_migrator/src/bin/crm_comment_import/runner.rs@@ -0,0 +1,336 @@+//! Database-only operator tooling. No application request or authorization path.+//!+//! Every run projects the legacy `crm_thread` / `crm_comment` rows onto the+//! shared message tables in one transaction. A comment keeps its id as its+//! message id, and a thread's root is its first comment by creation time, so+//! reruns agree on identity without a mapping table. Rows whose projection+//! already matches are left alone, and a store row that changed after it was+//! imported is never reverted by an older legacy row.++use std::fmt;++use sqlx::{Connection, PgConnection, Postgres, Transaction};++#[cfg(test)]+mod test;++/// Distinct from the document comment importer's lock.+const LOCK_ID: i64 = 732_847_302;++/// What a run found and wrote.+#[derive(Debug, Default, Clone, PartialEq, Eq)]+pub(super) struct Report {+ /// Legacy data the store cannot represent; any makes a run abort.+ pub blockers: Blockers,+ /// Legacy comments with no message yet, before this run.+ pub pending_comments: i64,+ /// Legacy comments that differ from their imported message and are at+ /// least as new, before this run.+ pub stale_comments: i64,+ /// Legacy threads with no comments, which have nothing to import.+ pub empty_threads: i64,+ /// Messages this run inserted.+ pub messages_inserted: u64,+ /// Messages this run updated from newer legacy rows.+ pub messages_updated: u64,+ /// Thread rows this run inserted or updated.+ pub threads_written: u64,+ /// Import invariants after the run; all zero on success.+ pub invariants: Invariants,+}++/// Legacy fields with no place in the message store.+#[derive(Debug, Default, Clone, PartialEq, Eq)]+pub(super) struct Blockers {+ /// Threads or comments carrying client metadata.+ pub metadata: i64,+ /// Comments whose sender differs from their owner.+ pub foreign_senders: i64,+ /// Comments with an explicit display order.+ pub explicit_order: i64,+ /// Comment ids already used by a message this importer did not write.+ pub id_collisions: i64,+}++impl Blockers {+ fn any(&self) -> bool {+ self.metadata + self.foreign_senders + self.explicit_order + self.id_collisions > 0+ }+}++/// Checks that must all be zero once a run commits.+#[derive(Debug, Default, Clone, PartialEq, Eq)]+pub(super) struct Invariants {+ /// Legacy comments in a non-empty thread with no message.+ pub missing_messages: i64,+ /// Imported messages on another parent or thread than their legacy comment.+ pub misplaced_messages: i64,+ /// Imported roots with no thread row.+ pub roots_without_threads: i64,+ /// Imported messages whose content, sender, creation or deletion differs+ /// from a legacy comment that is at least as new.+ pub content_mismatches: i64,+}++impl Invariants {+ fn any(&self) -> bool {+ self.missing_messages+ + self.misplaced_messages+ + self.roots_without_threads+ + self.content_mismatches+ > 0+ }+}++impl fmt::Display for Report {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let b = &self.blockers;+ let i = &self.invariants;+ writeln!(+ f,+ "blockers: metadata={} foreign_senders={} explicit_order={} id_collisions={}",+ b.metadata, b.foreign_senders, b.explicit_order, b.id_collisions+ )?;+ writeln!(+ f,+ "pending: comments={} stale={} empty_threads={}",+ self.pending_comments, self.stale_comments, self.empty_threads+ )?;+ writeln!(+ f,+ "written: messages_inserted={} messages_updated={} threads_written={}",+ self.messages_inserted, self.messages_updated, self.threads_written+ )?;+ write!(+ f,+ "invariants: missing_messages={} misplaced_messages={} roots_without_threads={} content_mismatches={}",+ i.missing_messages, i.misplaced_messages, i.roots_without_threads, i.content_mismatches+ )+ }+}++/// Report blockers, pending work and invariants without writing.+pub(super) async fn check(connection: &mut PgConnection) -> Result<Report, rootcause::Report> {+ let mut tx = connection.begin().await?;+ let mut report = preflight(&mut tx).await?;+ report.invariants = invariants(&mut tx).await?;+ tx.rollback().await?;+ Ok(report)+}++/// Import everything pending in one transaction. Nothing is written when a+/// blocker is found or an invariant fails afterwards.+pub(super) async fn run(connection: &mut PgConnection) -> Result<Report, rootcause::Report> {+ let mut tx = connection.begin().await?;+ let acquired = sqlx::query_scalar!(+ r#"SELECT pg_try_advisory_xact_lock($1) AS "acquired!""#,+ LOCK_ID+ )+ .fetch_one(&mut *tx)+ .await?;+ if !acquired {+ rootcause::bail!("another CRM comment import is running");+ }+ lock_legacy_tables(&mut tx).await?;+ let mut report = preflight(&mut tx).await?;+ if report.blockers.any() {+ tx.rollback().await?;+ rootcause::bail!("preflight blocked the import:\n{report}");+ }+ let (inserted, updated) = upsert_messages(&mut tx).await?;+ report.messages_inserted = inserted;+ report.messages_updated = updated;+ report.threads_written = upsert_threads(&mut tx).await?;+ report.invariants = invariants(&mut tx).await?;+ if report.invariants.any() {+ tx.rollback().await?;+ rootcause::bail!("import invariants failed, nothing was written:\n{report}");+ }+ tx.commit().await?;+ Ok(report)+}++/// Legacy writes wait for the run instead of landing between the snapshot+/// and the invariants.+#[expect(+ clippy::disallowed_methods,+ reason = "utility statements carry no result shape for SQLx to check"+)]+async fn lock_legacy_tables(tx: &mut Transaction<'_, Postgres>) -> Result<(), sqlx::Error> {+ sqlx::query("SET LOCAL lock_timeout = '5s'")+ .execute(&mut **tx)+ .await?;+ sqlx::query("LOCK TABLE crm_thread, crm_comment IN SHARE ROW EXCLUSIVE MODE")+ .execute(&mut **tx)+ .await?;+ // The 5s timeout bounds only the table-lock wait.+ sqlx::query("SET LOCAL lock_timeout = 0")+ .execute(&mut **tx)+ .await?;+ Ok(())+}++async fn preflight(tx: &mut Transaction<'_, Postgres>) -> Result<Report, rootcause::Report> {+ let row = sqlx::query!(+ r#"SELECT+ (SELECT count(*) FROM crm_thread WHERE metadata IS NOT NULL)+ + (SELECT count(*) FROM crm_comment WHERE metadata IS NOT NULL) AS "metadata!",+ (SELECT count(*) FROM crm_comment WHERE sender IS NOT NULL AND sender <> owner) AS "foreign_senders!",+ (SELECT count(*) FROM crm_comment WHERE "order" IS NOT NULL) AS "explicit_order!",+ (SELECT count(*) FROM crm_comment c JOIN comms_messages m ON m.id = c.id+ WHERE m.import_metadata->>'source' IS DISTINCT FROM 'crm_comment') AS "id_collisions!",+ (SELECT count(*) FROM crm_comment c+ WHERE NOT EXISTS (SELECT 1 FROM comms_messages m WHERE m.id = c.id)) AS "pending_comments!",+ (SELECT count(*) FROM crm_comment c+ JOIN crm_thread t ON t.id = c.thread_id+ JOIN comms_messages m ON m.id = c.id+ WHERE m.import_metadata->>'source' = 'crm_comment'+ AND m.updated_at <= c.updated_at+ AND (m.content, m.updated_at, m.deleted_at)+ IS DISTINCT FROM+ (c.text, c.updated_at, COALESCE(c.deleted_at, t.deleted_at) AT TIME ZONE 'UTC')) AS "stale_comments!",+ (SELECT count(*) FROM crm_thread t+ WHERE NOT EXISTS (SELECT 1 FROM crm_comment c WHERE c.thread_id = t.id)) AS "empty_threads!""#+ )+ .fetch_one(&mut **tx)+ .await?;+ Ok(Report {+ blockers: Blockers {+ metadata: row.metadata,+ foreign_senders: row.foreign_senders,+ explicit_order: row.explicit_order,+ id_collisions: row.id_collisions,+ },+ pending_comments: row.pending_comments,+ stale_comments: row.stale_comments,+ empty_threads: row.empty_threads,+ ..Default::default()+ })+}++/// Every legacy comment. A comment in a deleted thread reads as deleted. An+/// imported message changes only when the legacy row differs and is not older,+/// so an edit made through the new API is never reverted.+async fn upsert_messages(+ tx: &mut Transaction<'_, Postgres>,+) -> Result<(u64, u64), rootcause::Report> {+ let rows = sqlx::query_scalar!(+ r#"INSERT INTO comms_messages (+ id, parent_entity_type, parent_entity_id, thread_id, sender_id, content,+ created_at, updated_at, edited_at, deleted_at, import_metadata+ )+ SELECT c.id,+ CASE WHEN t.contact_id IS NULL THEN 'crm_company' ELSE 'crm_contact' END,+ COALESCE(t.contact_id, t.company_id)::text,+ NULLIF(first_value(c.id) OVER (PARTITION BY c.thread_id ORDER BY c.created_at, c.id), c.id),+ c.owner, c.text, c.created_at, c.updated_at,+ CASE WHEN c.updated_at > c.created_at THEN c.updated_at AT TIME ZONE 'UTC' END,+ COALESCE(c.deleted_at, t.deleted_at) AT TIME ZONE 'UTC',+ jsonb_build_object('source', 'crm_comment', 'legacy_thread_id', c.thread_id)+ FROM crm_comment c+ JOIN crm_thread t ON t.id = c.thread_id+ ON CONFLICT (id) DO UPDATE SET+ content = EXCLUDED.content,+ updated_at = EXCLUDED.updated_at,+ edited_at = EXCLUDED.edited_at,+ deleted_at = EXCLUDED.deleted_at+ WHERE comms_messages.import_metadata->>'source' = 'crm_comment'+ AND comms_messages.updated_at <= EXCLUDED.updated_at+ AND (comms_messages.content, comms_messages.updated_at, comms_messages.edited_at,+ comms_messages.deleted_at)+ IS DISTINCT FROM+ (EXCLUDED.content, EXCLUDED.updated_at, EXCLUDED.edited_at, EXCLUDED.deleted_at)+ RETURNING (xmax = 0) AS "inserted!""#+ )+ .fetch_all(&mut **tx)+ .await?;+ let inserted = rows.iter().filter(|inserted| **inserted).count() as u64;+ Ok((inserted, rows.len() as u64 - inserted))+}++/// One thread row per non-empty legacy thread, keyed by its root comment, with+/// the same newer-wins rule as messages. Inserting a root makes the store's+/// trigger initialize a bare thread row; the id-collision blocker guarantees any+/// such row on an imported root came from this run, so it is taken over.+async fn upsert_threads(tx: &mut Transaction<'_, Postgres>) -> Result<u64, rootcause::Report> {+ let written = sqlx::query!(+ r#"INSERT INTO comms_message_threads (+ root_id, parent_entity_type, parent_entity_id, user_id, resolved,+ import_metadata, created_at, updated_at, deleted_at+ )+ SELECT root.id,+ CASE WHEN t.contact_id IS NULL THEN 'crm_company' ELSE 'crm_contact' END,+ COALESCE(t.contact_id, t.company_id)::text,+ t.owner, t.resolved,+ jsonb_build_object('source', 'crm_thread', 'legacy_thread_id', t.id),+ t.created_at, t.updated_at, t.deleted_at+ FROM crm_thread t+ CROSS JOIN LATERAL (+ SELECT c.id FROM crm_comment c+ WHERE c.thread_id = t.id+ ORDER BY c.created_at, c.id+ LIMIT 1+ ) root+ ON CONFLICT (root_id) DO UPDATE SET+ user_id = EXCLUDED.user_id,+ resolved = EXCLUDED.resolved,+ import_metadata = EXCLUDED.import_metadata,+ created_at = EXCLUDED.created_at,+ updated_at = EXCLUDED.updated_at,+ deleted_at = EXCLUDED.deleted_at+ WHERE (comms_message_threads.import_metadata IS NULL+ OR (comms_message_threads.import_metadata->>'source' = 'crm_thread'+ AND comms_message_threads.updated_at <= EXCLUDED.updated_at))+ AND (comms_message_threads.import_metadata,+ comms_message_threads.user_id, comms_message_threads.resolved,+ comms_message_threads.created_at, comms_message_threads.updated_at,+ comms_message_threads.deleted_at)+ IS DISTINCT FROM+ (EXCLUDED.import_metadata, EXCLUDED.user_id, EXCLUDED.resolved,+ EXCLUDED.created_at, EXCLUDED.updated_at, EXCLUDED.deleted_at)"#+ )+ .execute(&mut **tx)+ .await?+ .rows_affected();+ Ok(written)+}++async fn invariants(tx: &mut Transaction<'_, Postgres>) -> Result<Invariants, rootcause::Report> {+ let row = sqlx::query!(+ r#"WITH legacy AS (+ SELECT c.id, c.text, c.owner, c.created_at, c.updated_at,+ COALESCE(c.deleted_at, t.deleted_at) AT TIME ZONE 'UTC' AS deleted_at,+ CASE WHEN t.contact_id IS NULL THEN 'crm_company' ELSE 'crm_contact' END AS parent_type,+ COALESCE(t.contact_id, t.company_id)::text AS parent_id,+ NULLIF(first_value(c.id) OVER (PARTITION BY c.thread_id ORDER BY c.created_at, c.id), c.id) AS root_id+ FROM crm_comment c+ JOIN crm_thread t ON t.id = c.thread_id+ )+ SELECT+ count(*) FILTER (WHERE m.id IS NULL) AS "missing_messages!",+ count(*) FILTER (+ WHERE m.id IS NOT NULL+ AND (m.parent_entity_type, m.parent_entity_id, m.thread_id)+ IS DISTINCT FROM (l.parent_type, l.parent_id, l.root_id)+ ) AS "misplaced_messages!",+ count(*) FILTER (+ WHERE m.id IS NOT NULL AND l.root_id IS NULL+ AND NOT EXISTS (SELECT 1 FROM comms_message_threads th WHERE th.root_id = m.id)+ ) AS "roots_without_threads!",+ count(*) FILTER (+ WHERE m.updated_at <= l.updated_at+ AND (m.content, m.sender_id, m.created_at, m.deleted_at)+ IS DISTINCT FROM (l.text, l.owner, l.created_at, l.deleted_at)+ ) AS "content_mismatches!"+ FROM legacy l+ LEFT JOIN comms_messages m ON m.id = l.id"#+ )+ .fetch_one(&mut **tx)+ .await?;+ Ok(Invariants {+ missing_messages: row.missing_messages,+ misplaced_messages: row.misplaced_messages,+ roots_without_threads: row.roots_without_threads,+ content_mismatches: row.content_mismatches,+ })+}diff --git a/crates/macro_db_migrator/src/bin/crm_comment_import/test.rs b/crates/macro_db_migrator/src/bin/crm_comment_import/test.rsnew file mode 100644index 0000000000..195a017c62--- /dev/null+++ b/crates/macro_db_migrator/src/bin/crm_comment_import/test.rs@@ -0,0 +1,452 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_uuid::Uuid;+use serde_json::{Value, json};+use sqlx::PgPool;++const OWNER: &str = "macro|[email protected]";+const MEMBER: &str = "macro|[email protected]";++struct Crm {+ company: Uuid,+ contact: Uuid,+}++async fn user(pool: &PgPool, id: &str) {+ let macro_user = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $3)",+ )+ .bind(macro_user)+ .bind(id)+ .bind(format!("stripe_{macro_user}"))+ .execute(pool)+ .await+ .unwrap();+ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#)+ .bind(id)+ .bind(macro_user)+ .execute(pool)+ .await+ .unwrap();+}++async fn crm(pool: &PgPool) -> Crm {+ user(pool, OWNER).await;+ user(pool, MEMBER).await;+ let team = Uuid::now_v7();+ sqlx::query("INSERT INTO team (id, name, owner_id) VALUES ($1, 'team', $2)")+ .bind(team)+ .bind(OWNER)+ .execute(pool)+ .await+ .unwrap();+ let company = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO crm_companies (id, team_id, email_sync, first_interaction, last_interaction)+ VALUES ($1, $2, true, now(), now())",+ )+ .bind(company)+ .bind(team)+ .execute(pool)+ .await+ .unwrap();+ let contact = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction)+ VALUES ($1, $2, '[email protected]', now(), now())",+ )+ .bind(contact)+ .bind(company)+ .execute(pool)+ .await+ .unwrap();+ Crm { company, contact }+}++enum Record {+ Company(Uuid),+ Contact(Uuid),+}++async fn thread(pool: &PgPool, record: Record, owner: &str, resolved: bool) -> Uuid {+ let (company, contact) = match record {+ Record::Company(id) => (Some(id), None),+ Record::Contact(id) => (None, Some(id)),+ };+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO crm_thread (id, company_id, contact_id, owner, resolved, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, now() - interval '3 hours', now() - interval '3 hours')",+ )+ .bind(id)+ .bind(company)+ .bind(contact)+ .bind(owner)+ .bind(resolved)+ .execute(pool)+ .await+ .unwrap();+ id+}++/// A comment created `hours_ago`, last updated `updated_hours_ago`.+async fn comment(+ pool: &PgPool,+ thread: Uuid,+ owner: &str,+ text: &str,+ hours_ago: i32,+ updated_hours_ago: i32,+) -> Uuid {+ let id = Uuid::now_v7();+ sqlx::query(+ "INSERT INTO crm_comment (id, thread_id, owner, sender, text, created_at, updated_at)+ VALUES ($1, $2, $3, $3, $4,+ now() - make_interval(hours => $5), now() - make_interval(hours => $6))",+ )+ .bind(id)+ .bind(thread)+ .bind(owner)+ .bind(text)+ .bind(hours_ago)+ .bind(updated_hours_ago)+ .execute(pool)+ .await+ .unwrap();+ id+}++#[derive(Debug, PartialEq)]+struct Stored {+ parent: (String, String),+ thread_id: Option<Uuid>,+ sender: String,+ content: String,+ edited: bool,+ deleted: bool,+ import_metadata: Option<Value>,+}++async fn message(pool: &PgPool, id: Uuid) -> Stored {+ let row: (+ String,+ String,+ Option<Uuid>,+ String,+ String,+ bool,+ bool,+ Option<Value>,+ ) = sqlx::query_as(+ "SELECT parent_entity_type, parent_entity_id, thread_id, sender_id, content,+ edited_at IS NOT NULL, deleted_at IS NOT NULL, import_metadata+ FROM comms_messages WHERE id = $1",+ )+ .bind(id)+ .fetch_one(pool)+ .await+ .unwrap();+ Stored {+ parent: (row.0, row.1),+ thread_id: row.2,+ sender: row.3,+ content: row.4,+ edited: row.5,+ deleted: row.6,+ import_metadata: row.7,+ }+}++#[derive(Debug, PartialEq)]+struct StoredThread {+ parent: (String, String),+ user_id: String,+ resolved: bool,+ deleted: bool,+}++async fn stored_thread(pool: &PgPool, root: Uuid) -> Option<StoredThread> {+ sqlx::query_as::<_, (String, String, String, bool, bool)>(+ "SELECT parent_entity_type, parent_entity_id, user_id, resolved, deleted_at IS NOT NULL+ FROM comms_message_threads WHERE root_id = $1",+ )+ .bind(root)+ .fetch_optional(pool)+ .await+ .unwrap()+ .map(|row| StoredThread {+ parent: (row.0, row.1),+ user_id: row.2,+ resolved: row.3,+ deleted: row.4,+ })+}++async fn message_count(pool: &PgPool) -> i64 {+ sqlx::query_scalar("SELECT count(*) FROM comms_messages")+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn legacy_threads_become_discussions_keyed_by_their_first_comment(pool: PgPool) {+ let crm = crm(&pool).await;+ let company_thread = thread(&pool, Record::Company(crm.company), OWNER, true).await;+ let root = comment(&pool, company_thread, OWNER, "root", 3, 3).await;+ let edited_reply = comment(&pool, company_thread, MEMBER, "edited reply", 2, 1).await;+ let contact_thread = thread(&pool, Record::Contact(crm.contact), MEMBER, false).await;+ let contact_root = comment(&pool, contact_thread, MEMBER, "on the contact", 2, 2).await;+ let deleted_reply = comment(&pool, contact_thread, OWNER, "gone", 1, 1).await;+ sqlx::query("UPDATE crm_comment SET deleted_at = now() WHERE id = $1")+ .bind(deleted_reply)+ .execute(&pool)+ .await+ .unwrap();++ let mut connection = pool.acquire().await.unwrap();+ let report = run(&mut connection).await.unwrap();++ assert_eq!(report.blockers, Blockers::default());+ assert_eq!(report.invariants, Invariants::default());+ assert_eq!(report.pending_comments, 4);+ assert_eq!((report.messages_inserted, report.messages_updated), (4, 0));+ assert_eq!(report.threads_written, 2);++ let company = ("crm_company".to_owned(), crm.company.to_string());+ let contact = ("crm_contact".to_owned(), crm.contact.to_string());+ assert_eq!(+ message(&pool, root).await,+ Stored {+ parent: company.clone(),+ thread_id: None,+ sender: OWNER.to_owned(),+ content: "root".to_owned(),+ edited: false,+ deleted: false,+ import_metadata: Some(+ json!({"source": "crm_comment", "legacy_thread_id": company_thread})+ ),+ }+ );+ assert_eq!(+ message(&pool, edited_reply).await,+ Stored {+ parent: company.clone(),+ thread_id: Some(root),+ sender: MEMBER.to_owned(),+ content: "edited reply".to_owned(),+ edited: true,+ deleted: false,+ import_metadata: Some(+ json!({"source": "crm_comment", "legacy_thread_id": company_thread})+ ),+ }+ );+ assert_eq!(message(&pool, contact_root).await.parent, contact);+ let deleted = message(&pool, deleted_reply).await;+ assert_eq!(+ (deleted.thread_id, deleted.deleted),+ (Some(contact_root), true)+ );++ assert_eq!(+ stored_thread(&pool, root).await,+ Some(StoredThread {+ parent: company,+ user_id: OWNER.to_owned(),+ resolved: true,+ deleted: false,+ })+ );+ assert_eq!(+ stored_thread(&pool, contact_root).await,+ Some(StoredThread {+ parent: contact,+ user_id: MEMBER.to_owned(),+ resolved: false,+ deleted: false,+ })+ );+ assert_eq!(stored_thread(&pool, edited_reply).await, None);++ let rerun = run(&mut connection).await.unwrap();+ assert_eq!(+ (rerun.pending_comments, rerun.stale_comments),+ (0, 0),+ "{rerun}"+ );+ assert_eq!(+ (+ rerun.messages_inserted,+ rerun.messages_updated,+ rerun.threads_written+ ),+ (0, 0, 0)+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_deleted_legacy_thread_deletes_every_message(pool: PgPool) {+ let crm = crm(&pool).await;+ let legacy = thread(&pool, Record::Company(crm.company), OWNER, false).await;+ let root = comment(&pool, legacy, OWNER, "root", 2, 2).await;+ let reply = comment(&pool, legacy, OWNER, "reply", 1, 1).await;+ sqlx::query("UPDATE crm_thread SET deleted_at = now() WHERE id = $1")+ .bind(legacy)+ .execute(&pool)+ .await+ .unwrap();++ let mut connection = pool.acquire().await.unwrap();+ run(&mut connection).await.unwrap();++ assert!(message(&pool, root).await.deleted);+ assert!(message(&pool, reply).await.deleted);+ assert!(stored_thread(&pool, root).await.unwrap().deleted);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn newer_legacy_rows_update_and_newer_store_rows_win(pool: PgPool) {+ let crm = crm(&pool).await;+ let legacy = thread(&pool, Record::Company(crm.company), OWNER, false).await;+ let root = comment(&pool, legacy, OWNER, "root", 2, 2).await;+ let reply = comment(&pool, legacy, OWNER, "reply", 1, 1).await;+ let mut connection = pool.acquire().await.unwrap();+ run(&mut connection).await.unwrap();++ sqlx::query("UPDATE crm_comment SET text = 'edited in legacy' WHERE id = $1")+ .bind(root)+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query("UPDATE crm_thread SET resolved = true WHERE id = $1")+ .bind(legacy)+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query(+ "UPDATE comms_messages SET content = 'edited in store', updated_at = now() + interval '1 hour'+ WHERE id = $1",+ )+ .bind(reply)+ .execute(&pool)+ .await+ .unwrap();++ let check = check(&mut connection).await.unwrap();+ assert_eq!(check.stale_comments, 1);+ assert_eq!(check.invariants.content_mismatches, 1);++ let report = run(&mut connection).await.unwrap();+ assert_eq!((report.messages_inserted, report.messages_updated), (0, 1));+ assert_eq!(report.threads_written, 1);+ assert_eq!(report.invariants, Invariants::default());+ let root = message(&pool, root).await;+ assert_eq!(+ (root.content.as_str(), root.edited),+ ("edited in legacy", true)+ );+ assert_eq!(message(&pool, reply).await.content, "edited in store");+ assert!(+ stored_thread(&pool, root_id(&pool, legacy).await)+ .await+ .unwrap()+ .resolved+ );+}++async fn root_id(pool: &PgPool, legacy_thread: Uuid) -> Uuid {+ sqlx::query_scalar(+ "SELECT root_id FROM comms_message_threads+ WHERE import_metadata->>'legacy_thread_id' = $1::text",+ )+ .bind(legacy_thread)+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn unrepresentable_legacy_rows_block_the_whole_import(pool: PgPool) {+ let crm = crm(&pool).await;+ let legacy = thread(&pool, Record::Company(crm.company), OWNER, false).await;+ comment(&pool, legacy, OWNER, "fine", 2, 2).await;+ let foreign = comment(&pool, legacy, OWNER, "sent for someone", 1, 1).await;+ sqlx::query("UPDATE crm_comment SET sender = $2 WHERE id = $1")+ .bind(foreign)+ .bind(MEMBER)+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query("UPDATE crm_thread SET metadata = '{}' WHERE id = $1")+ .bind(legacy)+ .execute(&pool)+ .await+ .unwrap();++ let mut connection = pool.acquire().await.unwrap();+ let error = run(&mut connection).await.unwrap_err();++ assert!(error.to_string().contains("preflight blocked"), "{error}");+ assert_eq!(message_count(&pool).await, 0);+ let report = check(&mut connection).await.unwrap();+ assert_eq!(+ report.blockers,+ Blockers {+ metadata: 1,+ foreign_senders: 1,+ explicit_order: 0,+ id_collisions: 0,+ }+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_comment_id_used_by_another_message_blocks_the_import(pool: PgPool) {+ let crm = crm(&pool).await;+ let legacy = thread(&pool, Record::Company(crm.company), OWNER, false).await;+ let id = comment(&pool, legacy, OWNER, "legacy", 1, 1).await;+ sqlx::query(+ "INSERT INTO comms_messages (id, parent_entity_type, parent_entity_id, sender_id, content)+ VALUES ($1, 'crm_company', $2, $3, 'posted through the store')",+ )+ .bind(id)+ .bind(crm.company.to_string())+ .bind(OWNER)+ .execute(&pool)+ .await+ .unwrap();++ let mut connection = pool.acquire().await.unwrap();+ assert!(run(&mut connection).await.is_err());++ assert_eq!(+ check(&mut connection).await.unwrap().blockers.id_collisions,+ 1+ );+ assert_eq!(message(&pool, id).await.content, "posted through the store");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn check_writes_nothing_and_empty_threads_are_skipped(pool: PgPool) {+ let crm = crm(&pool).await;+ thread(&pool, Record::Company(crm.company), OWNER, false).await;+ let legacy = thread(&pool, Record::Contact(crm.contact), OWNER, false).await;+ comment(&pool, legacy, OWNER, "only comment", 1, 1).await;++ let mut connection = pool.acquire().await.unwrap();+ let report = check(&mut connection).await.unwrap();+ assert_eq!((report.pending_comments, report.empty_threads), (1, 1));+ assert_eq!(report.invariants.missing_messages, 1);+ assert_eq!(message_count(&pool).await, 0);++ let report = run(&mut connection).await.unwrap();+ assert_eq!(report.threads_written, 1);+ let threads: i64 = sqlx::query_scalar("SELECT count(*) FROM comms_message_threads")+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(threads, 1);+}diff --git a/crates/messages/src/domain/api.rs b/crates/messages/src/domain/api.rsindex 4207effb10..5d42470e0c 100644--- a/crates/messages/src/domain/api.rs+++ b/crates/messages/src/domain/api.rs@@ -41,6 +41,9 @@ pub trait MessageReader: Send + Sync + 'static {id: i64,is_thread: bool,) -> Result<Message, MessageError>;+ /// The parent a live message belongs to, for adapters addressed only by+ /// message id. Grants nothing: callers mint the parent's receipt before any read.+ async fn parent_of(&self, id: Uuid) -> Result<Option<MessageParent>, MessageError>;}/// Conversation mutations under a verified actor and parent capability.@@ -145,6 +148,9 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageReader for MessageSe) -> Result<Message, MessageError> {MessageService::resolve_legacy(self, access, id, is_thread).await}+ async fn parent_of(&self, id: Uuid) -> Result<Option<MessageParent>, MessageError> {+ MessageService::parent_of(self, id).await+ }}#[async_trait::async_trait]@@ -243,6 +249,8 @@ mockall::mock! {) -> Result<Vec<Message>, MessageError>;/// Read an old link under current parent access.async fn resolve_legacy(&self, access: EntityAccessReceipt<MessageView>, id: i64, is_thread: bool) -> Result<Message, MessageError>;+ /// The parent a message belongs to, for id-addressed adapters.+ async fn parent_of(&self, id: Uuid) -> Result<Option<MessageParent>, MessageError>;}#[async_trait::async_trait]impl MessageCommands for MessageServiceApi {diff --git a/crates/messages/src/domain/ports.rs b/crates/messages/src/domain/ports.rsindex d116240905..9320f8c78a 100644--- a/crates/messages/src/domain/ports.rs+++ b/crates/messages/src/domain/ports.rs@@ -306,6 +306,14 @@ pub trait MessageRepository: Send + Sync + 'static {id: i64,is_thread: bool,) -> impl Future<Output = Result<Option<Uuid>, MessageError>> + Send;+ /// The parent a live message belongs to; `None` once it is deleted. Grants+ /// nothing: it only tells an id-addressed adapter which parent receipt to mint.+ fn parent_of(+ &self,+ _id: Uuid,+ ) -> impl Future<Output = Result<Option<MessageParent>, MessageError>> + Send {+ async { Ok(None) }+ }}/// Publish committed changes, deriving delivery policy from the persisted parent.diff --git a/crates/messages/src/domain/service.rs b/crates/messages/src/domain/service.rsindex d5683afa82..6db09ccd9c 100644--- a/crates/messages/src/domain/service.rs+++ b/crates/messages/src/domain/service.rs@@ -489,6 +489,13 @@ impl<R: MessageRepository, E: MessageEventPublisher> MessageService<R, E> {Ok(state)}+ /// The parent a live message belongs to, so an adapter addressed only by+ /// message id can mint that parent's receipt. Grants nothing on its own.+ #[tracing::instrument(err, skip(self))]+ pub async fn parent_of(&self, id: Uuid) -> Result<Option<MessageParent>, MessageError> {+ self.repo.parent_of(id).await+ }+/// Resolve an old link through the sole message store under current parent access.#[tracing::instrument(err, skip(self, access))]pub async fn resolve_legacy(diff --git a/crates/messages/src/outbound/pg_message_repo.rs b/crates/messages/src/outbound/pg_message_repo.rsindex 41e3903b7d..ab8ace2a6a 100644--- a/crates/messages/src/outbound/pg_message_repo.rs+++ b/crates/messages/src/outbound/pg_message_repo.rs@@ -791,6 +791,22 @@ impl MessageRepository for PgMessageRepository {.await}+ async fn parent_of(&self, id: Uuid) -> Result<Option<MessageParent>, MessageError> {+ let row = sqlx::query!(+ "SELECT parent_entity_type, parent_entity_id FROM comms_messages+ WHERE id = $1 AND deleted_at IS NULL",+ id+ )+ .fetch_optional(&self.pool)+ .await+ .map_err(database_error)?;+ row.map(|row| {+ MessageParent::parse(&row.parent_entity_type, &row.parent_entity_id)+ .map_err(|_| MessageError::Invalid("stored message has an invalid parent"))+ })+ .transpose()+ }+async fn resolve_legacy(&self,parent: &MessageParent,diff --git a/crates/messages/src/outbound/pg_message_repo/test.rs b/crates/messages/src/outbound/pg_message_repo/test.rsindex c56ba3e05b..d802ef8c50 100644--- a/crates/messages/src/outbound/pg_message_repo/test.rs+++ b/crates/messages/src/outbound/pg_message_repo/test.rs@@ -1251,3 +1251,26 @@ async fn highlight_threads_read_the_text_the_highlight_covers(pool: PgPool) {.unwrap();assert_eq!(patched.anchor, anchor(covered, Some("edited words")));}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn parent_of_names_only_a_live_message_parent(pool: PgPool) {+ setup(&pool).await;+ let repo = PgMessageRepository::new(pool.clone());+ let parent = MessageParent::parse("document", "message-doc-a").unwrap();+ let root = repo+ .create(command("message-doc-a", None, "root"))+ .await+ .unwrap();+ let reply = repo+ .create(command("message-doc-a", Some(root.id), "reply"))+ .await+ .unwrap();++ assert_eq!(+ repo.parent_of(reply.id).await.unwrap(),+ Some(parent.clone())+ );+ repo.delete(&parent, reply.id).await.unwrap();+ assert_eq!(repo.parent_of(reply.id).await.unwrap(), None);+ assert_eq!(repo.parent_of(Uuid::now_v7()).await.unwrap(), None);+}diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 9d1f4b84b2..acd61cc340 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -1014,8 +1014,8 @@ export class Sdk extends HeyApiClient {}/**- * 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+ * Delete a CRM comment, scoped to the requesting user's team. Deleting a+ * thread's first comment deletes the whole discussion, as on documents* (reported via `threadDeleted`).*/public deleteCrmComment<ThrowOnError extends boolean = false>(options: Options<DeleteCrmCommentData, ThrowOnError>): RequestResult<DeleteCrmCommentResponses, DeleteCrmCommentErrors, ThrowOnError> {diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 6aecef0c5a..ca23c8b4af 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -3470,7 +3470,7 @@ export type CreateCommentResponse = CommentThread & {*/export type CreateCrmCommentRequest = {/**- * Arbitrary client metadata for the comment.+ * Ignored: messages keep no client metadata.*/metadata?: unknown;/**@@ -3483,8 +3483,7 @@ export type CreateCrmCommentRequest = {*/threadId?: string | null;/**- * Metadata to set on a newly created thread (ignored when replying- * without a value).+ * Ignored: discussions keep no thread metadata.*/threadMetadata?: unknown;};@@ -4483,8 +4482,8 @@ export type DeleteCommentResponse = {};/**- * 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).+ * Outcome of deleting a CRM comment: reports whether its discussion went with+ * it (it does when the deleted comment was the discussion's first).*/export type DeleteCrmCommentResult = {/**@@ -4492,8 +4491,8 @@ export type DeleteCrmCommentResult = {*/commentId: string;/**- * Whether the thread itself was soft-deleted because no live comments- * remained.+ * Whether the whole discussion was deleted because the comment was its+ * first.*/threadDeleted: boolean;/**diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 2470085cb8..b78a547f99 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -6270,7 +6270,7 @@"/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`).",+ "summary": "Delete a CRM comment, scoped to the requesting user's team. Deleting a\nthread's first comment deletes the whole discussion, as on documents\n(reported via `threadDeleted`).","operationId": "delete_crm_comment","parameters": [{@@ -20487,7 +20487,7 @@"required": ["text"],"properties": {"metadata": {- "description": "Arbitrary client metadata for the comment."+ "description": "Ignored: messages keep no client metadata."},"text": {"type": "string",@@ -20499,7 +20499,7 @@"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)."+ "description": "Ignored: discussions keep no thread metadata."}}},@@ -21795,7 +21795,7 @@},"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).",+ "description": "Outcome of deleting a CRM comment: reports whether its discussion went with\nit (it does when the deleted comment was the discussion's first).","required": ["commentId", "threadId", "threadDeleted"],"properties": {"commentId": {@@ -21805,7 +21805,7 @@},"threadDeleted": {"type": "boolean",- "description": "Whether the thread itself was soft-deleted because no live comments\nremained."+ "description": "Whether the whole discussion was deleted because the comment was its\nfirst."},"threadId": {"type": "string",diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex a922b5b321..4e268ccd54 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -1734,6 +1734,7 @@ async fn run() -> anyhow::Result<()> {)),entity_access_service: entity_access_service.clone(),authorization_state: authorization_state.clone(),+ messages: message_service.clone(),},};