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): rename companies and contacts via inline editable title (#5102)

Evan Hutnik7d4acd20b7b1
diff --git a/.sqlx/query-a2bd7d99a2a3f896b78072bc25fd990906e7593d3f1a71fdb2199c901bbe6498.json b/.sqlx/query-a2bd7d99a2a3f896b78072bc25fd990906e7593d3f1a71fdb2199c901bbe6498.json
new file mode 100644
index 0000000000..87924fadb8
--- /dev/null
+++ b/.sqlx/query-a2bd7d99a2a3f896b78072bc25fd990906e7593d3f1a71fdb2199c901bbe6498.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE crm_contacts ct\n SET name = $3\n FROM crm_companies co\n WHERE ct.id = $1\n AND ct.company_id = co.id\n AND co.team_id = $2\n AND ($4 OR (ct.hidden = FALSE AND co.hidden = FALSE))\n RETURNING ct.id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "a2bd7d99a2a3f896b78072bc25fd990906e7593d3f1a71fdb2199c901bbe6498"
+}
diff --git a/.sqlx/query-ff120a949509f94a7f3415bc807d1011df822148f9f077d0ab676a963b616c97.json b/.sqlx/query-ff120a949509f94a7f3415bc807d1011df822148f9f077d0ab676a963b616c97.json
new file mode 100644
index 0000000000..b04bbde530
--- /dev/null
+++ b/.sqlx/query-ff120a949509f94a7f3415bc807d1011df822148f9f077d0ab676a963b616c97.json
@@ -0,0 +1,25 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE crm_companies\n SET custom_name = $3\n WHERE id = $1\n AND team_id = $2\n AND (NOT hidden OR $4)\n RETURNING id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "ff120a949509f94a7f3415bc807d1011df822148f9f077d0ab676a963b616c97"
+}
diff --git a/apps/web/src/features/companies/Company/CompanyHeader.tsx b/apps/web/src/features/companies/Company/CompanyHeader.tsx
index 1d2af06ad9..1a31e26473 100644
--- a/apps/web/src/features/companies/Company/CompanyHeader.tsx
+++ b/apps/web/src/features/companies/Company/CompanyHeader.tsx
@@ -1,5 +1,7 @@
import { EntityIcon } from '@core/component/EntityIcon';
+import { InlineTitleEditor } from '@core/component/InlineTitleEditor';
import type { CrmCompanyEntity } from '@entity';
+import { useSetCompanyNameMutation } from '@queries/crm/companies';
import { createEffect, createSignal, Show } from 'solid-js';
function Description(props: { text: string }) {
@@ -39,6 +41,22 @@ function Description(props: { text: string }) {
);
}
+// Renames write the team-scoped `custom_name` override, never the global
+// directory.
+function TitleEditor(props: { company: CrmCompanyEntity }) {
+ const renameMutation = useSetCompanyNameMutation();
+ return (
+ <InlineTitleEditor
+ value={props.company.name}
+ placeholder="Company"
+ ariaLabel="Company name"
+ onRename={(name) =>
+ renameMutation.mutate({ companyId: props.company.id, name })
+ }
+ />
+ );
+}
+
export function CompanyHeader(props: { company?: CrmCompanyEntity }) {
return (
<div class="flex items-start gap-3">
@@ -46,8 +64,10 @@ export function CompanyHeader(props: { company?: CrmCompanyEntity }) {
<EntityIcon targetType="crm_company" size="fill" />
</div>
<div class="flex min-w-0 flex-col gap-1">
- <h1 class="min-w-0 truncate text-xl font-semibold">
- {props.company ? props.company.name || 'Company' : 'Loading company…'}
+ <h1 class="min-w-0 text-xl font-semibold">
+ <Show when={props.company} fallback={'Loading company…'}>
+ {(company) => <TitleEditor company={company()} />}
+ </Show>
</h1>
<Show when={props.company?.description}>
{(description) => <Description text={description()} />}
diff --git a/apps/web/src/features/contacts/Contact/ContactHeader.tsx b/apps/web/src/features/contacts/Contact/ContactHeader.tsx
index 3ce88bd1e8..50cfff14f3 100644
--- a/apps/web/src/features/contacts/Contact/ContactHeader.tsx
+++ b/apps/web/src/features/contacts/Contact/ContactHeader.tsx
@@ -1,11 +1,34 @@
+import { InlineTitleEditor } from '@core/component/InlineTitleEditor';
import { getInitialsFromName } from '@core/user';
import { AnimatedContactIcon } from '@icon/wide-contact';
+import { useSetContactNameMutation } from '@queries/crm/contacts';
import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
import { Avatar } from '@ui';
import { Show } from 'solid-js';
+// Renames overwrite `crm_contacts.name`, which is already team-scoped —
+// no global directory involved (unlike company renames).
+function TitleEditor(props: { contact: CrmContactResponse }) {
+ const renameMutation = useSetContactNameMutation();
+ return (
+ <InlineTitleEditor
+ // Nameless contacts display their email; committing it unchanged
+ // is a no-op rather than a save.
+ value={props.contact.name ?? props.contact.email}
+ placeholder="Contact"
+ ariaLabel="Contact name"
+ onRename={(name) =>
+ renameMutation.mutate({
+ contactId: props.contact.id,
+ companyId: props.contact.companyId,
+ name,
+ })
+ }
+ />
+ );
+}
+
export function ContactHeader(props: { contact?: CrmContactResponse }) {
- const displayName = () => props.contact?.name ?? props.contact?.email;
const showSubtitle = () =>
props.contact?.name != null && props.contact.name !== props.contact.email;
@@ -35,8 +58,10 @@ export function ContactHeader(props: { contact?: CrmContactResponse }) {
</Show>
</Avatar>
<div class="flex min-w-0 flex-col gap-1">
- <h1 class="min-w-0 truncate text-xl font-semibold">
- {displayName() ?? 'Contact'}
+ <h1 class="min-w-0 text-xl font-semibold">
+ <Show when={props.contact} fallback={'Loading contact…'}>
+ {(contact) => <TitleEditor contact={contact()} />}
+ </Show>
</h1>
<Show when={showSubtitle()}>
<p class="truncate text-sm text-ink-muted">{props.contact?.email}</p>
diff --git a/apps/web/src/lib/core/component/InlineTitleEditor.tsx b/apps/web/src/lib/core/component/InlineTitleEditor.tsx
new file mode 100644
index 0000000000..5ea0e3bc4d
--- /dev/null
+++ b/apps/web/src/lib/core/component/InlineTitleEditor.tsx
@@ -0,0 +1,69 @@
+import PencilIcon from '@phosphor/pencil-simple.svg';
+import { createSignal } from 'solid-js';
+
+/**
+ * Inline-editable entity title, mirroring the markdown-document title UX:
+ * the title is always editable in place — click to put the caret in it,
+ * type, and the rename commits on blur/Enter (Escape discards). Blank or
+ * unchanged edits are dropped rather than committed.
+ */
+export function InlineTitleEditor(props: {
+ /** Current display name; shown whenever the user isn't mid-edit. */
+ value: string;
+ placeholder: string;
+ ariaLabel: string;
+ onRename: (name: string) => void;
+}) {
+ // Local draft while the user is typing; null = show the current value.
+ const [draft, setDraft] = createSignal<string | null>(null);
+ let inputRef: HTMLInputElement | undefined;
+
+ const commit = () => {
+ const raw = draft();
+ setDraft(null);
+ if (raw == null) return;
+ const next = raw.trim();
+ if (!next || next === props.value) return;
+ props.onRename(next);
+ };
+
+ return (
+ <div class="group flex min-w-0 items-center gap-1.5">
+ <input
+ ref={inputRef}
+ type="text"
+ aria-label={props.ariaLabel}
+ autocomplete="off"
+ data-1p-ignore
+ class="field-sizing-content min-w-0 max-w-full truncate bg-transparent text-xl font-semibold outline-none"
+ placeholder={props.placeholder}
+ value={draft() ?? props.value}
+ onInput={(e) => setDraft(e.currentTarget.value)}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ e.currentTarget.blur();
+ } else if (e.key === 'Escape') {
+ setDraft(null);
+ e.currentTarget.blur();
+ }
+ }}
+ />
+ {/* Hover-only affordance; the input itself is the tab stop, and the
+ pencil hides while editing (group-focus-within). */}
+ <button
+ type="button"
+ aria-hidden="true"
+ tabIndex={-1}
+ class="shrink-0 text-ink-muted opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-0"
+ onClick={() => {
+ inputRef?.focus();
+ inputRef?.select();
+ }}
+ >
+ <PencilIcon class="size-4" />
+ </button>
+ </div>
+ );
+}
diff --git a/apps/web/src/lib/queries/crm/companies.ts b/apps/web/src/lib/queries/crm/companies.ts
index b2ee466463..3ae167a533 100644
--- a/apps/web/src/lib/queries/crm/companies.ts
+++ b/apps/web/src/lib/queries/crm/companies.ts
@@ -175,6 +175,55 @@ export function useCreateContactMutation() {
}));
}
+/**
+ * Renames a company via `PUT /crm/companies/{id}/name`. The name is a
+ * team-scoped override (`crm_companies.custom_name`) that read paths resolve
+ * over the global directory name — the shared directory is never touched.
+ * Optimistically updates the company detail cache (with rollback on error) so
+ * the title flips immediately, then invalidates it plus soup so the Customers
+ * listings pick up the new name.
+ */
+export function useSetCompanyNameMutation() {
+ return useMutation(() => ({
+ mutationFn: ({ companyId, name }: { companyId: string; name: string }) =>
+ throwOnErr(() =>
+ storageServiceClient.setCompanyName({ companyId, name })
+ ),
+ onMutate: async ({ companyId, name }) => {
+ const queryKey = crmKeys.company(companyId).queryKey;
+ await queryClient.cancelQueries({ queryKey });
+ const previous = queryClient.getQueryData<CrmCompanyResponse>(queryKey);
+ if (previous) {
+ queryClient.setQueryData<CrmCompanyResponse>(queryKey, {
+ ...previous,
+ name,
+ });
+ }
+ return { previous, optimisticName: name };
+ },
+ // Roll back only if the cache still holds this mutation's optimistic
+ // name — a stale failure must not clobber a newer rename's update.
+ onError: (_err, { companyId }, context) => {
+ if (context?.previous) {
+ queryClient.setQueryData<CrmCompanyResponse>(
+ crmKeys.company(companyId).queryKey,
+ (current) =>
+ current?.name === context.optimisticName
+ ? context.previous
+ : current
+ );
+ }
+ },
+ onSettled: (_data, _err, { companyId }) =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: crmKeys.company(companyId).queryKey,
+ }),
+ queryClient.invalidateQueries({ queryKey: soupKeys._def }),
+ ]),
+ }));
+}
+
/**
* Toggles `crm_companies.hidden` via `PUT /crm/companies/{id}/hidden`. Hiding
* also disables `email_sync` and soft-hides the company's contacts; un-hide
diff --git a/apps/web/src/lib/queries/crm/contacts.ts b/apps/web/src/lib/queries/crm/contacts.ts
index bda1923399..a86e458a63 100644
--- a/apps/web/src/lib/queries/crm/contacts.ts
+++ b/apps/web/src/lib/queries/crm/contacts.ts
@@ -1,5 +1,6 @@
import { throwOnErr } from '@core/util/result';
import { storageServiceClient } from '@service-storage/client';
+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
import { useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
import { queryClient } from '../client';
@@ -33,6 +34,65 @@ export function useContactQuery(contactId: Accessor<string>) {
});
}
+/**
+ * Renames a contact via `PUT /crm/contacts/{id}/name`. Unlike company names
+ * there is no global directory involved — `crm_contacts.name` is already
+ * team-scoped, so the write is a plain overwrite. Optimistically updates the
+ * contact detail cache (with rollback on error) so the title flips
+ * immediately, then invalidates it plus the parent company (whose response
+ * embeds the contact list) and soup so every listing picks up the new name.
+ */
+export function useSetContactNameMutation() {
+ return useMutation(() => ({
+ mutationFn: ({
+ contactId,
+ name,
+ }: {
+ contactId: string;
+ companyId: string;
+ name: string;
+ }) =>
+ throwOnErr(() =>
+ storageServiceClient.setContactName({ contactId, name })
+ ),
+ onMutate: async ({ contactId, name }) => {
+ const queryKey = crmKeys.contact(contactId).queryKey;
+ await queryClient.cancelQueries({ queryKey });
+ const previous = queryClient.getQueryData<CrmContactResponse>(queryKey);
+ if (previous) {
+ queryClient.setQueryData<CrmContactResponse>(queryKey, {
+ ...previous,
+ name,
+ });
+ }
+ return { previous, optimisticName: name };
+ },
+ // Roll back only if the cache still holds this mutation's optimistic
+ // name — a stale failure must not clobber a newer rename's update.
+ onError: (_err, { contactId }, context) => {
+ if (context?.previous) {
+ queryClient.setQueryData<CrmContactResponse>(
+ crmKeys.contact(contactId).queryKey,
+ (current) =>
+ current?.name === context.optimisticName
+ ? context.previous
+ : current
+ );
+ }
+ },
+ onSettled: (_data, _err, { contactId, companyId }) =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: crmKeys.contact(contactId).queryKey,
+ }),
+ queryClient.invalidateQueries({
+ queryKey: crmKeys.company(companyId).queryKey,
+ }),
+ queryClient.invalidateQueries({ queryKey: soupKeys._def }),
+ ]),
+ }));
+}
+
/**
* Toggles `crm_contacts.hidden` via `PUT /crm/contacts/{id}/hidden`.
* Hidden contacts disappear from the parent company's contact list
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index bd6dd5b78e..932c01f95a 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -139,6 +139,8 @@ import type { Project } from './generated/schemas/project';
import type { RemoveParticipantsRequest } from './generated/schemas/removeParticipantsRequest';
import type { ReorderPinRequest } from './generated/schemas/reorderPinRequest';
import type { SaveDocumentResponseData } from './generated/schemas/saveDocumentResponseData';
+import type { SetCompanyNameRequest } from './generated/schemas/setCompanyNameRequest';
+import type { SetContactNameRequest } from './generated/schemas/setContactNameRequest';
import type { SharePermissionV2 } from './generated/schemas/sharePermissionV2';
import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';
import type { ThreadResponse } from './generated/schemas/threadResponse';
@@ -2327,6 +2329,15 @@ export const storageServiceClient = {
body: JSON.stringify({ hidden }),
});
},
+ async setContactName({
+ contactId,
+ ...body
+ }: { contactId: string } & SetContactNameRequest) {
+ return await dssFetch(`/crm/contacts/${contactId}/name`, {
+ method: 'PUT',
+ body: JSON.stringify(body),
+ });
+ },
async setCompanyHidden({
companyId,
hidden,
@@ -2339,6 +2350,15 @@ export const storageServiceClient = {
body: JSON.stringify({ hidden }),
});
},
+ async setCompanyName({
+ companyId,
+ ...body
+ }: { companyId: string } & SetCompanyNameRequest) {
+ return await dssFetch(`/crm/companies/${companyId}/name`, {
+ method: 'PUT',
+ body: JSON.stringify(body),
+ });
+ },
async setEmailSync({
companyId,
emailSync,
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 8cd126c9bc..ae1024d235 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -830,7 +830,9 @@ export * from './saveDocumentResponse';
export * from './saveDocumentResponseData';
export * from './saveDocumentResponseDataPresignedUrl';
export * from './setCompanyHiddenRequest';
+export * from './setCompanyNameRequest';
export * from './setContactHiddenRequest';
+export * from './setContactNameRequest';
export * from './setDocumentTeamShareRequest';
export * from './setEmailSyncRequest';
export * from './setPropertyValue';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/setCompanyNameRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setCompanyNameRequest.ts
new file mode 100644
index 0000000000..67ac8c9883
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setCompanyNameRequest.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for `PUT /companies/{company_id}/name`.
+ */
+export interface SetCompanyNameRequest {
+ /** New display name for the company. Stored on the team-scoped
+`crm_companies.custom_name` override, which read paths COALESCE
+over the global directory name — the shared directory is never
+modified. Must be non-blank (400 otherwise). */
+ name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/setContactNameRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setContactNameRequest.ts
new file mode 100644
index 0000000000..211e67aa0e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setContactNameRequest.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Request body for `PUT /contacts/{contact_id}/name`.
+ */
+export interface SetContactNameRequest {
+ /** New display name for the contact. Stored on `crm_contacts.name`,
+which is already team-scoped — unlike company renames no global
+directory is involved. Must be non-blank (400 otherwise). */
+ name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 3561c1ee10..fd712fc0dd 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -3561,6 +3561,27 @@ export const setCompanyHiddenBody = zod
})
.describe('Request body for `PUT \/companies\/{company_id}\/hidden`.');
+/**
+ * @summary Rename a CRM company. Access is enforced by
+[`CrmCompanyAccessLevelExtractor`]: the caller must be on the team
+that owns the company (hidden companies are reachable for
+admin/owner only). The name is a team-scoped override
+(`custom_name`) and never touches the global domain directory.
+ */
+export const setCrmCompanyNameParams = zod.object({
+ company_id: zod.uuid().describe('The CRM company to rename'),
+});
+
+export const setCrmCompanyNameBody = zod
+ .object({
+ name: zod
+ .string()
+ .describe(
+ 'New display name for the company. Stored on the team-scoped\n`crm_companies.custom_name` override, which read paths COALESCE\nover the global directory name — the shared directory is never\nmodified. Must be non-blank (400 otherwise).'
+ ),
+ })
+ .describe('Request body for `PUT \/companies\/{company_id}\/name`.');
+
/**
* @summary Fetch a single CRM contact by id. Access is enforced by
[`CrmContactAccessLevelExtractor`]: the user must be on the team that
@@ -3623,6 +3644,27 @@ export const setContactHiddenBody = zod
})
.describe('Request body for `PUT \/contacts\/{contact_id}\/hidden`.');
+/**
+ * @summary Rename a CRM contact. Access is enforced by
+[`CrmContactAccessLevelExtractor`]: the caller must be on the team
+that owns the contact's company (hidden contacts are reachable for
+admin/owner only). The name overwrites the team-scoped
+`crm_contacts.name` column.
+ */
+export const setCrmContactNameParams = zod.object({
+ contact_id: zod.uuid().describe('The CRM contact to rename'),
+});
+
+export const setCrmContactNameBody = zod
+ .object({
+ name: zod
+ .string()
+ .describe(
+ 'New display name for the contact. Stored on `crm_contacts.name`,\nwhich is already team-scoped — unlike company renames no global\ndirectory is involved. Must be non-blank (400 otherwise).'
+ ),
+ })
+ .describe('Request body for `PUT \/contacts\/{contact_id}\/name`.');
+
/**
* @summary Read the caller's team CRM configuration. Any team member may read;
teams without a settings row get the defaults.
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index ee95e0d1c5..c63e0f1294 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -4698,6 +4698,80 @@
}
}
},
+ "/crm/companies/{company_id}/name": {
+ "put": {
+ "tags": ["crm::inbound::axum_router::set_company_name"],
+ "summary": "Rename a CRM company. Access is enforced by\n[`CrmCompanyAccessLevelExtractor`]: the caller must be on the team\nthat owns the company (hidden companies are reachable for\nadmin/owner only). The name is a team-scoped override\n(`custom_name`) and never touches the global domain directory.",
+ "operationId": "set_crm_company_name",
+ "parameters": [
+ {
+ "name": "company_id",
+ "in": "path",
+ "description": "The CRM company to rename",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetCompanyNameRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "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}": {
"get": {
"tags": ["crm::inbound::axum_router::get_contact"],
@@ -4823,6 +4897,80 @@
}
}
},
+ "/crm/contacts/{contact_id}/name": {
+ "put": {
+ "tags": ["crm::inbound::axum_router::set_contact_name"],
+ "summary": "Rename a CRM contact. Access is enforced by\n[`CrmContactAccessLevelExtractor`]: the caller must be on the team\nthat owns the contact's company (hidden contacts are reachable for\nadmin/owner only). The name overwrites the team-scoped\n`crm_contacts.name` column.",
+ "operationId": "set_crm_contact_name",
+ "parameters": [
+ {
+ "name": "contact_id",
+ "in": "path",
+ "description": "The CRM contact to rename",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetContactNameRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "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/settings": {
"get": {
"tags": ["crm::inbound::axum_router::team_settings"],
@@ -18500,6 +18648,17 @@
}
}
},
+ "SetCompanyNameRequest": {
+ "type": "object",
+ "description": "Request body for `PUT /companies/{company_id}/name`.",
+ "required": ["name"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "New display name for the company. Stored on the team-scoped\n`crm_companies.custom_name` override, which read paths COALESCE\nover the global directory name — the shared directory is never\nmodified. Must be non-blank (400 otherwise)."
+ }
+ }
+ },
"SetContactHiddenRequest": {
"type": "object",
"description": "Request body for `PUT /contacts/{contact_id}/hidden`.",
@@ -18511,6 +18670,17 @@
}
}
},
+ "SetContactNameRequest": {
+ "type": "object",
+ "description": "Request body for `PUT /contacts/{contact_id}/name`.",
+ "required": ["name"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "New display name for the contact. Stored on `crm_contacts.name`,\nwhich is already team-scoped — unlike company renames no global\ndirectory is involved. Must be non-blank (400 otherwise)."
+ }
+ }
+ },
"SetDocumentTeamShareRequest": {
"type": "object",
"description": "Request body for setting a document's team-share state.",
diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rs
index 770b4b5e09..74b749db16 100644
--- a/crates/crm/src/domain/companies_repo.rs
+++ b/crates/crm/src/domain/companies_repo.rs
@@ -385,6 +385,24 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
+ /// Set the team-scoped display-name override
+ /// (`crm_companies.custom_name`) for `(company_id, team_id)`. Read
+ /// paths COALESCE the override over the global
+ /// `crm_domain_directory` name, so the new name takes effect on
+ /// every listing/search immediately; the directory itself is never
+ /// touched (it is global across teams). `include_hidden` mirrors
+ /// the other write paths: `false` (member) callers can't reach
+ /// hidden companies. Returns
+ /// [`CrmError::CompanyNotFoundForTeam`] when the company doesn't
+ /// exist, belongs to another team, or is hidden from the caller.
+ fn set_company_custom_name(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ name: &str,
+ include_hidden: bool,
+ ) -> impl Future<Output = Result<(), CrmError>> + Send;
+
/// Toggle `crm_contacts.hidden` for `contact_id`, scoped to
/// `team_id` via the contact's company. Returns
/// [`CrmError::ContactNotFoundForTeam`] when the contact does not
@@ -396,6 +414,25 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
+ /// Set `crm_contacts.name` for `contact_id`, scoped to `team_id`
+ /// via the contact's company. Unlike company names there is no
+ /// global directory involved — `name` is already a team-scoped
+ /// column — so this is a plain overwrite. `include_hidden` mirrors
+ /// the read paths ([`get_contact_for_team`]): `false` (member)
+ /// callers can't reach a hidden contact or a contact under a
+ /// hidden company. Returns [`CrmError::ContactNotFoundForTeam`]
+ /// when the contact doesn't exist, belongs to another team, or is
+ /// hidden from the caller.
+ ///
+ /// [`get_contact_for_team`]: CompaniesRepository::get_contact_for_team
+ fn set_contact_name(
+ &self,
+ team_id: &uuid::Uuid,
+ contact_id: &uuid::Uuid,
+ name: &str,
+ include_hidden: bool,
+ ) -> impl Future<Output = Result<(), CrmError>> + Send;
+
/// Batched authorization probe for a CRM-scoped email query. Returns
/// per-input status the email service maps into typed `EmailErr`
/// variants (`CrmDomainNotFound`, `CrmDomainNotPermitted`,
diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rs
index e08ecc2124..ef54f371fa 100644
--- a/crates/crm/src/domain/service.rs
+++ b/crates/crm/src/domain/service.rs
@@ -216,6 +216,22 @@ pub trait CrmService: Clone + Send + Sync + 'static {
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
+ /// Set the team-scoped display-name override for the company
+ /// addressed by `access` (`crm_companies.custom_name`, which every
+ /// read path COALESCEs over the global directory name). Any team
+ /// member who can see the company may rename it — the same access
+ /// model as [`CrmService::create_contact`]; the receipt's role
+ /// decides whether a hidden company is reachable. The name is
+ /// validated like the creation flows (non-blank, within a sane
+ /// length; [`CrmError::InvalidRequest`] otherwise) and is never
+ /// written to the global `crm_domain_directory`. See
+ /// [`crate::domain::companies_repo::CompaniesRepository::set_company_custom_name`].
+ fn set_company_name(
+ &self,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
+ name: &str,
+ ) -> impl Future<Output = Result<(), CrmError>> + Send;
+
/// Toggle the `hidden` flag on the contact addressed by `access`.
/// Hiding is a display-only opt-out and does not affect
/// populate/depopulate.
@@ -225,6 +241,21 @@ pub trait CrmService: Clone + Send + Sync + 'static {
hidden: bool,
) -> impl Future<Output = Result<(), CrmError>> + Send;
+ /// Set the display name for the contact addressed by `access`
+ /// (`crm_contacts.name` — already team-scoped, so unlike company
+ /// renames no global directory is involved). Any team member who
+ /// can see the contact may rename it — the same access model as
+ /// [`CrmService::set_company_name`]; the receipt's role decides
+ /// whether a hidden contact is reachable. The name is validated
+ /// like the creation flows (non-blank, within a sane length;
+ /// [`CrmError::InvalidRequest`] otherwise). See
+ /// [`crate::domain::companies_repo::CompaniesRepository::set_contact_name`].
+ fn set_contact_name(
+ &self,
+ access: &CrmContactReceipt<ViewAccessLevel>,
+ name: &str,
+ ) -> impl Future<Output = Result<(), CrmError>> + Send;
+
/// Batched authorization probe for a CRM-scoped email query. See
/// [`CompaniesRepository::crm_scope_precheck`].
fn crm_scope_precheck(
@@ -714,6 +745,20 @@ where
.await
}
+ #[tracing::instrument(skip(self, access), err)]
+ async fn set_company_name(
+ &self,
+ access: &CrmCompanyReceipt<ViewAccessLevel>,
+ name: &str,
+ ) -> Result<(), CrmError> {
+ let name = validate_display_name(name)?;
+ let team_id = access.team_id();
+ let company_id = access.company_id()?;
+ self.companies_repository
+ .set_company_custom_name(&team_id, &company_id, name, access.include_hidden())
+ .await
+ }
+
#[tracing::instrument(skip(self, access), err)]
async fn set_contact_hidden(
&self,
@@ -727,6 +772,20 @@ where
.await
}
+ #[tracing::instrument(skip(self, access), err)]
+ async fn set_contact_name(
+ &self,
+ access: &CrmContactReceipt<ViewAccessLevel>,
+ name: &str,
+ ) -> Result<(), CrmError> {
+ let name = validate_display_name(name)?;
+ let team_id = access.team_id();
+ let contact_id = access.contact_id()?;
+ self.companies_repository
+ .set_contact_name(&team_id, &contact_id, name, access.include_hidden())
+ .await
+ }
+
#[tracing::instrument(skip(self), err)]
async fn crm_scope_precheck(
&self,
@@ -1027,6 +1086,14 @@ impl CrmService for NoOpCrmService {
unimplemented!("NoOpCrmService.set_company_hidden")
}
+ async fn set_company_name(
+ &self,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
+ _name: &str,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.set_company_name")
+ }
+
async fn set_contact_hidden(
&self,
_access: &CrmContactReceipt<EditAccessLevel>,
@@ -1035,6 +1102,14 @@ impl CrmService for NoOpCrmService {
unimplemented!("NoOpCrmService.set_contact_hidden")
}
+ async fn set_contact_name(
+ &self,
+ _access: &CrmContactReceipt<ViewAccessLevel>,
+ _name: &str,
+ ) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmService.set_contact_name")
+ }
+
async fn crm_scope_precheck(
&self,
_team_id: &uuid::Uuid,
diff --git a/crates/crm/src/domain/service/test.rs b/crates/crm/src/domain/service/test.rs
index 920dcf7f9c..6ef4e5ba25 100644
--- a/crates/crm/src/domain/service/test.rs
+++ b/crates/crm/src/domain/service/test.rs
@@ -108,6 +108,26 @@ impl CompaniesRepository for StubRepo {
unimplemented!()
}
+ async fn set_company_custom_name(
+ &self,
+ _team_id: &uuid::Uuid,
+ _company_id: &uuid::Uuid,
+ _name: &str,
+ _include_hidden: bool,
+ ) -> Result<(), CrmError> {
+ unimplemented!()
+ }
+
+ async fn set_contact_name(
+ &self,
+ _team_id: &uuid::Uuid,
+ _contact_id: &uuid::Uuid,
+ _name: &str,
+ _include_hidden: bool,
+ ) -> Result<(), CrmError> {
+ unimplemented!()
+ }
+
async fn set_contact_hidden(
&self,
_team_id: &uuid::Uuid,
@@ -410,6 +430,50 @@ fn company_receipt() -> CrmCompanyReceipt<ViewAccessLevel> {
CrmCompanyReceipt::dangerously_internal(uuid::Uuid::now_v7(), uuid::Uuid::now_v7())
}
+#[tokio::test]
+async fn set_company_name_rejects_blank_name() {
+ let access = company_receipt();
+ for name in ["", " ", "\t\n"] {
+ let err = service().set_company_name(&access, name).await.unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "name {name:?}");
+ }
+}
+
+#[tokio::test]
+async fn set_company_name_rejects_overlong_name() {
+ let access = company_receipt();
+ let name = "x".repeat(201);
+ let err = service()
+ .set_company_name(&access, &name)
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)));
+}
+
+fn contact_receipt() -> CrmContactReceipt<ViewAccessLevel> {
+ CrmContactReceipt::dangerously_internal(uuid::Uuid::now_v7(), uuid::Uuid::now_v7())
+}
+
+#[tokio::test]
+async fn set_contact_name_rejects_blank_name() {
+ let access = contact_receipt();
+ for name in ["", " ", "\t\n"] {
+ let err = service().set_contact_name(&access, name).await.unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "name {name:?}");
+ }
+}
+
+#[tokio::test]
+async fn set_contact_name_rejects_overlong_name() {
+ let access = contact_receipt();
+ let name = "x".repeat(201);
+ let err = service()
+ .set_contact_name(&access, &name)
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)));
+}
+
#[tokio::test]
async fn create_contact_rejects_blank_name() {
let access = company_receipt();
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
index f593ac5d4a..dd4a22e80b 100644
--- a/crates/crm/src/inbound/axum_extractors/test.rs
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -315,6 +315,22 @@ impl CrmService for FakeCrmService {
panic!("unexpected set_company_hidden call")
}
+ async fn set_company_name(
+ &self,
+ _access: &CrmCompanyReceipt<ViewAccessLevel>,
+ _name: &str,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected set_company_name call")
+ }
+
+ async fn set_contact_name(
+ &self,
+ _access: &CrmContactReceipt<ViewAccessLevel>,
+ _name: &str,
+ ) -> Result<(), CrmError> {
+ panic!("unexpected set_contact_name call")
+ }
+
async fn set_contact_hidden(
&self,
_access: &CrmContactReceipt<EditAccessLevel>,
diff --git a/crates/crm/src/inbound/axum_router/mod.rs b/crates/crm/src/inbound/axum_router/mod.rs
index 69183d2eb8..9c716864e5 100644
--- a/crates/crm/src/inbound/axum_router/mod.rs
+++ b/crates/crm/src/inbound/axum_router/mod.rs
@@ -6,9 +6,16 @@ pub mod set_email_sync;
/// Toggle the `hidden` flag on a `crm_companies` row.
pub mod set_company_hidden;
+/// Set the team-scoped display-name override (`custom_name`) on a
+/// `crm_companies` row.
+pub mod set_company_name;
+
/// Toggle the `hidden` flag on a `crm_contacts` row.
pub mod set_contact_hidden;
+/// Set the display name (`name`) on a `crm_contacts` row.
+pub mod set_contact_name;
+
/// List contacts of a `crm_companies` row. Role-aware: members see
/// visible contacts only; admin/owner see hidden contacts too.
pub mod list_company_contacts;
@@ -121,6 +128,10 @@ where
"/companies/{company_id}/hidden",
put(set_company_hidden::handler::<C, Eas, Auth>),
)
+ .route(
+ "/companies/{company_id}/name",
+ put(set_company_name::handler::<C, Eas, Auth>),
+ )
.route(
"/companies/{company_id}",
get(get_company::handler::<C, Eas, Auth>),
@@ -138,6 +149,10 @@ where
"/contacts/{contact_id}/hidden",
put(set_contact_hidden::handler::<C, Eas, Auth>),
)
+ .route(
+ "/contacts/{contact_id}/name",
+ put(set_contact_name::handler::<C, Eas, Auth>),
+ )
.route(
"/comments/{entity_type}/{entity_id}",
get(comments::list_handler::<C, Eas, Auth>)
diff --git a/crates/crm/src/inbound/axum_router/set_company_name.rs b/crates/crm/src/inbound/axum_router/set_company_name.rs
new file mode 100644
index 0000000000..d67fbfd408
--- /dev/null
+++ b/crates/crm/src/inbound/axum_router/set_company_name.rs
@@ -0,0 +1,63 @@
+use axum::{
+ Json,
+ extract::{Path, State},
+ http::StatusCode,
+};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
+use model_error_response::ErrorResponse;
+use serde::Deserialize;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::{
+ domain::{model::CrmError, service::CrmService},
+ inbound::axum_extractors::CrmCompanyAccessLevelExtractor,
+};
+
+use super::CrmRouterState;
+
+/// Request body for `PUT /companies/{company_id}/name`.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct SetCompanyNameRequest {
+ /// New display name for the company. Stored on the team-scoped
+ /// `crm_companies.custom_name` override, which read paths COALESCE
+ /// over the global directory name — the shared directory is never
+ /// modified. Must be non-blank (400 otherwise).
+ pub name: String,
+}
+
+/// Rename a CRM company. Access is enforced by
+/// [`CrmCompanyAccessLevelExtractor`]: the caller must be on the team
+/// that owns the company (hidden companies are reachable for
+/// admin/owner only). The name is a team-scoped override
+/// (`custom_name`) and never touches the global domain directory.
+#[utoipa::path(
+ put,
+ path = "/crm/companies/{company_id}/name",
+ operation_id = "set_crm_company_name",
+ params(
+ ("company_id" = Uuid, Path, description = "The CRM company to rename"),
+ ),
+ request_body = SetCompanyNameRequest,
+ responses(
+ (status = 204),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
+pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+ access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
+ Path(company_id): Path<Uuid>,
+ Json(req): Json<SetCompanyNameRequest>,
+) -> Result<StatusCode, CrmError> {
+ state
+ .service
+ .set_company_name(&access.receipt, &req.name)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/crates/crm/src/inbound/axum_router/set_contact_name.rs b/crates/crm/src/inbound/axum_router/set_contact_name.rs
new file mode 100644
index 0000000000..db8a8d5bb8
--- /dev/null
+++ b/crates/crm/src/inbound/axum_router/set_contact_name.rs
@@ -0,0 +1,62 @@
+use axum::{
+ Json,
+ extract::{Path, State},
+ http::StatusCode,
+};
+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};
+use macro_authorization::MacroAuthorizationService;
+use model_error_response::ErrorResponse;
+use serde::Deserialize;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::{
+ domain::{model::CrmError, service::CrmService},
+ inbound::axum_extractors::CrmContactAccessLevelExtractor,
+};
+
+use super::CrmRouterState;
+
+/// Request body for `PUT /contacts/{contact_id}/name`.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct SetContactNameRequest {
+ /// New display name for the contact. Stored on `crm_contacts.name`,
+ /// which is already team-scoped — unlike company renames no global
+ /// directory is involved. Must be non-blank (400 otherwise).
+ pub name: String,
+}
+
+/// Rename a CRM contact. Access is enforced by
+/// [`CrmContactAccessLevelExtractor`]: the caller must be on the team
+/// that owns the contact's company (hidden contacts are reachable for
+/// admin/owner only). The name overwrites the team-scoped
+/// `crm_contacts.name` column.
+#[utoipa::path(
+ put,
+ path = "/crm/contacts/{contact_id}/name",
+ operation_id = "set_crm_contact_name",
+ params(
+ ("contact_id" = Uuid, Path, description = "The CRM contact to rename"),
+ ),
+ request_body = SetContactNameRequest,
+ responses(
+ (status = 204),
+ (status = 400, body = ErrorResponse),
+ (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, Auth: MacroAuthorizationService>(
+ access: CrmContactAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
+ State(state): State<CrmRouterState<C, Eas, Auth>>,
+ Path(contact_id): Path<Uuid>,
+ Json(req): Json<SetContactNameRequest>,
+) -> Result<StatusCode, CrmError> {
+ state
+ .service
+ .set_contact_name(&access.receipt, &req.name)
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rs
index d80ffbbcfc..a584151534 100644
--- a/crates/crm/src/outbound/companies_repo.rs
+++ b/crates/crm/src/outbound/companies_repo.rs
@@ -1145,6 +1145,42 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
Ok(())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn set_company_custom_name(
+ &self,
+ team_id: &uuid::Uuid,
+ company_id: &uuid::Uuid,
+ name: &str,
+ include_hidden: bool,
+ ) -> Result<(), CrmError> {
+ // Scoping on id AND team_id rejects cross-team callers as
+ // NotFound; the hidden guard keeps member (include_hidden =
+ // false) callers off hidden companies, matching the read paths.
+ let updated = sqlx::query_scalar!(
+ r#"
+ UPDATE crm_companies
+ SET custom_name = $3
+ WHERE id = $1
+ AND team_id = $2
+ AND (NOT hidden OR $4)
+ RETURNING id
+ "#,
+ company_id,
+ team_id,
+ name,
+ include_hidden,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ if updated.is_none() {
+ return Err(CrmError::CompanyNotFoundForTeam);
+ }
+
+ Ok(())
+ }
+
#[tracing::instrument(skip(self), err)]
async fn set_contact_hidden(
&self,
@@ -1178,6 +1214,45 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
Ok(())
}
+ #[tracing::instrument(skip(self), err)]
+ async fn set_contact_name(
+ &self,
+ team_id: &uuid::Uuid,
+ contact_id: &uuid::Uuid,
+ name: &str,
+ include_hidden: bool,
+ ) -> Result<(), CrmError> {
+ // Scope via the contact's company; cross-team = NotFound. The
+ // hidden guard mirrors get_contact_for_team: member
+ // (include_hidden = false) callers can't reach a hidden
+ // contact or a contact under a hidden company.
+ let updated = sqlx::query_scalar!(
+ r#"
+ UPDATE crm_contacts ct
+ SET name = $3
+ FROM crm_companies co
+ WHERE ct.id = $1
+ AND ct.company_id = co.id
+ AND co.team_id = $2
+ AND ($4 OR (ct.hidden = FALSE AND co.hidden = FALSE))
+ RETURNING ct.id
+ "#,
+ contact_id,
+ team_id,
+ name,
+ include_hidden,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;
+
+ if updated.is_none() {
+ return Err(CrmError::ContactNotFoundForTeam);
+ }
+
+ Ok(())
+ }
+
#[tracing::instrument(skip(self), err)]
async fn get_team_id_for_user(&self, macro_id: &str) -> Result<Option<uuid::Uuid>, CrmError> {
sqlx::query_scalar!(
diff --git a/crates/crm/src/outbound/companies_repo/test.rs b/crates/crm/src/outbound/companies_repo/test.rs
index 9efcad8e67..fe03f11bd4 100644
--- a/crates/crm/src/outbound/companies_repo/test.rs
+++ b/crates/crm/src/outbound/companies_repo/test.rs
@@ -15,6 +15,8 @@ mod list_companies_for_soup;
mod list_contacts_for_company;
mod populate_contact;
mod set_company_hidden;
+mod set_company_name;
mod set_contact_hidden;
+mod set_contact_name;
mod set_email_sync;
mod team_settings;
diff --git a/crates/crm/src/outbound/companies_repo/test/helpers.rs b/crates/crm/src/outbound/companies_repo/test/helpers.rs
index ecb6e2eb10..f1e613bbdb 100644
--- a/crates/crm/src/outbound/companies_repo/test/helpers.rs
+++ b/crates/crm/src/outbound/companies_repo/test/helpers.rs
@@ -140,6 +140,30 @@ pub(super) async fn fetch_email_sync(
Ok(row.map(|(s,)| s))
}
+pub(super) async fn fetch_company_custom_name(
+ pool: &PgPool,
+ company_id: Uuid,
+) -> sqlx::Result<Option<Option<String>>> {
+ let row: Option<(Option<String>,)> =
+ sqlx::query_as(r#"SELECT custom_name FROM crm_companies WHERE id = $1"#)
+ .bind(company_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(n,)| n))
+}
+
+pub(super) async fn fetch_contact_name(
+ pool: &PgPool,
+ contact_id: Uuid,
+) -> sqlx::Result<Option<Option<String>>> {
+ let row: Option<(Option<String>,)> =
+ sqlx::query_as(r#"SELECT name FROM crm_contacts WHERE id = $1"#)
+ .bind(contact_id)
+ .fetch_optional(pool)
+ .await?;
+ Ok(row.map(|(n,)| n))
+}
+
pub(super) async fn fetch_company_hidden(
pool: &PgPool,
company_id: Uuid,
diff --git a/crates/crm/src/outbound/companies_repo/test/set_company_name.rs b/crates/crm/src/outbound/companies_repo/test/set_company_name.rs
new file mode 100644
index 0000000000..d672d35fb5
--- /dev/null
+++ b/crates/crm/src/outbound/companies_repo/test/set_company_name.rs
@@ -0,0 +1,138 @@
+use super::helpers::*;
+use crate::domain::auth::CrmCompanyReceipt;
+use crate::domain::companies_repo::CompaniesRepository;
+use crate::domain::model::CrmError;
+use crate::domain::service::{CrmService, CrmServiceImpl};
+use crate::outbound::companies_repo::CompaniesRepositoryImpl;
+use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;
+use entity_access::domain::models::ViewAccessLevel;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_company_name_writes_override_that_wins_over_directory(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ // Populate-style company: no custom_name, display name resolved
+ // from the global directory.
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ sqlx::query(r#"INSERT INTO crm_domain_directory (domain, name) VALUES ($1, $2)"#)
+ .bind("acme.com")
+ .bind("Acme Inc. (directory)")
+ .execute(&pool)
+ .await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.set_company_custom_name(&team_id, &company_id, "Acme (ours)", false)
+ .await?;
+
+ assert_eq!(
+ fetch_company_custom_name(&pool, company_id).await?,
+ Some(Some("Acme (ours)".to_string()))
+ );
+ // The override wins over the directory name on the read path.
+ let record = repo
+ .get_company_for_team(&team_id, &company_id, false)
+ .await?
+ .expect("company should be readable");
+ assert_eq!(record.name.as_deref(), Some("Acme (ours)"));
+
+ // Renaming again overwrites the previous override.
+ repo.set_company_custom_name(&team_id, &company_id, "Acme v2", false)
+ .await?;
+ assert_eq!(
+ fetch_company_custom_name(&pool, company_id).await?,
+ Some(Some("Acme v2".to_string()))
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_company_name_returns_not_found_for_unknown_company(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .set_company_custom_name(&team_id, &Uuid::now_v7(), "Acme", false)
+ .await;
+
+ assert!(matches!(result, Err(CrmError::CompanyNotFoundForTeam)));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_company_name_isolates_companies_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 repo = CompaniesRepositoryImpl::new(pool.clone());
+ let result = repo
+ .set_company_custom_name(&team_b, &company_a, "Hijacked", false)
+ .await;
+
+ assert!(matches!(result, Err(CrmError::CompanyNotFoundForTeam)));
+ assert_eq!(
+ fetch_company_custom_name(&pool, company_a).await?,
+ Some(None)
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_company_name_respects_hidden_gate(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.set_company_hidden(&team_id, &company_id, true).await?;
+
+ // Member callers (include_hidden = false) can't reach the hidden row.
+ let result = repo
+ .set_company_custom_name(&team_id, &company_id, "Sneaky", false)
+ .await;
+ assert!(matches!(result, Err(CrmError::CompanyNotFoundForTeam)));
+ assert_eq!(
+ fetch_company_custom_name(&pool, company_id).await?,
+ Some(None)
+ );
+
+ // Admin/owner callers (include_hidden = true) can rename it.
+ repo.set_company_custom_name(&team_id, &company_id, "Admin rename", true)
+ .await?;
+ assert_eq!(
+ fetch_company_custom_name(&pool, company_id).await?,
+ Some(Some("Admin rename".to_string()))
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn service_set_company_name_trims_and_persists(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+ let access = CrmCompanyReceipt::<ViewAccessLevel>::dangerously_internal(company_id, team_id);
+ service
+ .set_company_name(&access, " Acme Trimmed ")
+ .await?;
+
+ assert_eq!(
+ fetch_company_custom_name(&pool, company_id).await?,
+ Some(Some("Acme Trimmed".to_string()))
+ );
+ Ok(())
+}
diff --git a/crates/crm/src/outbound/companies_repo/test/set_contact_name.rs b/crates/crm/src/outbound/companies_repo/test/set_contact_name.rs
new file mode 100644
index 0000000000..8c55d54518
--- /dev/null
+++ b/crates/crm/src/outbound/companies_repo/test/set_contact_name.rs
@@ -0,0 +1,153 @@
+use super::helpers::*;
+use crate::domain::auth::CrmContactReceipt;
+use crate::domain::companies_repo::CompaniesRepository;
+use crate::domain::model::CrmError;
+use crate::domain::service::{CrmService, CrmServiceImpl};
+use crate::outbound::companies_repo::CompaniesRepositoryImpl;
+use crate::outbound::no_op_resolver::NoOpCompanyMetadataResolver;
+use entity_access::domain::models::ViewAccessLevel;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_contact_name_writes_and_overwrites_name(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ // Populate-style contact: no name yet, display falls back to email.
+ let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.set_contact_name(&team_id, &contact_id, "Jane Doe", false)
+ .await?;
+
+ assert_eq!(
+ fetch_contact_name(&pool, contact_id).await?,
+ Some(Some("Jane Doe".to_string()))
+ );
+ // The rename is visible on the read path.
+ let record = repo
+ .get_contact_for_team(&team_id, &contact_id, false)
+ .await?
+ .expect("contact should be readable");
+ assert_eq!(record.name.as_deref(), Some("Jane Doe"));
+
+ // Renaming again overwrites the previous name.
+ repo.set_contact_name(&team_id, &contact_id, "Jane Smith", false)
+ .await?;
+ assert_eq!(
+ fetch_contact_name(&pool, contact_id).await?,
+ Some(Some("Jane Smith".to_string()))
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_contact_name_returns_not_found_for_unknown_contact(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool);
+ let result = repo
+ .set_contact_name(&team_id, &Uuid::now_v7(), "Jane", false)
+ .await;
+
+ assert!(matches!(result, Err(CrmError::ContactNotFoundForTeam)));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_contact_name_isolates_contacts_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 contact_a = insert_contact(&pool, company_a, "[email protected]").await?;
+
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ let result = repo
+ .set_contact_name(&team_b, &contact_a, "Hijacked", false)
+ .await;
+
+ assert!(matches!(result, Err(CrmError::ContactNotFoundForTeam)));
+ assert_eq!(fetch_contact_name(&pool, contact_a).await?, Some(None));
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_contact_name_respects_hidden_contact_gate(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.set_contact_hidden(&team_id, &contact_id, true).await?;
+
+ // Member callers (include_hidden = false) can't reach the hidden row.
+ let result = repo
+ .set_contact_name(&team_id, &contact_id, "Sneaky", false)
+ .await;
+ assert!(matches!(result, Err(CrmError::ContactNotFoundForTeam)));
+ assert_eq!(fetch_contact_name(&pool, contact_id).await?, Some(None));
+
+ // Admin/owner callers (include_hidden = true) can rename it.
+ repo.set_contact_name(&team_id, &contact_id, "Admin rename", true)
+ .await?;
+ assert_eq!(
+ fetch_contact_name(&pool, contact_id).await?,
+ Some(Some("Admin rename".to_string()))
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn set_contact_name_respects_hidden_company_gate(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ repo.set_company_hidden(&team_id, &company_id, true).await?;
+
+ // A visible contact under a hidden company is unreachable for members.
+ let result = repo
+ .set_contact_name(&team_id, &contact_id, "Sneaky", false)
+ .await;
+ assert!(matches!(result, Err(CrmError::ContactNotFoundForTeam)));
+
+ // Admin/owner callers can still rename it.
+ repo.set_contact_name(&team_id, &contact_id, "Admin rename", true)
+ .await?;
+ assert_eq!(
+ fetch_contact_name(&pool, contact_id).await?,
+ Some(Some("Admin rename".to_string()))
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn service_set_contact_name_trims_and_persists(pool: PgPool) -> anyhow::Result<()> {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]").await?;
+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;
+ let contact_id = insert_contact(&pool, company_id, "[email protected]").await?;
+
+ let service = CrmServiceImpl::new(
+ CompaniesRepositoryImpl::new(pool.clone()),
+ NoOpCompanyMetadataResolver,
+ );
+ let access = CrmContactReceipt::<ViewAccessLevel>::dangerously_internal(contact_id, team_id);
+ service
+ .set_contact_name(&access, " Jane Trimmed ")
+ .await?;
+
+ assert_eq!(
+ fetch_contact_name(&pool, contact_id).await?,
+ Some(Some("Jane Trimmed".to_string()))
+ );
+ Ok(())
+}
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 0c59eedfb9..dfd5c136bd 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -320,7 +320,9 @@ use utoipa::OpenApi;
// /crm
crm::inbound::axum_router::set_email_sync::handler,
crm::inbound::axum_router::set_company_hidden::handler,
+ crm::inbound::axum_router::set_company_name::handler,
crm::inbound::axum_router::set_contact_hidden::handler,
+ crm::inbound::axum_router::set_contact_name::handler,
crm::inbound::axum_router::list_company_contacts::handler,
crm::inbound::axum_router::get_contact::handler,
crm::inbound::axum_router::get_company::handler,
@@ -603,7 +605,9 @@ use utoipa::OpenApi;
// CRM
crm::inbound::axum_router::set_email_sync::SetEmailSyncRequest,
crm::inbound::axum_router::set_company_hidden::SetCompanyHiddenRequest,
+ crm::inbound::axum_router::set_company_name::SetCompanyNameRequest,
crm::inbound::axum_router::set_contact_hidden::SetContactHiddenRequest,
+ crm::inbound::axum_router::set_contact_name::SetContactNameRequest,
crm::inbound::axum_router::list_company_contacts::CrmContactResponse,
crm::inbound::axum_router::get_company::CrmCompanyResponse,
crm::inbound::axum_router::get_company::CrmDomainResponse,