Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(crm): contact GET, soft-hide cascade, visibility-only sync (#3690)

Evan Hutnik9e3aa5aff24c
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
index b1406ce95b..2e56fe676b 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponse.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/crmContactResponse.ts
@@ -18,6 +18,11 @@ export interface CrmContactResponse {
email: string;
/** Earliest known interaction with this contact. */
firstInteraction: string;
+ /** Whether the contact is hidden from CRM listings for the
+requesting team. Non-admin viewers never see `hidden = true`
+rows (the endpoint filters them out); admin/owner callers see
+hidden contacts so they can render the right toggle state. */
+ hidden: boolean;
/** The id of the contact record. */
id: string;
/** Most recent known interaction with this contact. */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/setCompanyHiddenRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/setCompanyHiddenRequest.ts
index 8f20918b02..b7518d615e 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/setCompanyHiddenRequest.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/setCompanyHiddenRequest.ts
@@ -10,9 +10,12 @@
*/
export interface SetCompanyHiddenRequest {
/** New value for `crm_companies.hidden`. Setting to `true` hides
-the company from CRM listings AND disables `email_sync` (which
-permanently deletes the company's contacts and contact sources).
-Setting to `false` un-hides the company; `email_sync` is left
-untouched and the team must re-enable it explicitly. */
+the company from CRM listings, disables `email_sync`, and
+soft-hides every contact under it (`crm_contacts.hidden = true`).
+Contact rows and `crm_contact_sources` are preserved across the
+cycle, so un-hide is a true reverse. Setting to `false`
+un-hides the company and soft-restores its contacts;
+`email_sync` is left untouched and the team must re-enable it
+explicitly. */
hidden: boolean;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/setEmailSyncRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/setEmailSyncRequest.ts
index be1a9a4181..eaccba20b8 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/setEmailSyncRequest.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/setEmailSyncRequest.ts
@@ -9,7 +9,11 @@
* Request body for `PUT /crm/companies/{company_id}/email-sync`.
*/
export interface SetEmailSyncRequest {
- /** New value for `crm_companies.email_sync`. Setting to `false`
-permanently deletes the company's CRM contacts and contact sources. */
+ /** New value for `crm_companies.email_sync`. Purely a read-side
+visibility/permission gate — `soup` queries and email-permission
+checks require `email_sync = true` before exposing the
+company's emails team-wide. Populate continues to write CRM
+history regardless, so toggling never destroys data and
+re-enabling never requires a backfill. */
email_sync: boolean;
}
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 25acd6adf2..e1381d06ca 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -2902,10 +2902,12 @@ export const createCrmCommentResponse = zod
);
/**
- * @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 []`.
+ * @summary List the 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). Non-admin viewers also 404 on
+hidden companies and see only non-hidden contacts; admin/owner
+viewers reach hidden companies and see every owned contact
+regardless of `hidden` so they can render the right unhide UI.
*/
export const listCompanyContactsParams = zod.object({
company_id: zod.uuid().describe('The CRM company whose contacts to list'),
@@ -2923,6 +2925,11 @@ export const listCompanyContactsResponseItem = zod
firstInteraction: zod.iso
.datetime({})
.describe('Earliest known interaction with this contact.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the contact is hidden from CRM listings for the\nrequesting team. Non-admin viewers never see `hidden = true`\nrows (the endpoint filters them out); admin\/owner callers see\nhidden contacts so they can render the right toggle state.'
+ ),
id: zod.uuid().describe('The id of the contact record.'),
lastInteraction: zod.iso
.datetime({})
@@ -2943,9 +2950,9 @@ export const listCompanyContactsResponse = zod.array(
);
/**
- * @summary Toggle `email_sync` on a CRM company. `false` disables CRM email
-sharing for the company and permanently removes its existing CRM
-contacts and contact sources.
+ * @summary Toggle `email_sync` on a CRM company. Purely a visibility flag —
+it gates whether team members can see each other's emails with
+this company. Existing CRM data is unaffected.
*/
export const setEmailSyncParams = zod.object({
company_id: zod.uuid().describe('The CRM company to update'),
@@ -2956,7 +2963,7 @@ export const setEmailSyncBody = zod
email_sync: zod
.boolean()
.describe(
- "New value for `crm_companies.email_sync`. Setting to `false`\npermanently deletes the company's CRM contacts and contact sources."
+ "New value for `crm_companies.email_sync`. Purely a read-side\nvisibility\/permission gate — `soup` queries and email-permission\nchecks require `email_sync = true` before exposing the\ncompany's emails team-wide. Populate continues to write CRM\nhistory regardless, so toggling never destroys data and\nre-enabling never requires a backfill."
),
})
.describe(
@@ -2964,8 +2971,11 @@ export const setEmailSyncBody = zod
);
/**
- * @summary Toggle `hidden` on a CRM company. Hiding also disables `email_sync`
-and cascades to clearing the company's contacts and contact sources.
+ * @summary Toggle `hidden` on a CRM company. Hiding also disables
+`email_sync` and soft-hides every contact under the company.
+Un-hide restores contact visibility only; `email_sync` is left
+untouched (the team must re-enable it explicitly). Contact rows
+and contact sources survive the cycle.
*/
export const setCompanyHiddenParams = zod.object({
company_id: zod.uuid().describe('The CRM company to update'),
@@ -2976,11 +2986,55 @@ export const setCompanyHiddenBody = zod
hidden: zod
.boolean()
.describe(
- "New value for `crm_companies.hidden`. Setting to `true` hides\nthe company from CRM listings AND disables `email_sync` (which\npermanently deletes the company's contacts and contact sources).\nSetting to `false` un-hides the company; `email_sync` is left\nuntouched and the team must re-enable it explicitly."
+ 'New value for `crm_companies.hidden`. Setting to `true` hides\nthe company from CRM listings, disables `email_sync`, and\nsoft-hides every contact under it (`crm_contacts.hidden = true`).\nContact rows and `crm_contact_sources` are preserved across the\ncycle, so un-hide is a true reverse. Setting to `false`\nun-hides the company and soft-restores its contacts;\n`email_sync` is left untouched and the team must re-enable it\nexplicitly.'
),
})
.describe('Request body for `PUT \/companies\/{company_id}\/hidden`.');
+/**
+ * @summary Fetch a single CRM contact by id, scoped to the requesting user's
+team. Returns 404 when the contact doesn't exist or isn't owned by
+the team. Non-admin viewers also 404 on hidden contacts or hidden
+parent companies (so existence doesn't leak); admin/owner viewers
+reach every owned contact regardless of `hidden`.
+ */
+export const getContactParams = zod.object({
+ contact_id: zod.uuid().describe('The CRM contact to fetch'),
+});
+
+export const getContactResponse = 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.'),
+ hidden: zod
+ .boolean()
+ .describe(
+ 'Whether the contact is hidden from CRM listings for the\nrequesting team. Non-admin viewers never see `hidden = true`\nrows (the endpoint filters them out); admin\/owner callers see\nhidden contacts so they can render the right toggle state.'
+ ),
+ 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`.'
+ );
+
/**
* @summary Toggle `hidden` on a CRM contact. Hiding is a display-only opt-out
scoped to the team that owns the contact's company.
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 41da0d798d..f420651a34 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -3736,7 +3736,7 @@
"/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 []`.",
+ "summary": "List the contacts of a CRM company, scoped to the requesting user's\nteam. Returns 404 when the company isn't owned by the team (so\nexistence doesn't leak across teams). Non-admin viewers also 404 on\nhidden companies and see only non-hidden contacts; admin/owner\nviewers reach hidden companies and see every owned contact\nregardless of `hidden` so they can render the right unhide UI.",
"operationId": "list_company_contacts",
"parameters": [
{
@@ -3800,7 +3800,7 @@
"/crm/companies/{company_id}/email-sync": {
"put": {
"tags": ["crm::inbound::axum_router::set_email_sync"],
- "summary": "Toggle `email_sync` on a CRM company. `false` disables CRM email\nsharing for the company and permanently removes its existing CRM\ncontacts and contact sources.",
+ "summary": "Toggle `email_sync` on a CRM company. Purely a visibility flag —\nit gates whether team members can see each other's emails with\nthis company. Existing CRM data is unaffected.",
"operationId": "set_email_sync",
"parameters": [
{
@@ -3874,7 +3874,7 @@
"/crm/companies/{company_id}/hidden": {
"put": {
"tags": ["crm::inbound::axum_router::set_company_hidden"],
- "summary": "Toggle `hidden` on a CRM company. Hiding also disables `email_sync`\nand cascades to clearing the company's contacts and contact sources.",
+ "summary": "Toggle `hidden` on a CRM company. Hiding also disables\n`email_sync` and soft-hides every contact under the company.\nUn-hide restores contact visibility only; `email_sync` is left\nuntouched (the team must re-enable it explicitly). Contact rows\nand contact sources survive the cycle.",
"operationId": "set_company_hidden",
"parameters": [
{
@@ -3935,6 +3935,67 @@
}
}
},
+ "/crm/contacts/{contact_id}": {
+ "get": {
+ "tags": ["crm::inbound::axum_router::get_contact"],
+ "summary": "Fetch a single CRM contact by id, scoped to the requesting user's\nteam. Returns 404 when the contact doesn't exist or isn't owned by\nthe team. Non-admin viewers also 404 on hidden contacts or hidden\nparent companies (so existence doesn't leak); admin/owner viewers\nreach every owned contact regardless of `hidden`.",
+ "operationId": "get_contact",
+ "parameters": [
+ {
+ "name": "contact_id",
+ "in": "path",
+ "description": "The CRM contact to fetch",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$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/contacts/{contact_id}/hidden": {
"put": {
"tags": ["crm::inbound::axum_router::set_contact_hidden"],
@@ -10877,6 +10938,7 @@
"id",
"companyId",
"email",
+ "hidden",
"firstInteraction",
"lastInteraction",
"createdAt",
@@ -10902,6 +10964,10 @@
"format": "date-time",
"description": "Earliest known interaction with this contact."
},
+ "hidden": {
+ "type": "boolean",
+ "description": "Whether the contact is hidden from CRM listings for the\nrequesting team. Non-admin viewers never see `hidden = true`\nrows (the endpoint filters them out); admin/owner callers see\nhidden contacts so they can render the right toggle state."
+ },
"id": {
"type": "string",
"format": "uuid",
@@ -15314,7 +15380,7 @@
"properties": {
"hidden": {
"type": "boolean",
- "description": "New value for `crm_companies.hidden`. Setting to `true` hides\nthe company from CRM listings AND disables `email_sync` (which\npermanently deletes the company's contacts and contact sources).\nSetting to `false` un-hides the company; `email_sync` is left\nuntouched and the team must re-enable it explicitly."
+ "description": "New value for `crm_companies.hidden`. Setting to `true` hides\nthe company from CRM listings, disables `email_sync`, and\nsoft-hides every contact under it (`crm_contacts.hidden = true`).\nContact rows and `crm_contact_sources` are preserved across the\ncycle, so un-hide is a true reverse. Setting to `false`\nun-hides the company and soft-restores its contacts;\n`email_sync` is left untouched and the team must re-enable it\nexplicitly."
}
}
},
@@ -15336,7 +15402,7 @@
"properties": {
"email_sync": {
"type": "boolean",
- "description": "New value for `crm_companies.email_sync`. Setting to `false`\npermanently deletes the company's CRM contacts and contact sources."
+ "description": "New value for `crm_companies.email_sync`. Purely a read-side\nvisibility/permission gate — `soup` queries and email-permission\nchecks require `email_sync = true` before exposing the\ncompany's emails team-wide. Populate continues to write CRM\nhistory regardless, so toggling never destroys data and\nre-enabling never requires a backfill."
}
}
},
diff --git a/rust/cloud-storage/.sqlx/query-0a4ef2f94648e1a6de6dad96e942a9b987f96526f5865fcc9c43f6179567a891.json b/rust/cloud-storage/.sqlx/query-0a4ef2f94648e1a6de6dad96e942a9b987f96526f5865fcc9c43f6179567a891.json
new file mode 100644
index 0000000000..cbaea857b8
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-0a4ef2f94648e1a6de6dad96e942a9b987f96526f5865fcc9c43f6179567a891.json
@@ -0,0 +1,72 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n ct.id,\n ct.company_id,\n ct.email,\n ct.name,\n ct.hidden,\n ct.first_interaction,\n ct.last_interaction,\n ct.created_at,\n ct.updated_at\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n WHERE ct.id = $1\n AND co.team_id = $2\n AND ($3 OR (ct.hidden = FALSE AND co.hidden = FALSE))\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": "hidden",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
+ "name": "first_interaction",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "last_interaction",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "0a4ef2f94648e1a6de6dad96e942a9b987f96526f5865fcc9c43f6179567a891"
+}
diff --git a/rust/cloud-storage/.sqlx/query-1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c.json b/rust/cloud-storage/.sqlx/query-1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c.json
deleted file mode 100644
index 43eff5a888..0000000000
--- a/rust/cloud-storage/.sqlx/query-1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM crm_contact_sources\n WHERE contact_id IN (\n SELECT id FROM crm_contacts WHERE company_id = $1\n )\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "1e615fa31568d6c34562bfcddcb0bf15bc140116859a9af9e09dc1374f79629c"
-}
diff --git a/rust/cloud-storage/.sqlx/query-2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b.json b/rust/cloud-storage/.sqlx/query-2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b.json
deleted file mode 100644
index d12d20bcdf..0000000000
--- a/rust/cloud-storage/.sqlx/query-2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO crm_contacts (company_id, email, name, first_interaction, last_interaction)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (company_id, email) DO UPDATE\n SET name = COALESCE(crm_contacts.name, EXCLUDED.name),\n updated_at = now(),\n first_interaction = CASE\n WHEN $6 THEN LEAST(crm_contacts.first_interaction, EXCLUDED.first_interaction)\n ELSE crm_contacts.first_interaction\n END,\n last_interaction = GREATEST(crm_contacts.last_interaction, EXCLUDED.last_interaction)\n RETURNING id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Timestamptz",
- "Timestamptz",
- "Bool"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "2194bac364c297d48f6b8a5b196418b06f71f933fc2a9ecb5d04beb2c07fd35b"
-}
diff --git a/rust/cloud-storage/.sqlx/query-2db06a8049c3fa54997e62b47e3862e24a45c9278ff5671e190b594d0972946f.json b/rust/cloud-storage/.sqlx/query-2db06a8049c3fa54997e62b47e3862e24a45c9278ff5671e190b594d0972946f.json
new file mode 100644
index 0000000000..7115b37189
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2db06a8049c3fa54997e62b47e3862e24a45c9278ff5671e190b594d0972946f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT hidden FROM crm_companies WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "hidden",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "2db06a8049c3fa54997e62b47e3862e24a45c9278ff5671e190b594d0972946f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-30d2fd821db0a5161001069fa193d3fc449e51d833bb5b5b4df5904007bdd6a0.json b/rust/cloud-storage/.sqlx/query-30d2fd821db0a5161001069fa193d3fc449e51d833bb5b5b4df5904007bdd6a0.json
deleted file mode 100644
index bffb5c1c7a..0000000000
--- a/rust/cloud-storage/.sqlx/query-30d2fd821db0a5161001069fa193d3fc449e51d833bb5b5b4df5904007bdd6a0.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "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-ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8.json b/rust/cloud-storage/.sqlx/query-3dd2c8152498a2183ff2a944699251aaeac0e320a02b2504b1bc74402ad894cd.json
similarity index 66%
rename from rust/cloud-storage/.sqlx/query-ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8.json
rename to rust/cloud-storage/.sqlx/query-3dd2c8152498a2183ff2a944699251aaeac0e320a02b2504b1bc74402ad894cd.json
index 48d35a1bb7..3bfa3d5798 100644
--- a/rust/cloud-storage/.sqlx/query-ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8.json
+++ b/rust/cloud-storage/.sqlx/query-3dd2c8152498a2183ff2a944699251aaeac0e320a02b2504b1bc74402ad894cd.json
@@ -1,6 +1,6 @@
{
"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 ",
+ "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\n AND co.team_id = $2\n AND ($4 OR co.hidden = FALSE)\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\n AND co2.team_id = $2\n AND ($4 OR (ct.hidden = FALSE AND co2.hidden = FALSE))\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": [
{
@@ -58,7 +58,8 @@
"Left": [
"Uuid",
"Uuid",
- "Text"
+ "Text",
+ "Bool"
]
},
"nullable": [
@@ -74,5 +75,5 @@
true
]
},
- "hash": "ac97a0c3a3884599c3e6cb44445cc09a263823432506cf86961d68ea124ef1b8"
+ "hash": "3dd2c8152498a2183ff2a944699251aaeac0e320a02b2504b1bc74402ad894cd"
}
diff --git a/rust/cloud-storage/.sqlx/query-ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935.json b/rust/cloud-storage/.sqlx/query-40980d3ade1b42b14019fa0add93fb37a8a26d78f4e275d9bca1ebaa7e558f6b.json
similarity index 50%
rename from rust/cloud-storage/.sqlx/query-ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935.json
rename to rust/cloud-storage/.sqlx/query-40980d3ade1b42b14019fa0add93fb37a8a26d78f4e275d9bca1ebaa7e558f6b.json
index f7f58d59fa..b420aa09dc 100644
--- a/rust/cloud-storage/.sqlx/query-ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935.json
+++ b/rust/cloud-storage/.sqlx/query-40980d3ade1b42b14019fa0add93fb37a8a26d78f4e275d9bca1ebaa7e558f6b.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "DELETE FROM crm_contacts WHERE company_id = $1",
+ "query": "UPDATE crm_contacts SET hidden = TRUE WHERE company_id = $1",
"describe": {
"columns": [],
"parameters": {
@@ -10,5 +10,5 @@
},
"nullable": []
},
- "hash": "ea8465e511eb18380f7a05b5c02930a31d7729c0a357e3d3c5044f2906756935"
+ "hash": "40980d3ade1b42b14019fa0add93fb37a8a26d78f4e275d9bca1ebaa7e558f6b"
}
diff --git a/rust/cloud-storage/.sqlx/query-98a5db6c9f4cdfa6f855406ad26a11600e5f84094b73f3ce359c48e60b6921be.json b/rust/cloud-storage/.sqlx/query-98a5db6c9f4cdfa6f855406ad26a11600e5f84094b73f3ce359c48e60b6921be.json
new file mode 100644
index 0000000000..936333e4c9
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-98a5db6c9f4cdfa6f855406ad26a11600e5f84094b73f3ce359c48e60b6921be.json
@@ -0,0 +1,24 @@
+{
+ "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\n AND co.team_id = $2\n AND ($3 OR co.hidden = FALSE)\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\n AND co2.team_id = $2\n AND ($3 OR (ct.hidden = FALSE AND co2.hidden = FALSE))\n )\n )\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "98a5db6c9f4cdfa6f855406ad26a11600e5f84094b73f3ce359c48e60b6921be"
+}
diff --git a/rust/cloud-storage/.sqlx/query-a119f354b9c86006d705ba3190ae786b27205399c3295d82c636d07d7308bcf0.json b/rust/cloud-storage/.sqlx/query-a119f354b9c86006d705ba3190ae786b27205399c3295d82c636d07d7308bcf0.json
new file mode 100644
index 0000000000..3e60b22c3a
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-a119f354b9c86006d705ba3190ae786b27205399c3295d82c636d07d7308bcf0.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO crm_contacts (company_id, email, name, first_interaction, last_interaction, hidden)\n VALUES ($1, $2, $3, $4, $5, $7)\n ON CONFLICT (company_id, email) DO UPDATE\n SET name = COALESCE(crm_contacts.name, EXCLUDED.name),\n updated_at = now(),\n first_interaction = CASE\n WHEN $6 THEN LEAST(crm_contacts.first_interaction, EXCLUDED.first_interaction)\n ELSE crm_contacts.first_interaction\n END,\n last_interaction = GREATEST(crm_contacts.last_interaction, EXCLUDED.last_interaction)\n RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz",
+ "Bool",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "a119f354b9c86006d705ba3190ae786b27205399c3295d82c636d07d7308bcf0"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b10ef9924835c2dce77ce8b77c877a78ca0d7a1e7efff35864c58ba34028f2e6.json b/rust/cloud-storage/.sqlx/query-b10ef9924835c2dce77ce8b77c877a78ca0d7a1e7efff35864c58ba34028f2e6.json
new file mode 100644
index 0000000000..8378b42025
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b10ef9924835c2dce77ce8b77c877a78ca0d7a1e7efff35864c58ba34028f2e6.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_contacts SET hidden = FALSE WHERE company_id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b10ef9924835c2dce77ce8b77c877a78ca0d7a1e7efff35864c58ba34028f2e6"
+}
diff --git a/rust/cloud-storage/.sqlx/query-30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51.json b/rust/cloud-storage/.sqlx/query-b3c25afc80ddf84ba0a49578a6b1d5e70039c2d64a25a54ef42b25889e75b653.json
similarity index 55%
rename from rust/cloud-storage/.sqlx/query-30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51.json
rename to rust/cloud-storage/.sqlx/query-b3c25afc80ddf84ba0a49578a6b1d5e70039c2d64a25a54ef42b25889e75b653.json
index 8d99aa7295..28de32369e 100644
--- a/rust/cloud-storage/.sqlx/query-30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51.json
+++ b/rust/cloud-storage/.sqlx/query-b3c25afc80ddf84ba0a49578a6b1d5e70039c2d64a25a54ef42b25889e75b653.json
@@ -1,6 +1,6 @@
{
"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 ",
+ "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\n AND co.team_id = $2\n AND ($3 OR (c.hidden = FALSE AND co.hidden = FALSE))\n ) AS \"exists!\"\n ",
"describe": {
"columns": [
{
@@ -12,12 +12,13 @@
"parameters": {
"Left": [
"Uuid",
- "Uuid"
+ "Uuid",
+ "Bool"
]
},
"nullable": [
null
]
},
- "hash": "30fb559248a2c9be387134727f7fb6a6f128577bf64c91c5ad68c563088dff51"
+ "hash": "b3c25afc80ddf84ba0a49578a6b1d5e70039c2d64a25a54ef42b25889e75b653"
}
diff --git a/rust/cloud-storage/.sqlx/query-c3381d086690011cad23f03e78a79a08ac84dde454e716e5d21dd52cd9b75ec6.json b/rust/cloud-storage/.sqlx/query-c3381d086690011cad23f03e78a79a08ac84dde454e716e5d21dd52cd9b75ec6.json
deleted file mode 100644
index 31b865c178..0000000000
--- a/rust/cloud-storage/.sqlx/query-c3381d086690011cad23f03e78a79a08ac84dde454e716e5d21dd52cd9b75ec6.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "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-9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e.json b/rust/cloud-storage/.sqlx/query-c777a32bdb434216895e8011885c8fa8858a6c5470f1c921ab0265cf7d1c9b2a.json
similarity index 53%
rename from rust/cloud-storage/.sqlx/query-9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e.json
rename to rust/cloud-storage/.sqlx/query-c777a32bdb434216895e8011885c8fa8858a6c5470f1c921ab0265cf7d1c9b2a.json
index 4bae9fea4c..00c9ed9c51 100644
--- a/rust/cloud-storage/.sqlx/query-9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e.json
+++ b/rust/cloud-storage/.sqlx/query-c777a32bdb434216895e8011885c8fa8858a6c5470f1c921ab0265cf7d1c9b2a.json
@@ -1,6 +1,6 @@
{
"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 ",
+ "query": "\n SELECT EXISTS (\n SELECT 1 FROM crm_companies\n WHERE id = $1\n AND team_id = $2\n AND ($3 OR hidden = FALSE)\n ) AS \"exists!\"\n ",
"describe": {
"columns": [
{
@@ -12,12 +12,13 @@
"parameters": {
"Left": [
"Uuid",
- "Uuid"
+ "Uuid",
+ "Bool"
]
},
"nullable": [
null
]
},
- "hash": "9c71c7c96d02c2b7c9a074ac6289ab2f9696648628b62910f86ba6d63a38005e"
+ "hash": "c777a32bdb434216895e8011885c8fa8858a6c5470f1c921ab0265cf7d1c9b2a"
}
diff --git a/rust/cloud-storage/.sqlx/query-cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a.json b/rust/cloud-storage/.sqlx/query-e12622009d9e824222ae86c7b823e4f4ba653a16b53f9ffb7b99566d202dbd68.json
similarity index 67%
rename from rust/cloud-storage/.sqlx/query-cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a.json
rename to rust/cloud-storage/.sqlx/query-e12622009d9e824222ae86c7b823e4f4ba653a16b53f9ffb7b99566d202dbd68.json
index e54333bbe3..41d0d39078 100644
--- a/rust/cloud-storage/.sqlx/query-cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a.json
+++ b/rust/cloud-storage/.sqlx/query-e12622009d9e824222ae86c7b823e4f4ba653a16b53f9ffb7b99566d202dbd68.json
@@ -1,6 +1,6 @@
{
"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 ",
+ "query": "\n SELECT\n id,\n company_id,\n email,\n name,\n hidden,\n first_interaction,\n last_interaction,\n created_at,\n updated_at\n FROM crm_contacts\n WHERE company_id = $1\n AND ($2 OR hidden = FALSE)\n ORDER BY LOWER(COALESCE(name, email)) ASC, id DESC\n ",
"describe": {
"columns": [
{
@@ -25,28 +25,34 @@
},
{
"ordinal": 4,
+ "name": "hidden",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 5,
"name": "first_interaction",
"type_info": "Timestamptz"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "last_interaction",
"type_info": "Timestamptz"
},
{
- "ordinal": 6,
+ "ordinal": 7,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 7,
+ "ordinal": 8,
"name": "updated_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
- "Uuid"
+ "Uuid",
+ "Bool"
]
},
"nullable": [
@@ -57,8 +63,9 @@
false,
false,
false,
+ false,
false
]
},
- "hash": "cf7829381786a1ba819cd67025d27af41e61ae7a323d29a5b7e807f34949146a"
+ "hash": "e12622009d9e824222ae86c7b823e4f4ba653a16b53f9ffb7b99566d202dbd68"
}
diff --git a/rust/cloud-storage/.sqlx/query-c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e.json b/rust/cloud-storage/.sqlx/query-ebd8690a2a7068b485816697c3d6660c82f616f8f3456a6137b872043404d282.json
similarity index 50%
rename from rust/cloud-storage/.sqlx/query-c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e.json
rename to rust/cloud-storage/.sqlx/query-ebd8690a2a7068b485816697c3d6660c82f616f8f3456a6137b872043404d282.json
index adcd04d499..d7dd77cdc8 100644
--- a/rust/cloud-storage/.sqlx/query-c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e.json
+++ b/rust/cloud-storage/.sqlx/query-ebd8690a2a7068b485816697c3d6660c82f616f8f3456a6137b872043404d282.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT c.id, c.email_sync\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",
+ "query": "\n SELECT c.id, c.hidden\n FROM crm_companies c\n JOIN crm_domains d ON d.company_id = c.id\n WHERE c.team_id = $1\n AND LOWER(d.domain) = $2\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -10,7 +10,7 @@
},
{
"ordinal": 1,
- "name": "email_sync",
+ "name": "hidden",
"type_info": "Bool"
}
],
@@ -25,5 +25,5 @@
false
]
},
- "hash": "c4896935fe37524d12c5745fdbf087d0d6bd11642a303dfc2213eaf8d6eb8e4e"
+ "hash": "ebd8690a2a7068b485816697c3d6660c82f616f8f3456a6137b872043404d282"
}
diff --git a/rust/cloud-storage/crm/src/domain/companies_repo.rs b/rust/cloud-storage/crm/src/domain/companies_repo.rs
index 31ad6d0e6d..a68f0360e7 100644
--- a/rust/cloud-storage/crm/src/domain/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/domain/companies_repo.rs
@@ -57,12 +57,12 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// disable — which flips the flag and purges `crm_companies` in
/// one tx — can't race past us and leave an orphan row.
/// 1. Look up the company for `(team_id, domain)`.
- /// - If a row exists with `email_sync = false` the team has opted
- /// this domain out (the per-domain killswitch): no rows are
- /// written and the method returns `Ok(())` so the caller can
- /// ack the job.
- /// - If a row exists with `email_sync = true` it is reused and its
- /// `updated_at` is refreshed.
+ /// - If a row exists it is reused and its `updated_at` is
+ /// refreshed. Populate runs regardless of the company's
+ /// `email_sync` — that flag is purely a visibility/permission
+ /// gate consumed at read time (soup, email permissions). The
+ /// decoupling means re-enabling sync exposes the full history
+ /// with no backfill, because the writes never stopped.
/// - Otherwise a new `crm_companies` row and a matching
/// `crm_domains` row are inserted. The company name itself
/// lives in `crm_domain_directory` keyed by `domain`, not on
@@ -104,9 +104,8 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// get `last_interaction = GREATEST(...)` only. Upsert
/// `crm_contact_sources`.
///
- /// The `email_sync=false` per-domain killswitch short-circuits in
- /// both directions. Source rows track all interactions (sent or
- /// received), not just sent — see also
+ /// Source rows track all interactions (sent or received), not
+ /// just sent — see also
/// [`CompaniesRepository::depopulate_contact`].
///
/// The caller is expected to have ensured a `crm_domain_directory`
@@ -167,12 +166,14 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// source rows remain for that contact, then `crm_companies` (cascading
/// to `crm_domains`) if no other contact rows remain for that company
/// **and** the company has `email_sync = true`. Companies with
- /// `email_sync = false` (the killswitch opt-out) are kept so the
- /// team's configuration survives teardown — a future populate will
- /// re-discover the row and short-circuit on the same flag.
+ /// `email_sync = false` are kept because that flag is an explicit
+ /// team-side opt-out (the team turned off email sharing for this
+ /// company) — preserving the row makes the choice survive a link
+ /// teardown so a future populate doesn't re-discover the company
+ /// in a "default sync = true" state.
///
/// Source and contact rows are derived data and are always cleaned
- /// up regardless of the killswitch.
+ /// up regardless of the company's `email_sync`.
///
/// The whole cascade runs in a single transaction that begins by
/// acquiring the same advisory lock [`populate_contact`] takes (key
@@ -202,8 +203,8 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// 3. Delete every `crm_companies` row in `team_id` that has no
/// remaining `crm_contacts` AND `email_sync = true`. Companies
/// with `email_sync = false` are preserved so the team's
- /// killswitch configuration survives teardown. `crm_domains`
- /// falls out via FK cascade.
+ /// explicit "off" choice survives the link teardown.
+ /// `crm_domains` falls out via FK cascade.
///
/// Scoping every query to `team_id` keeps the blast radius bounded
/// — sources the link contributed to a *different* team (from a
@@ -235,13 +236,16 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;
/// Toggle `crm_companies.email_sync` for `(company_id, team_id)`.
- /// On disable, the same tx also deletes the company's
- /// `crm_contacts` and `crm_contact_sources`. Returns
+ /// The flag is purely a **visibility/permission gate** consumed at
+ /// read time — soup queries and email-permission checks require
+ /// `email_sync = true` before exposing emails team-wide. Populate
+ /// runs regardless, so toggling this flag never destroys data and
+ /// re-enabling never requires a backfill. Returns
/// [`CrmError::CompanyNotFoundForTeam`] on a non-matching pair.
/// Refuses to set `email_sync = true` when the company has
- /// `hidden = true` (returns [`CrmError::CompanyHidden`]) — a hidden
- /// company would otherwise have populate re-create contacts under
- /// it. Un-hide first if you really want sync back on.
+ /// `hidden = true` (returns [`CrmError::CompanyHidden`]) — keeps
+ /// the "hide = full opt-out" UX (un-hide first if you really want
+ /// sync back on).
fn set_email_sync(
&self,
team_id: &uuid::Uuid,
@@ -249,16 +253,34 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
email_sync: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
- /// Toggle `crm_companies.hidden` for `(company_id, team_id)`. When
- /// `hidden = true` this also sets `email_sync = false` and tears
- /// down the company's `crm_contacts` and `crm_contact_sources` in
- /// the **same transaction**, holding the same per-`(team, domain)`
- /// advisory locks [`set_email_sync`] takes. Un-hide (`hidden =
- /// false`) only flips the flag; `email_sync` is left as-is.
+ /// Toggle `crm_companies.hidden` for `(company_id, team_id)`. The
+ /// company's contacts cascade with the flag — hide soft-hides every
+ /// `crm_contacts` row (`hidden = TRUE`) and un-hide restores them
+ /// (`hidden = FALSE`). Contact data and `crm_contact_sources` are
+ /// preserved across the cycle, so un-hide is a true reverse of
+ /// hide. The cascade overwrites individual contact-hide state set
+ /// via [`set_contact_hidden`]; un-hide blanket-resets contacts to
+ /// visible regardless of how each one got hidden.
+ ///
+ /// Hide additionally forces `email_sync = false` — purely a
+ /// product/UX coupling that says "hide = full opt-out, including
+ /// team email sharing". Populate doesn't read `email_sync`, so the
+ /// flip has no write-side effect by itself; the contact-cascade
+ /// is what stops a hidden company from accumulating visible
+ /// contacts. Un-hide leaves `email_sync` alone — re-enable
+ /// explicitly via [`set_email_sync`].
+ ///
+ /// Both branches hold the same per-`(team, domain)` advisory locks
+ /// [`populate_contact`] takes so a populate-vs-hide race can't
+ /// observe a stale `hidden` value mid-cascade — without the lock,
+ /// a populate could read `hidden = false` then write a visible
+ /// contact under a company that's about to commit `hidden = true`.
+ ///
/// Returns [`CrmError::CompanyNotFoundForTeam`] on a non-matching
/// pair.
///
/// [`set_email_sync`]: CompaniesRepository::set_email_sync
+ /// [`set_contact_hidden`]: CompaniesRepository::set_contact_hidden
fn set_company_hidden(
&self,
team_id: &uuid::Uuid,
@@ -316,20 +338,38 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
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
+ /// Lists the 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`.
+ /// exist, isn't owned by the team, or — for non-admin viewers
+ /// (`include_hidden = false`) — is hidden. With `include_hidden =
+ /// false` hidden contacts are filtered out and hidden parent
+ /// companies 404; with `include_hidden = true` (admin/owner) every
+ /// owned contact is returned and hidden parent companies are
+ /// reachable. 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,
+ include_hidden: bool,
) -> impl Future<Output = Result<Vec<CrmContact>, CrmError>> + Send;
+ /// Fetches a single CRM contact by id, scoped to `team_id` via the
+ /// contact's company. Returns `Ok(None)` when the contact doesn't
+ /// exist, belongs to a different team, or — for non-admin viewers
+ /// (`include_hidden = false`) — the contact or its parent company
+ /// is hidden. With `include_hidden = true` (admin/owner) every
+ /// owned contact is reachable. The handler converts `None` into a
+ /// 404 [`CrmError::ContactNotFoundForTeam`].
+ fn get_contact_for_team(
+ &self,
+ team_id: &uuid::Uuid,
+ contact_id: &uuid::Uuid,
+ include_hidden: bool,
+ ) -> impl Future<Output = Result<Option<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
@@ -339,6 +379,9 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// 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.
+ /// `include_hidden` mirrors the read endpoints: non-admin callers
+ /// pass `false` (cannot comment on a hidden entity); admin/owner
+ /// callers pass `true` (can comment regardless of visibility).
#[allow(clippy::too_many_arguments)]
fn create_crm_comment(
&self,
@@ -350,6 +393,7 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
thread_metadata: Option<Value>,
text: &str,
metadata: Option<Value>,
+ include_hidden: bool,
) -> impl Future<Output = Result<CrmCommentThread, CrmError>> + Send;
/// List the non-deleted comment threads on `(entity_type, entity_id)`,
@@ -358,23 +402,28 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// 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![])`.
+ /// with no threads returns `Ok(vec![])`. Hidden entities 404 for
+ /// non-admin viewers (`include_hidden = false`); admins/owners can
+ /// see threads on hidden entities (`include_hidden = true`).
fn get_crm_comment_threads(
&self,
team_id: &uuid::Uuid,
entity_type: CrmCommentEntityType,
entity_id: &uuid::Uuid,
+ include_hidden: bool,
) -> 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.
+ /// the team. `include_hidden = false` (non-admin) additionally
+ /// returns `CommentNotFound` when the parent entity is hidden.
fn edit_crm_comment(
&self,
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
text: &str,
+ include_hidden: bool,
) -> impl Future<Output = Result<CrmComment, CrmError>> + Send;
/// Soft-delete a CRM comment (sets `deleted_at`), scoped to `team_id`.
@@ -382,10 +431,13 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
/// 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.
+ /// already deleted, or isn't owned by the team. `include_hidden =
+ /// false` (non-admin) additionally returns `CommentNotFound` when
+ /// the parent entity is hidden.
fn delete_crm_comment(
&self,
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
+ include_hidden: bool,
) -> 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 889c3117c9..4acbc6ed3a 100644
--- a/rust/cloud-storage/crm/src/domain/model.rs
+++ b/rust/cloud-storage/crm/src/domain/model.rs
@@ -144,6 +144,10 @@ pub struct CrmContact {
pub email: String,
/// Display name observed for the contact, if any
pub name: Option<String>,
+ /// Whether the contact is hidden from CRM listings for the owning
+ /// team. Set via [`crate::domain::service::CrmService::set_contact_hidden`]
+ /// (individual hide) or cascaded from a company-level hide.
+ pub hidden: bool,
/// Earliest known interaction with this contact
pub first_interaction: DateTime<Utc>,
/// Most recent known interaction with this contact
diff --git a/rust/cloud-storage/crm/src/domain/service.rs b/rust/cloud-storage/crm/src/domain/service.rs
index 5ceeec2537..9a639fc919 100644
--- a/rust/cloud-storage/crm/src/domain/service.rs
+++ b/rust/cloud-storage/crm/src/domain/service.rs
@@ -26,9 +26,11 @@ pub trait CrmService: Clone + Send + Sync + 'static {
/// identified by `link_id`, for the team `team_id`. Upserts
/// `crm_companies` (+ `crm_domains`), `crm_contacts`, and
/// `crm_contact_sources` in a single transaction. The call is a
- /// no-op when either killswitch is engaged: the team-level
- /// `team_crm_settings.crm_enabled = false`, or the per-domain
- /// `crm_companies.email_sync = false` for the contact's domain.
+ /// no-op only when the team-level
+ /// `team_crm_settings.crm_enabled = false` killswitch is engaged.
+ /// The per-company `email_sync` flag is a visibility gate only —
+ /// populate writes regardless, so re-enabling sync exposes the
+ /// full history with no backfill.
///
/// `name` is the display name observed for `email` on this user's
/// link — typically `email_contacts.name`, which the caller looks up
@@ -64,13 +66,13 @@ pub trait CrmService: Clone + Send + Sync + 'static {
/// `is_sent` flags whether the populating message was sent by the
/// user. The write matrix:
///
- /// | `is_sent` | No `crm_companies` row | Existing `crm_companies` row (`email_sync=true`) |
+ /// | `is_sent` | No `crm_companies` row | Existing `crm_companies` row |
/// |---|---|---|
/// | `true` | INSERT company + contact + source; `first_interaction = $first_at`, `last_interaction = $last_at`. | UPDATE company `first=LEAST(stored, $first_at), last=GREATEST(stored, $last_at)` + upsert contact (same merge) + upsert source. |
/// | `false` | **No-op** — no domain-metadata resolve, no inserts. | UPDATE company `last=GREATEST(stored, $last_at)` only (do NOT touch `first_interaction`) + upsert contact (INSERT sets both endpoints; ON CONFLICT bumps `last` only) + upsert source. |
///
- /// The `email_sync=false` per-domain killswitch short-circuits in
- /// both directions.
+ /// `email_sync` is *not* consulted by this method — it's purely a
+ /// read-side visibility gate.
#[allow(clippy::too_many_arguments)]
fn populate_contact(
&self,
@@ -134,8 +136,9 @@ pub trait CrmService: Clone + Send + Sync + 'static {
macro_id: &str,
) -> impl Future<Output = Result<Option<uuid::Uuid>, CrmError>> + Send;
- /// Toggle `email_sync` for `(company_id, team_id)`. Disable cascades
- /// to contacts and contact_sources; see
+ /// Toggle `email_sync` for `(company_id, team_id)`. Purely a
+ /// visibility/permission flag — populate continues to write CRM
+ /// rows regardless. See
/// [`crate::domain::companies_repo::CompaniesRepository::set_email_sync`].
/// Authorization is the caller's responsibility.
fn set_email_sync(
@@ -146,12 +149,13 @@ pub trait CrmService: Clone + Send + Sync + 'static {
) -> impl Future<Output = Result<(), CrmError>> + Send;
/// Toggle the `hidden` flag on a CRM company for `(company_id,
- /// team_id)`. Hiding (`true`) also forces `email_sync = false` and
- /// tears down contacts/sources atomically; see
+ /// team_id)`. The company's contacts cascade with the flag — hide
+ /// soft-hides every contact (`hidden = TRUE`), un-hide soft-restores
+ /// them (`hidden = FALSE`). Contact rows and `crm_contact_sources`
+ /// are preserved across the cycle. Hide additionally forces
+ /// `email_sync = false`; un-hide leaves `email_sync` as-is. See
/// [`crate::domain::companies_repo::CompaniesRepository::set_company_hidden`].
- /// Un-hiding (`false`) leaves `email_sync` as-is — the team must
- /// re-enable sync explicitly. Authorization is the caller's
- /// responsibility.
+ /// Authorization is the caller's responsibility.
fn set_company_hidden(
&self,
team_id: &uuid::Uuid,
@@ -191,19 +195,38 @@ pub trait CrmService: Clone + Send + Sync + 'static {
limit: i64,
) -> impl Future<Output = Result<Vec<CrmCompanyForSoup>, CrmError>> + Send;
- /// List a company's non-hidden contacts, scoped to `team_id`. See
+ /// List a company's contacts, scoped to `team_id`. `include_hidden`
+ /// reflects the caller's role: non-admin viewers pass `false`
+ /// (hidden contacts filtered out, hidden parent companies 404);
+ /// admin/owner pass `true` (every owned contact returned, hidden
+ /// parent companies reachable). See
/// [`CompaniesRepository::list_contacts_for_company`].
fn list_contacts_for_company(
&self,
team_id: &uuid::Uuid,
company_id: &uuid::Uuid,
+ include_hidden: bool,
) -> impl Future<Output = Result<Vec<CrmContact>, CrmError>> + Send;
+ /// Fetch a single CRM contact by id, scoped to `team_id`.
+ /// `include_hidden = false` hides contacts whose own `hidden` flag
+ /// or whose parent company's `hidden` is set; `true` (admin/owner)
+ /// reveals every owned contact. See
+ /// [`CompaniesRepository::get_contact_for_team`].
+ fn get_contact_for_team(
+ &self,
+ team_id: &uuid::Uuid,
+ contact_id: &uuid::Uuid,
+ include_hidden: bool,
+ ) -> impl Future<Output = Result<Option<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.
+ /// scoping is enforced in the repository. `include_hidden` mirrors
+ /// the read side: non-admin callers can't comment on a hidden
+ /// entity (`false`); admin/owner can (`true`).
#[allow(clippy::too_many_arguments)]
fn create_crm_comment(
&self,
@@ -215,32 +238,40 @@ pub trait CrmService: Clone + Send + Sync + 'static {
thread_metadata: Option<Value>,
text: &str,
metadata: Option<Value>,
+ include_hidden: bool,
) -> impl Future<Output = Result<CrmCommentThread, CrmError>> + Send;
- /// List a CRM entity's comment threads. See
+ /// List a CRM entity's comment threads. `include_hidden` controls
+ /// whether hidden parent entities 404 (non-admin) or are
+ /// reachable (admin/owner). See
/// [`CompaniesRepository::get_crm_comment_threads`].
fn get_crm_comment_threads(
&self,
team_id: &uuid::Uuid,
entity_type: CrmCommentEntityType,
entity_id: &uuid::Uuid,
+ include_hidden: bool,
) -> impl Future<Output = Result<Vec<CrmCommentThread>, CrmError>> + Send;
- /// Edit a CRM comment's text, scoped to `team_id`. See
- /// [`CompaniesRepository::edit_crm_comment`].
+ /// Edit a CRM comment's text, scoped to `team_id`. `include_hidden
+ /// = false` (non-admin) treats comments on hidden entities as not
+ /// found. See [`CompaniesRepository::edit_crm_comment`].
fn edit_crm_comment(
&self,
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
text: &str,
+ include_hidden: bool,
) -> impl Future<Output = Result<CrmComment, CrmError>> + Send;
- /// Soft-delete a CRM comment, scoped to `team_id`. See
- /// [`CompaniesRepository::delete_crm_comment`].
+ /// Soft-delete a CRM comment, scoped to `team_id`. `include_hidden
+ /// = false` (non-admin) treats comments on hidden entities as not
+ /// found. See [`CompaniesRepository::delete_crm_comment`].
fn delete_crm_comment(
&self,
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
+ include_hidden: bool,
) -> impl Future<Output = Result<DeleteCrmCommentResult, CrmError>> + Send;
}
@@ -509,9 +540,22 @@ where
&self,
team_id: &uuid::Uuid,
company_id: &uuid::Uuid,
+ include_hidden: bool,
) -> Result<Vec<CrmContact>, CrmError> {
self.companies_repository
- .list_contacts_for_company(team_id, company_id)
+ .list_contacts_for_company(team_id, company_id, include_hidden)
+ .await
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_contact_for_team(
+ &self,
+ team_id: &uuid::Uuid,
+ contact_id: &uuid::Uuid,
+ include_hidden: bool,
+ ) -> Result<Option<CrmContact>, CrmError> {
+ self.companies_repository
+ .get_contact_for_team(team_id, contact_id, include_hidden)
.await
}
@@ -527,6 +571,7 @@ where
thread_metadata: Option<Value>,
text: &str,
metadata: Option<Value>,
+ include_hidden: bool,
) -> Result<CrmCommentThread, CrmError> {
self.companies_repository
.create_crm_comment(
@@ -538,6 +583,7 @@ where
thread_metadata,
text,
metadata,
+ include_hidden,
)
.await
}
@@ -548,9 +594,10 @@ where
team_id: &uuid::Uuid,
entity_type: CrmCommentEntityType,
entity_id: &uuid::Uuid,
+ include_hidden: bool,
) -> Result<Vec<CrmCommentThread>, CrmError> {
self.companies_repository
- .get_crm_comment_threads(team_id, entity_type, entity_id)
+ .get_crm_comment_threads(team_id, entity_type, entity_id, include_hidden)
.await
}
@@ -560,9 +607,10 @@ where
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
text: &str,
+ include_hidden: bool,
) -> Result<CrmComment, CrmError> {
self.companies_repository
- .edit_crm_comment(team_id, comment_id, text)
+ .edit_crm_comment(team_id, comment_id, text, include_hidden)
.await
}
@@ -571,9 +619,10 @@ where
&self,
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
+ include_hidden: bool,
) -> Result<DeleteCrmCommentResult, CrmError> {
self.companies_repository
- .delete_crm_comment(team_id, comment_id)
+ .delete_crm_comment(team_id, comment_id, include_hidden)
.await
}
}
@@ -681,10 +730,20 @@ impl CrmService for NoOpCrmService {
&self,
_team_id: &uuid::Uuid,
_company_id: &uuid::Uuid,
+ _include_hidden: bool,
) -> Result<Vec<CrmContact>, CrmError> {
Ok(Vec::new())
}
+ async fn get_contact_for_team(
+ &self,
+ _team_id: &uuid::Uuid,
+ _contact_id: &uuid::Uuid,
+ _include_hidden: bool,
+ ) -> Result<Option<CrmContact>, CrmError> {
+ Ok(None)
+ }
+
#[allow(clippy::too_many_arguments)]
async fn create_crm_comment(
&self,
@@ -696,6 +755,7 @@ impl CrmService for NoOpCrmService {
_thread_metadata: Option<Value>,
_text: &str,
_metadata: Option<Value>,
+ _include_hidden: bool,
) -> Result<CrmCommentThread, CrmError> {
unimplemented!("NoOpCrmService.create_crm_comment")
}
@@ -705,6 +765,7 @@ impl CrmService for NoOpCrmService {
_team_id: &uuid::Uuid,
_entity_type: CrmCommentEntityType,
_entity_id: &uuid::Uuid,
+ _include_hidden: bool,
) -> Result<Vec<CrmCommentThread>, CrmError> {
Ok(Vec::new())
}
@@ -714,6 +775,7 @@ impl CrmService for NoOpCrmService {
_team_id: &uuid::Uuid,
_comment_id: &uuid::Uuid,
_text: &str,
+ _include_hidden: bool,
) -> Result<CrmComment, CrmError> {
unimplemented!("NoOpCrmService.edit_crm_comment")
}
@@ -722,6 +784,7 @@ impl CrmService for NoOpCrmService {
&self,
_team_id: &uuid::Uuid,
_comment_id: &uuid::Uuid,
+ _include_hidden: bool,
) -> 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
index 5dd52e827d..10f27e2b2b 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/comments.rs
@@ -10,7 +10,10 @@ use axum::{
extract::{Path, State},
};
use entity_access::{
- domain::{models::MemberTeamRole, ports::EntityAccessService},
+ domain::{
+ models::{MemberTeamRole, TeamRole},
+ ports::EntityAccessService,
+ },
inbound::axum_extractors::MacroUserTeamExtractor,
};
use model_error_response::ErrorResponse;
@@ -77,10 +80,14 @@ pub async fn list_handler<C: CrmService, Eas: EntityAccessService>(
) -> 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 include_hidden = access
+ .entity_access_receipt
+ .entity_permission()
+ .allows_team_role(TeamRole::Admin);
let threads = state
.service
- .get_crm_comment_threads(&team_id, entity_type, &entity_id)
+ .get_crm_comment_threads(&team_id, entity_type, &entity_id, include_hidden)
.await?;
Ok(Json(threads))
@@ -115,6 +122,10 @@ pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
) -> Result<Json<CrmCommentThread>, CrmError> {
let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
.map_err(|_| CrmError::InvalidTeamId)?;
+ let include_hidden = access
+ .entity_access_receipt
+ .entity_permission()
+ .allows_team_role(TeamRole::Admin);
let owner = access
.entity_access_receipt
.get_authenticated_user()
@@ -138,6 +149,7 @@ pub async fn create_handler<C: CrmService, Eas: EntityAccessService>(
req.thread_metadata,
text,
req.metadata,
+ include_hidden,
)
.await?;
@@ -170,6 +182,10 @@ pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
) -> Result<Json<CrmComment>, CrmError> {
let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
.map_err(|_| CrmError::InvalidTeamId)?;
+ let include_hidden = access
+ .entity_access_receipt
+ .entity_permission()
+ .allows_team_role(TeamRole::Admin);
let text = req.text.trim();
if text.is_empty() {
@@ -180,7 +196,7 @@ pub async fn edit_handler<C: CrmService, Eas: EntityAccessService>(
let comment = state
.service
- .edit_crm_comment(&team_id, &comment_id, text)
+ .edit_crm_comment(&team_id, &comment_id, text, include_hidden)
.await?;
Ok(Json(comment))
@@ -211,10 +227,14 @@ pub async fn delete_handler<C: CrmService, Eas: EntityAccessService>(
) -> Result<Json<DeleteCrmCommentResult>, CrmError> {
let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
.map_err(|_| CrmError::InvalidTeamId)?;
+ let include_hidden = access
+ .entity_access_receipt
+ .entity_permission()
+ .allows_team_role(TeamRole::Admin);
let result = state
.service
- .delete_crm_comment(&team_id, &comment_id)
+ .delete_crm_comment(&team_id, &comment_id, include_hidden)
.await?;
Ok(Json(result))
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/get_contact.rs b/rust/cloud-storage/crm/src/inbound/axum_router/get_contact.rs
new file mode 100644
index 0000000000..b32efe8b1d
--- /dev/null
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/get_contact.rs
@@ -0,0 +1,58 @@
+use axum::{
+ Json,
+ extract::{Path, State},
+};
+use entity_access::{
+ domain::{
+ models::{MemberTeamRole, TeamRole},
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::MacroUserTeamExtractor,
+};
+use model_error_response::ErrorResponse;
+use uuid::Uuid;
+
+use crate::domain::{model::CrmError, service::CrmService};
+
+use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
+
+/// Fetch a single CRM contact by id, scoped to the requesting user's
+/// team. Returns 404 when the contact doesn't exist or isn't owned by
+/// the team. Non-admin viewers also 404 on hidden contacts or hidden
+/// parent companies (so existence doesn't leak); admin/owner viewers
+/// reach every owned contact regardless of `hidden`.
+#[utoipa::path(
+ get,
+ path = "/crm/contacts/{contact_id}",
+ operation_id = "get_contact",
+ params(
+ ("contact_id" = Uuid, Path, description = "The CRM contact to fetch"),
+ ),
+ responses(
+ (status = 200, body = CrmContactResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id))]
+pub async fn handler<C: CrmService, Eas: EntityAccessService>(
+ access: MacroUserTeamExtractor<MemberTeamRole, Eas>,
+ State(state): State<CrmRouterState<C, Eas>>,
+ Path(contact_id): Path<Uuid>,
+) -> Result<Json<CrmContactResponse>, CrmError> {
+ let team_id = macro_uuid::string_to_uuid(&access.entity_access_receipt.entity().entity_id)
+ .map_err(|_| CrmError::InvalidTeamId)?;
+ let include_hidden = access
+ .entity_access_receipt
+ .entity_permission()
+ .allows_team_role(TeamRole::Admin);
+
+ let contact = state
+ .service
+ .get_contact_for_team(&team_id, &contact_id, include_hidden)
+ .await?
+ .ok_or(CrmError::ContactNotFoundForTeam)?;
+
+ Ok(Json(contact.into()))
+}
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
index 885add7d45..631bda0d80 100644
--- 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
@@ -4,7 +4,10 @@ use axum::{
};
use chrono::{DateTime, Utc};
use entity_access::{
- domain::{models::MemberTeamRole, ports::EntityAccessService},
+ domain::{
+ models::{MemberTeamRole, TeamRole},
+ ports::EntityAccessService,
+ },
inbound::axum_extractors::MacroUserTeamExtractor,
};
use model_error_response::ErrorResponse;
@@ -31,6 +34,11 @@ pub struct CrmContactResponse {
pub email: String,
/// Display name observed for the contact, if any.
pub name: Option<String>,
+ /// Whether the contact is hidden from CRM listings for the
+ /// requesting team. Non-admin viewers never see `hidden = true`
+ /// rows (the endpoint filters them out); admin/owner callers see
+ /// hidden contacts so they can render the right toggle state.
+ pub hidden: bool,
/// Earliest known interaction with this contact.
pub first_interaction: DateTime<Utc>,
/// Most recent known interaction with this contact.
@@ -48,6 +56,7 @@ impl From<CrmContact> for CrmContactResponse {
company_id: c.company_id,
email: c.email,
name: c.name,
+ hidden: c.hidden,
first_interaction: c.first_interaction,
last_interaction: c.last_interaction,
created_at: c.created_at,
@@ -56,10 +65,12 @@ impl From<CrmContact> for CrmContactResponse {
}
}
-/// 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 []`.
+/// List the 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). Non-admin viewers also 404 on
+/// hidden companies and see only non-hidden contacts; admin/owner
+/// viewers reach hidden companies and see every owned contact
+/// regardless of `hidden` so they can render the right unhide UI.
#[utoipa::path(
get,
path = "/crm/companies/{company_id}/contacts",
@@ -82,10 +93,14 @@ pub async fn handler<C: CrmService, Eas: EntityAccessService>(
) -> 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 include_hidden = access
+ .entity_access_receipt
+ .entity_permission()
+ .allows_team_role(TeamRole::Admin);
let contacts = state
.service
- .list_contacts_for_company(&team_id, &company_id)
+ .list_contacts_for_company(&team_id, &company_id, include_hidden)
.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 e36bb7ca0a..4ad77188f4 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/mod.rs
@@ -12,6 +12,9 @@ pub mod set_contact_hidden;
/// List the non-hidden contacts of a `crm_companies` row.
pub mod list_company_contacts;
+/// Fetch a single non-hidden CRM contact by id.
+pub mod get_contact;
+
/// Comment threads on a `crm_companies` / `crm_contacts` row.
pub mod comments;
@@ -73,6 +76,10 @@ where
"/companies/{company_id}/contacts",
get(list_company_contacts::handler::<C, Eas>),
)
+ .route(
+ "/contacts/{contact_id}",
+ get(get_contact::handler::<C, Eas>),
+ )
.route(
"/contacts/{contact_id}/hidden",
put(set_contact_hidden::handler::<C, Eas>),
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs
index 33e6a84292..f706934804 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_company_hidden.rs
@@ -20,15 +20,21 @@ use super::CrmRouterState;
#[derive(Debug, Deserialize, ToSchema)]
pub struct SetCompanyHiddenRequest {
/// New value for `crm_companies.hidden`. Setting to `true` hides
- /// the company from CRM listings AND disables `email_sync` (which
- /// permanently deletes the company's contacts and contact sources).
- /// Setting to `false` un-hides the company; `email_sync` is left
- /// untouched and the team must re-enable it explicitly.
+ /// the company from CRM listings, disables `email_sync`, and
+ /// soft-hides every contact under it (`crm_contacts.hidden = true`).
+ /// Contact rows and `crm_contact_sources` are preserved across the
+ /// cycle, so un-hide is a true reverse. Setting to `false`
+ /// un-hides the company and soft-restores its contacts;
+ /// `email_sync` is left untouched and the team must re-enable it
+ /// explicitly.
pub hidden: bool,
}
-/// Toggle `hidden` on a CRM company. Hiding also disables `email_sync`
-/// and cascades to clearing the company's contacts and contact sources.
+/// Toggle `hidden` on a CRM company. Hiding also disables
+/// `email_sync` and soft-hides every contact under the company.
+/// Un-hide restores contact visibility only; `email_sync` is left
+/// untouched (the team must re-enable it explicitly). Contact rows
+/// and contact sources survive the cycle.
#[utoipa::path(
put,
path = "/crm/companies/{company_id}/hidden",
diff --git a/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs b/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs
index b770ed3a72..98586a2dda 100644
--- a/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs
+++ b/rust/cloud-storage/crm/src/inbound/axum_router/set_email_sync.rs
@@ -19,14 +19,18 @@ use super::CrmRouterState;
/// Request body for `PUT /crm/companies/{company_id}/email-sync`.
#[derive(Debug, Deserialize, ToSchema)]
pub struct SetEmailSyncRequest {
- /// New value for `crm_companies.email_sync`. Setting to `false`
- /// permanently deletes the company's CRM contacts and contact sources.
+ /// New value for `crm_companies.email_sync`. Purely a read-side
+ /// visibility/permission gate — `soup` queries and email-permission
+ /// checks require `email_sync = true` before exposing the
+ /// company's emails team-wide. Populate continues to write CRM
+ /// history regardless, so toggling never destroys data and
+ /// re-enabling never requires a backfill.
pub email_sync: bool,
}
-/// Toggle `email_sync` on a CRM company. `false` disables CRM email
-/// sharing for the company and permanently removes its existing CRM
-/// contacts and contact sources.
+/// Toggle `email_sync` on a CRM company. Purely a visibility flag —
+/// it gates whether team members can see each other's emails with
+/// this company. Existing CRM data is unaffected.
#[utoipa::path(
put,
path = "/crm/companies/{company_id}/email-sync",
diff --git a/rust/cloud-storage/crm/src/outbound/companies_repo.rs b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
index 31cc67d6a2..e166debcc0 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo.rs
@@ -66,36 +66,6 @@ impl CompaniesRepositoryImpl {
Ok(())
}
-
- /// Drop the company's sources then contacts. Caller must hold the
- /// per-domain advisory locks (see [`Self::lock_company_domains`]).
- async fn delete_company_contacts(
- tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
- company_id: &uuid::Uuid,
- ) -> Result<(), CrmError> {
- sqlx::query!(
- r#"
- DELETE FROM crm_contact_sources
- WHERE contact_id IN (
- SELECT id FROM crm_contacts WHERE company_id = $1
- )
- "#,
- company_id,
- )
- .execute(&mut **tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- sqlx::query!(
- r#"DELETE FROM crm_contacts WHERE company_id = $1"#,
- company_id,
- )
- .execute(&mut **tx)
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
-
- Ok(())
- }
}
impl CompaniesRepository for CompaniesRepositoryImpl {
@@ -215,11 +185,16 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
return Ok(());
}
- // Per-domain killswitch: existing row with email_sync=false
- // means the team has opted this domain out, no-op.
+ // Look up the existing company row (by team + lowercased
+ // domain). `email_sync` is read solely so the caller's
+ // visibility/permission gates can later check it; populate
+ // itself runs regardless. Hide is the only opt-out that
+ // affects what gets written (and even then only via the
+ // `hidden` cascade onto new contacts, not by skipping the
+ // write entirely).
let existing = sqlx::query!(
r#"
- SELECT c.id, c.email_sync
+ SELECT c.id, c.hidden
FROM crm_companies c
JOIN crm_domains d ON d.company_id = c.id
WHERE c.team_id = $1
@@ -233,14 +208,9 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- let company_id = match existing {
- Some(row) if !row.email_sync => {
- // Killswitch: domain opted out, ack and exit.
- tx.commit()
- .await
- .map_err(|e| CrmError::StorageLayerError(e.into()))?;
- return Ok(());
- }
+ // Track the company's current hidden state alongside its id so
+ // new contacts inherit it on INSERT.
+ let (company_id, company_hidden) = match existing {
Some(row) => {
// `last_interaction` always bumps via GREATEST.
// `first_interaction` only LEAST-merges on is_sent=true:
@@ -264,7 +234,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- row.id
+ (row.id, row.hidden)
}
None if !is_sent => {
// Received-direction never creates a company row.
@@ -349,9 +319,20 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- existing_company_id
+ // Race winner is already visible (no hide cascade ran
+ // since insertion); read its current hidden defensively.
+ let winner_hidden = sqlx::query_scalar!(
+ r#"SELECT hidden FROM crm_companies WHERE id = $1"#,
+ existing_company_id,
+ )
+ .fetch_one(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ (existing_company_id, winner_hidden)
} else {
- new_company.id
+ // Fresh company — defaults to hidden = FALSE.
+ (new_company.id, false)
}
}
};
@@ -359,10 +340,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
// First non-NULL name wins (COALESCE preserves existing).
// `last_interaction` always GREATEST; `first_interaction`
// LEAST-merges only on is_sent=true (mirrors company rule).
+ // New contacts inherit the company's current `hidden` so a
+ // populate-vs-hide race can't sneak a visible contact under a
+ // hidden company. On CONFLICT we leave `hidden` alone —
+ // preserves any individual `set_contact_hidden` state and any
+ // company-cascade state from a prior hide.
let contact_id = sqlx::query_scalar!(
r#"
- INSERT INTO crm_contacts (company_id, email, name, first_interaction, last_interaction)
- VALUES ($1, $2, $3, $4, $5)
+ INSERT INTO crm_contacts (company_id, email, name, first_interaction, last_interaction, hidden)
+ VALUES ($1, $2, $3, $4, $5, $7)
ON CONFLICT (company_id, email) DO UPDATE
SET name = COALESCE(crm_contacts.name, EXCLUDED.name),
updated_at = now(),
@@ -379,6 +365,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
first_at,
last_at,
is_sent,
+ company_hidden,
)
.fetch_one(&mut *tx)
.await
@@ -755,13 +742,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- if !email_sync {
- // Hold the same per-domain locks populate_contact takes so
- // an in-flight populate can't slip past our killswitch.
- Self::lock_company_domains(&mut tx, team_id, company_id).await?;
- } else {
- // Refuse enable on hidden — populate would recreate under a
- // hidden company. FOR UPDATE blocks concurrent hide.
+ if email_sync {
+ // Refuse enable on a hidden company. Populate doesn't care
+ // about either flag now, so the constraint is purely a
+ // product/UX one — "hide" should mean "team has fully
+ // opted out of this company"; enabling team-visible
+ // emails for a company the team can't see in CRM is
+ // nonsensical. Un-hide first if you really want sync on.
+ // FOR UPDATE blocks a concurrent hide flipping `hidden`
+ // out from under us between the SELECT and the UPDATE.
let row = sqlx::query!(
r#"
SELECT hidden
@@ -804,9 +793,12 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
return Err(CrmError::CompanyNotFoundForTeam);
}
- if !email_sync {
- Self::delete_company_contacts(&mut tx, company_id).await?;
- }
+ // `email_sync` is a read-side visibility/permission gate only —
+ // populate continues to write CRM history regardless of its
+ // value. Toggling this flag is therefore non-destructive in
+ // either direction. Teams that want to drop contact visibility
+ // entirely should hide the company instead; that path
+ // soft-hides contacts (preserving data for un-hide).
tx.commit()
.await
@@ -828,13 +820,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
+ // Domain locks block in-flight populates past their killswitch
+ // check on both branches (a populate racing with un-hide must
+ // not see a half-applied cascade either).
+ Self::lock_company_domains(&mut tx, team_id, company_id).await?;
+
if hidden {
// Hiding implies email_sync=false; flip both atomically.
- // Domain locks block in-flight populates past their
- // killswitch check.
- Self::lock_company_domains(&mut tx, team_id, company_id).await?;
-
- // Scoping UPDATE on both id AND team_id rejects cross-team callers as NotFound.
+ // Scoping UPDATE on both id AND team_id rejects cross-team
+ // callers as NotFound.
let updated = sqlx::query_scalar!(
r#"
UPDATE crm_companies
@@ -853,7 +847,21 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
return Err(CrmError::CompanyNotFoundForTeam);
}
- Self::delete_company_contacts(&mut tx, company_id).await?;
+ // Soft-hide every contact under this company so un-hide can
+ // restore them verbatim. Sources are preserved too — they
+ // record per-link populate provenance and shouldn't drop.
+ // Individual hides get overwritten here; the un-hide
+ // cascade likewise resets every contact to visible. This is
+ // the documented trade-off (simpler company-cascade
+ // semantics in exchange for losing individual hide state
+ // across a hide/un-hide cycle).
+ sqlx::query!(
+ r#"UPDATE crm_contacts SET hidden = TRUE WHERE company_id = $1"#,
+ company_id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
} else {
// Un-hide leaves email_sync alone; re-enable is separate.
let updated = sqlx::query_scalar!(
@@ -873,6 +881,17 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
if updated.is_none() {
return Err(CrmError::CompanyNotFoundForTeam);
}
+
+ // Cascade: every contact under the now-visible company
+ // becomes visible. Wipes individual hides — see the hide
+ // branch comment.
+ sqlx::query!(
+ r#"UPDATE crm_contacts SET hidden = FALSE WHERE company_id = $1"#,
+ company_id,
+ )
+ .execute(&mut *tx)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
}
tx.commit()
@@ -1194,26 +1213,33 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
&self,
team_id: &uuid::Uuid,
company_id: &uuid::Uuid,
+ include_hidden: bool,
) -> 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!(
+ // id belongs to another team). `include_hidden = false` (the
+ // member-role default) also treats hidden companies as not
+ // found; `include_hidden = true` (admin/owner) makes hidden
+ // companies reachable so admins can manage their contacts.
+ let visible = sqlx::query_scalar!(
r#"
SELECT EXISTS (
SELECT 1 FROM crm_companies
- WHERE id = $1 AND team_id = $2
+ WHERE id = $1
+ AND team_id = $2
+ AND ($3 OR hidden = FALSE)
) AS "exists!"
"#,
company_id,
team_id,
+ include_hidden,
)
.fetch_one(&self.pool)
.await
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
- if !owns_company {
+ if !visible {
return Err(CrmError::CompanyNotFoundForTeam);
}
@@ -1224,16 +1250,18 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
company_id,
email,
name,
+ hidden,
first_interaction,
last_interaction,
created_at,
updated_at
FROM crm_contacts
WHERE company_id = $1
- AND hidden = FALSE
+ AND ($2 OR hidden = FALSE)
ORDER BY LOWER(COALESCE(name, email)) ASC, id DESC
"#,
company_id,
+ include_hidden,
)
.fetch_all(&self.pool)
.await
@@ -1246,6 +1274,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
company_id: row.company_id,
email: row.email,
name: row.name,
+ hidden: row.hidden,
first_interaction: row.first_interaction,
last_interaction: row.last_interaction,
created_at: row.created_at,
@@ -1254,7 +1283,60 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.collect())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_contact_for_team(
+ &self,
+ team_id: &uuid::Uuid,
+ contact_id: &uuid::Uuid,
+ include_hidden: bool,
+ ) -> Result<Option<CrmContact>, CrmError> {
+ // Team scope is enforced via the company join (same pattern as
+ // set_contact_hidden). For non-admins (`include_hidden =
+ // false`), a hidden contact OR a hidden parent company is
+ // treated as "not found" so existence doesn't leak. For
+ // admin/owner (`include_hidden = true`) every owned contact is
+ // reachable so the admin can see and unhide it.
+ let row = sqlx::query!(
+ r#"
+ SELECT
+ ct.id,
+ ct.company_id,
+ ct.email,
+ ct.name,
+ ct.hidden,
+ ct.first_interaction,
+ ct.last_interaction,
+ ct.created_at,
+ ct.updated_at
+ FROM crm_contacts ct
+ JOIN crm_companies co ON co.id = ct.company_id
+ WHERE ct.id = $1
+ AND co.team_id = $2
+ AND ($3 OR (ct.hidden = FALSE AND co.hidden = FALSE))
+ "#,
+ contact_id,
+ team_id,
+ include_hidden,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ Ok(row.map(|row| CrmContact {
+ id: row.id,
+ company_id: row.company_id,
+ email: row.email,
+ name: row.name,
+ hidden: row.hidden,
+ first_interaction: row.first_interaction,
+ last_interaction: row.last_interaction,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ }))
+ }
+
#[tracing::instrument(skip(self, thread_metadata, text, metadata), err, fields(entity_id = %entity_id))]
+ #[allow(clippy::too_many_arguments)]
async fn create_crm_comment(
&self,
team_id: &uuid::Uuid,
@@ -1265,6 +1347,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
thread_metadata: Option<Value>,
text: &str,
metadata: Option<Value>,
+ include_hidden: bool,
) -> Result<CrmCommentThread, CrmError> {
// Exactly one parent column is set; the CHECK constraint enforces it.
let (company_id, contact_id) = match entity_type {
@@ -1278,9 +1361,10 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.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? {
+ // Authorize: the entity must belong to the requesting team and
+ // be reachable (visible for non-admins; any for admin/owner).
+ // Done in-tx so a concurrent teardown can't slip past us.
+ if !entity_owned_by_team(&mut *tx, team_id, entity_type, entity_id, include_hidden).await? {
return Err(entity_not_found_err(entity_type));
}
@@ -1391,8 +1475,11 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
team_id: &uuid::Uuid,
entity_type: CrmCommentEntityType,
entity_id: &uuid::Uuid,
+ include_hidden: bool,
) -> Result<Vec<CrmCommentThread>, CrmError> {
- if !entity_owned_by_team(&self.pool, team_id, entity_type, entity_id).await? {
+ if !entity_owned_by_team(&self.pool, team_id, entity_type, entity_id, include_hidden)
+ .await?
+ {
return Err(entity_not_found_err(entity_type));
}
@@ -1457,9 +1544,12 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
text: &str,
+ include_hidden: bool,
) -> 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.
+ // contact owned by the team, so cross-team edits 404. For
+ // non-admins (`include_hidden = false`) the parent must also
+ // be visible (matches the visibility rule on the read side).
let row = sqlx::query!(
r#"
UPDATE crm_comment c
@@ -1471,12 +1561,16 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
AND (
EXISTS (
SELECT 1 FROM crm_companies co
- WHERE co.id = t.company_id AND co.team_id = $2
+ WHERE co.id = t.company_id
+ AND co.team_id = $2
+ AND ($4 OR co.hidden = FALSE)
)
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
+ WHERE ct.id = t.contact_id
+ AND co2.team_id = $2
+ AND ($4 OR (ct.hidden = FALSE AND co2.hidden = FALSE))
)
)
RETURNING c.id, c.thread_id, c."order", c.owner, c.sender, c.text,
@@ -1485,6 +1579,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
comment_id,
team_id,
text,
+ include_hidden,
)
.fetch_optional(&self.pool)
.await
@@ -1512,6 +1607,7 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
&self,
team_id: &uuid::Uuid,
comment_id: &uuid::Uuid,
+ include_hidden: bool,
) -> Result<DeleteCrmCommentResult, CrmError> {
let mut tx = self
.pool
@@ -1520,7 +1616,8 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
.map_err(|e| CrmError::StorageLayerError(e.into()))?;
// Resolve the thread and authorize in one shot; absent / cross-team
- // comments are reported as not found.
+ // / (for non-admins) hidden-parent comments are reported as not
+ // found.
let thread_id = sqlx::query_scalar!(
r#"
SELECT t.id
@@ -1531,17 +1628,22 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
AND (
EXISTS (
SELECT 1 FROM crm_companies co
- WHERE co.id = t.company_id AND co.team_id = $2
+ WHERE co.id = t.company_id
+ AND co.team_id = $2
+ AND ($3 OR co.hidden = FALSE)
)
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
+ WHERE ct.id = t.contact_id
+ AND co2.team_id = $2
+ AND ($3 OR (ct.hidden = FALSE AND co2.hidden = FALSE))
)
)
"#,
comment_id,
team_id,
+ include_hidden,
)
.fetch_optional(&mut *tx)
.await
@@ -1605,14 +1707,19 @@ fn entity_not_found_err(entity_type: CrmCommentEntityType) -> CrmError {
}
}
-/// 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.
+/// Returns whether `(entity_type, entity_id)` is reachable to the caller —
+/// always requires team ownership; `include_hidden = false` (non-admin)
+/// additionally rejects hidden entities (for a contact, both the
+/// contact's own `hidden` AND its parent company's `hidden` must be
+/// false). `include_hidden = true` (admin/owner) requires only team
+/// ownership. 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,
+ include_hidden: bool,
) -> Result<bool, CrmError>
where
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
@@ -1622,11 +1729,15 @@ where
sqlx::query_scalar!(
r#"
SELECT EXISTS (
- SELECT 1 FROM crm_companies WHERE id = $1 AND team_id = $2
+ SELECT 1 FROM crm_companies
+ WHERE id = $1
+ AND team_id = $2
+ AND ($3 OR hidden = FALSE)
) AS "exists!"
"#,
entity_id,
team_id,
+ include_hidden,
)
.fetch_one(executor)
.await
@@ -1637,11 +1748,14 @@ where
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
+ WHERE c.id = $1
+ AND co.team_id = $2
+ AND ($3 OR (c.hidden = FALSE AND co.hidden = FALSE))
) AS "exists!"
"#,
entity_id,
team_id,
+ include_hidden,
)
.fetch_one(executor)
.await
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 52fd3ea29b..49ed520139 100644
--- a/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
+++ b/rust/cloud-storage/crm/src/outbound/companies_repo/test.rs
@@ -316,24 +316,29 @@ async fn returns_company_when_email_sync_is_false(pool: PgPool) -> anyhow::Resul
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn set_email_sync_disable_clears_contacts_and_sources(pool: PgPool) -> anyhow::Result<()> {
+async fn set_email_sync_disable_preserves_contacts_and_sources(pool: PgPool) -> anyhow::Result<()> {
+ // Disabling email_sync only affects read-side visibility /
+ // permission checks — it must not touch existing contacts.
+ // Populate continues to write while sync is off; visibility is
+ // controlled by `hidden`. Teams that want to drop contacts should
+ // hide the company.
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?;
- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
-
- assert_eq!(count_contacts(&pool, company_id).await?, 2);
- assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);
+ let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
let repo = CompaniesRepositoryImpl::new(pool.clone());
repo.set_email_sync(&team_id, &company_id, false).await?;
assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));
- assert_eq!(count_contacts(&pool, company_id).await?, 0);
- assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ // Contacts + sources stay put; their hidden state is untouched.
+ assert_eq!(count_contacts(&pool, company_id).await?, 2);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);
+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(false));
+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(false));
Ok(())
}
@@ -399,6 +404,8 @@ async fn set_email_sync_isolates_companies_across_teams(pool: PgPool) -> anyhow:
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn set_email_sync_disable_handles_multi_domain_company(pool: PgPool) -> anyhow::Result<()> {
+ // Multi-domain companies lock each (team, domain) on disable; the
+ // flag flips but contacts/sources/domains are preserved.
let team_id = Uuid::now_v7();
let owner_id = "macro|[email protected]";
seed_team(&pool, team_id, owner_id).await?;
@@ -412,8 +419,8 @@ async fn set_email_sync_disable_handles_multi_domain_company(pool: PgPool) -> an
repo.set_email_sync(&team_id, &company_id, false).await?;
assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));
- assert_eq!(count_contacts(&pool, company_id).await?, 0);
- assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ assert_eq!(count_contacts(&pool, company_id).await?, 2);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);
// Company + its domain rows survive the disable so future populates short-circuit.
let (domain_count,): (i64,) =
sqlx::query_as(r#"SELECT COUNT(*) FROM crm_domains WHERE company_id = $1"#)
@@ -566,16 +573,19 @@ async fn set_email_sync_disable_allowed_on_hidden_company(pool: PgPool) -> anyho
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn service_set_company_hidden_true_also_disables_email_sync(
+async fn service_set_company_hidden_true_soft_hides_contacts_and_disables_email_sync(
pool: PgPool,
) -> anyhow::Result<()> {
+ // Hide flips the company flag, forces email_sync = false, and
+ // cascades hidden = TRUE onto every contact. Contact rows AND
+ // contact_sources are preserved so un-hide can restore them.
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?;
- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
- insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ let alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
let service = CrmServiceImpl::new(
CompaniesRepositoryImpl::new(pool.clone()),
@@ -587,8 +597,45 @@ async fn service_set_company_hidden_true_also_disables_email_sync(
assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(true));
assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));
- assert_eq!(count_contacts(&pool, company_id).await?, 0);
- assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ // Contacts and sources preserved; both contacts now hidden.
+ assert_eq!(count_contacts(&pool, company_id).await?, 2);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);
+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));
+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(true));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_company_hidden_false_cascades_contacts_visible(pool: PgPool) -> anyhow::Result<()> {
+ // After un-hide, every contact under the company becomes visible —
+ // including ones an admin previously hid individually. Cascade
+ // overwrites individual hide state by design.
+ 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 alice = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ let bob = insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ // Individually hide `alice` before any company-level toggling.
+ repo.set_contact_hidden(&team_id, &alice, true).await?;
+ // Then hide the whole company (cascades `bob` to hidden too).
+ repo.set_company_hidden(&team_id, &company_id, true).await?;
+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));
+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(true));
+
+ // Un-hide cascades EVERY contact back to visible, blowing away
+ // alice's individual hide too.
+ repo.set_company_hidden(&team_id, &company_id, false)
+ .await?;
+
+ assert_eq!(fetch_company_hidden(&pool, company_id).await?, Some(false));
+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(false));
+ assert_eq!(fetch_contact_hidden(&pool, bob).await?, Some(false));
+ // Un-hide does NOT re-enable email_sync; that's a separate action.
+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));
Ok(())
}
@@ -1412,24 +1459,24 @@ async fn populate_contact_team_killswitch_off_noops_both_directions(
Ok(())
}
-/// Per-domain killswitch (`crm_companies.email_sync = false`)
-/// short-circuits populate in both directions: interaction columns
-/// stay at the stored baseline and no contact / source rows land.
+/// `email_sync = false` no longer gates populate. The flag is now
+/// purely a visibility/permission check consumed at read time
+/// (soup, email permissions). Populate updates interaction columns
+/// and writes contact / source rows just like it would with
+/// `email_sync = true`, so re-enabling sync exposes the full history
+/// with zero backfill.
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn populate_contact_per_domain_killswitch_noops_both_directions(
- pool: PgPool,
-) -> anyhow::Result<()> {
+async fn populate_contact_runs_regardless_of_email_sync_flag(pool: PgPool) -> anyhow::Result<()> {
let team_id = Uuid::now_v7();
let owner_id = "macro|[email protected]";
seed_team(&pool, team_id, owner_id).await?;
enable_crm_for_team(&pool, team_id).await?;
let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
- // Seed a killswitched company for the domain. Baseline timestamp
- // is parsed from a string so it has zero sub-microsecond precision
- // — Postgres `TIMESTAMPTZ` only stores microseconds, and
- // `chrono::Utc::now()` would carry nanos that get silently
- // truncated and break the `assert_eq` below.
+ // Seed a sync-off company. Baseline timestamp parsed from a string
+ // (no sub-microsecond precision — Postgres `TIMESTAMPTZ` only
+ // stores micros and `chrono::Utc::now()`'s nanos would get
+ // silently truncated and break the `assert_eq` below).
let company_id = insert_company(&pool, team_id, false, &["acme.com"]).await?;
let baseline: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;
sqlx::query(
@@ -1448,31 +1495,31 @@ async fn populate_contact_per_domain_killswitch_noops_both_directions(
);
let later: chrono::DateTime<chrono::Utc> = "2024-01-08T00:00:00Z".parse()?;
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ later,
+ later,
+ true,
+ )
+ .await?;
- for is_sent in [true, false] {
- service
- .populate_contact(
- &team_id,
- &link_id,
- None,
- later,
- later,
- is_sent,
- )
- .await?;
- }
-
- // Killswitch must keep the company's interaction columns at the
- // baseline and prevent contact / source inserts.
+ // Company `last_interaction` advances; first_interaction
+ // LEAST-merges on is_sent=true so it stays at the earlier
+ // baseline. Contact + source rows land regardless of email_sync.
let (first, last) = fetch_company_interactions(&pool, company_id)
.await?
.expect("company");
assert_eq!(first, baseline);
- assert_eq!(last, baseline);
- assert_eq!(count_contacts(&pool, company_id).await?, 0);
- assert_eq!(count_sources_for_company(&pool, company_id).await?, 0);
+ assert_eq!(last, later);
+ assert_eq!(count_contacts(&pool, company_id).await?, 1);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);
+ // email_sync itself is unchanged — populate never touches it.
+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));
Ok(())
}
@@ -1549,6 +1596,188 @@ async fn populate_contact_seed_style_range_merges_into_existing(
Ok(())
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn email_sync_disable_then_re_enable_preserves_full_history_with_no_backfill(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // Regression: the whole point of decoupling populate from
+ // email_sync. While sync is OFF, new emails arriving for this
+ // company must still write CRM rows. Re-enabling sync must surface
+ // the complete history without any explicit backfill step.
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+
+ // Phase 1: sync ON. First contact lands normally.
+ let t1: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ t1,
+ t1,
+ true,
+ )
+ .await?;
+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")
+ .await?
+ .expect("company");
+ assert_eq!(count_contacts(&pool, company_id).await?, 1);
+
+ // Phase 2: admin disables sync. Existing data stays put.
+ repo.set_email_sync(&team_id, &company_id, false).await?;
+ assert_eq!(count_contacts(&pool, company_id).await?, 1);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 1);
+
+ // Phase 3: a new email arrives during the sync-off window. This
+ // is the critical assertion — populate must still write the new
+ // contact + source so there's no gap to backfill later.
+ let t2: chrono::DateTime<chrono::Utc> = "2024-02-15T00:00:00Z".parse()?;
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ t2,
+ t2,
+ true,
+ )
+ .await?;
+ assert_eq!(count_contacts(&pool, company_id).await?, 2);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);
+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(false));
+
+ // Phase 4: admin re-enables sync. No backfill is run — but the
+ // history written during the off-window is already there.
+ repo.set_email_sync(&team_id, &company_id, true).await?;
+ assert_eq!(fetch_email_sync(&pool, company_id).await?, Some(true));
+ assert_eq!(count_contacts(&pool, company_id).await?, 2);
+ assert_eq!(count_sources_for_company(&pool, company_id).await?, 2);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_into_hidden_company_inserts_hidden_contact(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // Defensive: new contacts inserted into a hidden company must
+ // inherit `hidden = TRUE` so a populate-vs-hide race can't sneak a
+ // visible contact under an otherwise-hidden company. Populate
+ // doesn't itself gate on `hidden` (it always writes when the
+ // team-level CRM killswitch is on), so this is the only line of
+ // defense.
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+ let now: chrono::DateTime<chrono::Utc> = "2024-01-15T00:00:00Z".parse()?;
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ now,
+ now,
+ true,
+ )
+ .await?;
+
+ let alice = fetch_contact_id(&pool, company_id, "[email protected]")
+ .await?
+ .expect("alice should have been inserted");
+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn populate_contact_upsert_does_not_overwrite_individual_hide(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // Populate upsert (ON CONFLICT path) must preserve a contact's
+ // existing `hidden` so individual `set_contact_hidden` actions
+ // survive subsequent email activity.
+ let team_id = Uuid::now_v7();
+ let owner_id = "macro|[email protected]";
+ seed_team(&pool, team_id, owner_id).await?;
+ enable_crm_for_team(&pool, team_id).await?;
+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+ let first_at: chrono::DateTime<chrono::Utc> = "2024-01-01T00:00:00Z".parse()?;
+ let later: chrono::DateTime<chrono::Utc> = "2024-02-01T00:00:00Z".parse()?;
+
+ // Seed the contact via a normal populate.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ first_at,
+ first_at,
+ true,
+ )
+ .await?;
+ let company_id = fetch_company_for_domain(&pool, team_id, "acme.com")
+ .await?
+ .expect("company");
+ let alice = fetch_contact_id(&pool, company_id, "[email protected]")
+ .await?
+ .expect("alice");
+
+ // Admin hides alice individually.
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.set_contact_hidden(&team_id, &alice, true).await?;
+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));
+
+ // A later populate (new email from alice) must NOT un-hide her.
+ service
+ .populate_contact(
+ &team_id,
+ &link_id,
+ None,
+ later,
+ later,
+ true,
+ )
+ .await?;
+
+ assert_eq!(fetch_contact_hidden(&pool, alice).await?, Some(true));
+ 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();
@@ -1937,7 +2166,7 @@ async fn list_contacts_returns_visible_ordered_alphabetically(pool: PgPool) -> a
let repo = CompaniesRepositoryImpl::new(pool);
let contacts = repo
- .list_contacts_for_company(&team_id, &company_id)
+ .list_contacts_for_company(&team_id, &company_id, false)
.await?;
let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();
// "anna smith" (carol) < "[email protected]" (mike) < "zoe adams" (zoe)
@@ -1961,7 +2190,7 @@ async fn list_contacts_excludes_hidden(pool: PgPool) -> anyhow::Result<()> {
let repo = CompaniesRepositoryImpl::new(pool);
let contacts = repo
- .list_contacts_for_company(&team_id, &company_id)
+ .list_contacts_for_company(&team_id, &company_id, false)
.await?;
let ids: Vec<Uuid> = contacts.iter().map(|c| c.id).collect();
assert_eq!(ids, vec![visible]);
@@ -1978,7 +2207,7 @@ async fn list_contacts_owned_company_with_no_contacts_returns_empty(
let repo = CompaniesRepositoryImpl::new(pool);
let contacts = repo
- .list_contacts_for_company(&team_id, &company_id)
+ .list_contacts_for_company(&team_id, &company_id, false)
.await?;
assert!(contacts.is_empty());
Ok(())
@@ -1991,7 +2220,7 @@ async fn list_contacts_unknown_company_returns_not_found(pool: PgPool) -> anyhow
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .list_contacts_for_company(&team_id, &Uuid::now_v7())
+ .list_contacts_for_company(&team_id, &Uuid::now_v7(), false)
.await;
assert!(matches!(
result,
@@ -2012,7 +2241,9 @@ async fn list_contacts_does_not_leak_across_teams(pool: PgPool) -> anyhow::Resul
// 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;
+ let result = repo
+ .list_contacts_for_company(&team_b, &company_a, false)
+ .await;
assert!(matches!(
result,
Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
@@ -2020,85 +2251,335 @@ async fn list_contacts_does_not_leak_across_teams(pool: PgPool) -> anyhow::Resul
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<()> {
+async fn get_contact_returns_owned_visible_contact(pool: PgPool) -> anyhow::Result<()> {
let team_id = Uuid::now_v7();
- let owner = "macro|[email protected]";
- seed_team(&pool, team_id, owner).await?;
+ 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 contact_id =
+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ sqlx::query(r#"UPDATE crm_contacts SET name = 'Alice Adams' WHERE id = $1"#)
+ .bind(contact_id)
+ .execute(&pool)
+ .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?;
+ let contact = repo
+ .get_contact_for_team(&team_id, &contact_id, false)
+ .await?
+ .expect("contact should be returned");
- 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);
+ assert_eq!(contact.id, contact_id);
+ assert_eq!(contact.company_id, company_id);
+ assert_eq!(contact.email, "[email protected]");
+ assert_eq!(contact.name.as_deref(), Some("Alice Adams"));
Ok(())
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn create_crm_comment_opens_thread_on_contact(pool: PgPool) -> anyhow::Result<()> {
+async fn get_contact_returns_none_for_unknown_id(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?;
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
let repo = CompaniesRepositoryImpl::new(pool);
- let ct = repo
- .create_crm_comment(
- &team_id,
- CrmCommentEntityType::CrmContact,
- &contact_id,
- owner,
+ let result = repo
+ .get_contact_for_team(&team_id, &Uuid::now_v7(), false)
+ .await?;
+ assert!(result.is_none());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_contact_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?;
+ let contact_a = insert_contact_with_source(&pool, company_a, "[email protected]", link_a).await?;
+
+ // Team B fetching team A's contact must get None, not the row.
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .get_contact_for_team(&team_b, &contact_a, false)
+ .await?;
+ assert!(result.is_none());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_contact_returns_none_for_hidden_contact(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 contact_id =
+ 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(contact_id)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .get_contact_for_team(&team_id, &contact_id, false)
+ .await?;
+ assert!(result.is_none());
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_contact_returns_none_when_parent_company_is_hidden(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // Defensive: a non-hidden contact whose parent company is hidden
+ // must not be reachable. In practice `set_company_hidden` tears
+ // down contacts on hide, but the query enforces the invariant.
+ 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 contact_id =
+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ // Force company hidden directly (bypassing the service cascade)
+ // to simulate a stale row from a prior buggy code path.
+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .get_contact_for_team(&team_id, &contact_id, false)
+ .await?;
+ assert!(result.is_none());
+ Ok(())
+}
+
+// ---------------------------------------------------------------------------
+// Admin-visibility: include_hidden = true reveals hidden contacts /
+// hidden parent companies. Mirrors what the read handlers do when the
+// user's resolved team role is Admin or Owner.
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_contacts_admin_sees_hidden_contacts(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);
+
+ // Member: only the visible contact.
+ let member = repo
+ .list_contacts_for_company(&team_id, &company_id, false)
+ .await?;
+ let member_ids: Vec<Uuid> = member.iter().map(|c| c.id).collect();
+ assert_eq!(member_ids, vec![visible]);
+
+ // Admin: both contacts; the response carries the hidden flag so the
+ // admin UI can render the right toggle state.
+ let admin = repo
+ .list_contacts_for_company(&team_id, &company_id, true)
+ .await?;
+ let admin_ids: Vec<Uuid> = admin.iter().map(|c| c.id).collect();
+ assert_eq!(admin_ids.len(), 2);
+ assert!(admin_ids.contains(&visible));
+ assert!(admin_ids.contains(&hidden));
+ let hidden_contact = admin.iter().find(|c| c.id == hidden).expect("hidden");
+ assert!(hidden_contact.hidden);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_contacts_admin_reaches_hidden_company(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?;
+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+
+ // Member: hidden parent → 404 (CompanyNotFoundForTeam).
+ let member = repo
+ .list_contacts_for_company(&team_id, &company_id, false)
+ .await;
+ assert!(matches!(
+ member,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+
+ // Admin: the hidden company is reachable.
+ let admin = repo
+ .list_contacts_for_company(&team_id, &company_id, true)
+ .await?;
+ assert_eq!(admin.len(), 1);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_contact_admin_sees_hidden_contact(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 contact_id =
+ 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(contact_id)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+
+ // Member: hidden contact → None (404).
+ assert!(
+ repo.get_contact_for_team(&team_id, &contact_id, false)
+ .await?
+ .is_none()
+ );
+
+ // Admin: contact is reachable; response carries hidden=true.
+ let admin = repo
+ .get_contact_for_team(&team_id, &contact_id, true)
+ .await?
+ .expect("admin should see hidden contact");
+ assert_eq!(admin.id, contact_id);
+ assert!(admin.hidden);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_contact_admin_reaches_contact_under_hidden_company(
+ 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 contact_id =
+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;
+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ assert!(
+ repo.get_contact_for_team(&team_id, &contact_id, false)
+ .await?
+ .is_none()
+ );
+ let admin = repo
+ .get_contact_for_team(&team_id, &contact_id, true)
+ .await?
+ .expect("admin should reach a contact under a hidden company");
+ assert_eq!(admin.id, contact_id);
+ 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,
+ false,
+ )
+ .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,
+ false,
)
.await?;
@@ -2126,6 +2607,7 @@ async fn create_crm_comment_reply_appends_to_thread(pool: PgPool) -> anyhow::Res
None,
"root",
None,
+ false,
)
.await?;
let thread_id = root.thread.thread_id;
@@ -2139,12 +2621,18 @@ async fn create_crm_comment_reply_appends_to_thread(pool: PgPool) -> anyhow::Res
None,
"reply",
None,
+ false,
)
.await?;
// One thread, two comments, oldest-first.
let threads = repo
- .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
.await?;
assert_eq!(threads.len(), 1);
assert_eq!(threads[0].thread.thread_id, thread_id);
@@ -2171,6 +2659,7 @@ async fn create_crm_comment_unknown_company_404(pool: PgPool) -> anyhow::Result<
None,
"x",
None,
+ false,
)
.await;
assert!(matches!(
@@ -2200,6 +2689,7 @@ async fn create_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
None,
"x",
None,
+ false,
)
.await;
assert!(matches!(
@@ -2228,6 +2718,7 @@ async fn create_crm_comment_reply_to_foreign_thread_404(pool: PgPool) -> anyhow:
None,
"root",
None,
+ false,
)
.await?;
@@ -2242,6 +2733,7 @@ async fn create_crm_comment_reply_to_foreign_thread_404(pool: PgPool) -> anyhow:
None,
"reply",
None,
+ false,
)
.await;
assert!(matches!(
@@ -2259,7 +2751,12 @@ async fn get_crm_comment_threads_empty_for_owned_company(pool: PgPool) -> anyhow
let repo = CompaniesRepositoryImpl::new(pool);
let threads = repo
- .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
.await?;
assert!(threads.is_empty());
Ok(())
@@ -2272,7 +2769,12 @@ async fn get_crm_comment_threads_unknown_company_404(pool: PgPool) -> anyhow::Re
let repo = CompaniesRepositoryImpl::new(pool);
let result = repo
- .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &Uuid::now_v7())
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &Uuid::now_v7(),
+ false,
+ )
.await;
assert!(matches!(
result,
@@ -2299,17 +2801,23 @@ async fn edit_crm_comment_updates_text(pool: PgPool) -> anyhow::Result<()> {
None,
"before",
None,
+ false,
)
.await?;
let comment_id = ct.comments[0].comment_id;
let updated = repo
- .edit_crm_comment(&team_id, &comment_id, "after")
+ .edit_crm_comment(&team_id, &comment_id, "after", false)
.await?;
assert_eq!(updated.text, "after");
let threads = repo
- .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
.await?;
assert_eq!(threads[0].comments[0].text, "after");
Ok(())
@@ -2334,11 +2842,12 @@ async fn edit_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
None,
"secret",
None,
+ false,
)
.await?;
let result = repo
- .edit_crm_comment(&team_b, &ct.comments[0].comment_id, "hacked")
+ .edit_crm_comment(&team_b, &ct.comments[0].comment_id, "hacked", false)
.await;
assert!(matches!(
result,
@@ -2365,18 +2874,24 @@ async fn delete_crm_comment_removes_empty_thread(pool: PgPool) -> anyhow::Result
None,
"only comment",
None,
+ false,
)
.await?;
let result = repo
- .delete_crm_comment(&team_id, &ct.comments[0].comment_id)
+ .delete_crm_comment(&team_id, &ct.comments[0].comment_id, false)
.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)
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
.await?;
assert!(threads.is_empty());
Ok(())
@@ -2400,6 +2915,7 @@ async fn delete_crm_comment_keeps_thread_with_remaining(pool: PgPool) -> anyhow:
None,
"root",
None,
+ false,
)
.await?;
repo.create_crm_comment(
@@ -2411,17 +2927,23 @@ async fn delete_crm_comment_keeps_thread_with_remaining(pool: PgPool) -> anyhow:
None,
"reply",
None,
+ false,
)
.await?;
// Deleting the root leaves the thread alive with the reply.
let result = repo
- .delete_crm_comment(&team_id, &root.comments[0].comment_id)
+ .delete_crm_comment(&team_id, &root.comments[0].comment_id, false)
.await?;
assert!(!result.thread_deleted);
let threads = repo
- .get_crm_comment_threads(&team_id, CrmCommentEntityType::CrmCompany, &company_id)
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
.await?;
assert_eq!(threads.len(), 1);
assert_eq!(threads[0].comments.len(), 1);
@@ -2448,11 +2970,12 @@ async fn delete_crm_comment_cross_team_404(pool: PgPool) -> anyhow::Result<()> {
None,
"secret",
None,
+ false,
)
.await?;
let result = repo
- .delete_crm_comment(&team_b, &ct.comments[0].comment_id)
+ .delete_crm_comment(&team_b, &ct.comments[0].comment_id, false)
.await;
assert!(matches!(
result,
@@ -2478,6 +3001,7 @@ async fn deleting_company_cascades_to_threads(pool: PgPool) -> anyhow::Result<()
None,
"doomed",
None,
+ false,
)
.await?;
assert_eq!(count_threads(&pool).await?, 1);
@@ -2490,3 +3014,267 @@ async fn deleting_company_cascades_to_threads(pool: PgPool) -> anyhow::Result<()
assert_eq!(count_threads(&pool).await?, 0);
Ok(())
}
+
+// ---------------------------------------------------------------------------
+// Comments: admin-visibility on hidden parent entities
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_crm_comment_threads_admin_sees_hidden_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.clone());
+ // Seed a thread while the company is visible.
+ repo.create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "hi",
+ None,
+ false,
+ )
+ .await?;
+
+ // Hide the company.
+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+
+ // Member: 404 — hidden parent treated as not found.
+ let member = repo
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ false,
+ )
+ .await;
+ assert!(matches!(
+ member,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+
+ // Admin: thread is reachable.
+ let admin = repo
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ true,
+ )
+ .await?;
+ assert_eq!(admin.len(), 1);
+ assert_eq!(admin[0].comments.len(), 1);
+ assert_eq!(admin[0].comments[0].text, "hi");
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_crm_comment_blocks_member_on_hidden_entity(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?;
+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ // Member: can't write to a hidden parent.
+ let member = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "blocked",
+ None,
+ false,
+ )
+ .await;
+ assert!(matches!(
+ member,
+ Err(crate::domain::model::CrmError::CompanyNotFoundForTeam)
+ ));
+
+ // Admin: write succeeds.
+ let admin = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "ok",
+ None,
+ true,
+ )
+ .await?;
+ assert_eq!(admin.comments.len(), 1);
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn edit_delete_crm_comment_block_member_on_hidden_entity(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 thread = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmCompany,
+ &company_id,
+ owner,
+ None,
+ None,
+ "first",
+ None,
+ false,
+ )
+ .await?;
+ let comment_id = thread.comments[0].comment_id;
+
+ // Hide the company AFTER the comment was created (so a hidden-parent
+ // edit/delete is the only thing under test).
+ sqlx::query(r#"UPDATE crm_companies SET hidden = TRUE WHERE id = $1"#)
+ .bind(company_id)
+ .execute(&pool)
+ .await?;
+
+ // Member: edit and delete both 404 because the parent is hidden.
+ assert!(matches!(
+ repo.edit_crm_comment(&team_id, &comment_id, "edited", false)
+ .await,
+ Err(crate::domain::model::CrmError::CommentNotFound)
+ ));
+ assert!(matches!(
+ repo.delete_crm_comment(&team_id, &comment_id, false).await,
+ Err(crate::domain::model::CrmError::CommentNotFound)
+ ));
+
+ // Admin: edit succeeds, then delete succeeds.
+ let edited = repo
+ .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)
+ .await?;
+ assert_eq!(edited.text, "edited by admin");
+ repo.delete_crm_comment(&team_id, &comment_id, true).await?;
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn crm_comment_visibility_on_hidden_contact_with_visible_company(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ // Closes the contact-side dimension of the hide matrix:
+ // company is visible, but `crm_contacts.hidden = TRUE`. Members
+ // 404 on every read/write touching the contact; admins reach
+ // everything. Without this case the `entity_owned_by_team` helper's
+ // contact arm (which checks BOTH `c.hidden` and `co.hidden`) is
+ // only exercised end-to-end via the cascade — this pins
+ // contact-only hide as a first-class state.
+ 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.clone());
+ // Seed a thread on the contact while it's visible.
+ let thread = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmContact,
+ &contact_id,
+ owner,
+ None,
+ None,
+ "first",
+ None,
+ false,
+ )
+ .await?;
+ let comment_id = thread.comments[0].comment_id;
+
+ // Hide just the contact; parent company stays visible.
+ sqlx::query(r#"UPDATE crm_contacts SET hidden = TRUE WHERE id = $1"#)
+ .bind(contact_id)
+ .execute(&pool)
+ .await?;
+
+ // Member view: every operation on the now-hidden contact 404s.
+ let member_list = repo
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmContact,
+ &contact_id,
+ false,
+ )
+ .await;
+ assert!(matches!(
+ member_list,
+ Err(crate::domain::model::CrmError::ContactNotFoundForTeam)
+ ));
+
+ let member_create = repo
+ .create_crm_comment(
+ &team_id,
+ CrmCommentEntityType::CrmContact,
+ &contact_id,
+ owner,
+ None,
+ None,
+ "blocked",
+ None,
+ false,
+ )
+ .await;
+ assert!(matches!(
+ member_create,
+ Err(crate::domain::model::CrmError::ContactNotFoundForTeam)
+ ));
+
+ assert!(matches!(
+ repo.edit_crm_comment(&team_id, &comment_id, "edited", false)
+ .await,
+ Err(crate::domain::model::CrmError::CommentNotFound)
+ ));
+ assert!(matches!(
+ repo.delete_crm_comment(&team_id, &comment_id, false).await,
+ Err(crate::domain::model::CrmError::CommentNotFound)
+ ));
+
+ // Admin view: everything reachable. Thread + comment survive,
+ // edit + delete succeed in sequence.
+ let admin_threads = repo
+ .get_crm_comment_threads(
+ &team_id,
+ CrmCommentEntityType::CrmContact,
+ &contact_id,
+ true,
+ )
+ .await?;
+ assert_eq!(admin_threads.len(), 1);
+ assert_eq!(admin_threads[0].comments.len(), 1);
+
+ let edited = repo
+ .edit_crm_comment(&team_id, &comment_id, "edited by admin", true)
+ .await?;
+ assert_eq!(edited.text, "edited by admin");
+
+ repo.delete_crm_comment(&team_id, &comment_id, true).await?;
+ Ok(())
+}
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 f6bcb74c11..ade8d2cc5d 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -290,6 +290,7 @@ use utoipa::OpenApi;
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::get_contact::handler,
crm::inbound::axum_router::comments::list_handler,
crm::inbound::axum_router::comments::create_handler,
crm::inbound::axum_router::comments::edit_handler,