Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: add CRM settings UI and AI tools for company management (#4586)
Jacob Beckerman385ec6ca0919
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 847d3136cf..4f812c8e29 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -125,8 +125,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -136,7 +139,10 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_config","macro_config_derive",@@ -144,12 +150,15 @@"macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -157,11 +166,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit","remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -389,6 +403,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","referral","remote_env_var",@@ -496,6 +511,7 @@"non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -590,6 +606,7 @@"non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -775,6 +792,7 @@"non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -873,6 +891,7 @@"non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -1070,6 +1089,8 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","convert_service","cowlike","crm",@@ -1083,9 +1104,11 @@"entity_access_management","filter_ast","frecency",+ "invite_email","ip_extractor","item_filters","lambda_client",+ "last_online_tracker","macro_auth","macro_aws_config","macro_config",@@ -1098,12 +1121,15 @@"macro_env_vars/database_env_vars","macro_middleware","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -1116,7 +1142,10 @@"models_properties","models_team","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit","remote_env_var","s3_client","s3_key",@@ -1137,23 +1166,41 @@"ai_toolset","ai_usage","attachment",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","entity_access",+ "entity_access_db_utils",+ "invite_email",+ "last_online_tracker",+ "macro_auth",+ "macro_env","macro_env_var",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload",+ "models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var",+ "system_properties","unfurl","workspace-hack"],@@ -1198,8 +1245,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","deleted_item_poller","document_sub_type","email",@@ -1210,19 +1260,25 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_db_client","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -1235,7 +1291,11 @@"models_properties","models_team","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client","system_properties",@@ -1605,6 +1665,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -1692,6 +1753,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -1713,8 +1775,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","docx_unzip_handler","email",@@ -1725,21 +1790,27 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters","lambda_client",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_db_client","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_sha_count_client","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -1752,7 +1823,11 @@"models_properties","models_team","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_client","s3_key","sqs_client",@@ -1775,8 +1850,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -1786,22 +1864,35 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth",+ "macro_env","macro_env_var",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload","models_email","models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var",+ "system_properties","unfurl","workspace-hack"],@@ -1848,8 +1939,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -1860,18 +1954,24 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -1879,10 +1979,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -1892,8 +1998,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -1904,18 +2013,24 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -1923,10 +2038,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -1995,6 +2116,7 @@"non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","s3_client",@@ -2014,8 +2136,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -2026,22 +2151,35 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth",+ "macro_env","macro_env_var",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_bulk_upload","models_email","models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var",+ "system_properties","unfurl","workspace-hack"],@@ -2051,8 +2189,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -2063,18 +2204,24 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -2082,10 +2229,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -2331,6 +2484,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -2599,6 +2753,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -2773,8 +2928,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -2784,15 +2942,22 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth",+ "macro_env","macro_env_var","macro_project_utils",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -2800,10 +2965,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -3290,6 +3461,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -3371,6 +3543,7 @@"non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -3559,8 +3732,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -3570,18 +3746,24 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -3589,11 +3771,17 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","organization_retention_handler","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -3603,8 +3791,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -3614,18 +3805,24 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -3633,11 +3830,17 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","organization_retention_trigger","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -4136,6 +4339,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -4154,8 +4358,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_storage_service_client","document_sub_type","email",@@ -4166,7 +4373,10 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env",@@ -4175,10 +4385,12 @@"macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -4186,11 +4398,17 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","search_upload_handler","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -4263,6 +4481,7 @@"non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -4392,8 +4611,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","email","email_db_client",@@ -4403,14 +4625,21 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth",+ "macro_env","macro_env_var",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -4418,10 +4647,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","workspace-hack"],@@ -4604,6 +4839,7 @@"opensearch_client","opensearch_query_builder","prompt",+ "properties","rate_limit","remote_env_var","s3_key",@@ -4660,14 +4896,17 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty","notification","prompt",+ "properties","rate_limit","remote_env_var","roles_and_permissions","s3_key","sqs_client",+ "system_properties","teams","unfurl","workspace-hack"@@ -4694,10 +4933,13 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","connection_gateway_client","connection_gateway_models","cowlike","crm",+ "decode_jwt","document_storage_service_client","document_sub_type","dynamodb_client",@@ -4709,7 +4951,10 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env",@@ -4717,10 +4962,12 @@"macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -4728,10 +4975,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","upload_extractor_lambda_handler","workspace-hack"@@ -4742,8 +4995,11 @@"ai_usage","attachment","authentication_service_client",+ "bot_id",+ "channel_sender","cowlike","crm",+ "decode_jwt","document_sub_type","dynamodb_client","email",@@ -4754,18 +5010,24 @@"entity_access_management","filter_ast","frecency",+ "invite_email","item_filters",+ "last_online_tracker",+ "macro_auth","macro_aws_config","macro_entrypoint","macro_env","macro_env_var","macro_queues",+ "macro_service_urls","macro_user_id","macro_uuid",+ "mention_utils","model","model-entity","model-error-response","model_file_type",+ "model_notifications","model_user","models_ai_projection","models_bulk_upload",@@ -4773,10 +5035,16 @@"models_entity_access_management","models_pagination","models_permissions",+ "models_properties","non_empty",+ "notification","prompt",+ "properties",+ "rate_limit",+ "remote_env_var","s3_key","sqs_client",+ "system_properties","unfurl","upload_extractor_lambda_trigger","workspace-hack"diff --git a/js/app/packages/app/component/next-soup/filters/configs/base.ts b/js/app/packages/app/component/next-soup/filters/configs/base.tsindex 1e5a24d187..b1b843fc3d 100644--- a/js/app/packages/app/component/next-soup/filters/configs/base.ts+++ b/js/app/packages/app/component/next-soup/filters/configs/base.ts@@ -4,6 +4,9 @@ import type { PropertyFilter, Query } from '../filter-store';export const NO_ASSIGNEE = 'NO_ASSIGNEE';+/** Sentinel stage-filter id matching companies without a Stage set. */+export const NO_STAGE = 'NO_STAGE';+export const NIL_UUID = '00000000-0000-0000-0000-000000000000';export const IMAGE_EXTENSIONS = [@@ -46,6 +49,18 @@ export type FilterContext = {assignees?: string[];/** Selected company Owner ids for the Customers view's owner filter. */owners?: string[];+ /**+ * Selected stage option ids for the Customers view's stage filter (may+ * include the `NO_STAGE` sentinel).+ */+ stages?: string[];+ /**+ * Company → active stage option id, resolved against the team's deal+ * stage set (legacy system-stage values are label-mapped). Supplied by+ * the soup view provider from `useDealStages` so plain predicate+ * functions bucket companies exactly like the kanban does.+ */+ resolveCompanyStage?: (entity: EntityData) => string | undefined;};export type Predicate = (entity: EntityData, ctx: FilterContext) => boolean;diff --git a/js/app/packages/app/component/next-soup/filters/configs/company.ts b/js/app/packages/app/component/next-soup/filters/configs/company.tsindex da87f077ba..47faa8abf6 100644--- a/js/app/packages/app/component/next-soup/filters/configs/company.ts+++ b/js/app/packages/app/component/next-soup/filters/configs/company.ts@@ -1,42 +1,25 @@-import { PROPERTY_OPTION_IDS } from '@property/constants';import {companyOwnedByUsersFilter,- hasCompanyStage,- hasNoCompanyStage,+ companyStageFilter as companyStagePredicate,} from '../predicates';-import { config, type Predicate } from './base';+import { config } from './base';// Companies are fetched via the dedicated CRM soup request (capped at 500// per team) rather than the dynamic filter AST, which has no property// support for the `ccf` target — so stage/owner filters are client-side// predicates with a no-op server query.-const stageFilter = <TId extends string>(id: TId, predicate: Predicate) =>- config({ id, predicate, query: {} });-export const COMPANY_STAGE_FILTERS = [- stageFilter('company-stage-lead', (e) =>- hasCompanyStage(e, PROPERTY_OPTION_IDS.STAGE.LEAD)- ),- stageFilter('company-stage-qualified', (e) =>- hasCompanyStage(e, PROPERTY_OPTION_IDS.STAGE.QUALIFIED)- ),- stageFilter('company-stage-demo', (e) =>- hasCompanyStage(e, PROPERTY_OPTION_IDS.STAGE.DEMO)- ),- stageFilter('company-stage-trial', (e) =>- hasCompanyStage(e, PROPERTY_OPTION_IDS.STAGE.TRIAL)- ),- stageFilter('company-stage-negotiation', (e) =>- hasCompanyStage(e, PROPERTY_OPTION_IDS.STAGE.NEGOTIATION)- ),- stageFilter('company-stage-customer', (e) =>- hasCompanyStage(e, PROPERTY_OPTION_IDS.STAGE.CUSTOMER)- ),- stageFilter('company-stage-churned', (e) =>- hasCompanyStage(e, PROPERTY_OPTION_IDS.STAGE.CHURNED)- ),- stageFilter('company-no-stage', hasNoCompanyStage),-] as const;+/**+ * Stage filter for the Customers view, driven by the view's stage+ * selection (`ctx.stages`, option ids from the team's active deal-stage+ * set plus the `NO_STAGE` sentinel). Mirrors `companyOwnerFilter`.+ */+export const companyStageFilter = config({+ id: 'company-stage',+ predicate: (e, ctx) =>+ companyStagePredicate(() => ctx.stages, ctx.resolveCompanyStage)(e),+ query: {},+});export const companyOwnerFilter = config({id: 'company-owner',diff --git a/js/app/packages/app/component/next-soup/filters/configs/index.ts b/js/app/packages/app/component/next-soup/filters/configs/index.tsindex 39de8fa7e2..74c90368bf 100644--- a/js/app/packages/app/component/next-soup/filters/configs/index.ts+++ b/js/app/packages/app/component/next-soup/filters/configs/index.ts@@ -10,7 +10,7 @@ export * from './general';export * from './task';import type { FilterGroupConfig } from './base';-import { COMPANY_STAGE_FILTERS, companyOwnerFilter } from './company';+import { companyOwnerFilter, companyStageFilter } from './company';import {DOCUMENT_CONTEXTUAL_FILTERS,emailAttachmentsFilter,@@ -90,11 +90,11 @@ export const SOUP_FILTERS = [crmCompanyActiveFilter,crmCompanyHiddenFilter,companyOwnerFilter,+ companyStageFilter,emailAttachmentsFilter,inFolderFilter,searchSupportedFilter,...ENTITY_TYPE_FILTERS,- ...COMPANY_STAGE_FILTERS,...TASK_STATUS_FILTERS,...TASK_PRIORITY_FILTERS,...DOCUMENT_CONTEXTUAL_FILTERS,diff --git a/js/app/packages/app/component/next-soup/filters/index.ts b/js/app/packages/app/component/next-soup/filters/index.tsindex 1437b65d95..d1ee321985 100644--- a/js/app/packages/app/component/next-soup/filters/index.ts+++ b/js/app/packages/app/component/next-soup/filters/index.ts@@ -2,5 +2,6 @@ export {type FilterContext,type FilterID,NO_ASSIGNEE,+ NO_STAGE,} from './configs/index';export {} from './inbox-filters';diff --git a/js/app/packages/app/component/next-soup/filters/predicates.ts b/js/app/packages/app/component/next-soup/filters/predicates.tsindex 005f985702..c90ba77dbf 100644--- a/js/app/packages/app/component/next-soup/filters/predicates.ts+++ b/js/app/packages/app/component/next-soup/filters/predicates.ts@@ -13,7 +13,7 @@ import {import { getTaskPriorityOptionId } from '@entity/utils/task-properties';import { compositeEntity, type NotificationSource } from '@notifications';import { PROPERTY_OPTION_IDS } from '@property/constants';-import { NO_ASSIGNEE } from './configs/base';+import { NO_ASSIGNEE, NO_STAGE } from './configs/base';function getPredicateNotifications(entity: EntityData,@@ -158,19 +158,29 @@ export function crmCompanyHiddenFilter(entity: EntityData): boolean {return entity.type === 'crm_company' && entity.hidden;}-/** True when the company's Stage property matches the given option id. */-export function hasCompanyStage(- entity: EntityData,- stageOptionId: string-): boolean {- if (entity.type !== 'crm_company') return false;- return getCompanyStageOptionId(entity) === stageOptionId;-}--/** True when the company has no Stage set. */-export function hasNoCompanyStage(entity: EntityData): boolean {- if (entity.type !== 'crm_company') return false;- return getCompanyStageOptionId(entity) === undefined;+/**+ * Stage filter for companies, driven by the view's stage selection+ * (`ctx.stages`). `NO_STAGE` matches companies without a Stage set. Stage+ * resolution goes through `resolveStage` (the team's active deal-stage+ * set, from `ctx.resolveCompanyStage`) when supplied, so the filter+ * buckets companies exactly like the kanban — legacy system-stage values+ * included; otherwise it falls back to the raw system Stage value.+ */+export function companyStageFilter(+ stageIds: () => string[] | undefined,+ resolveStage?: (entity: EntityData) => string | undefined+) {+ return (entity: EntityData): boolean => {+ const stages = stageIds();+ if (!stages?.length) return true;+ if (entity.type !== 'crm_company') return false;+ const stageId = resolveStage+ ? resolveStage(entity)+ : getCompanyStageOptionId(entity);+ return stages.some((id) =>+ id === NO_STAGE ? stageId === undefined : stageId === id+ );+ };}/**diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsxindex dac8226d18..4e5dd45e42 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx@@ -2,6 +2,7 @@ import { getViewPreset } from '@app/component/app-sidebar/soup-filter-presets';import {type FilterContext,NO_ASSIGNEE,+ NO_STAGE,} from '@app/component/next-soup/filters/configs/';import {buildDocumentTypeQuery,@@ -22,6 +23,8 @@ import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import type { ListView } from '@app/constants/list-views';import { isListViewID } from '@app/constants/list-views';import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useDealStages } from '@companies/crm/deal-stages';+import { CrmStageIcon } from '@companies/crm/StageIcon';import { EntityIcon } from '@core/component/EntityIcon';import { UserIcon } from '@core/component/UserIcon';import {@@ -299,48 +302,10 @@ const TASKS_FILTER_CATEGORIES: FilterCategory[] = [},];-const COMPANIES_FILTER_CATEGORIES: FilterCategory[] = [- {- id: 'stage',- label: 'Stage',- labelPlural: 'Stages',- options: [- ...(- [- ['company-stage-lead', 'Lead', PROPERTY_OPTION_IDS.STAGE.LEAD],- [- 'company-stage-qualified',- 'Qualified',- PROPERTY_OPTION_IDS.STAGE.QUALIFIED,- ],- ['company-stage-demo', 'Demo', PROPERTY_OPTION_IDS.STAGE.DEMO],- ['company-stage-trial', 'Trial', PROPERTY_OPTION_IDS.STAGE.TRIAL],- [- 'company-stage-negotiation',- 'Negotiation',- PROPERTY_OPTION_IDS.STAGE.NEGOTIATION,- ],- [- 'company-stage-customer',- 'Customer',- PROPERTY_OPTION_IDS.STAGE.CUSTOMER,- ],- [- 'company-stage-churned',- 'Churned',- PROPERTY_OPTION_IDS.STAGE.CHURNED,- ],- ] as const- ).map(([id, label, optionId]) => ({- id,- label,- icon: () => <PropertyValueIcon optionId={optionId} class="size-3.5" />,- })),- { id: 'company-no-stage', label: 'No Stage' },- ],- multiple: true,- },-];+// The Customers view's Stage filter is context-driven (team-customizable+// stage set), rendered as a searchable submenu next to Owner — no static+// categories here.+const COMPANIES_FILTER_CATEGORIES: FilterCategory[] = [];const DOCUMENTS_FILTER_CATEGORIES: FilterCategory[] = [{@@ -582,12 +547,15 @@ export const UnifiedFilterDropdown = (setAssigneeFilter,ownerFilter,setOwnerFilter,+ stageFilter,+ setStageFilter,activeTab,readFilter,setReadFilter,} = useSoupView();const contacts = useContacts();const userId = useUserId();+ const dealStages = useDealStages();const currentView = createMemo((): ListView | undefined => {const content = panel.handle.content();@@ -795,6 +763,34 @@ export const UnifiedFilterDropdown = (});};+ // Stage options for the Customers view: the team's active deal-stage set+ // plus a trailing "No stage" row.+ const stageOptions = createMemo((): SearchableOption[] => [+ ...dealStages.stages().map((stage, index) => ({+ id: stage.id,+ label: stage.label,+ icon: () => (+ <CrmStageIcon optionId={stage.id} index={index} class="size-3.5" />+ ),+ })),+ {+ id: NO_STAGE,+ label: 'No stage',+ icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,+ },+ ]);++ // Stage filtering is a client-side predicate, mirroring the owner filter.+ const handleStageChange = (ids: string[]) => {+ batch(() => {+ setStageFilter(ids);+ const shouldBeActive = ids.length > 0;+ if (shouldBeActive !== soup.predicates.isActive('company-stage')) {+ soup.predicates.toggle({ and: ['company-stage'] });+ }+ });+ };+const isTasksView = () => currentView() === 'tasks';const isCompaniesView = () => currentView() === 'companies';const isDocumentsView = () => currentView() === 'documents';@@ -846,6 +842,7 @@ export const UnifiedFilterDropdown = (when={categories().length > 0 ||isTasksView() ||+ isCompaniesView() ||isNewInbox() ||showTagsFilter()}@@ -943,8 +940,15 @@ export const UnifiedFilterDropdown = (/></Show>- {/* Owner filter for the Customers view */}+ {/* Stage + Owner filters for the Customers view */}<Show when={isCompaniesView()}>+ <SearchableFilterSubmenu+ label="Stage"+ options={stageOptions}+ activeIds={stageFilter}+ onChange={handleStageChange}+ placeholder="Filter stages..."+ /><SearchableFilterSubmenulabel="Owner"options={ownerOptions}diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsxindex d1de7a12cb..174159d271 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx@@ -7,6 +7,7 @@ import {type FilterContext,type FilterID,NO_ASSIGNEE,+ NO_STAGE,} from '@app/component/next-soup/filters';import {buildDocumentTypeQuery,@@ -22,6 +23,8 @@ import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-conteximport { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import type { ListView } from '@app/constants/list-views';import { isListViewID } from '@app/constants/list-views';+import { useDealStages } from '@companies/crm/deal-stages';+import { CrmStageIcon } from '@companies/crm/StageIcon';import { UserIcon } from '@core/component/UserIcon';import { useUserContext, useUserId } from '@core/context/user';import { deepEqual } from '@core/util/compareUtils';@@ -72,6 +75,8 @@ export function useFilterRefinements() {setAssigneeFilter,ownerFilter,setOwnerFilter,+ stageFilter,+ setStageFilter,activeTab,} = useSoupView();const filterData = () => queryFilters.state;@@ -81,6 +86,7 @@ export function useFilterRefinements() {const currentUserId = useUserId();const taskStatus = useTaskStatusFilter();const tagFilter = useTagFilter();+ const dealStages = useDealStages();const getPresetContext = (): PresetContext => ({userId: user.userId(),@@ -134,7 +140,9 @@ export function useFilterRefinements() {currentFilterData.emailView !== presetFilters.emailView;const hasSubFilters =- assigneeFilter().length > 0 || ownerFilter().length > 0;+ assigneeFilter().length > 0 ||+ ownerFilter().length > 0 ||+ stageFilter().length > 0;return hasClientFilterDiff || hasQueryFilterDiff || hasSubFilters;});@@ -290,6 +298,52 @@ export function useFilterRefinements() {});};+ /**+ * Stage options for the Customers view's stage sub-filter: the team's+ * active deal-stage set plus a trailing "No stage" row.+ */+ const stageSearchableOptions = createMemo((): SearchableOption[] => [+ ...dealStages.stages().map((stage, index) => ({+ id: stage.id,+ label: stage.label,+ icon: () => (+ <CrmStageIcon optionId={stage.id} index={index} class="size-3.5" />+ ),+ })),+ {+ id: NO_STAGE,+ label: 'No stage',+ icon: () => <CircleDashedIcon class="size-3.5 text-ink-muted" />,+ },+ ]);++ const stageOptionsMap = createMemo(+ (): Map<string, { label: string; icon?: () => JSX.Element }> => {+ const map = new Map<+ string,+ { label: string; icon?: () => JSX.Element }+ >();+ for (const option of stageSearchableOptions()) {+ map.set(option.id, { label: option.label, icon: option.icon });+ }+ return map;+ }+ );++ /**+ * Handler for stage filter changes (Customers view). Client-side+ * predicate only, mirroring the owner filter.+ */+ const handleStageChange = (ids: string[]) => {+ batch(() => {+ setStageFilter(ids);+ const shouldBeActive = ids.length > 0;+ if (shouldBeActive !== soup.predicates.isActive('company-stage')) {+ soup.predicates.toggle({ and: ['company-stage'] });+ }+ });+ };+/*** Handler for assignee filter changes.*/@@ -721,8 +775,57 @@ export function useFilterRefinements() {);};+ // Stage filter (consolidated) for the Customers view.+ const pushStageConsolidatedChip = () => {+ if (view !== 'companies') return;+ const key = 'stage';+ const popupOpen =+ consolidatedChipCache.get(key)?.isPopupOpen?.() ?? false;+ const ids = stageFilter();+ if (ids.length === 0 && !popupOpen) return;++ seenKeys.add(key);++ const getValues = (): FilterValue[] =>+ stageFilter().map((id) => {+ const opt = stageOptionsMap().get(id);+ return {+ id,+ label: opt?.label ?? id,+ icon: opt?.icon,+ };+ });++ filters.push(+ getOrCreateConsolidatedChip(key, () => {+ const [isPopupOpen, _setPopupOpen] = createSignal(false);+ const setPopupOpen = (v: boolean) => {+ if (!v) {+ queueMicrotask(() =>+ panel.panelRef()?.focus({ preventScroll: true })+ );+ }+ _setPopupOpen(v);+ };+ return {+ key,+ categoryLabel: 'Stage',+ values: getValues,+ searchableOptions: stageSearchableOptions,+ activeSearchableIds: stageFilter,+ onSearchableChange: handleStageChange,+ searchPlaceholder: 'Filter stages...',+ isPopupOpen,+ setPopupOpen,+ onRemoveAll: () => handleStageChange([]),+ };+ })+ );+ };+pushTaskStatusChip();pushAssigneeConsolidatedChip();+ pushStageConsolidatedChip();pushOwnerConsolidatedChip();pushTagsConsolidatedChip();@@ -845,6 +948,7 @@ export function useFilterRefinements() {queryFilters.replace(preset.filters ?? null);setAssigneeFilter([]);setOwnerFilter([]);+ setStageFilter([]);if (presetSeedsStatusSubset) taskStatus.clear();});};diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsxindex 159a02cc7a..833a1dfd26 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx@@ -39,6 +39,7 @@ import {soupItemMatchesTagFilter,} from '@app/constants/list-views';import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { useDealStages } from '@companies/crm/deal-stages';import {ENABLE_FEATURED_SEARCH_RESULTS,ENABLE_GRAPHQL_SOUP_FLAG,@@ -57,6 +58,7 @@ import {toNotificationEntity,} from '@entity';import { useNotificationsForEntity } from '@notifications';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';import { useQueryClient } from '@queries/client';import type {GroupMeta as ApiGroupMeta,@@ -127,6 +129,8 @@ interface SoupViewContextValues {setAssigneeFilter: Setter<string[]>;ownerFilter: Accessor<string[]>;setOwnerFilter: Setter<string[]>;+ stageFilter: Accessor<string[]>;+ setStageFilter: Setter<string[]>;inboxFilter: Accessor<string[] | undefined>;setInboxFilter: Setter<string[] | undefined>;activeTab: Accessor<string | undefined>;@@ -280,6 +284,10 @@ export const SoupViewContextProvider: FlowComponent<'soup.ownerFilter',{ default: [] });+ const [stageFilter, setStageFilter] = useEntryState<string[]>(+ 'soup.stageFilter',+ { default: [] }+ );const [inboxFilter, setInboxFilter] = useEntryState<string[] | undefined>(INBOX_FILTER_ENTRY_KEY,{ default: undefined }@@ -339,19 +347,31 @@ export const SoupViewContextProvider: FlowComponent<}});- // Clear the owner sub-filter when leaving the CRM company presets+ // Clear the owner/stage sub-filters when leaving the CRM company presetscreateEffect(() => {if (!soup.predicates.isActive('crm-company-active') &&!soup.predicates.isActive('crm-company-hidden')) {setOwnerFilter([]);+ setStageFilter([]);}});const notificationSource = useGlobalNotificationSource();const userId = useUserId();+ // Active deal-stage set (team-customized when present). Drives the+ // Customers view's stage grouping, stage filter and group labels.+ const dealStages = useDealStages();++ // `resolveStage` takes the minimal company shape; widen it to any soup+ // entity (non-companies resolve to undefined since they carry no stage).+ const resolveCompanyStage = (entity: EntityData): string | undefined =>+ dealStages.resolveStage(+ entity as Parameters<typeof dealStages.resolveStage>[0]+ );+const activeListView = createMemo<ListView | undefined>(() => {const content = panel.handle.content();if (content.type !== 'component') return;@@ -498,6 +518,8 @@ export const SoupViewContextProvider: FlowComponent<notificationSource,assignees: assigneeFilter(),owners: ownerFilter(),+ stages: stageFilter(),+ resolveCompanyStage,});const attachNotifications = (entity: EntityData) => {@@ -685,8 +707,28 @@ export const SoupViewContextProvider: FlowComponent<const hasNextGroupPage = (groupKey: string) =>groupQueryFor(groupKey)?.hasNextPage() ?? false;+ // True when grouping by the canonical Stage id (the "group by Stage"+ // presets always use the system definition id, even when the team's own+ // stage set is active).+ const isStageGrouping = () => {+ const field = groupByField();+ return (+ field?.type === 'property' &&+ field.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STAGE+ );+ };++ // Group-key → label, preferring the active deal-stage set for stage+ // groupings (custom option ids are unknown to the static option table).+ const resolveGroupLabel = (key: string): string | undefined => {+ if (isStageGrouping()) {+ return dealStages.stageLabel(key) ?? getPropertyOptionLabel(key);+ }+ return getPropertyOptionLabel(key);+ };+const buildGroupMeta = (group: ApiGroupMeta): GroupMeta => {- const resolvedLabel = getPropertyOptionLabel(group.key) ?? group.label;+ const resolvedLabel = resolveGroupLabel(group.key) ?? group.label;return {key: group.key,value: group.key,@@ -732,9 +774,14 @@ export const SoupViewContextProvider: FlowComponent<if (enabled() && isClientPropertyGroup() && !search.isSearching()) {const definitionId =field?.type === 'property' ? field.propertyDefinitionId : '';+ // Stage grouping resolves through the active deal-stage set so legacy+ // system-stage values land in the matching custom-stage bucket.+ const isStage = definitionId === SYSTEM_PROPERTY_IDS.STAGE;const buckets = new Map<string, SoupEntity[]>();for (const entity of entities()) {- const key = clientPropertyGroupKey(entity, definitionId);+ const key = isStage+ ? (resolveCompanyStage(entity) ?? '')+ : clientPropertyGroupKey(entity, definitionId);const bucket = buckets.get(key);if (bucket) {bucket.push(entity);@@ -743,7 +790,9 @@ export const SoupViewContextProvider: FlowComponent<}}- const stageOrder = COMPANY_STAGE_OPTIONS.map((o) => o.value as string);+ const stageOrder = isStage+ ? dealStages.stages().map((stage) => stage.id)+ : COMPANY_STAGE_OPTIONS.map((o) => o.value as string);const order = [...buckets.keys()].sort((a, b) => {if (a === '') return 1;if (b === '') return -1;@@ -755,8 +804,8 @@ export const SoupViewContextProvider: FlowComponent<(bStage === -1 ? stageOrder.length : bStage));}- const aLabel = getPropertyOptionLabel(a) ?? a;- const bLabel = getPropertyOptionLabel(b) ?? b;+ const aLabel = resolveGroupLabel(a) ?? a;+ const bLabel = resolveGroupLabel(b) ?? b;return aLabel.localeCompare(bLabel);});@@ -767,7 +816,7 @@ export const SoupViewContextProvider: FlowComponent<const groupMeta: GroupMeta = {key,value: key,- label: key === '' ? 'Not set' : (getPropertyOptionLabel(key) ?? key),+ label: key === '' ? 'Not set' : (resolveGroupLabel(key) ?? key),count: groupEntities.length,isExpanded: () => soup.grouping.isExpanded(key),toggle: () => soup.grouping.toggle(key),@@ -962,6 +1011,8 @@ export const SoupViewContextProvider: FlowComponent<setAssigneeFilter,ownerFilter,setOwnerFilter,+ stageFilter,+ setStageFilter,inboxFilter,setInboxFilter,activeTab,diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsxindex fde3ceb732..dd526a5fad 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx@@ -40,9 +40,18 @@ import {SoupViewTabs,useApplyPreset,} from '@app/component/next-soup/soup-view/soup-view-tabs';+import {+ useIsNewInboxEnabled,+ usePreviewPaneVisiblity,+ WIDE_SPLIT_PANEL_BREAKPOINT,+} from '@app/component/next-soup/soup-view/use-preview-pane-visibility';import { CompanyKanban } from '@app/component/next-soup/soup-view/views/companies/CompanyKanban';import { CompanyListEntity } from '@app/component/next-soup/soup-view/views/companies/CompanyListEntity';import { ResponsiveCompanyListHeader } from '@app/component/next-soup/soup-view/views/companies/CompanyListHeader';+import {+ CompanyDisplayMenu,+ CompanyViewsMenu,+} from '@app/component/next-soup/soup-view/views/companies/CompanyViewsMenu';import { DateGroupHeader } from '@app/component/next-soup/soup-view/views/inbox/date-group-header';import { InboxListEntity } from '@app/component/next-soup/soup-view/views/inbox/InboxListEntity';import { TaskListEntity } from '@app/component/next-soup/soup-view/views/tasks/TaskListEntity';@@ -67,18 +76,16 @@ import { useEntryState } from '@app/component/split-layout/entry-state';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';import { LIST_VIEW_DOCS_URL } from '@app/constants/docs-links';import { isListViewID, type ListView } from '@app/constants/list-views';-import { useFeatureFlag } from '@app/lib/analytics/posthog';import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';import { usePreference } from '@app/preferences/use-preference';+import { useDealStages } from '@companies/crm/deal-stages';+import { CrmStageIcon } from '@companies/crm/StageIcon';+import type { CrmViewConfig } from '@companies/crm/saved-views';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { LoadingBlock } from '@core/component/LoadingBlock';import { Resize } from '@core/component/Resize';-import {- ENABLE_NEW_INBOX_FLAG,- ENABLE_NEW_INBOX_OVERRIDE,- ENABLE_UNIFIED_LIST_AI_INPUT,-} from '@core/constant/featureFlags';+import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import {soupListContainerAttribute,@@ -140,11 +147,34 @@ import { SoupEntitySelectionToolbar } from './soup-entity-selection-toolbar';import { useSoupNavigationHotkeys } from './use-soup-navigation-hotkeys';import { useSoupViewHotkeys } from './use-soup-view-hotkeys';-const WIDE_SPLIT_PANEL_BREAKPOINT = 512;-export const DefaultGroupHeader = (props: GroupHeaderProps & { highlighted?: boolean }) => {+ const panel = useSplitPanelOrThrow();+ const dealStages = useDealStages();++ // The Customers view groups by option ids from the team's deal-stage set+ // (or other custom select options) that the static PropertyValueIcon+ // table doesn't know — render those through CrmStageIcon instead.+ const isCompaniesView = () => {+ const content = panel.handle.content();+ return content.type === 'component' && content.id === 'companies';+ };++ // Index into the active stage set so header dots match kanban columns.+ const stageIndex = (optionId: string): number | undefined => {+ const index = dealStages+ .stages()+ .findIndex((stage) => stage.id === optionId);+ return index === -1 ? undefined : index;+ };++ const stageOptionId = () => {+ if (!isCompaniesView()) return undefined;+ const value = props.group.value ?? props.group.key;+ return typeof value === 'string' && value ? value : undefined;+ };+return (<SoupSectionHeaderonClick={() => props.group.toggle()}@@ -160,6 +190,15 @@ export const DefaultGroupHeader = (</div></Layer>+ <Show when={stageOptionId()}>+ {(value) => (+ <CrmStageIcon+ optionId={value()}+ index={stageIndex(value())}+ class="size-3.5"+ />+ )}+ </Show><span class="truncate">{props.group.label}</span><spanclass={cn(@@ -291,6 +330,11 @@ interface SoupViewProps {* preset whose `clientFilters` include a predicate that matches them.*/additionalEntities?: Accessor<EntityData[]>;+ /**+ * Shared CRM view opened via a `?crmView=` link (Customers view only).+ * When set, its pieces win over persisted/preset state during init.+ */+ initialCrmView?: CrmViewConfig;}type SoupViewMode = 'list' | 'board';@@ -382,6 +426,19 @@ export const SoupView = (props: SoupViewProps) => {{ default: [] });+ // List/board display mode — currently only the Customers view offers a+ // board (kanban grouped by Stage). Per-entry state so back/forward+ // restores the mode the user left each entry with. Declared before the+ // init effect below so a shared CRM view can set it during init.+ const [viewMode, setViewMode] = useEntryState<SoupViewMode>('soup.viewMode', {+ default: 'list',+ });++ // Shared CRM view opened via a `?crmView=` link — only honored on the+ // Customers view; its pieces win over persisted/preset values in init.+ const initialCrmView =+ contentId === 'companies' ? props.initialCrmView : undefined;+// We handle the restore of the persistence here instead of within the context// because the context is no longer recreated for each soup view because we// moved it within the `SplitPanel`.@@ -398,22 +455,32 @@ export const SoupView = (props: SoupViewProps) => {batch(() => {soupView.initialize({initialQuery: stripGatedTagFilters(- persistedFilters ?? props.initialFilters+ initialCrmView+ ? (initialCrmView.filters as Query | undefined)+ : (persistedFilters ?? props.initialFilters)),- initialClientFilters: persistedPredicates ?? props.initialClientFilters,- initialSearchText: persistedSearchText ?? props.initialSearchText,+ initialClientFilters: initialCrmView+ ? (initialCrmView.clientFilters ?? {})+ : (persistedPredicates ?? props.initialClientFilters),+ initialSearchText: initialCrmView+ ? (initialCrmView.searchText ?? '')+ : (persistedSearchText ?? props.initialSearchText),disableLocalSearch: props.disableLocalSearch,additionalEntities: props.additionalEntities,});- const initialGroupBy = persistedGroupBy ?? props.initialGroupBy;+ // `groupBy: null` in a shared view records an explicit "no grouping",+ // which the grouping store expresses as `undefined`.+ const initialGroupBy = initialCrmView+ ? (initialCrmView.groupBy ?? undefined)+ : (persistedGroupBy ?? props.initialGroupBy);- let initialSortIds = sortPref();+ let initialSortIds = initialCrmView?.sort ?? sortPref();if (initialSortIds.length === 0) {initialSortIds = ['updated_at'];}- let initialActiveTab = persistedActiveTab;+ let initialActiveTab = initialCrmView?.activeTab ?? persistedActiveTab;if (initialActiveTab === undefined && isListViewID(contentId)) {initialActiveTab = VIEW_TAB_PRESETS[contentId].default;@@ -427,6 +494,24 @@ export const SoupView = (props: SoupViewProps) => {);soupView.setActiveTab(initialActiveTab);++ if (initialCrmView) {+ // Stage/owner sub-filters ride separate signals plus a client+ // predicate that must be active iff the selection is non-empty+ // (same rule as handleStageChange/handleOwnerChange in+ // unified-filter-dropdown).+ const stages = initialCrmView.stageFilter ?? [];+ soupView.setStageFilter(stages);+ if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {+ soup.predicates.toggle({ and: ['company-stage'] });+ }+ const owners = initialCrmView.ownerFilter ?? [];+ soupView.setOwnerFilter(owners);+ if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {+ soup.predicates.toggle({ and: ['company-owner'] });+ }+ setViewMode(initialCrmView.viewMode ?? 'list');+ }});});@@ -496,12 +581,6 @@ export const SoupView = (props: SoupViewProps) => {return view ? LIST_VIEW_DOCS_URL[view] : undefined;});- // List/board display mode — currently only the Customers view offers a- // board (kanban grouped by Stage). Per-entry state so back/forward- // restores the mode the user left each entry with.- const [viewMode, setViewMode] = useEntryState<SoupViewMode>('soup.viewMode', {- default: 'list',- });const isBoardMode = createMemo(() => activeListView() === 'companies' && viewMode() === 'board');@@ -606,6 +685,11 @@ export const SoupView = (props: SoupViewProps) => {!narrowSearchExpanded() && isComponentListView('companies')}>+ <CompanyViewsMenu+ viewMode={viewMode()}+ setViewMode={setViewMode}+ />+ <CompanyDisplayMenu /><SoupViewModeToggle mode={viewMode()} onChange={setViewMode} /></Show><Show@@ -704,60 +788,6 @@ export const SoupView = (props: SoupViewProps) => {);};-export function useIsNewInboxEnabled() {- const panel = useSplitPanelOrThrow();-- const currentView = () => {- const { type, id } = panel.handle.content();- if (type !== 'component') return;- return isListViewID(id) ? id : undefined;- };-- const newInboxFlag = useFeatureFlag(ENABLE_NEW_INBOX_FLAG, {- enabledOverride: ENABLE_NEW_INBOX_OVERRIDE,- });-- const isNewInboxEnabled = () =>- currentView() === 'inbox' && newInboxFlag().enabled;-- return isNewInboxEnabled;-}--export function usePreviewPaneVisiblity() {- const panel = useSplitPanelOrThrow();-- const { soup, rows } = useSoupView();-- const isNewInboxEnabled = useIsNewInboxEnabled();-- const isWideSplitPanel = createMemo(() => {- return (panel.panelSize.width ?? 0) > WIDE_SPLIT_PANEL_BREAKPOINT;- });-- const previewVisible = createMemo(- () =>- isWideSplitPanel() &&- (!!soup.previewEntity() || panel.previewState[0]()) &&- !!soup.focus.item()- );-- // Placeholder display only for new inbox where the preview panel is open by default- // Only open while no items are focused- const previewPlaceholderVisible = createMemo(() => {- return isWideSplitPanel() && isNewInboxEnabled() && !soup.focus.item();- });-- const previewPaneVisible = createMemo(- () => rows().length > 0 && (previewVisible() || previewPlaceholderVisible())- );-- return {- paneVisible: previewPaneVisible,- placeholderVisible: previewPlaceholderVisible,- previewVisible,- };-}-interface SoupViewListProps {customScrollbarHidden?: boolean;scopeId?: string;diff --git a/js/app/packages/app/component/next-soup/soup-view/use-preview-pane-visibility.ts b/js/app/packages/app/component/next-soup/soup-view/use-preview-pane-visibility.tsnew file mode 100644index 0000000000..9a1122198c--- /dev/null+++ b/js/app/packages/app/component/next-soup/soup-view/use-preview-pane-visibility.ts@@ -0,0 +1,65 @@+import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';+import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';+import { isListViewID } from '@app/constants/list-views';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import {+ ENABLE_NEW_INBOX_FLAG,+ ENABLE_NEW_INBOX_OVERRIDE,+} from '@core/constant/featureFlags';+import { createMemo } from 'solid-js';++export const WIDE_SPLIT_PANEL_BREAKPOINT = 512;++export function useIsNewInboxEnabled() {+ const panel = useSplitPanelOrThrow();++ const currentView = () => {+ const { type, id } = panel.handle.content();+ if (type !== 'component') return;+ return isListViewID(id) ? id : undefined;+ };++ const newInboxFlag = useFeatureFlag(ENABLE_NEW_INBOX_FLAG, {+ enabledOverride: ENABLE_NEW_INBOX_OVERRIDE,+ });++ const isNewInboxEnabled = () =>+ currentView() === 'inbox' && newInboxFlag().enabled;++ return isNewInboxEnabled;+}++export function usePreviewPaneVisiblity() {+ const panel = useSplitPanelOrThrow();++ const { soup, rows } = useSoupView();++ const isNewInboxEnabled = useIsNewInboxEnabled();++ const isWideSplitPanel = createMemo(() => {+ return (panel.panelSize.width ?? 0) > WIDE_SPLIT_PANEL_BREAKPOINT;+ });++ const previewVisible = createMemo(+ () =>+ isWideSplitPanel() &&+ (!!soup.previewEntity() || panel.previewState[0]()) &&+ !!soup.focus.item()+ );++ // Placeholder display only for new inbox where the preview panel is open by default+ // Only open while no items are focused+ const previewPlaceholderVisible = createMemo(() => {+ return isWideSplitPanel() && isNewInboxEnabled() && !soup.focus.item();+ });++ const previewPaneVisible = createMemo(+ () => rows().length > 0 && (previewVisible() || previewPlaceholderVisible())+ );++ return {+ paneVisible: previewPaneVisible,+ placeholderVisible: previewPlaceholderVisible,+ previewVisible,+ };+}diff --git a/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyKanban.tsx b/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyKanban.tsxindex 11552817b5..14659ea12a 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyKanban.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyKanban.tsx@@ -1,26 +1,41 @@+import { useGlobalBlockOrchestrator } from '@app/component/GlobalAppState';import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';+import { usePreviewPaneVisiblity } from '@app/component/next-soup/soup-view/use-preview-pane-visibility';import { openEntityInSplitFromUnifiedList } from '@app/component/next-soup/utils';+import { PreviewPanel } from '@app/component/PreviewPanel';import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';+import { useDealStages } from '@companies/crm/deal-stages';+import {+ type CrmDisplayOptions,+ useCrmDisplayOptions,+} from '@companies/crm/display-options';+import { CrmStageIcon } from '@companies/crm/StageIcon';+import {+ useClosedStageIds,+ useCrmPermissions,+} from '@companies/crm/team-crm-config';+import { Resize } from '@core/component/Resize';import { UserIcon } from '@core/component/UserIcon';+import EmptyStatePreviewIcon from '@design/empty-state-doc.svg';import {- COMPANY_STAGE_OPTIONS,Entity,type EntityData,formatTimestamp,getCompanyOwnerId,- getCompanyStageOptionId,isCrmCompanyEntity,} from '@entity';-import { buildCompanyDefaultProperties } from '@entity/extractors-property';import CircleDashed from '@phosphor/circle-dashed.svg';-import { PropertyValueIcon } from '@property/component/propertyValue/PropertyValueIcon';-import { SYSTEM_PROPERTY_IDS } from '@property/constants';-import type { Property } from '@property/types';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';-import { useIsTeamAdmin } from '@queries/team/teams';import { EntityType } from '@service-properties/generated/schemas/entityType';-import { cn, Layer } from '@ui';-import { createMemo, createSignal, For, Show } from 'solid-js';+import { cn, EmptyStatePanel, Layer } from '@ui';+import {+ createEffect,+ createMemo,+ createSignal,+ For,+ onCleanup,+ Show,+} from 'solid-js';/** Column key for companies without a Stage value. */const NO_STAGE_KEY = '';@@ -30,57 +45,93 @@ type StageColumn = {label: string;};-const STAGE_COLUMNS: StageColumn[] = [- ...COMPANY_STAGE_OPTIONS.map((option) => ({- key: option.value as string,- label: option.label,- })),- { key: NO_STAGE_KEY, label: 'No stage' },-];-/**- * Kanban board for the Customers view: one column per Stage option (plus- * "No stage"), fed by the same filtered soup entities as the list. Cards+ * Kanban board for the Customers view: one column per active deal stage+ * (team-customized set when present, else the seeded system stages) plus+ * "No stage", fed by the same filtered soup entities as the list. Cards* drag between columns to update the company's Stage property (team- * admins/owners only, matching CRM edit access).+ * admins/owners only, matching CRM edit access; moving deals out of a+ * closed stage additionally requires the move-closed-deals permission).+ *+ * Like the list, the board supports the toggleable preview pane (Preview+ * button / space in the filters bar): while it's open, clicking a card+ * previews the company to the side instead of replacing the split.*/export function CompanyKanban() {const { source, soup } = useSoupView();const panel = useSplitPanelOrThrow();- const isTeamAdmin = useIsTeamAdmin();const saveMutation = useBulkSaveEntityPropertiesMutation();+ const orchestrator = useGlobalBlockOrchestrator();- const stageProperty = createMemo(- (): Property =>- buildCompanyDefaultProperties().find(- (property) =>- property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STAGE- )!+ const { stages, stageProperty, resolveStage } = useDealStages();+ const { canEditCrm, canMoveClosedDeals } = useCrmPermissions();+ const closedStageIds = useClosedStageIds(stages);+ // Personal display options gate which fields render on cards; read once+ // here and passed down rather than per-card.+ const displayOptions = useCrmDisplayOptions();++ const stageColumns = createMemo((): StageColumn[] => [+ ...stages().map((stage) => ({ key: stage.id, label: stage.label })),+ { key: NO_STAGE_KEY, label: 'No stage' },+ ]);++ // Preview-pane open state is per history entry, mirroring SoupViewList:+ // restored synchronously so the first render sees the pane, captured on+ // nav-away so back/forward returns to the same state.+ const persistedPreview = panel.handle.currentEntryState()?.['soup.preview'] as+ | string+ | undefined;+ soup.setPreviewEntity(persistedPreview);+ const previewCaptorTeardown = panel.handle.registerEntryStateCaptor(+ 'soup.preview',+ () => soup.previewEntity());+ onCleanup(previewCaptorTeardown);++ const { paneVisible, previewVisible } = usePreviewPaneVisiblity();++ // Keep the panel-level preview flag in sync (entity toolbars read it),+ // and clear it when the board unmounts so it doesn't go stale.+ createEffect(() => {+ const hasPreviewEntity = !!soup.previewEntity();+ const [getPreview, setPreview] = panel.previewState;+ if (hasPreviewEntity !== getPreview()) {+ setPreview(hasPreviewEntity);+ }+ });+ onCleanup(() => panel.previewState[1](false));const companies = createMemo(() => source.data().filter(isCrmCompanyEntity));const columns = createMemo(() => {const buckets = new Map<string, EntityData[]>(- STAGE_COLUMNS.map((column) => [column.key, []])+ stageColumns().map((column) => [column.key, []]));for (const company of companies()) {- const key = getCompanyStageOptionId(company) ?? NO_STAGE_KEY;+ const key = resolveStage(company) ?? NO_STAGE_KEY;(buckets.get(buckets.has(key) ? key : NO_STAGE_KEY) ?? []).push(company);}- return STAGE_COLUMNS.map((column) => ({+ return stageColumns().map((column) => ({...column,entities: buckets.get(column.key) ?? [],}));});+ // A card can be dragged when the user can edit CRM data at all, and its+ // current stage is either open or the user may move closed deals.+ const canDragFrom = (stageKey: string) =>+ canEditCrm() &&+ (stageKey === NO_STAGE_KEY ||+ !closedStageIds().has(stageKey) ||+ canMoveClosedDeals());+const [draggedId, setDraggedId] = createSignal<string>();const [dropTarget, setDropTarget] = createSignal<string>();const moveToStage = (entityId: string, stageKey: string) => {const entity = companies().find((company) => company.id === entityId);if (!entity) return;- const currentStage = getCompanyStageOptionId(entity) ?? NO_STAGE_KEY;+ const currentStage = resolveStage(entity) ?? NO_STAGE_KEY;if (currentStage === stageKey) return;saveMutation.mutate({@@ -100,6 +151,14 @@ export function CompanyKanban() {const openCompany = (entity: EntityData, event: MouseEvent) => {soup.focus.set(entity.id);++ // While the preview pane is open, card clicks retarget it instead of+ // replacing the split (mirrors the list view's behavior).+ if (previewVisible() && soup.previewEntity()) {+ soup.setPreviewEntity(entity.id);+ return;+ }+void openEntityInSplitFromUnifiedList(entity, {openInNewSplit: event.shiftKey,splitHandle: panel.handle,@@ -108,86 +167,128 @@ export function CompanyKanban() {};return (- <div class="size-full min-w-0 overflow-x-auto overflow-y-hidden">- <div class="flex h-full gap-3 p-3">- <For each={columns()}>- {(column) => (- <div- class={cn(- 'flex h-full w-64 shrink-0 flex-col rounded-lg border border-edge-muted bg-surface',- dropTarget() === column.key &&- draggedId() &&- 'border-accent/50 bg-accent/5'- )}- onDragOver={(e) => {- if (!draggedId()) return;- e.preventDefault();- setDropTarget(column.key);- }}- onDragLeave={(e) => {- if (- e.relatedTarget instanceof Node &&- e.currentTarget.contains(e.relatedTarget)- ) {- return;- }- if (dropTarget() === column.key) setDropTarget(undefined);- }}- onDrop={(e) => {- e.preventDefault();- const id = draggedId() ?? e.dataTransfer?.getData('text/plain');- setDropTarget(undefined);- setDraggedId(undefined);- if (id) moveToStage(id, column.key);- }}- >- <div class="flex items-center gap-2 px-3 py-2.5 text-xs font-semibold text-ink-muted">- <Show- when={column.key !== NO_STAGE_KEY}- fallback={- <CircleDashed class="size-3.5 text-ink-extra-muted" />- }- >- <PropertyValueIcon optionId={column.key} class="size-3.5" />- </Show>- <span class="truncate">{column.label}</span>- <span class="ml-auto shrink-0 tabular-nums px-1.5 py-px rounded-full bg-ink/10 text-ink-extra-muted font-medium">- {column.entities.length}- </span>- </div>- <div class="min-h-0 flex-1 overflow-y-auto scrollbar-hidden flex flex-col gap-2 px-2 pb-2">- <For each={column.entities}>- {(entity) => (- <CompanyKanbanCard- entity={entity}- draggable={isTeamAdmin()}- dragging={draggedId() === entity.id}- onDragStart={(e) => {- e.dataTransfer?.setData('text/plain', entity.id);- if (e.dataTransfer) {- e.dataTransfer.effectAllowed = 'move';- }- setDraggedId(entity.id);- }}- onDragEnd={() => {- setDraggedId(undefined);- setDropTarget(undefined);- }}- onClick={(e) => openCompany(entity, e)}- />- )}- </For>- </div>- </div>+ <Resize.Zone direction="horizontal" gutter={0}>+ <Resize.Panel id="company-kanban" minSize={200}>+ <div+ class={cn(+ 'size-full min-w-0 overflow-x-auto overflow-y-hidden',+ paneVisible() && 'border-r border-edge-muted')}- </For>- </div>- </div>+ >+ <div class="flex h-full gap-3 p-3">+ <For each={columns()}>+ {(column, columnIndex) => (+ <div+ class={cn(+ 'flex h-full w-64 shrink-0 flex-col rounded-lg border border-edge-muted bg-surface',+ dropTarget() === column.key &&+ draggedId() &&+ 'border-accent/50 bg-accent/5'+ )}+ onDragOver={(e) => {+ if (!draggedId()) return;+ e.preventDefault();+ setDropTarget(column.key);+ }}+ onDragLeave={(e) => {+ if (+ e.relatedTarget instanceof Node &&+ e.currentTarget.contains(e.relatedTarget)+ ) {+ return;+ }+ if (dropTarget() === column.key) setDropTarget(undefined);+ }}+ onDrop={(e) => {+ e.preventDefault();+ const id =+ draggedId() ?? e.dataTransfer?.getData('text/plain');+ setDropTarget(undefined);+ setDraggedId(undefined);+ if (id) moveToStage(id, column.key);+ }}+ >+ <div class="flex items-center gap-2 px-3 py-2.5 text-xs font-semibold text-ink-muted">+ <Show+ when={column.key !== NO_STAGE_KEY}+ fallback={+ <CircleDashed class="size-3.5 text-ink-extra-muted" />+ }+ >+ <CrmStageIcon+ optionId={column.key}+ index={columnIndex()}+ class="size-3.5"+ />+ </Show>+ <span class="truncate">{column.label}</span>+ <span class="ml-auto shrink-0 tabular-nums px-1.5 py-px rounded-full bg-ink/10 text-ink-extra-muted font-medium">+ {column.entities.length}+ </span>+ </div>+ <div class="min-h-0 flex-1 overflow-y-auto scrollbar-hidden flex flex-col gap-2 px-2 pb-2">+ <For each={column.entities}>+ {(entity) => (+ <CompanyKanbanCard+ entity={entity}+ fields={displayOptions.options().kanbanFields}+ draggable={canDragFrom(column.key)}+ dragging={draggedId() === entity.id}+ onDragStart={(e) => {+ e.dataTransfer?.setData('text/plain', entity.id);+ if (e.dataTransfer) {+ e.dataTransfer.effectAllowed = 'move';+ }+ setDraggedId(entity.id);+ }}+ onDragEnd={() => {+ setDraggedId(undefined);+ setDropTarget(undefined);+ }}+ onClick={(e) => openCompany(entity, e)}+ />+ )}+ </For>+ </div>+ </div>+ )}+ </For>+ </div>+ </div>+ </Resize.Panel>+ <Show when={paneVisible()}>+ <Resize.Panel+ id="soup-preview"+ minSize={500}+ target={{ kind: 'percent', percent: 70 }}+ >+ <Show+ when={soup.focus.item()}+ fallback={+ <EmptyStatePanel+ graphic={EmptyStatePreviewIcon}+ title="Nothing selected"+ description="Select a card from the board to preview it here"+ centered+ />+ }+ >+ <PreviewPanel+ selectedEntity={soup.focus.item()}+ orchestrator={orchestrator}+ splitPanelContext={panel}+ />+ </Show>+ </Resize.Panel>+ </Show>+ </Resize.Zone>);}function CompanyKanbanCard(props: {entity: EntityData;+ /** Which optional card fields render (personal display options). */+ fields: CrmDisplayOptions['kanbanFields'];draggable: boolean;dragging: boolean;onDragStart: (e: DragEvent) => void;@@ -223,7 +324,7 @@ function CompanyKanbanCard(props: {<span class="ph-no-capture truncate font-semibold min-w-0"><Entity.Title entity={props.entity} /></span>- <Show when={ownerId()}>+ <Show when={props.fields.owner && ownerId()}>{(id) => (<span class="ml-auto shrink-0"><UserIcon id={id()} size="sm" suppressClick />@@ -231,17 +332,19 @@ function CompanyKanbanCard(props: {)}</Show></div>- <div class="flex items-center gap-2 min-w-0 text-xs text-ink-extra-muted">- <Show when={primaryDomain()}>- {(domain) => <span class="truncate min-w-0">{domain()}</span>}- </Show>- {/* Last interaction — updatedAt carries crm_companies.last_interaction. */}- <Show when={props.entity.updatedAt}>- {(ts) => (- <span class="ml-auto shrink-0">{formatTimestamp(ts())}</span>- )}- </Show>- </div>+ <Show when={props.fields.domain || props.fields.lastInteraction}>+ <div class="flex items-center gap-2 min-w-0 text-xs text-ink-extra-muted">+ <Show when={props.fields.domain && primaryDomain()}>+ {(domain) => <span class="truncate min-w-0">{domain()}</span>}+ </Show>+ {/* Last interaction — updatedAt carries crm_companies.last_interaction. */}+ <Show when={props.fields.lastInteraction && props.entity.updatedAt}>+ {(ts) => (+ <span class="ml-auto shrink-0">{formatTimestamp(ts())}</span>+ )}+ </Show>+ </div>+ </Show></div></Layer>);diff --git a/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyListHeader.tsx b/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyListHeader.tsxindex 9dbadd0d8d..d112a7a818 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyListHeader.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyListHeader.tsx@@ -1,5 +1,6 @@import type { SystemSortOption } from '@app/component/next-soup/soup-view/sort-options';import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';+import { useCrmDisplayOptions } from '@companies/crm/display-options';import { useListLayout } from '@entity/composed/list-entity/shared';import ArrowDownIcon from '@phosphor/arrow-down.svg';import { cn } from '@ui/utils/classname';@@ -7,8 +8,8 @@ import { createMemo, For, Show } from 'solid-js';import '../tasks/list-property-value.css';import {COMPANY_GRID_COLUMNS,- COMPANY_GRID_TEMPLATE_AREAS,- COMPANY_GRID_TEMPLATE_COLUMNS,+ companyGridTemplateAreas,+ companyGridTemplateColumns,} from './company-grid-template';/**@@ -34,6 +35,15 @@ export function ResponsiveCompanyListHeader(props: { class?: string }) {*/function CompanyListHeader(props: { class?: string }) {const { soup } = useSoupView();+ const displayOptions = useCrmDisplayOptions();++ // Mirror the row grid: hidden display-option columns collapse here too so+ // the header tracks stay aligned with CompanyGridLayout.+ const visibleColumns = createMemo(() =>+ COMPANY_GRID_COLUMNS.filter(+ (col) => displayOptions.options().listColumns[col.id]+ )+ );const activeSort = createMemo(() => soup.sort.active()[0]);const setSort = (id: SystemSortOption) => {if (activeSort()?.id === id) {@@ -55,15 +65,21 @@ function CompanyListHeader(props: { class?: string }) {props.class)}style={{- 'grid-template-columns': COMPANY_GRID_TEMPLATE_COLUMNS,- 'grid-template-areas': COMPANY_GRID_TEMPLATE_AREAS,+ 'grid-template-columns': companyGridTemplateColumns(+ visibleColumns(),+ false+ ),+ 'grid-template-areas': companyGridTemplateAreas(+ visibleColumns(),+ false+ ),}}><div style={{ 'grid-area': 'indicator' }} /><div style={{ 'grid-area': 'content' }} class="truncate">Customer</div>- <For each={COMPANY_GRID_COLUMNS}>+ <For each={visibleColumns()}>{(col) => (<divstyle={{ 'grid-area': col.id }}diff --git a/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx b/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyViewsMenu.tsxnew file mode 100644index 0000000000..5529a0dda9--- /dev/null+++ b/js/app/packages/app/component/next-soup/soup-view/views/companies/CompanyViewsMenu.tsx@@ -0,0 +1,366 @@+import type { Query } from '@app/component/next-soup/filters/filter-store';+import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-context';+import {+ CRM_KANBAN_FIELD_LABELS,+ CRM_LIST_COLUMN_LABELS,+ type CrmKanbanFieldId,+ type CrmListColumnId,+ useCrmDisplayOptions,+} from '@companies/crm/display-options';+import {+ buildCrmViewShareUrl,+ type CrmViewConfig,+ usePersonalCrmViews,+ useTeamCrmViews,+} from '@companies/crm/saved-views';+import { useCrmPermissions } from '@companies/crm/team-crm-config';+import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';+import FloppyDiskIcon from '@phosphor/floppy-disk.svg';+import LinkIcon from '@phosphor/link.svg';+import SlidersIcon from '@phosphor/sliders-horizontal.svg';+import StackIcon from '@phosphor/stack.svg';+import TrashIcon from '@phosphor/trash.svg';+import { Button, cn, Dropdown, SegmentedControl, Tooltip } from '@ui';+import { batch, createSignal, For, type JSX, Show } from 'solid-js';+import { unwrap } from 'solid-js/store';++type SoupViewMode = 'list' | 'board';++/** Copy a view's share link, with a toast either way. */+const copyShareLink = (config: CrmViewConfig) => {+ navigator.clipboard+ .writeText(buildCrmViewShareUrl(config))+ .then(() => toast.success('Link copied to clipboard'))+ .catch(() => toast.failure('Failed to copy link'));+};++/**+ * Saved-view row: the name applies the view; trailing hover actions copy+ * its share link or delete it.+ */+const SavedViewRow = (props: {+ name: string;+ onApply: () => void;+ onCopyLink: () => void;+ onDelete?: () => void;+}) => (+ <div class="group rounded-lg w-full flex items-center gap-0.5 pl-2 pr-1 hover:bg-ink/5">+ <button+ type="button"+ class="flex-1 min-w-0 truncate py-1.5 text-left text-sm"+ onClick={props.onApply}+ >+ {props.name}+ </button>+ <Tooltip label="Copy link">+ <Button+ variant="ghost"+ size="icon-sm"+ label="Copy link"+ class="size-6 shrink-0 rounded-md p-1 text-ink-muted opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ onClick={props.onCopyLink}+ >+ <LinkIcon class="size-3.5" />+ </Button>+ </Tooltip>+ <Show when={props.onDelete}>+ {(onDelete) => (+ <Tooltip label="Delete view">+ <Button+ variant="ghost"+ size="icon-sm"+ label="Delete view"+ class="size-6 shrink-0 rounded-md p-1 text-ink-muted opacity-0 group-hover:opacity-100 focus-visible:opacity-100"+ onClick={() => onDelete()()}+ >+ <TrashIcon class="size-3.5" />+ </Button>+ </Tooltip>+ )}+ </Show>+ </div>+);++const EmptyViewsHint = (props: { children: JSX.Element }) => (+ <div class="px-2 py-1.5 text-xs text-ink-extra-muted">{props.children}</div>+);++/**+ * Saved-views dropdown for the Customers view: personal and team-shared+ * snapshots of the full view state (filters, search, grouping, sort,+ * list/board mode, stage/owner sub-filters, tab), plus share links that+ * encode the same state into the URL (see `@companies/crm/saved-views`).+ */+export function CompanyViewsMenu(props: {+ viewMode: SoupViewMode;+ setViewMode: (mode: SoupViewMode) => void;+}) {+ const {+ soup,+ queryFilters,+ searchText,+ setSearchText,+ stageFilter,+ setStageFilter,+ ownerFilter,+ setOwnerFilter,+ activeTab,+ setActiveTab,+ } = useSoupView();+ const personal = usePersonalCrmViews();+ const team = useTeamCrmViews();+ const { canEditCrm } = useCrmPermissions();+ const userId = useUserId();++ const [open, setOpen] = createSignal(false);+ const [saveFormOpen, setSaveFormOpen] = createSignal(false);+ const [saveName, setSaveName] = createSignal('');+ const [saveScope, setSaveScope] = createSignal<'personal' | 'team'>(+ 'personal'+ );++ const captureCurrentView = (): CrmViewConfig => ({+ kind: 'crm',+ // JSON-safe snapshot — the store's state must not leak by reference.+ filters: structuredClone(unwrap(queryFilters.state)),+ clientFilters: {+ and: [...soup.predicates.andIds()],+ or: [...soup.predicates.orIds()],+ },+ searchText: searchText(),+ groupBy: soup.grouping.activeGroupId() ?? null,+ sort: soup.sort.active().map((s) => s.id),+ viewMode: props.viewMode,+ stageFilter: [...stageFilter()],+ ownerFilter: [...ownerFilter()],+ activeTab: activeTab(),+ });++ // Mirrors the init/applyTabPreset path: replace filters + predicates+ // atomically, then re-derive the stage/owner predicate active state from+ // the saved sub-filter selections (same rule as handleStageChange /+ // handleOwnerChange in unified-filter-dropdown).+ const applyView = (config: CrmViewConfig) => {+ batch(() => {+ queryFilters.replace((config.filters as Query | undefined) ?? null);+ soup.predicates.set(config.clientFilters ?? {});+ setSearchText(config.searchText ?? '');+ // `groupBy: null` records an explicit "no grouping"; the grouping+ // store expresses that as `undefined` (same as the init path).+ soup.grouping.setActiveGroupId(config.groupBy ?? undefined);+ soup.sort.setAll(+ (config.sort?.length ? config.sort : ['updated_at']) as Parameters<+ typeof soup.sort.setAll+ >[0]+ );+ const stages = config.stageFilter ?? [];+ setStageFilter(stages);+ if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {+ soup.predicates.toggle({ and: ['company-stage'] });+ }+ const owners = config.ownerFilter ?? [];+ setOwnerFilter(owners);+ if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {+ soup.predicates.toggle({ and: ['company-owner'] });+ }+ props.setViewMode(config.viewMode ?? 'list');+ if (config.activeTab !== undefined) setActiveTab(config.activeTab);+ });+ setOpen(false);+ };++ const saveCurrentView = () => {+ const name = saveName().trim();+ if (!name) return;+ const config = captureCurrentView();+ if (saveScope() === 'team') {+ team.add(name, config);+ } else {+ personal.create.mutate({ name, config });+ }+ setSaveFormOpen(false);+ setSaveName('');+ setOpen(false);+ toast.success('View saved');+ };++ const canDeleteTeamView = (createdBy: string | undefined) =>+ canEditCrm() || (createdBy !== undefined && createdBy === userId());++ const handleOpenChange = (isOpen: boolean) => {+ setOpen(isOpen);+ if (!isOpen) {+ setSaveFormOpen(false);+ setSaveName('');+ }+ };++ return (+ <Dropdown open={open()} onOpenChange={handleOpenChange}>+ <Dropdown.Trigger depth={2} class="bg-surface">+ <StackIcon />+ <span>Views</span>+ </Dropdown.Trigger>++ <Dropdown.Content class="w-64 shadow-menu">+ <Dropdown.Group>+ <Dropdown.GroupLabel>My views</Dropdown.GroupLabel>+ <For+ each={personal.views()}+ fallback={<EmptyViewsHint>No saved views</EmptyViewsHint>}+ >+ {(view) => (+ <SavedViewRow+ name={view.name}+ onApply={() => applyView(view.config)}+ onCopyLink={() => copyShareLink(view.config)}+ onDelete={() => personal.remove.mutate({ id: view.id })}+ />+ )}+ </For>+ </Dropdown.Group>++ <Dropdown.Group>+ <Dropdown.GroupLabel>Team views</Dropdown.GroupLabel>+ <For+ each={team.views()}+ fallback={<EmptyViewsHint>No team views</EmptyViewsHint>}+ >+ {(view) => (+ <SavedViewRow+ name={view.name}+ onApply={() => applyView(view.config as CrmViewConfig)}+ onCopyLink={() => copyShareLink(view.config as CrmViewConfig)}+ onDelete={+ canDeleteTeamView(view.createdBy)+ ? () => team.remove(view.id)+ : undefined+ }+ />+ )}+ </For>+ </Dropdown.Group>++ <Dropdown.Group>+ <Show+ when={saveFormOpen()}+ fallback={+ <Dropdown.Item+ closeOnSelect={false}+ onSelect={() => setSaveFormOpen(true)}+ >+ <FloppyDiskIcon class="size-3.5 shrink-0 text-ink-muted" />+ <span class="flex-1 truncate">Save current view…</span>+ </Dropdown.Item>+ }+ >+ <div class="flex flex-col gap-1.5 p-1.5">+ <input+ ref={(el) => requestAnimationFrame(() => el.focus())}+ value={saveName()}+ onInput={(e) => setSaveName(e.currentTarget.value)}+ onKeyDown={(e) => {+ // Keep character keys / Enter away from the menu's+ // typeahead and item selection; Escape still closes.+ if (e.key === 'Escape') return;+ e.stopPropagation();+ if (e.key === 'Enter') saveCurrentView();+ }}+ placeholder="View name"+ class={cn(+ 'w-full rounded-md border border-edge-muted bg-transparent px-2 py-1 text-sm',+ 'outline-none focus:border-accent placeholder:text-ink-faint'+ )}+ />+ <div class="flex items-center justify-between gap-1.5">+ <SegmentedControl+ size="sm"+ aria-label="View visibility"+ value={saveScope()}+ onChange={(value) => setSaveScope(value)}+ options={[+ { value: 'personal', label: 'Personal' },+ { value: 'team', label: 'Team' },+ ]}+ />+ <Button+ variant="base"+ size="sm"+ disabled={!saveName().trim()}+ onClick={saveCurrentView}+ >+ Save+ </Button>+ </div>+ </div>+ </Show>+ <Dropdown.Item+ closeOnSelect+ onSelect={() => copyShareLink(captureCurrentView())}+ >+ <LinkIcon class="size-3.5 shrink-0 text-ink-muted" />+ <span class="flex-1 truncate">Copy link to current view</span>+ </Dropdown.Item>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ );+}++/**+ * Personal display options for the Customers view: which property columns+ * show in the list and which fields show on board cards. Device-level+ * (preference-backed) — deliberately not captured by saved views.+ */+export function CompanyDisplayMenu() {+ const { options, toggleListColumn, toggleKanbanField } =+ useCrmDisplayOptions();++ return (+ <Dropdown>+ <Tooltip label="Display options">+ <Dropdown.Trigger depth={2} class="bg-surface" label="Display options">+ <SlidersIcon />+ </Dropdown.Trigger>+ </Tooltip>++ <Dropdown.Content class="w-56 shadow-menu">+ <Dropdown.Group>+ <Dropdown.GroupLabel>List columns</Dropdown.GroupLabel>+ <For each={Object.keys(CRM_LIST_COLUMN_LABELS) as CrmListColumnId[]}>+ {(column) => (+ <Dropdown.CheckboxItem+ checked={options().listColumns[column]}+ onChange={() => toggleListColumn(column)}+ closeOnSelect={false}+ >+ <span class="flex-1 truncate">+ {CRM_LIST_COLUMN_LABELS[column]}+ </span>+ </Dropdown.CheckboxItem>+ )}+ </For>+ </Dropdown.Group>+ <Dropdown.Group>+ <Dropdown.GroupLabel>Board card fields</Dropdown.GroupLabel>+ <For+ each={Object.keys(CRM_KANBAN_FIELD_LABELS) as CrmKanbanFieldId[]}+ >+ {(field) => (+ <Dropdown.CheckboxItem+ checked={options().kanbanFields[field]}+ onChange={() => toggleKanbanField(field)}+ closeOnSelect={false}+ >+ <span class="flex-1 truncate">+ {CRM_KANBAN_FIELD_LABELS[field]}+ </span>+ </Dropdown.CheckboxItem>+ )}+ </For>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ );+}diff --git a/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-layout.tsx b/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-layout.tsxindex d8c1df9273..61fadd0aba 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-layout.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-layout.tsx@@ -1,3 +1,5 @@+import { useDealStages } from '@companies/crm/deal-stages';+import { useCrmDisplayOptions } from '@companies/crm/display-options';import {Entity,type EntityData,@@ -11,6 +13,7 @@ import {soupPropertyToProperty,} from '@entity/extractors-property';import { Modals } from '@property/component/modal';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';import {PropertiesProvider,type PropertySaveHandler,@@ -24,10 +27,8 @@ import { createMemo, For, Show, Suspense } from 'solid-js';import { ListPropertyValue } from '../tasks/list-property-value';import {COMPANY_GRID_COLUMNS,- COMPANY_GRID_TEMPLATE_AREAS,- COMPANY_GRID_TEMPLATE_AREAS_NO_INDICATOR,- COMPANY_GRID_TEMPLATE_COLUMNS,- COMPANY_GRID_TEMPLATE_COLUMNS_NO_INDICATOR,+ companyGridTemplateAreas,+ companyGridTemplateColumns,} from './company-grid-template';/**@@ -37,6 +38,16 @@ import {*/export function CompanyGridLayout(props: LayoutProps) {const isTeamAdmin = useIsTeamAdmin();+ const dealStages = useDealStages();+ const displayOptions = useCrmDisplayOptions();++ // Only the columns toggled on in the personal display options render;+ // hidden ones collapse out of the grid template entirely.+ const visibleColumns = createMemo(() =>+ COMPANY_GRID_COLUMNS.filter(+ (col) => displayOptions.options().listColumns[col.id]+ )+ );const primaryDomain = () => {const entity = props.entity as EntityData;@@ -63,6 +74,31 @@ export function CompanyGridLayout(props: LayoutProps) {map.set(stub.propertyDefinitionId, stub);}}++ // The Stage column reads/writes the active stage definition (the+ // team's own Stage set when customized). When the company has no value+ // under the active definition but a legacy system-stage value maps+ // onto it, surface the mapped id so the cell displays — and edits+ // write to — the active definition.+ const stageDefinitionId = dealStages.stageDefinitionId();+ const existingStage = map.get(stageDefinitionId);+ const hasStageValue =+ existingStage?.valueType === 'SELECT_STRING' &&+ (existingStage.value?.length ?? 0) > 0;+ if (!hasStageValue) {+ const stageStub = dealStages.stageProperty();+ const resolvedId = dealStages.resolveStage(entity);+ map.set(+ stageDefinitionId,+ stageStub.valueType === 'SELECT_STRING' && resolvedId+ ? { ...stageStub, value: [resolvedId] }+ : stageStub+ );+ }+ // Once customized, the system Stage stub is superseded entirely.+ if (stageDefinitionId !== SYSTEM_PROPERTY_IDS.STAGE) {+ map.delete(SYSTEM_PROPERTY_IDS.STAGE);+ }return map;});@@ -104,12 +140,14 @@ export function CompanyGridLayout(props: LayoutProps) {'gap-2 grid grid-rows-[1fr]')}style={{- 'grid-template-columns': props.hideCheckbox- ? COMPANY_GRID_TEMPLATE_COLUMNS_NO_INDICATOR- : COMPANY_GRID_TEMPLATE_COLUMNS,- 'grid-template-areas': props.hideCheckbox- ? COMPANY_GRID_TEMPLATE_AREAS_NO_INDICATOR- : COMPANY_GRID_TEMPLATE_AREAS,+ 'grid-template-columns': companyGridTemplateColumns(+ visibleColumns(),+ !!props.hideCheckbox+ ),+ 'grid-template-areas': companyGridTemplateAreas(+ visibleColumns(),+ !!props.hideCheckbox+ ),}}><Show when={!props.hideCheckbox}>@@ -155,13 +193,19 @@ export function CompanyGridLayout(props: LayoutProps) {</Show></Entity.Slot>- <For each={COMPANY_GRID_COLUMNS}>+ <For each={visibleColumns()}>{(col) => (<Entity.Slotplacement={col.id}class="flex items-center min-w-0 text-xs ph-no-capture @container/slot @max-[840px]/u-list:justify-center">- <Show when={propertyMap().get(col.defId)}>+ <Show+ when={propertyMap().get(+ col.id === 'stage'+ ? dealStages.stageDefinitionId()+ : col.defId+ )}+ >{(property) => <ListPropertyValue property={property()} />}</Show></Entity.Slot>diff --git a/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-template.ts b/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-template.tsindex c81af15778..1e22f9b70a 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-template.ts+++ b/js/app/packages/app/component/next-soup/soup-view/views/companies/company-grid-template.ts@@ -42,20 +42,51 @@ export type CompanyGridColumn = (typeof COMPANY_GRID_COLUMNS)[number];/** Width for the trailing Last Interaction timestamp column. */const LAST_INTERACTION_COLUMN_WIDTH = 'var(--company-col-timestamp, 7rem)';-export const COMPANY_GRID_TEMPLATE_COLUMNS = `1rem minmax(0, 100%) ${COMPANY_GRID_COLUMNS.map(- (c) => c.width-).join(' ')} ${LAST_INTERACTION_COLUMN_WIDTH}`;+/**+ * `grid-template-columns` for the given visible property columns (hidden+ * columns collapse entirely). `hideIndicator` drops the leading+ * indicator (checkbox) track.+ */+export function companyGridTemplateColumns(+ visible: readonly CompanyGridColumn[],+ hideIndicator: boolean+): string {+ return [+ ...(hideIndicator ? [] : ['1rem']),+ 'minmax(0, 100%)',+ ...visible.map((c) => c.width),+ LAST_INTERACTION_COLUMN_WIDTH,+ ].join(' ');+}++/** `grid-template-areas` counterpart of {@link companyGridTemplateColumns}. */+export function companyGridTemplateAreas(+ visible: readonly CompanyGridColumn[],+ hideIndicator: boolean+): string {+ const areas = [+ ...(hideIndicator ? [] : ['indicator']),+ 'content',+ ...visible.map((c) => c.id),+ 'timestamp',+ ].join(' ');+ return `"${areas}"`;+}++export const COMPANY_GRID_TEMPLATE_COLUMNS = companyGridTemplateColumns(+ COMPANY_GRID_COLUMNS,+ false+);/** Template without the leading indicator (checkbox) column. */-export const COMPANY_GRID_TEMPLATE_COLUMNS_NO_INDICATOR = `minmax(0, 100%) ${COMPANY_GRID_COLUMNS.map(- (c) => c.width-).join(' ')} ${LAST_INTERACTION_COLUMN_WIDTH}`;+export const COMPANY_GRID_TEMPLATE_COLUMNS_NO_INDICATOR =+ companyGridTemplateColumns(COMPANY_GRID_COLUMNS, true);-export const COMPANY_GRID_TEMPLATE_AREAS = `"indicator content ${COMPANY_GRID_COLUMNS.map(- (c) => c.id-).join(' ')} timestamp"`;+export const COMPANY_GRID_TEMPLATE_AREAS = companyGridTemplateAreas(+ COMPANY_GRID_COLUMNS,+ false+);/** Template areas without the leading indicator (checkbox) column. */-export const COMPANY_GRID_TEMPLATE_AREAS_NO_INDICATOR = `"content ${COMPANY_GRID_COLUMNS.map(- (c) => c.id-).join(' ')} timestamp"`;+export const COMPANY_GRID_TEMPLATE_AREAS_NO_INDICATOR =+ companyGridTemplateAreas(COMPANY_GRID_COLUMNS, true);diff --git a/js/app/packages/app/component/settings/Crm.tsx b/js/app/packages/app/component/settings/Crm.tsxnew file mode 100644index 0000000000..172024dd95--- /dev/null+++ b/js/app/packages/app/component/settings/Crm.tsx@@ -0,0 +1,1135 @@+/**+ * CRM settings tab: team admins manage the CRM here — enablement, deal+ * stages (with the closed-stage set), custom company properties, and the+ * team's CRM permission thresholds.+ *+ * Deal stages are Macro's system defaults until the team customizes them,+ * which materializes a team-scoped `Stage` select property whose options are+ * the stages (see `@companies/crm/deal-stages`). Permissions and the closed+ * stage set live in the shared team CRM config+ * (see `@companies/crm/team-crm-config`).+ */++import {+ CRM_TEAM_STAGE_DEFINITION_NAME,+ type DealStage,+ findTeamStageDefinition,+ useDealStages,+} from '@companies/crm/deal-stages';+import {+ type CrmPermissionRole,+ type CrmPermissions,+ isReservedPropertyDefinitionName,+ useClosedStageIds,+ useCrmPermissions,+ useTeamCrmConfig,+} from '@companies/crm/team-crm-config';+import { toast } from '@core/component/Toast/Toast';+import { SERVER_HOSTS } from '@core/constant/servers';+import { throwOnErr } from '@core/util/result';+import type { CollectionNode } from '@kobalte/core';+import { Select } from '@kobalte/core/select';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CaretUpIcon from '@phosphor/caret-up.svg';+import CheckIcon from '@phosphor/check.svg';+import PlusIcon from '@phosphor/plus.svg';+import SpinnerIcon from '@phosphor/spinner.svg';+import TrashIcon from '@phosphor/trash.svg';+import XIcon from '@phosphor/x.svg';+import {+ useCreatePropertyDefinitionMutation,+ useDeletePropertyDefinitionMutation,+ useListPropertiesQuery,+} from '@queries/properties/definitions';+import {+ useAddPropertyOptionMutation,+ useDeletePropertyOptionMutation,+ useUpdatePropertyOptionMutation,+} from '@queries/properties/options';+import {+ invalidateUserTeams,+ useCurrentTeamQuery,+ useIsTeamAdmin,+} from '@queries/team/teams';+import { fetchWithAuth } from '@service-auth/fetch';+import type { PatchTeamCrmSettingsRequest } from '@service-auth/generated/schemas/patchTeamCrmSettingsRequest';+import type { PatchTeamCrmSettingsResponse } from '@service-auth/generated/schemas/patchTeamCrmSettingsResponse';+import type { PropertyDataType } from '@service-properties/generated/schemas/propertyDataType';+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';+import type { PropertyOption } from '@service-properties/generated/schemas/propertyOption';+import { useMutation, useQueryClient } from '@tanstack/solid-query';+import { Button, Checkbox, Dialog, Panel, Tooltip } from '@ui';+import {+ createMemo,+ createSignal,+ For,+ type JSX,+ Show,+ Suspense,+} from 'solid-js';+import { match } from 'ts-pattern';+import {+ SettingsCard,+ SettingsPage,+ SettingsRow,+ SettingsSection,+} from './primitives';++const authHost = SERVER_HOSTS['auth-service'];++/* ------------------------------------------------------------------ */+/* Shared bits */+/* ------------------------------------------------------------------ */++/** Read the label text out of a select-string property option. */+function optionLabel(option: PropertyOption): string {+ const value = option.value;+ if (+ value &&+ typeof value === 'object' &&+ 'value' in value &&+ typeof value.value === 'string'+ ) {+ return value.value;+ }+ return '';+}++/** Confirm dialog matching the Team tab's destructive-action dialogs. */+function ConfirmDialog(props: {+ open: boolean;+ title: string;+ confirmLabel: string;+ pending?: boolean;+ confirmDisabled?: boolean;+ onConfirm: () => void;+ onClose: () => void;+ children: JSX.Element;+}) {+ return (+ <Dialog open={props.open} onOpenChange={(open) => !open && props.onClose()}>+ <Panel depth={2} class="max-h-[75vh] text-ink rounded-xl">+ <Panel.Header class="px-2 gap-1">+ <Dialog.CloseButton as={Button} variant="ghost" size="icon-sm">+ <XIcon />+ </Dialog.CloseButton>+ <Dialog.Title as="span" class="text-sm font-medium p-0 m-0">+ {props.title}+ </Dialog.Title>+ </Panel.Header>+ <Panel.Body class="p-3 flex flex-col gap-3">+ {props.children}+ <div class="flex justify-end gap-1 pt-2">+ <Button+ variant="ghost"+ class="rounded-xs"+ disabled={props.pending}+ onClick={props.onClose}+ >+ Cancel+ </Button>+ <Button+ variant="danger"+ class="rounded-xs"+ disabled={props.pending || props.confirmDisabled}+ onClick={props.onConfirm}+ >+ <Show when={props.pending} fallback={props.confirmLabel}>+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </div>+ </Panel.Body>+ </Panel>+ </Dialog>+ );+}++/** Small single-select dropdown in the style of the Team tab's role select. */+function InlineSelect<T extends string>(props: {+ options: { value: T; label: string }[];+ value: T;+ onChange: (value: T) => void;+ disabled?: boolean;+}) {+ type Option = { value: T; label: string };+ const selectedOption = () =>+ props.options.find((o) => o.value === props.value) ?? props.options[0];++ return (+ <Select<Option>+ options={props.options}+ value={selectedOption()}+ onChange={(opt) => opt && props.onChange(opt.value)}+ optionValue="value"+ optionTextValue="label"+ gutter={4}+ placement="bottom-end"+ disabled={props.disabled}+ itemComponent={(itemProps: { item: CollectionNode<Option> }) => (+ <Select.Item+ item={itemProps.item}+ class="flex items-center justify-between gap-2 px-2 py-1.5 text-sm rounded-xs hover:bg-hover outline-none data-highlighted:bg-hover"+ >+ <Select.ItemLabel>{itemProps.item.rawValue.label}</Select.ItemLabel>+ <Select.ItemIndicator>+ <CheckIcon class="size-3" />+ </Select.ItemIndicator>+ </Select.Item>+ )}+ >+ <Select.Trigger+ as={Button}+ class="rounded-xs px-1.5 py-0.5 text-xs data-expanded:bg-ink/10"+ disabled={props.disabled}+ >+ <Select.Value<Option>>+ {(state) => state.selectedOption().label}+ </Select.Value>+ <CaretDownIcon class="size-3 text-ink-muted shrink-0" />+ </Select.Trigger>+ <Select.Portal>+ <Select.Content class="z-50 bg-surface ring-1 ring-edge rounded shadow-lg min-w-25 p-1">+ <Select.Listbox />+ </Select.Content>+ </Select.Portal>+ </Select>+ );+}++/* ------------------------------------------------------------------ */+/* CRM enablement */+/* ------------------------------------------------------------------ */++/**+ * PATCH /team/crm on the auth service. The generated orval client+ * (`patchTeamCrmSettings`) issues a bare relative `fetch` with no auth, so we+ * go through `fetchWithAuth` against the auth host like `authServiceClient`.+ */+function usePatchTeamCrmSettingsMutation() {+ return useMutation(() => ({+ mutationFn: async (enabled: boolean) =>+ await throwOnErr(() =>+ fetchWithAuth<PatchTeamCrmSettingsResponse>(`${authHost}/team/crm`, {+ method: 'PATCH',+ body: JSON.stringify({+ enabled,+ } satisfies PatchTeamCrmSettingsRequest),+ })+ ),+ onSuccess: (data: PatchTeamCrmSettingsResponse) => {+ invalidateUserTeams();+ toast.success(data.enabled ? 'CRM enabled' : 'CRM disabled');+ },+ onError: (error: Error) => {+ console.error('Failed to update CRM settings', error);+ toast.failure('Failed to update CRM settings');+ },+ }));+}++const DISABLE_CRM_PHRASE = 'Disable CRM';++function CrmEnablementSection() {+ const isTeamAdmin = useIsTeamAdmin();+ const patchCrmMutation = usePatchTeamCrmSettingsMutation();++ // The team API doesn't report `crm_enabled`, so the toggle is optimistic:+ // it starts from "enabled" and tracks the results of changes made here.+ const [crmEnabled, setCrmEnabled] = createSignal(true);+ const [showDisableModal, setShowDisableModal] = createSignal(false);+ const [disableConfirmation, setDisableConfirmation] = createSignal('');++ const handleToggle = (next: boolean) => {+ if (!isTeamAdmin() || patchCrmMutation.isPending) return;+ if (next) {+ patchCrmMutation.mutate(true, {+ onSuccess: (data) => setCrmEnabled(data.enabled),+ });+ } else {+ // Disabling purges the team's CRM data — force a typed confirmation.+ setDisableConfirmation('');+ setShowDisableModal(true);+ }+ };++ const handleDisable = () => {+ patchCrmMutation.mutate(false, {+ onSuccess: (data) => {+ setCrmEnabled(data.enabled);+ setShowDisableModal(false);+ },+ });+ };++ return (+ <SettingsSection title="General">+ <SettingsCard>+ <SettingsRow+ label="Enable CRM"+ description="Turns the CRM on for everyone on your team. This setting isn't reported by the server, so the toggle reflects your latest change here."+ hideDescriptionOnMobile+ >+ <Show+ when={isTeamAdmin()}+ fallback={+ <Tooltip label="Only team admins can change CRM settings.">+ <span>+ <Button variant="base" size="sm" class="rounded-xs" disabled>+ Admins only+ </Button>+ </span>+ </Tooltip>+ }+ >+ <div class="flex items-center gap-2">+ <Show when={patchCrmMutation.isPending}>+ <SpinnerIcon class="size-4 animate-spin text-ink-muted" />+ </Show>+ <Button+ variant={crmEnabled() ? 'danger' : 'active'}+ size="sm"+ class="rounded-xs"+ disabled={patchCrmMutation.isPending}+ onClick={() => handleToggle(!crmEnabled())}+ >+ {crmEnabled() ? 'Disable CRM' : 'Enable CRM'}+ </Button>+ </div>+ </Show>+ </SettingsRow>+ </SettingsCard>++ <ConfirmDialog+ open={showDisableModal()}+ title="Disable CRM"+ confirmLabel="Disable CRM"+ pending={patchCrmMutation.isPending}+ confirmDisabled={disableConfirmation() !== DISABLE_CRM_PHRASE}+ onConfirm={handleDisable}+ onClose={() => setShowDisableModal(false)}+ >+ <p>+ Disabling the CRM <span class="font-medium">permanently purges</span>{' '}+ your team's CRM data — companies, contacts, and their history.+ Re-enabling later starts from a fresh backfill.+ </p>+ <p class="text-sm text-ink-muted">+ Type <span class="font-medium text-ink">{DISABLE_CRM_PHRASE}</span> to+ confirm.+ </p>+ <input+ type="text"+ value={disableConfirmation()}+ onInput={(e) => setDisableConfirmation(e.currentTarget.value)}+ placeholder={DISABLE_CRM_PHRASE}+ class="w-full px-3 py-2 text-sm border border-edge-muted rounded-lg bg-surface text-ink placeholder:text-ink/30 outline-none focus:border-accent"+ />+ </ConfirmDialog>+ </SettingsSection>+ );+}++/* ------------------------------------------------------------------ */+/* Deal stages */+/* ------------------------------------------------------------------ */++function StageDot() {+ return <span class="size-2 shrink-0 rounded-full bg-accent/70" />;+}++/** Editable row for a custom stage: inline rename, reorder, delete. */+function StageEditorRow(props: {+ label: string;+ index: number;+ count: number;+ disabled: boolean;+ pending: boolean;+ onRename: (value: string) => void;+ onMove: (direction: -1 | 1) => void;+ onDelete: () => void;+}) {+ const [editing, setEditing] = createSignal<string>();+ const value = () => editing() ?? props.label;+ const hasChanged = () => {+ const edited = editing();+ return (+ edited !== undefined &&+ edited.trim() !== '' &&+ edited.trim() !== props.label+ );+ };+ const commit = () => {+ if (!hasChanged()) return;+ props.onRename(value().trim());+ setEditing(undefined);+ };+ const cancel = () => setEditing(undefined);+ const isLastStage = () => props.count <= 1;++ return (+ <div class="flex items-center gap-2 px-6 py-2.5">+ <StageDot />+ <input+ type="text"+ value={value()}+ disabled={props.disabled}+ onInput={(e) => setEditing(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ commit();+ } else if (e.key === 'Escape') {+ cancel();+ e.currentTarget.blur();+ }+ }}+ placeholder="Stage name"+ class="settings-input flex-1 min-w-0"+ />+ <Show when={hasChanged()}>+ <Tooltip label="Save">+ <Button+ variant="active"+ size="icon-sm"+ class="rounded-xs shrink-0"+ disabled={props.pending}+ onClick={commit}+ >+ <Show when={props.pending} fallback={<CheckIcon class="size-4" />}>+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </Tooltip>+ <Tooltip label="Cancel">+ <Button+ variant="ghost"+ size="icon-sm"+ class="rounded-xs shrink-0"+ disabled={props.pending}+ onClick={cancel}+ >+ <XIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show>+ <div class="flex items-center gap-0.5 shrink-0">+ <Tooltip label="Move up">+ <Button+ variant="ghost"+ size="icon-sm"+ class="rounded-xs"+ disabled={props.disabled || props.pending || props.index === 0}+ onClick={() => props.onMove(-1)}+ >+ <CaretUpIcon class="size-4" />+ </Button>+ </Tooltip>+ <Tooltip label="Move down">+ <Button+ variant="ghost"+ size="icon-sm"+ class="rounded-xs"+ disabled={+ props.disabled || props.pending || props.index === props.count - 1+ }+ onClick={() => props.onMove(1)}+ >+ <CaretDownIcon class="size-4" />+ </Button>+ </Tooltip>+ <Tooltip+ label={+ isLastStage() ? 'At least one stage is required' : 'Delete stage'+ }+ >+ <Button+ variant="ghost"+ size="icon-sm"+ class="rounded-xs"+ disabled={props.disabled || props.pending || isLastStage()}+ onClick={() => props.onDelete()}+ >+ <TrashIcon class="size-4" />+ </Button>+ </Tooltip>+ </div>+ </div>+ );+}++function DealStagesSection() {+ const queryClient = useQueryClient();+ const dealStages = useDealStages();+ const crmPermissions = useCrmPermissions();+ const isTeamAdmin = useIsTeamAdmin();+ const teamCrmConfig = useTeamCrmConfig();+ const closedStageIds = useClosedStageIds(dealStages.stages);++ const teamDefinitionsQuery = useListPropertiesQuery(() => ({+ scope: 'team',+ includeOptions: true,+ }));+ const stageDefinition = createMemo(() =>+ findTeamStageDefinition(teamDefinitionsQuery.data)+ );++ const canEdit = createMemo(+ () => isTeamAdmin() && crmPermissions.canEditStages()+ );++ // The option mutations only invalidate the per-definition options query;+ // the stage list here is derived from the team definitions listing, so+ // refresh that too after every option change.+ const invalidateDefinitions = () =>+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) =>+ queryKey.includes('properties') && queryKey.includes('definitions'),+ });+ const optionCallbacks = { onSuccess: () => invalidateDefinitions() };++ const createDefinitionMutation = useCreatePropertyDefinitionMutation();+ const deleteDefinitionMutation = useDeletePropertyDefinitionMutation();+ const addOptionMutation = useAddPropertyOptionMutation(optionCallbacks);+ const updateOptionMutation = useUpdatePropertyOptionMutation(optionCallbacks);+ const deleteOptionMutation = useDeletePropertyOptionMutation(optionCallbacks);++ const [isCustomizing, setIsCustomizing] = createSignal(false);+ const [newStageName, setNewStageName] = createSignal('');+ const [stageToDelete, setStageToDelete] = createSignal<PropertyOption | null>(+ null+ );+ const [showResetModal, setShowResetModal] = createSignal(false);++ /** Team stage options in display order (empty when not customized). */+ const stageOptions = createMemo((): PropertyOption[] => {+ const definition = stageDefinition();+ if (!definition) return [];+ return [...definition.property_options].sort(+ (a, b) => a.display_order - b.display_order+ );+ });++ const mutationPending = () =>+ addOptionMutation.isPending ||+ updateOptionMutation.isPending ||+ deleteOptionMutation.isPending;++ /** Seed the team stage set from the currently active (default) stages. */+ const handleCustomize = async () => {+ if (isCustomizing()) return;+ setIsCustomizing(true);+ try {+ const seedStages: DealStage[] = dealStages.stages();+ const definition = await createDefinitionMutation.mutateAsync({+ body: {+ display_name: CRM_TEAM_STAGE_DEFINITION_NAME,+ data_type: { type: 'select_string', multi: false, options: [] },+ scope: 'team',+ },+ });+ for (const [index, stage] of seedStages.entries()) {+ await addOptionMutation.mutateAsync({+ propertyDefinitionId: definition.id,+ body: {+ type: 'select_string',+ option: { value: stage.label, display_order: index },+ },+ });+ }+ toast.success('Stages are now customizable');+ } catch (error) {+ console.error('Failed to customize stages', error);+ // The mutations already toast their own failures.+ } finally {+ setIsCustomizing(false);+ }+ };++ const handleRename = (option: PropertyOption, value: string) => {+ const definition = stageDefinition();+ if (!definition) return;+ updateOptionMutation.mutate({+ propertyDefinitionId: definition.definition.id,+ optionId: option.id,+ body: { value },+ });+ };++ /** Swap display orders with the neighbor in the given direction. */+ const handleMove = async (index: number, direction: -1 | 1) => {+ const definition = stageDefinition();+ const options = stageOptions();+ const current = options[index];+ const neighbor = options[index + direction];+ if (!definition || !current || !neighbor) return;+ // Swap the stored orders; fall back to list indices if they collide.+ let currentOrder = neighbor.display_order;+ let neighborOrder = current.display_order;+ if (currentOrder === neighborOrder) {+ currentOrder = index + direction;+ neighborOrder = index;+ }+ await updateOptionMutation.mutateAsync({+ propertyDefinitionId: definition.definition.id,+ optionId: current.id,+ body: { display_order: currentOrder },+ });+ await updateOptionMutation.mutateAsync({+ propertyDefinitionId: definition.definition.id,+ optionId: neighbor.id,+ body: { display_order: neighborOrder },+ });+ };++ const handleAddStage = () => {+ const definition = stageDefinition();+ const value = newStageName().trim();+ if (!definition || value === '') return;+ addOptionMutation.mutate(+ {+ propertyDefinitionId: definition.definition.id,+ body: {+ type: 'select_string',+ option: { value, display_order: stageOptions().length },+ },+ },+ { onSuccess: () => setNewStageName('') }+ );+ };++ const handleDeleteStage = () => {+ const definition = stageDefinition();+ const option = stageToDelete();+ if (!definition || !option) return;+ deleteOptionMutation.mutate(+ {+ propertyDefinitionId: definition.definition.id,+ optionId: option.id,+ },+ { onSuccess: () => setStageToDelete(null) }+ );+ };++ const handleReset = () => {+ const definition = stageDefinition();+ if (!definition) return;+ deleteDefinitionMutation.mutate(+ { definitionId: definition.definition.id },+ {+ onSuccess: () => {+ setShowResetModal(false);+ toast.success('Stages reset to Macro defaults');+ },+ }+ );+ };++ const toggleClosedStage = (stageId: string) => {+ const next = new Set(closedStageIds());+ if (next.has(stageId)) {+ next.delete(stageId);+ } else {+ next.add(stageId);+ }+ teamCrmConfig.update.mutate((cfg) => ({+ ...cfg,+ closedStageIds: [...next],+ }));+ };++ return (+ <SettingsSection+ title="Deal stages"+ description="The pipeline stages deals move through on the CRM board."+ actions={+ <Show when={stageDefinition() && canEdit()}>+ <Button+ variant="base"+ size="sm"+ class="rounded-xs"+ disabled={deleteDefinitionMutation.isPending}+ onClick={() => setShowResetModal(true)}+ >+ Reset to defaults+ </Button>+ </Show>+ }+ >+ <Show+ when={stageDefinition()}+ fallback={+ <SettingsCard>+ <div class="flex flex-col gap-1 px-6 py-4">+ <For each={dealStages.stages()}>+ {(stage) => (+ <div class="flex items-center gap-2 py-1">+ <StageDot />+ <span class="text-sm text-ink">{stage.label}</span>+ </div>+ )}+ </For>+ </div>+ <div class="flex items-center justify-between gap-4 px-6 py-3.5">+ <p class="text-xs text-ink-muted">+ Stages are Macro's defaults. Customize them for your team.+ </p>+ <Show when={canEdit()}>+ <Button+ variant="base"+ size="sm"+ class="rounded-xs shrink-0"+ disabled={isCustomizing()}+ onClick={handleCustomize}+ >+ <Show when={isCustomizing()} fallback="Customize stages">+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </Show>+ </div>+ </SettingsCard>+ }+ >+ <SettingsCard>+ <For each={stageOptions()}>+ {(option, index) => (+ <StageEditorRow+ label={optionLabel(option)}+ index={index()}+ count={stageOptions().length}+ disabled={!canEdit()}+ pending={mutationPending()}+ onRename={(value) => handleRename(option, value)}+ onMove={(direction) => handleMove(index(), direction)}+ onDelete={() => setStageToDelete(option)}+ />+ )}+ </For>+ <Show when={canEdit()}>+ <div class="flex items-center gap-2 px-6 py-2.5">+ <PlusIcon class="size-4 shrink-0 text-ink-muted" />+ <input+ type="text"+ value={newStageName()}+ onInput={(e) => setNewStageName(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') handleAddStage();+ }}+ placeholder="Add stage"+ class="settings-input flex-1 min-w-0"+ />+ <Button+ variant="base"+ size="sm"+ class="rounded-xs shrink-0"+ disabled={newStageName().trim() === '' || mutationPending()}+ onClick={handleAddStage}+ >+ Add+ </Button>+ </div>+ </Show>+ </SettingsCard>+ </Show>++ <SettingsCard>+ <SettingsRow+ align="start"+ label="Closed stages"+ description="Stages that count as closed deals. Moving deals out of a closed stage can be restricted under Permissions."+ >+ <div class="flex flex-col items-start gap-1.5">+ <For each={dealStages.stages()}>+ {(stage) => (+ <Checkbox+ checked={closedStageIds().has(stage.id)}+ onChange={() => toggleClosedStage(stage.id)}+ disabled={!canEdit() || teamCrmConfig.update.isPending}+ class="cursor-default"+ >+ <Checkbox.Control>+ <Checkbox.Indicator />+ </Checkbox.Control>+ <span class="text-sm text-ink">{stage.label}</span>+ </Checkbox>+ )}+ </For>+ </div>+ </SettingsRow>+ </SettingsCard>++ <ConfirmDialog+ open={!!stageToDelete()}+ title="Delete Stage"+ confirmLabel="Delete Stage"+ pending={deleteOptionMutation.isPending}+ onConfirm={handleDeleteStage}+ onClose={() => setStageToDelete(null)}+ >+ <p>+ Are you sure you want to delete{' '}+ <span class="font-medium">+ {stageToDelete()+ ? optionLabel(stageToDelete() as PropertyOption)+ : ''}+ </span>+ ? Companies currently in this stage keep their stored value but will+ no longer appear under it on the board.+ </p>+ </ConfirmDialog>++ <ConfirmDialog+ open={showResetModal()}+ title="Reset Stages"+ confirmLabel="Reset to Defaults"+ pending={deleteDefinitionMutation.isPending}+ onConfirm={handleReset}+ onClose={() => setShowResetModal(false)}+ >+ <p>+ This removes your team's custom stage set and returns everyone to+ Macro's default stages.+ </p>+ <p class="text-sm text-ink-muted">+ Companies keep their stored stage values, and stages whose names match+ a default continue to display as before.+ </p>+ </ConfirmDialog>+ </SettingsSection>+ );+}++/* ------------------------------------------------------------------ */+/* Company properties */+/* ------------------------------------------------------------------ */++const DATA_TYPE_LABELS: Record<string, string> = {+ STRING: 'Text',+ NUMBER: 'Number',+ DATE: 'Date',+ BOOLEAN: 'Checkbox',+ SELECT_STRING: 'Select',+ SELECT_NUMBER: 'Number select',+ TAG: 'Tag',+ ENTITY: 'Relation',+ LINK: 'Link',+};++type NewPropertyType =+ | 'string'+ | 'number'+ | 'date'+ | 'boolean'+ | 'select_string'+ | 'link';++const NEW_PROPERTY_TYPE_OPTIONS: { value: NewPropertyType; label: string }[] = [+ { value: 'string', label: 'Text' },+ { value: 'number', label: 'Number' },+ { value: 'date', label: 'Date' },+ { value: 'boolean', label: 'Checkbox' },+ { value: 'select_string', label: 'Select' },+ { value: 'link', label: 'Link' },+];++/** Mirrors `buildDataType` in the property package's CreatePropertyModal. */+function buildDataType(type: NewPropertyType): PropertyDataType {+ return match<NewPropertyType, PropertyDataType>(type)+ .with('string', () => ({ type: 'string' }))+ .with('number', () => ({ type: 'number' }))+ .with('date', () => ({ type: 'date' }))+ .with('boolean', () => ({ type: 'boolean' }))+ .with('select_string', () => ({+ // Options are added later from the property's editors.+ type: 'select_string',+ multi: false,+ options: [],+ }))+ .with('link', () => ({ type: 'link', multi: false }))+ .exhaustive();+}++function CompanyPropertiesSection() {+ const isTeamAdmin = useIsTeamAdmin();+ const teamDefinitionsQuery = useListPropertiesQuery(() => ({+ scope: 'team',+ includeOptions: true,+ }));++ const createDefinitionMutation = useCreatePropertyDefinitionMutation();+ const deleteDefinitionMutation = useDeletePropertyDefinitionMutation();++ const [newName, setNewName] = createSignal('');+ const [newType, setNewType] = createSignal<NewPropertyType>('string');+ const [propertyToDelete, setPropertyToDelete] =+ createSignal<PropertyDefinition | null>(null);++ // Team-scoped custom properties, excluding internal reserved definitions+ // and the team Stage definition (managed in the section above).+ const customProperties = createMemo((): PropertyDefinition[] => {+ const entries = teamDefinitionsQuery.data ?? [];+ return entries+ .map((entry) => ('definition' in entry ? entry.definition : entry))+ .filter(+ (definition) =>+ definition.owner.scope === 'team' &&+ !definition.is_system &&+ !isReservedPropertyDefinitionName(definition.display_name) &&+ definition.display_name !== CRM_TEAM_STAGE_DEFINITION_NAME+ );+ });++ const canAdd = () =>+ newName().trim() !== '' && !createDefinitionMutation.isPending;++ const handleAdd = () => {+ if (!canAdd()) return;+ createDefinitionMutation.mutate(+ {+ body: {+ display_name: newName().trim(),+ data_type: buildDataType(newType()),+ scope: 'team',+ },+ },+ {+ onSuccess: () => {+ setNewName('');+ setNewType('string');+ toast.success('Property added');+ },+ }+ );+ };++ const handleDelete = () => {+ const property = propertyToDelete();+ if (!property) return;+ deleteDefinitionMutation.mutate(+ { definitionId: property.id },+ { onSuccess: () => setPropertyToDelete(null) }+ );+ };++ return (+ <SettingsSection+ title="Company properties"+ description="Custom fields that appear on every company in the CRM side panel."+ >+ <SettingsCard>+ <Show+ when={customProperties().length > 0}+ fallback={+ <div class="px-6 py-6 text-center text-sm text-ink-muted">+ No custom properties yet.+ </div>+ }+ >+ <For each={customProperties()}>+ {(definition) => (+ <div class="flex items-center justify-between gap-3 px-6 py-3">+ <div class="min-w-0 flex-1">+ <div class="text-sm text-ink truncate">+ {definition.display_name}+ </div>+ <div class="text-xs text-ink-muted">+ {DATA_TYPE_LABELS[definition.data_type] ??+ definition.data_type}+ </div>+ </div>+ <Show when={isTeamAdmin()}>+ <Tooltip label="Delete property">+ <Button+ variant="ghost"+ size="icon-sm"+ class="rounded-xs shrink-0"+ disabled={deleteDefinitionMutation.isPending}+ onClick={() => setPropertyToDelete(definition)}+ >+ <TrashIcon class="size-4" />+ </Button>+ </Tooltip>+ </Show>+ </div>+ )}+ </For>+ </Show>+ <Show when={isTeamAdmin()}>+ <div class="flex items-center gap-2 px-6 py-2.5">+ <PlusIcon class="size-4 shrink-0 text-ink-muted" />+ <input+ type="text"+ value={newName()}+ onInput={(e) => setNewName(e.currentTarget.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') handleAdd();+ }}+ placeholder="Add property"+ class="settings-input flex-1 min-w-0"+ />+ <InlineSelect+ options={NEW_PROPERTY_TYPE_OPTIONS}+ value={newType()}+ onChange={setNewType}+ />+ <Button+ variant="base"+ size="sm"+ class="rounded-xs shrink-0"+ disabled={!canAdd()}+ onClick={handleAdd}+ >+ <Show when={createDefinitionMutation.isPending} fallback="Add">+ <SpinnerIcon class="size-4 animate-spin" />+ </Show>+ </Button>+ </div>+ </Show>+ </SettingsCard>++ <ConfirmDialog+ open={!!propertyToDelete()}+ title="Delete Property"+ confirmLabel="Delete Property"+ pending={deleteDefinitionMutation.isPending}+ onConfirm={handleDelete}+ onClose={() => setPropertyToDelete(null)}+ >+ <p>+ Are you sure you want to delete{' '}+ <span class="font-medium">{propertyToDelete()?.display_name}</span>?+ Its values are removed from every company. This cannot be undone.+ </p>+ </ConfirmDialog>+ </SettingsSection>+ );+}++/* ------------------------------------------------------------------ */+/* Permissions */+/* ------------------------------------------------------------------ */++const PERMISSION_ROLE_OPTIONS: { value: CrmPermissionRole; label: string }[] = [+ { value: 'admin', label: 'Admins and owner' },+ { value: 'owner', label: 'Owner only' },+];++const PERMISSION_ROWS: {+ key: keyof CrmPermissions;+ label: string;+ description: string;+}[] = [+ {+ key: 'editStages',+ label: 'Edit deal stages',+ description: 'Who can change the deal stage set above.',+ },+ {+ key: 'moveClosedDeals',+ label: 'Move closed deals',+ description: 'Who can move deals out of a closed stage.',+ },+ {+ key: 'deleteRecords',+ label: 'Delete records',+ description: 'Who can delete companies and contacts from the CRM.',+ },+];++function PermissionsSection() {+ const isTeamAdmin = useIsTeamAdmin();+ const crmPermissions = useCrmPermissions();+ const teamCrmConfig = useTeamCrmConfig();++ const setPermission = (key: keyof CrmPermissions, value: CrmPermissionRole) =>+ teamCrmConfig.update.mutate((cfg) => ({+ ...cfg,+ permissions: { ...cfg.permissions, [key]: value },+ }));++ const roleLabel = (value: CrmPermissionRole) =>+ PERMISSION_ROLE_OPTIONS.find((o) => o.value === value)?.label ?? value;++ return (+ <SettingsSection+ title="Permissions"+ description="Team members are view-only in the CRM; these control what admins can change."+ >+ <SettingsCard>+ <For each={PERMISSION_ROWS}>+ {(row) => (+ <SettingsRow+ label={row.label}+ description={row.description}+ hideDescriptionOnMobile+ >+ <Show+ when={isTeamAdmin()}+ fallback={+ <span class="text-xs text-ink-muted">+ {roleLabel(crmPermissions.permissions()[row.key])}+ </span>+ }+ >+ <InlineSelect+ options={PERMISSION_ROLE_OPTIONS}+ value={crmPermissions.permissions()[row.key]}+ onChange={(value) => setPermission(row.key, value)}+ disabled={teamCrmConfig.update.isPending}+ />+ </Show>+ </SettingsRow>+ )}+ </For>+ </SettingsCard>+ </SettingsSection>+ );+}++/* ------------------------------------------------------------------ */+/* Page */+/* ------------------------------------------------------------------ */++function NoTeamState() {+ return (+ <SettingsPage title="CRM">+ <SettingsSection>+ <SettingsCard>+ <div class="px-6 py-8 text-center text-sm text-ink-muted">+ Join or create a team to set up the CRM.+ </div>+ </SettingsCard>+ </SettingsSection>+ </SettingsPage>+ );+}++function CrmContent() {+ const teamQuery = useCurrentTeamQuery();++ return (+ <Show when={teamQuery.data} fallback={<NoTeamState />}>+ <SettingsPage+ title="CRM"+ description="Manage deal stages, company properties, and permissions for your team's CRM."+ >+ <CrmEnablementSection />+ <DealStagesSection />+ <CompanyPropertiesSection />+ <PermissionsSection />+ </SettingsPage>+ </Show>+ );+}++export function Crm() {+ return (+ <Suspense+ fallback={+ <div class="animate-pulse bg-ink-extra-muted rounded h-4 w-32 m-6" />+ }+ >+ <CrmContent />+ </Suspense>+ );+}diff --git a/js/app/packages/app/component/settings/Settings.tsx b/js/app/packages/app/component/settings/Settings.tsxindex 87cd9e24f1..2fac748aeb 100644--- a/js/app/packages/app/component/settings/Settings.tsx+++ b/js/app/packages/app/component/settings/Settings.tsx@@ -39,6 +39,7 @@ import { Admin } from './Admin';import { Agent } from './Agent';import { Appearance } from './Appearance';import { ConnectedAccounts } from './ConnectedAccounts';+import { Crm } from './Crm';import { MobileApp } from './MobileApp';import { Shortcuts } from './Shortcuts';import { Team } from './Team';@@ -389,6 +390,11 @@ export function SettingsPanel(props: SettingsPanelProps) {<Team /></Suspense></Show>+ <Show when={isCurrentTab('CRM')}>+ <Suspense>+ <Crm />+ </Suspense>+ </Show><Show when={isCurrentTab('Connected')}><Suspense><ConnectedAccounts />diff --git a/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsx b/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsxindex 6c1041acc3..11e626a1e1 100644--- a/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsx+++ b/js/app/packages/app/component/side-panel/properties/EntityPropertiesSection.tsx@@ -1,4 +1,5 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { isReservedPropertyDefinitionName } from '@companies/crm/team-crm-config';import type { BlockAlias, BlockName } from '@core/block';import { PopupPreview } from '@core/component/DocumentPreview';import { HoverCard } from '@core/component/HoverCard';@@ -62,6 +63,12 @@ export interface EntityPropertiesSectionProps {* properties with the same definition id take precedence.*/defaultProperties?: () => Property[];+ /**+ * Fetched properties with these definition ids are dropped before+ * merging with `defaultProperties` — e.g. the system Stage row when the+ * team has its own stage set.+ */+ hidePropertyDefinitionIds?: string[];}const TAGGABLE_ENTITY_TYPES: ReadonlySet<EntityType> = new Set<EntityType>([@@ -94,9 +101,15 @@ export function EntityPropertiesSection(props: EntityPropertiesSectionProps) {);// Fetched properties merged with any default placeholders whose- // definition the entity doesn't carry yet.+ // definition the entity doesn't carry yet. Hidden definitions and+ // reserved internal definitions (`__macro:*`) are dropped first.const mergedProperties = createMemo(() => {- const fetched = properties();+ const hiddenDefinitionIds = new Set(props.hidePropertyDefinitionIds ?? []);+ const fetched = properties().filter(+ (property) =>+ !hiddenDefinitionIds.has(property.propertyDefinitionId) &&+ !isReservedPropertyDefinitionName(property.displayName)+ );const defaults = props.defaultProperties?.() ?? [];if (defaults.length === 0) return fetched;const fetchedDefinitionIds = new Set(diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex 8833b365aa..9add6078b5 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -8,6 +8,11 @@ import type { Query } from '@app/component/next-soup/filters/filter-store/types'import { SoupView } from '@app/component/next-soup/soup-view/soup-view';import { ChannelCompose } from '@block-channel/component/Compose';import { ComposeTask } from '@block-md/component/ComposeTask';+import {+ CRM_VIEW_URL_PARAM,+ type CrmViewConfig,+ decodeCrmViewParam,+} from '@companies/crm/saved-views';import { useIsAuthenticated } from '@core/auth';import { LoadingBlock } from '@core/component/LoadingBlock';import {@@ -280,12 +285,21 @@ registerComponent(}usePageViewTracking('companies');const preset = getViewPreset('companies');+ // Share links land here as `/companies?crmView=<encoded config>` — the+ // param carries the full view state (never data), decoded client-side.+ const crmViewParam = new URLSearchParams(window.location.search).get(+ CRM_VIEW_URL_PARAM+ );+ const initialCrmView: CrmViewConfig | undefined = crmViewParam+ ? decodeCrmViewParam(crmViewParam)+ : undefined;return (<SoupViewviewName="Customers"initialFilters={preset?.filters}initialClientFilters={preset?.clientFilters}initialGroupBy={preset?.groupBy}+ initialCrmView={initialCrmView}/>);})diff --git a/js/app/packages/companies/Company/CompanyPropertiesSection.tsx b/js/app/packages/companies/Company/CompanyPropertiesSection.tsxindex 8fed093b42..a1842f967c 100644--- a/js/app/packages/companies/Company/CompanyPropertiesSection.tsx+++ b/js/app/packages/companies/Company/CompanyPropertiesSection.tsx@@ -1,32 +1,50 @@import { EntityPropertiesSection } from '@app/component/side-panel/properties/EntityPropertiesSection';+import { useDealStages } from '@companies/crm/deal-stages';import { buildCompanyDefaultProperties } from '@entity/extractors-property';import { SYSTEM_PROPERTY_IDS } from '@property/constants';import { useIsTeamAdmin } from '@queries/team/teams';-/** Fixed display order: builtin CRM defaults first, custom ones after. */-const COMPANY_PINNED_ORDER = [- SYSTEM_PROPERTY_IDS.STAGE,- SYSTEM_PROPERTY_IDS.COMPANY_OWNER,- SYSTEM_PROPERTY_IDS.REVENUE,-] as const;-/*** CRM properties for a company (Stage / Owner / Revenue + custom),* mirroring the task side panel's properties section. The builtin* defaults render as editable placeholders even before the company has* any values saved. Editing follows CRM access: team admins/owners can* edit, members see read-only values.+ *+ * Stage goes through the team's active deal-stage set: when the team has+ * customized stages, the panel edits the team Stage definition and the+ * fetched system Stage row is hidden.*/export function CompanyPropertiesSection(props: { companyId: string }) {const isTeamAdmin = useIsTeamAdmin();+ const dealStages = useDealStages();++ // Builtin CRM defaults, with the Stage stub swapped for the active+ // stage definition (the team's own when customized).+ const defaultProperties = () =>+ buildCompanyDefaultProperties().map((property) =>+ property.propertyDefinitionId === SYSTEM_PROPERTY_IDS.STAGE+ ? dealStages.stageProperty()+ : property+ );++ /** Fixed display order: builtin CRM defaults first, custom ones after. */+ const pinnedOrder = () => [+ dealStages.stageDefinitionId(),+ SYSTEM_PROPERTY_IDS.COMPANY_OWNER,+ SYSTEM_PROPERTY_IDS.REVENUE,+ ];return (<EntityPropertiesSectionentityId={props.companyId}entityType="COMPANY"canEdit={isTeamAdmin()}- defaultProperties={buildCompanyDefaultProperties}- pinnedPropertyDefinitionOrder={COMPANY_PINNED_ORDER}+ defaultProperties={defaultProperties}+ pinnedPropertyDefinitionOrder={pinnedOrder()}+ hidePropertyDefinitionIds={+ dealStages.isCustomized() ? [SYSTEM_PROPERTY_IDS.STAGE] : undefined+ }/>);}diff --git a/js/app/packages/companies/crm/StageIcon.tsx b/js/app/packages/companies/crm/StageIcon.tsxnew file mode 100644index 0000000000..7e9c4c9358--- /dev/null+++ b/js/app/packages/companies/crm/StageIcon.tsx@@ -0,0 +1,65 @@+/**+ * Stage icon that works for both the builtin system stages and+ * team-customized stage options. System stage option ids render through+ * `PropertyValueIcon` (fixed tints); custom option ids — which+ * `PropertyValueIcon` doesn't know — render as a colored dot with a tint+ * picked from a small palette by column index (or a stable hash of the+ * option id when no index is supplied).+ */++import { PropertyValueIcon } from '@property/component/propertyValue/PropertyValueIcon';+import { PROPERTY_OPTION_IDS } from '@property/constants';+import { Show } from 'solid-js';+import { twMerge } from 'tailwind-merge';++const SYSTEM_STAGE_OPTION_IDS = new Set<string>(+ Object.values(PROPERTY_OPTION_IDS.STAGE)+);++const STAGE_TINT_PALETTE = [+ 'text-ink-muted',+ 'text-task',+ 'text-note',+ 'text-alert-ink',+ 'text-accent',+ 'text-success',+ 'text-failure-ink',+] as const;++/** Stable non-negative hash so untinted custom stages keep their color. */+function hashOptionId(optionId: string): number {+ let hash = 0;+ for (let i = 0; i < optionId.length; i++) {+ hash = (hash * 31 + optionId.charCodeAt(i)) | 0;+ }+ return Math.abs(hash);+}++export function CrmStageIcon(props: {+ optionId: string;+ index?: number;+ class?: string;+}) {+ const tint = () =>+ STAGE_TINT_PALETTE[+ (props.index ?? hashOptionId(props.optionId)) % STAGE_TINT_PALETTE.length+ ];++ return (+ <Show+ when={!SYSTEM_STAGE_OPTION_IDS.has(props.optionId)}+ fallback={+ <PropertyValueIcon optionId={props.optionId} class={props.class} />+ }+ >+ {/* Same filled dot PropertyValueIcon uses for the system stages. */}+ <svg+ viewBox="0 0 12 12"+ class={twMerge('size-3', props.class, tint())}+ aria-hidden="true"+ >+ <circle cx="6" cy="6" r="4" fill="currentColor" />+ </svg>+ </Show>+ );+}diff --git a/js/app/packages/companies/crm/deal-stages.ts b/js/app/packages/companies/crm/deal-stages.tsnew file mode 100644index 0000000000..5a6adccb4a--- /dev/null+++ b/js/app/packages/companies/crm/deal-stages.ts@@ -0,0 +1,273 @@+/**+ * Team-customizable deal stages for the CRM.+ *+ * The builtin Stage property is a system definition whose options cannot be+ * modified through the API, so team customization works by giving the team+ * its own team-scoped `Stage` property definition (created from CRM+ * settings). When that definition exists, every stage surface — kanban+ * columns, list cells, filters, grouping, the company panel — reads and+ * writes it instead of the system property; otherwise the seeded system+ * stages apply. `useDealStages` is the single source of truth for which set+ * is active.+ */++// Imports come from the concrete @entity modules, not the barrel: this+// module loads inside soup-view-context's import chain, where the barrel+// can still be mid-initialization (circular import) and its re-exports+// undefined at module-eval time.+import { soupPropertyToProperty } from '@entity/extractors-property';+import { getCompanyStageOptionId } from '@entity/utils/company-properties';+import {+ COMPANY_STAGE_OPTIONS,+ getPropertyOptionLabel,+} from '@entity/utils/task-properties';+import {+ CRM_TEAM_STAGE_DEFINITION_NAME,+ SYSTEM_PROPERTY_IDS,+} from '@property/constants';+import type { Property } from '@property/types';+import { useListPropertiesQuery } from '@queries/properties/definitions';+import type { PropertyDefinitionResponse } from '@service-properties/generated/schemas/propertyDefinitionResponse';+import type { PropertyDefinitionWithOptions } from '@service-properties/generated/schemas/propertyDefinitionWithOptions';+import type { PropertyOption } from '@service-properties/generated/schemas/propertyOption';+import { type Accessor, createMemo } from 'solid-js';++// Canonical home is `@property/constants` (property pickers filter on it);+// re-exported here for the CRM-side callers.+export { CRM_TEAM_STAGE_DEFINITION_NAME } from '@property/constants';++export type DealStage = {+ /** Property option id — the value stored on companies. */+ id: string;+ label: string;+};++export type DealStages = {+ /** Active stages, in display order (team set when customized). */+ stages: Accessor<DealStage[]>;+ /** True when the team has its own stage set. */+ isCustomized: Accessor<boolean>;+ /** Definition id stage values are read from / written to. */+ stageDefinitionId: Accessor<string>;+ /**+ * `Property` stub for the active stage definition, for property editors+ * and saves (mirrors `buildCompanyDefaultProperties` for the builtin).+ */+ stageProperty: Accessor<Property>;+ /**+ * The company's stage within the active set. When the team has custom+ * stages, legacy values stored on the system Stage property are mapped+ * onto the custom set by label so boards/lists don't blank out after+ * customizing; moving a card writes the value to the team definition.+ */+ resolveStage: (entity: CompanyLike) => string | undefined;+ /** Label for an option id in the active set (legacy system ids included). */+ stageLabel: (optionId: string) => string | undefined;+ isLoading: Accessor<boolean>;+};++/** Minimal company shape needed to read stage values. */+type CompanyLike = {+ properties?: Array<{+ definition: { id: string };+ value?: unknown;+ }> | null;+};++const DEFAULT_STAGES: DealStage[] = COMPANY_STAGE_OPTIONS.map((option) => ({+ id: option.value as string,+ label: option.label,+}));++function optionLabel(option: PropertyOption): string {+ const value = option.value;+ if (+ value &&+ typeof value === 'object' &&+ 'value' in value &&+ typeof value.value === 'string'+ ) {+ return value.value;+ }+ return '';+}++function hasOptions(+ definition: PropertyDefinitionResponse+): definition is PropertyDefinitionWithOptions {+ return (+ 'definition' in definition && Array.isArray(definition.property_options)+ );+}++/** Read the first select-option id stored for a definition on a company. */+export function getCompanySelectOptionId(+ entity: CompanyLike,+ definitionId: string+): string | undefined {+ const property = entity.properties?.find(+ (p) => p.definition.id === definitionId+ );+ const value = property?.value;+ if (+ !value ||+ typeof value !== 'object' ||+ !('type' in value) ||+ value.type !== 'SelectOption' ||+ !('value' in value) ||+ !Array.isArray(value.value)+ ) {+ return undefined;+ }+ const optionId = value.value[0];+ return typeof optionId === 'string' ? optionId : undefined;+}++/**+ * Find the team's stage definition (with options) in a team-scope+ * definitions listing, if the team has customized stages.+ */+export function findTeamStageDefinition(+ definitions: PropertyDefinitionResponse[] | undefined+): PropertyDefinitionWithOptions | undefined {+ return definitions?.find(+ (entry): entry is PropertyDefinitionWithOptions =>+ hasOptions(entry) &&+ entry.definition.display_name === CRM_TEAM_STAGE_DEFINITION_NAME &&+ entry.definition.data_type === 'SELECT_STRING' &&+ !entry.definition.is_system &&+ entry.definition.owner.scope === 'team'+ );+}++/** Stages (ordered) from a team stage definition's options. */+export function stagesFromDefinition(+ definition: PropertyDefinitionWithOptions+): DealStage[] {+ return [...definition.property_options]+ .sort((a, b) => a.display_order - b.display_order)+ .map((option) => ({ id: option.id, label: optionLabel(option) }))+ .filter((stage) => stage.label !== '');+}++function buildStagePropertyStub(+ definition: PropertyDefinitionWithOptions | undefined+): Property {+ if (!definition) {+ // System default — same stub the CRM list/kanban always used.+ return soupPropertyToProperty({+ definition: {+ id: SYSTEM_PROPERTY_IDS.STAGE,+ display_name: 'Stage',+ data_type: 'SELECT_STRING',+ is_metadata: false,+ is_multi_select: false,+ is_system: true,+ owner: { scope: 'system' },+ specific_entity_type: undefined,+ created_at: new Date(0).toISOString(),+ updated_at: new Date(0).toISOString(),+ },+ });+ }+ const property = soupPropertyToProperty({+ definition: {+ id: definition.definition.id,+ display_name: definition.definition.display_name,+ data_type: 'SELECT_STRING',+ is_metadata: false,+ is_multi_select: false,+ is_system: false,+ owner: definition.definition.owner,+ specific_entity_type: undefined,+ created_at: definition.definition.created_at,+ updated_at: definition.definition.updated_at,+ },+ });+ return { ...property, options: definition.property_options };+}++/**+ * The active deal-stage set for the current team. See module docs for the+ * system-vs-team resolution rules.+ */+export function useDealStages(): DealStages {+ const teamDefinitionsQuery = useListPropertiesQuery(() => ({+ scope: 'team',+ includeOptions: true,+ }));++ const teamStageDefinition = createMemo(() =>+ findTeamStageDefinition(teamDefinitionsQuery.data)+ );++ // Customized only once the team set actually has stages; an empty custom+ // set keeps the system defaults active (see stages() below).+ const isCustomized = createMemo(() => {+ const definition = teamStageDefinition();+ return !!definition && stagesFromDefinition(definition).length > 0;+ });++ const stages = createMemo((): DealStage[] => {+ const definition = teamStageDefinition();+ if (!definition) return DEFAULT_STAGES;+ const customStages = stagesFromDefinition(definition);+ // An empty custom set would render an unusable board — treat it as+ // not-yet-populated and keep the defaults.+ return customStages.length > 0 ? customStages : DEFAULT_STAGES;+ });++ const stageDefinitionId = createMemo(() => {+ const definition = teamStageDefinition();+ return definition && stagesFromDefinition(definition).length > 0+ ? definition.definition.id+ : SYSTEM_PROPERTY_IDS.STAGE;+ });++ const stageProperty = createMemo(() => {+ const definition = teamStageDefinition();+ return buildStagePropertyStub(+ definition && stagesFromDefinition(definition).length > 0+ ? definition+ : undefined+ );+ });++ const stageIds = createMemo(() => new Set(stages().map((s) => s.id)));++ const labelById = createMemo(() => {+ const map = new Map<string, string>();+ for (const stage of stages()) map.set(stage.id, stage.label);+ return map;+ });++ const resolveStage = (entity: CompanyLike): string | undefined => {+ const direct = getCompanySelectOptionId(entity, stageDefinitionId());+ if (direct && stageIds().has(direct)) return direct;+ if (stageDefinitionId() === SYSTEM_PROPERTY_IDS.STAGE) return direct;++ // Legacy value on the system Stage property → map by label onto the+ // custom set (the customize flow seeds the same labels).+ const legacy = getCompanyStageOptionId(+ entity as Parameters<typeof getCompanyStageOptionId>[0]+ );+ if (!legacy) return undefined;+ const legacyLabel = getPropertyOptionLabel(legacy)?.toLowerCase();+ if (!legacyLabel) return undefined;+ return stages().find((stage) => stage.label.toLowerCase() === legacyLabel)+ ?.id;+ };++ const stageLabel = (optionId: string): string | undefined =>+ labelById().get(optionId) ?? getPropertyOptionLabel(optionId);++ return {+ stages,+ isCustomized,+ stageDefinitionId,+ stageProperty,+ resolveStage,+ stageLabel,+ isLoading: () => teamDefinitionsQuery.isLoading,+ };+}diff --git a/js/app/packages/companies/crm/display-options.ts b/js/app/packages/companies/crm/display-options.tsnew file mode 100644index 0000000000..816ba8529c--- /dev/null+++ b/js/app/packages/companies/crm/display-options.ts@@ -0,0 +1,86 @@+/**+ * Personal display options for the CRM Customers view: which property+ * columns show in the list and which fields show on kanban cards.+ * Persisted per-user (localStorage preference), same mechanism as other+ * sticky view settings.+ */++import { makePersisted } from '@solid-primitives/storage';+import { createSignal } from 'solid-js';++export type CrmListColumnId = 'stage' | 'owner' | 'revenue';+export type CrmKanbanFieldId = 'owner' | 'domain' | 'lastInteraction';++export type CrmDisplayOptions = {+ /** Visible list columns (order stays fixed; this only hides/shows). */+ listColumns: Record<CrmListColumnId, boolean>;+ /** Fields rendered on kanban cards. */+ kanbanFields: Record<CrmKanbanFieldId, boolean>;+};++export const DEFAULT_CRM_DISPLAY_OPTIONS: CrmDisplayOptions = {+ listColumns: { stage: true, owner: true, revenue: true },+ kanbanFields: { owner: true, domain: true, lastInteraction: true },+};++export const CRM_LIST_COLUMN_LABELS: Record<CrmListColumnId, string> = {+ stage: 'Stage',+ owner: 'Owner',+ revenue: 'Revenue',+};++export const CRM_KANBAN_FIELD_LABELS: Record<CrmKanbanFieldId, string> = {+ owner: 'Owner',+ domain: 'Domain',+ lastInteraction: 'Last interaction',+};++// One shared signal for the whole app (module-level), so toggling in the+// Display menu re-renders every consumer (list, kanban) immediately.+// `usePreference` would give each component its own signal that only+// shares the localStorage key — updates would not propagate until reload.+const [displayOptions, setDisplayOptions] = makePersisted(+ createSignal<CrmDisplayOptions>(DEFAULT_CRM_DISPLAY_OPTIONS),+ { name: 'macro:pref:crm:display' }+);++export function useCrmDisplayOptions() {+ const [options, setOptions] = [displayOptions, setDisplayOptions];++ // Merge with defaults so options saved by older builds keep working+ // when new fields are added.+ const merged = (): CrmDisplayOptions => ({+ listColumns: {+ ...DEFAULT_CRM_DISPLAY_OPTIONS.listColumns,+ ...options().listColumns,+ },+ kanbanFields: {+ ...DEFAULT_CRM_DISPLAY_OPTIONS.kanbanFields,+ ...options().kanbanFields,+ },+ });++ const toggleListColumn = (column: CrmListColumnId) => {+ const current = merged();+ setOptions({+ ...current,+ listColumns: {+ ...current.listColumns,+ [column]: !current.listColumns[column],+ },+ });+ };++ const toggleKanbanField = (field: CrmKanbanFieldId) => {+ const current = merged();+ setOptions({+ ...current,+ kanbanFields: {+ ...current.kanbanFields,+ [field]: !current.kanbanFields[field],+ },+ });+ };++ return { options: merged, toggleListColumn, toggleKanbanField };+}diff --git a/js/app/packages/companies/crm/saved-views.ts b/js/app/packages/companies/crm/saved-views.tsnew file mode 100644index 0000000000..cf141742d8--- /dev/null+++ b/js/app/packages/companies/crm/saved-views.ts@@ -0,0 +1,205 @@+/**+ * CRM saved views: named snapshots of the Customers view state.+ *+ * - Personal views persist per-user through the existing `/saved_views`+ * API (arbitrary JSON config, frontend-owned shape).+ * - Team views live in the shared team CRM config (see team-crm-config)+ * so every team member sees them.+ * - Any view can be shared as a link: the config is base64url-encoded in+ * the `crmView` search param of the Customers URL, so anyone on the+ * team can open it (the link carries only view state, never data).+ */++import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import type { View } from '@service-storage/generated/schemas/view';+import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query';+import { createMemo } from 'solid-js';+import { type TeamCrmSavedView, useTeamCrmConfig } from './team-crm-config';++/** Snapshot of the Customers view state. Fields are all optional so old+ * links/views keep working as the shape evolves. */+export type CrmViewConfig = {+ kind: 'crm';+ /** Server query filters (soup `Query`). */+ filters?: unknown;+ /** Client predicate ids ({ and, or }). */+ clientFilters?: { and?: string[]; or?: string[] };+ searchText?: string;+ /** Group-by id (e.g. `property:<definition-id>`); null = no grouping. */+ groupBy?: string | null;+ /** Sort ids (soup sort state). */+ sort?: string[];+ viewMode?: 'list' | 'board';+ /** Stage option ids selected in the Stage filter (may include NO_STAGE). */+ stageFilter?: string[];+ /** Owner ids selected in the Owner filter. */+ ownerFilter?: string[];+ activeTab?: string;+};++export function isCrmViewConfig(value: unknown): value is CrmViewConfig {+ return (+ typeof value === 'object' &&+ value !== null &&+ 'kind' in value &&+ (value as { kind: unknown }).kind === 'crm'+ );+}++export const CRM_VIEW_URL_PARAM = 'crmView';++/** Base64url-encode a view config for the share link. */+export function encodeCrmViewParam(config: CrmViewConfig): string {+ const json = JSON.stringify(config);+ const base64 = btoa(String.fromCharCode(...new TextEncoder().encode(json)));+ return base64.replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');+}++export function decodeCrmViewParam(param: string): CrmViewConfig | undefined {+ try {+ const base64 = param.replaceAll('-', '+').replaceAll('_', '/');+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));+ const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));+ return isCrmViewConfig(parsed) ? parsed : undefined;+ } catch {+ return undefined;+ }+}++/** Share link for a view config: /companies?crmView=<encoded>. */+export function buildCrmViewShareUrl(config: CrmViewConfig): string {+ const url = new URL('/companies', window.location.origin);+ url.searchParams.set(CRM_VIEW_URL_PARAM, encodeCrmViewParam(config));+ return url.toString();+}++const CRM_SAVED_VIEWS_QUERY_KEY = ['crm', 'saved-views'] as const;++export type PersonalCrmView = View & { config: CrmViewConfig };++/** Personal saved views (server-persisted via /saved_views). */+export function usePersonalCrmViews() {+ const queryClient = useQueryClient();++ const viewsQuery = useQuery(() => ({+ queryKey: CRM_SAVED_VIEWS_QUERY_KEY,+ queryFn: async () =>+ await throwOnErr(+ async () => await storageServiceClient.views.getSavedViews()+ ),+ }));++ const views = createMemo((): PersonalCrmView[] =>+ (viewsQuery.data?.views ?? []).filter((view): view is PersonalCrmView =>+ isCrmViewConfig(view.config)+ )+ );++ const invalidate = () =>+ queryClient.invalidateQueries({ queryKey: CRM_SAVED_VIEWS_QUERY_KEY });++ const createMutation = useMutation(() => ({+ mutationFn: async (vars: { name: string; config: CrmViewConfig }) =>+ await throwOnErr(+ async () =>+ await storageServiceClient.views.createSavedView({+ name: vars.name,+ config: vars.config,+ })+ ),+ onSuccess: () => invalidate(),+ onError: (error: Error) => {+ console.error('Failed to save view', error);+ toast.failure('Failed to save view');+ },+ }));++ const renameMutation = useMutation(() => ({+ mutationFn: async (vars: { id: string; name: string }) =>+ await throwOnErr(+ async () =>+ await storageServiceClient.views.patchView({+ saved_view_id: vars.id,+ name: vars.name,+ })+ ),+ onSuccess: () => invalidate(),+ onError: (error: Error) => {+ console.error('Failed to rename view', error);+ toast.failure('Failed to rename view');+ },+ }));++ const deleteMutation = useMutation(() => ({+ mutationFn: async (vars: { id: string }) =>+ await throwOnErr(+ async () =>+ await storageServiceClient.views.deleteView({ savedViewId: vars.id })+ ),+ onSuccess: () => invalidate(),+ onError: (error: Error) => {+ console.error('Failed to delete view', error);+ toast.failure('Failed to delete view');+ },+ }));++ return {+ views,+ isLoading: () => viewsQuery.isLoading,+ create: createMutation,+ rename: renameMutation,+ remove: deleteMutation,+ };+}++/** Team-shared saved views (stored in the shared team CRM config). */+export function useTeamCrmViews() {+ const userId = useUserId();+ const { config, update, isLoading } = useTeamCrmConfig();++ const views = createMemo((): TeamCrmSavedView[] =>+ (config().teamViews ?? []).filter((view) => isCrmViewConfig(view.config))+ );++ const add = (name: string, viewConfig: CrmViewConfig) => {+ const view: TeamCrmSavedView = {+ id: crypto.randomUUID(),+ name,+ config: viewConfig,+ createdBy: userId(),+ createdAt: new Date().toISOString(),+ };+ update.mutate(+ (current) => ({+ ...current,+ teamViews: [...(current.teamViews ?? []), view],+ }),+ {+ onError: (error: Error) => {+ console.error('Failed to save team view', error);+ toast.failure('Failed to save team view');+ },+ }+ );+ };++ const remove = (id: string) => {+ update.mutate(+ (current) => ({+ ...current,+ teamViews: (current.teamViews ?? []).filter((view) => view.id !== id),+ }),+ {+ onError: (error: Error) => {+ console.error('Failed to delete team view', error);+ toast.failure('Failed to delete team view');+ },+ }+ );+ };++ return { views, add, remove, isLoading, isSaving: () => update.isPending };+}diff --git a/js/app/packages/companies/crm/team-crm-config.ts b/js/app/packages/companies/crm/team-crm-config.tsnew file mode 100644index 0000000000..a6b8b99330--- /dev/null+++ b/js/app/packages/companies/crm/team-crm-config.ts@@ -0,0 +1,276 @@+/**+ * Team-shared CRM configuration (permissions, closed-stage set, team saved+ * views, display defaults).+ *+ * There is no generic team key-value store yet, so the config rides on the+ * existing team-scoped property-definition infrastructure: a reserved+ * definition (`__macro:crm-config`) holds a single select option whose+ * string value is the JSON config. Every team member can read it (team+ * definitions are team-visible) and writes go through the existing option+ * endpoints. Reserved `__macro:`-prefixed definitions are filtered out of+ * property pickers (see `isReservedPropertyDefinitionName`).+ */++import { useUserId } from '@core/context/user';+import { throwOnErr } from '@core/util/result';+import { RESERVED_PROPERTY_DEFINITION_PREFIX } from '@property/constants';+import { useListPropertiesQuery } from '@queries/properties/definitions';+import { useCurrentTeamQuery, useIsTeamAdmin } from '@queries/team/teams';+import { TeamRole } from '@service-auth/generated/schemas/teamRole';+import { propertiesServiceClient } from '@service-properties/client';+import type { PropertyDefinitionResponse } from '@service-properties/generated/schemas/propertyDefinitionResponse';+import type { PropertyDefinitionWithOptions } from '@service-properties/generated/schemas/propertyDefinitionWithOptions';+import { useMutation, useQueryClient } from '@tanstack/solid-query';+import { type Accessor, createMemo } from 'solid-js';++// Canonical home is `@property/constants`; re-exported for existing callers.+export {+ isReservedPropertyDefinitionName,+ RESERVED_PROPERTY_DEFINITION_PREFIX,+} from '@property/constants';++const CRM_CONFIG_DEFINITION_NAME = `${RESERVED_PROPERTY_DEFINITION_PREFIX}crm-config`;++/**+ * Minimum team role required for a CRM capability. Team members are+ * view-only at the platform level (the backend maps member → View access+ * on companies), so the configurable range is admin (default) vs owner.+ */+export type CrmPermissionRole = 'admin' | 'owner';++export type CrmPermissions = {+ /** Who can change the deal stage set in CRM settings. */+ editStages: CrmPermissionRole;+ /** Who can move deals out of a closed stage. */+ moveClosedDeals: CrmPermissionRole;+ /** Who can delete (hide) CRM records. */+ deleteRecords: CrmPermissionRole;+};++export type TeamCrmSavedView = {+ id: string;+ name: string;+ /** Serialized CRM view state (see crm/saved-views). */+ config: unknown;+ createdBy?: string;+ createdAt?: string;+};++export type TeamCrmConfig = {+ version: 1;+ permissions?: Partial<CrmPermissions>;+ /**+ * Stage option ids that count as "closed" deals (used by the+ * move-closed-deals permission). When unset, stages labeled like+ * closed/won/lost states are treated as closed.+ */+ closedStageIds?: string[];+ teamViews?: TeamCrmSavedView[];+};++export const DEFAULT_CRM_PERMISSIONS: CrmPermissions = {+ editStages: 'admin',+ moveClosedDeals: 'admin',+ deleteRecords: 'admin',+};++/** Labels treated as closed when no explicit closed set is configured. */+const DEFAULT_CLOSED_STAGE_LABEL = /customer|churned|closed|won|lost/i;++function findConfigDefinition(+ definitions: PropertyDefinitionResponse[] | undefined+): PropertyDefinitionWithOptions | undefined {+ return definitions?.find(+ (entry): entry is PropertyDefinitionWithOptions =>+ 'definition' in entry &&+ entry.definition.display_name === CRM_CONFIG_DEFINITION_NAME &&+ !entry.definition.is_system &&+ entry.definition.owner.scope === 'team'+ );+}++function parseConfig(definition: PropertyDefinitionWithOptions | undefined): {+ config: TeamCrmConfig;+ optionId?: string;+} {+ const empty: TeamCrmConfig = { version: 1 };+ if (!definition) return { config: empty };+ const option = [...definition.property_options].sort(+ (a, b) => a.display_order - b.display_order+ )[0];+ const raw = option?.value;+ if (+ !raw ||+ typeof raw !== 'object' ||+ !('value' in raw) ||+ typeof raw.value !== 'string'+ ) {+ return { config: empty, optionId: option?.id };+ }+ try {+ const parsed = JSON.parse(raw.value) as TeamCrmConfig;+ return { config: { ...empty, ...parsed }, optionId: option?.id };+ } catch {+ return { config: empty, optionId: option?.id };+ }+}++export function useTeamCrmConfig() {+ const queryClient = useQueryClient();+ const teamDefinitionsQuery = useListPropertiesQuery(() => ({+ scope: 'team',+ includeOptions: true,+ }));++ const parsed = createMemo(() =>+ parseConfig(findConfigDefinition(teamDefinitionsQuery.data))+ );++ const config = createMemo(() => parsed().config);++ const invalidate = () =>+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) =>+ queryKey.includes('properties') && queryKey.includes('definitions'),+ });++ /**+ * Read-modify-write of the shared config. Creates the reserved+ * definition/option on first write; concurrent writers are last-wins.+ */+ const updateMutation = useMutation(() => ({+ mutationFn: async (updater: (current: TeamCrmConfig) => TeamCrmConfig) => {+ // Re-list right before writing to reduce lost updates.+ const definitions = await throwOnErr(+ async () =>+ await propertiesServiceClient.listProperties({+ scope: 'team',+ include_options: true,+ })+ );+ const existing = findConfigDefinition(definitions);+ const definitionId = existing+ ? existing.definition.id+ : (+ await throwOnErr(+ async () =>+ await propertiesServiceClient.createPropertyDefinition({+ body: {+ display_name: CRM_CONFIG_DEFINITION_NAME,+ data_type: {+ type: 'select_string',+ multi: false,+ options: [],+ },+ scope: 'team',+ },+ })+ )+ ).id;+ const { config: current, optionId } = parseConfig(existing);+ const next = updater(current);+ const serialized = JSON.stringify(next);+ if (optionId) {+ await throwOnErr(+ async () =>+ await propertiesServiceClient.updatePropertyOption({+ definition_id: definitionId,+ option_id: optionId,+ body: { value: serialized },+ })+ );+ } else {+ await throwOnErr(+ async () =>+ await propertiesServiceClient.addPropertyOption({+ definition_id: definitionId,+ body: {+ type: 'select_string',+ option: { value: serialized, display_order: 0 },+ },+ })+ );+ }+ return next;+ },+ onSettled: () => invalidate(),+ }));++ return {+ config,+ isLoading: () => teamDefinitionsQuery.isLoading,+ update: updateMutation,+ };+}++/** Whether `role` satisfies a required minimum capability role. */+function roleSatisfies(+ role: TeamRole | undefined,+ required: CrmPermissionRole+): boolean {+ if (role === TeamRole.owner) return true;+ if (role === TeamRole.admin) return required === 'admin';+ return false;+}++/**+ * Effective CRM capabilities for the current user, combining the team's+ * configured permission thresholds with the platform-level rule that only+ * admins/owners can edit CRM data at all.+ */+export function useCrmPermissions() {+ const userId = useUserId();+ const teamQuery = useCurrentTeamQuery();+ const isTeamAdmin = useIsTeamAdmin();+ const { config, isLoading } = useTeamCrmConfig();++ const role = createMemo((): TeamRole | undefined => {+ const uid = userId();+ const team = teamQuery.data;+ if (!uid || !team) return undefined;+ return team.members.find((member) => member.user_id === uid)?.role;+ });++ const permissions = createMemo(+ (): CrmPermissions => ({+ ...DEFAULT_CRM_PERMISSIONS,+ ...config().permissions,+ })+ );++ return {+ role,+ permissions,+ isLoading,+ /** Can edit CRM data at all (platform rule: admin/owner). */+ canEditCrm: isTeamAdmin,+ canEditStages: createMemo(() =>+ roleSatisfies(role(), permissions().editStages)+ ),+ canMoveClosedDeals: createMemo(() =>+ roleSatisfies(role(), permissions().moveClosedDeals)+ ),+ canDeleteRecords: createMemo(() =>+ roleSatisfies(role(), permissions().deleteRecords)+ ),+ };+}++/**+ * The set of stage option ids considered "closed" — explicit config when+ * present, else a label heuristic over the active stages.+ */+export function useClosedStageIds(+ stages: Accessor<Array<{ id: string; label: string }>>+): Accessor<Set<string>> {+ const { config } = useTeamCrmConfig();+ return createMemo(() => {+ const explicit = config().closedStageIds;+ if (explicit && explicit.length > 0) return new Set(explicit);+ return new Set(+ stages()+ .filter((stage) => DEFAULT_CLOSED_STAGE_LABEL.test(stage.label))+ .map((stage) => stage.id)+ );+ });+}diff --git a/js/app/packages/core/component/AI/component/tool/Crm.tsx b/js/app/packages/core/component/AI/component/tool/Crm.tsxnew file mode 100644index 0000000000..378f473e2e--- /dev/null+++ b/js/app/packages/core/component/AI/component/tool/Crm.tsx@@ -0,0 +1,191 @@+import Buildings from '@phosphor-icons/core/regular/buildings.svg';+import type { NamedTool } from '@service-cognition/generated/tools/tool';+import { For, Show } from 'solid-js';+import { BaseTool } from './BaseTool';+import { Tool } from './Tool';+import { createToolRenderer } from './ToolRenderer';++type ListCompaniesResponse = NamedTool<'ListCompanies', 'response'>['data'];+type CompanyListItem = ListCompaniesResponse['companies'][number];+type GetCompanyResponse = NamedTool<'GetCompany', 'response'>['data'];++const pluralize = (count: number, singular: string, plural = `${singular}s`) =>+ `${count} ${count === 1 ? singular : plural}`;++function companySubtitle(company: CompanyListItem) {+ const parts: string[] = [];+ const domain = company.domains[0];+ if (domain) parts.push(domain);+ if (company.stage) parts.push(company.stage.label);+ return parts.join(' · ');+}++function CompanyRow(props: { company: CompanyListItem }) {+ return (+ <Tool.ListItem icon={<Buildings class="size-4" />}>+ <div class="min-w-0 flex-1">+ <div class="truncate text-xs text-ink">+ {props.company.name ?? props.company.domains[0] ?? props.company.id}+ </div>+ <Show when={companySubtitle(props.company)}>+ {(subtitle) => (+ <div class="truncate text-xs text-ink-placeholder">+ {subtitle()}+ </div>+ )}+ </Show>+ </div>+ </Tool.ListItem>+ );+}++function ListCompaniesToolResponse(props: ListCompaniesResponse) {+ return (+ <Tool.List>+ <Show+ when={props.companies.length > 0}+ fallback={<Tool.ListItem>No matching CRM companies.</Tool.ListItem>}+ >+ <For each={props.companies}>+ {(company) => <CompanyRow company={company} />}+ </For>+ </Show>+ </Tool.List>+ );+}++const listCompaniesHandler = createToolRenderer({+ name: 'ListCompanies',+ render: (ctx) => {+ const companies = () => ctx.response?.data.companies ?? [];+ const statusText = () => {+ if (!ctx.response) return undefined;+ if (companies().length === 0) return 'No results';+ return pluralize(companies().length, 'company', 'companies');+ };++ return (+ <BaseTool+ icon={Buildings}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <ListCompaniesToolResponse {...ctx.response.data} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">+ List CRM companies+ <Show when={ctx.tool.data.search}>+ {(search) => <> matching "{search()}"</>}+ </Show>+ <Show when={ctx.tool.data.stage}>+ {(stage) => <> in stage {stage()}</>}+ </Show>+ </span>+ <Show when={statusText()}>+ {(text) => (+ <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">+ {text()}+ </span>+ )}+ </Show>+ </div>+ </BaseTool>+ );+ },+});++function GetCompanyToolResponse(props: GetCompanyResponse) {+ const details = () => {+ const rows: { label: string; value: string }[] = [];+ if (props.domains.length > 0) {+ rows.push({ label: 'Domains', value: props.domains.join(', ') });+ }+ if (props.stage) rows.push({ label: 'Stage', value: props.stage.label });+ if (props.ownerUserId) {+ rows.push({ label: 'Owner', value: props.ownerUserId });+ }+ if (props.revenue !== undefined && props.revenue !== null) {+ rows.push({ label: 'Revenue', value: `$${props.revenue}` });+ }+ rows.push({+ label: 'Contacts',+ value: pluralize(props.contacts.length, 'contact'),+ });+ return rows;+ };++ return (+ <Tool.List>+ <Tool.ListItem icon={<Buildings class="size-4" />}>+ <div class="min-w-0 flex-1">+ <div class="truncate text-xs text-ink">+ {props.name ?? props.domains[0] ?? props.id}+ </div>+ <Show when={props.description}>+ {(description) => (+ <div class="truncate text-xs text-ink-placeholder">+ {description()}+ </div>+ )}+ </Show>+ </div>+ </Tool.ListItem>+ <For each={details()}>+ {(row) => (+ <Tool.ListItem>+ <div class="flex min-w-0 flex-1 gap-2 text-xs">+ <span class="shrink-0 text-ink-placeholder">{row.label}</span>+ <span class="min-w-0 truncate text-ink">{row.value}</span>+ </div>+ </Tool.ListItem>+ )}+ </For>+ </Tool.List>+ );+}++const getCompanyHandler = createToolRenderer({+ name: 'GetCompany',+ render: (ctx) => {+ const statusText = () => {+ if (!ctx.response) return undefined;+ const data = ctx.response.data;+ return data.stage?.label ?? data.domains[0];+ };++ return (+ <BaseTool+ icon={Buildings}+ renderContext={ctx.renderContext}+ type="call"+ response={+ ctx.response ? (+ <GetCompanyToolResponse {...ctx.response.data} />+ ) : undefined+ }+ >+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3 overflow-hidden">+ <span class="min-w-0 truncate">+ Read CRM company+ <Show when={ctx.response?.data.name}>+ {(name) => <> {name()}</>}+ </Show>+ </span>+ <Show when={statusText()}>+ {(text) => (+ <span class="shrink-0 whitespace-nowrap text-xs text-ink-extra-muted">+ {text()}+ </span>+ )}+ </Show>+ </div>+ </BaseTool>+ );+ },+});++export { getCompanyHandler, listCompaniesHandler };diff --git a/js/app/packages/core/component/AI/component/tool/handler.tsx b/js/app/packages/core/component/AI/component/tool/handler.tsxindex edb105b34f..f42344d6b0 100644--- a/js/app/packages/core/component/AI/component/tool/handler.tsx+++ b/js/app/packages/core/component/AI/component/tool/handler.tsx@@ -6,6 +6,7 @@ import {import { Dynamic } from 'solid-js/web';import { bashCodeExecutionHandler } from './BashCodeExecution';import { createDocumentHandler } from './CreateDocument';+import { getCompanyHandler, listCompaniesHandler } from './Crm';import { displayResultsHandler } from './DisplayResults';import { editDocumentHandler } from './EditDocument';import { getThreadHandler } from './GetThread';@@ -54,7 +55,9 @@ import { webFetchHandler } from './WebFetch';import { webSearchHandler } from './WebSearch';const toolHandlers: ToolHandlerMap<RenderContext> = {+ GetCompany: getCompanyHandler,GetEntityProperties: getEntityPropertiesHandler,+ ListCompanies: listCompaniesHandler,ListCallRecords: listCallRecordsHandler,ListEntities: listEntitiesHandler,ListInboxes: listInboxesHandler,diff --git a/js/app/packages/core/constant/SettingsState.tsx b/js/app/packages/core/constant/SettingsState.tsxindex 3699f56aff..a2e68997e1 100644--- a/js/app/packages/core/constant/SettingsState.tsx+++ b/js/app/packages/core/constant/SettingsState.tsx@@ -22,6 +22,7 @@ export type SettingsTab =| 'Mobile App'| 'Agent'| 'Team'+ | 'CRM'| 'Connected'| 'Email'| 'GitHub'diff --git a/js/app/packages/core/constant/settingsTabsConfig.tsx b/js/app/packages/core/constant/settingsTabsConfig.tsxindex 30cdefae0b..656aaf3a47 100644--- a/js/app/packages/core/constant/settingsTabsConfig.tsx+++ b/js/app/packages/core/constant/settingsTabsConfig.tsx@@ -1,5 +1,6 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import BugIcon from '@phosphor/bug.svg';+import BuildingsIcon from '@phosphor/buildings.svg';import CpuIcon from '@phosphor/cpu.svg';import CreditCardIcon from '@phosphor/credit-card.svg';import DeviceMobileIcon from '@phosphor/device-mobile-speaker.svg';@@ -54,6 +55,7 @@ export const SETTINGS_TAB_GROUPS: SettingsTabGroup[] = [label: 'Workspace',items: [{ tab: 'Team', label: 'Team', icon: UsersThreeIcon },+ { tab: 'CRM', label: 'CRM', icon: BuildingsIcon },{tab: 'Connected',label: 'Connections',@@ -90,6 +92,7 @@ const SETTINGS_TAB_SLUGS: Record<SettingsTab, string> = {'Mobile App': 'mobile-app',Agent: 'mcp-server',Team: 'team',+ CRM: 'crm',Connected: 'connections',Email: 'email',GitHub: 'github',@@ -141,6 +144,7 @@ export const useSettingsTabAvailable = () => {case 'Billing':return true;case 'Team':+ case 'CRM':return teamsFlag().enabled;case 'Connected':return true;diff --git a/js/app/packages/property/src/component/modal/SelectPropertyModal.tsx b/js/app/packages/property/src/component/modal/SelectPropertyModal.tsxindex 37ab9b7d11..5f62b5ae9c 100644--- a/js/app/packages/property/src/component/modal/SelectPropertyModal.tsx+++ b/js/app/packages/property/src/component/modal/SelectPropertyModal.tsx@@ -3,6 +3,10 @@ import { ENABLE_CREATE_PROPERTY } from '@core/constant/featureFlags';import { useListKeyBindings } from '@core/util/useListKeyBindings';import PlusIcon from '@phosphor/plus.svg';import LoadingSpinner from '@phosphor/spinner.svg';+import {+ CRM_TEAM_STAGE_DEFINITION_NAME,+ isReservedPropertyDefinitionName,+} from '@property/constants';import { useListPropertiesQuery } from '@queries/properties/definitions';import { useAddEntityPropertyMutation } from '@queries/properties/entity';import { cn, Dialog, Surface } from '@ui';@@ -57,15 +61,27 @@ export function SelectPropertyModal(props: PropertySelectorProps) {const data = listPropertiesQuery.data;const properties = Array.isArray(data) ? data : [];- return properties.map((item) => {- if ('definition' in item) {- return toPropertyDefinitionDomain(- item.definition,- item.property_options || []- );- }- return toPropertyDefinitionDomain(item);- });+ return properties+ .map((item) => {+ if ('definition' in item) {+ return toPropertyDefinitionDomain(+ item.definition,+ item.property_options || []+ );+ }+ return toPropertyDefinitionDomain(item);+ })+ .filter(+ // Reserved internal definitions (`__macro:*` config carriers) and+ // the CRM-managed team Stage definition must never surface in+ // property pickers.+ (property) =>+ !isReservedPropertyDefinitionName(property.displayName) &&+ !(+ property.displayName === CRM_TEAM_STAGE_DEFINITION_NAME &&+ !property.isSystem+ )+ );});let searchInputRef!: HTMLInputElement;diff --git a/js/app/packages/property/src/constants.ts b/js/app/packages/property/src/constants.tsindex 93ec05fcbe..0904ee6c28 100644--- a/js/app/packages/property/src/constants.ts+++ b/js/app/packages/property/src/constants.ts@@ -7,6 +7,21 @@ import type { BlockAlias, BlockName } from '@core/block';export const NUMBER_DECIMAL_PLACES = 4;+/** Prefix for internal, non-user-facing property definitions. */+export const RESERVED_PROPERTY_DEFINITION_PREFIX = '__macro:';++/** True for internal definitions that must not appear in property UIs. */+export function isReservedPropertyDefinitionName(displayName: string): boolean {+ return displayName.startsWith(RESERVED_PROPERTY_DEFINITION_PREFIX);+}++/**+ * Reserved display name of the team-scoped CRM deal-stage definition+ * (unique per team). Managed exclusively from CRM settings, so generic+ * property pickers must not offer it.+ */+export const CRM_TEAM_STAGE_DEFINITION_NAME = 'Stage';+/*** System property definition IDs (from backend seed migration).* These are stable UUIDs that match the database.diff --git a/js/app/packages/queries/properties/definitions.ts b/js/app/packages/queries/properties/definitions.tsindex 76e7c7818c..456b5cf557 100644--- a/js/app/packages/queries/properties/definitions.ts+++ b/js/app/packages/queries/properties/definitions.ts@@ -57,6 +57,37 @@ type CreatePropertyDefinitionParams = {body: CreatePropertyDefinitionRequest;};+type DeletePropertyDefinitionParams = {+ definitionId: string;+};++export function useDeletePropertyDefinitionMutation(+ callbacks?: MutationCallbacks<unknown, Error, DeletePropertyDefinitionParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: DeletePropertyDefinitionParams) => {+ return await throwOnErr(+ async () =>+ await propertiesServiceClient.deletePropertyDefinition({+ definition_id: vars.definitionId,+ })+ );+ },+ ...withCallbacks<unknown, Error, DeletePropertyDefinitionParams>(+ {+ onError(error) {+ console.error('Failed to delete property definition', error);+ toast.failure('Failed to delete property');+ },+ onSuccess: () => {+ invalidatePropertyDefinitions();+ },+ },+ callbacks+ ),+ }));+}+export function useCreatePropertyDefinitionMutation(callbacks?: MutationCallbacks<PropertyDefinition,diff --git a/js/app/packages/queries/properties/options.ts b/js/app/packages/queries/properties/options.tsindex 2322995559..fbb4fcf532 100644--- a/js/app/packages/queries/properties/options.ts+++ b/js/app/packages/queries/properties/options.ts@@ -5,6 +5,7 @@ import type { Accessor } from 'solid-js';import { propertiesServiceClient } from '../../service-clients/service-properties/client';import type { AddPropertyOptionRequest } from '../../service-clients/service-properties/generated/schemas/addPropertyOptionRequest';import type { PropertyOption } from '../../service-clients/service-properties/generated/schemas/propertyOption';+import type { UpdatePropertyOptionRequest } from '../../service-clients/service-properties/generated/schemas/updatePropertyOptionRequest';import { queryClient } from '../client';import { type MutationCallbacks, withCallbacks } from '../utils';import { propertiesKeys } from './keys';@@ -48,6 +49,79 @@ type AddPropertyOptionParams = {body: AddPropertyOptionRequest;};+type UpdatePropertyOptionParams = {+ propertyDefinitionId: string;+ optionId: string;+ body: UpdatePropertyOptionRequest;+};++export function useUpdatePropertyOptionMutation(+ callbacks?: MutationCallbacks<+ PropertyOption,+ Error,+ UpdatePropertyOptionParams+ >+) {+ return useMutation(() => ({+ mutationFn: async (vars: UpdatePropertyOptionParams) => {+ const result = await throwOnErr(+ async () =>+ await propertiesServiceClient.updatePropertyOption({+ definition_id: vars.propertyDefinitionId,+ option_id: vars.optionId,+ body: vars.body,+ })+ );+ return result;+ },+ ...withCallbacks<PropertyOption, Error, UpdatePropertyOptionParams>(+ {+ onError(error) {+ console.error('Failed to update property option', error);+ toast.failure('Failed to update option');+ },+ onSuccess: (_data, variables) => {+ invalidatePropertyOptions(variables.propertyDefinitionId);+ },+ },+ callbacks+ ),+ }));+}++type DeletePropertyOptionParams = {+ propertyDefinitionId: string;+ optionId: string;+};++export function useDeletePropertyOptionMutation(+ callbacks?: MutationCallbacks<unknown, Error, DeletePropertyOptionParams>+) {+ return useMutation(() => ({+ mutationFn: async (vars: DeletePropertyOptionParams) => {+ return await throwOnErr(+ async () =>+ await propertiesServiceClient.deletePropertyOption({+ definition_id: vars.propertyDefinitionId,+ option_id: vars.optionId,+ })+ );+ },+ ...withCallbacks<unknown, Error, DeletePropertyOptionParams>(+ {+ onError(error) {+ console.error('Failed to delete property option', error);+ toast.failure('Failed to delete option');+ },+ onSuccess: (_data, variables) => {+ invalidatePropertyOptions(variables.propertyDefinitionId);+ },+ },+ callbacks+ ),+ }));+}+export function useAddPropertyOptionMutation(callbacks?: MutationCallbacks<PropertyOption, Error, AddPropertyOptionParams>) {diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex 134cfdf2cd..a9227114aa 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -507,6 +507,49 @@ export const EditDocumentResponse = z.object({summary: z.string(),});+export const GetCompany = z.object({ company_id: z.string().uuid() });++export const GetCompanyResponse = z.object({+ contacts: z.array(+ z.object({+ email: z.string(),+ id: z.string().uuid(),+ lastInteraction: z.string().datetime({ offset: true }),+ name: z.union([z.string(), z.null()]).optional(),+ })+ ),+ description: z.union([z.string(), z.null()]).optional(),+ domains: z.array(z.string()),+ emailSync: z.boolean(),+ firstInteraction: z.string().datetime({ offset: true }),+ hidden: z.boolean(),+ id: z.string().uuid(),+ lastInteraction: z.string().datetime({ offset: true }),+ name: z.union([z.string(), z.null()]).optional(),+ ownerUserId: z.union([z.string(), z.null()]).optional(),+ properties: z.array(+ z.object({+ currentValue: z.any().optional(),+ dataType: z.string(),+ displayName: z.string(),+ isMultiSelect: z.boolean(),+ isSystem: z.boolean(),+ options: z.array(+ z.object({ displayValue: z.string(), id: z.string().uuid() })+ ),+ propertyDefinitionId: z.string().uuid(),+ })+ ),+ revenue: z.union([z.number(), z.null()]).optional(),+ stage: z+ .union([+ z.object({ label: z.string(), optionId: z.string().uuid() }),+ z.null(),+ ])+ .optional(),+ summary: z.string(),+});+export const GetEntityProperties = z.object({entity_id: z.string(),entity_type: z.enum([@@ -517,6 +560,7 @@ export const GetEntityProperties = z.object({'thread','channel','user',+ 'company',]),});@@ -612,6 +656,35 @@ export const ListCallRecordsResponse = z.object({),});+export const ListCompanies = z.object({+ include_hidden: z.union([z.boolean(), z.null()]).default(null),+ limit: z.union([z.number().int().gte(0).lte(65535), z.null()]).default(null),+ owner_user_id: z.union([z.string(), z.null()]).default(null),+ search: z.union([z.string(), z.null()]).default(null),+ stage: z.union([z.string(), z.null()]).default(null),+});++export const ListCompaniesResponse = z.object({+ companies: z.array(+ z.object({+ domains: z.array(z.string()),+ hidden: z.boolean(),+ id: z.string().uuid(),+ lastInteraction: z.string().datetime({ offset: true }),+ name: z.union([z.string(), z.null()]).optional(),+ ownerUserId: z.union([z.string(), z.null()]).optional(),+ revenue: z.union([z.number(), z.null()]).optional(),+ stage: z+ .union([+ z.object({ label: z.string(), optionId: z.string().uuid() }),+ z.null(),+ ])+ .optional(),+ })+ ),+ summary: z.string(),+});+export const ListEntities = z.object({callf: z.any().default(null),cf: z.any().default(null),@@ -2112,6 +2185,7 @@ export const SetEntityProperty = z.object({'thread','channel','user',+ 'company',]),}),z.null(),@@ -2130,6 +2204,7 @@ export const SetEntityProperty = z.object({'thread','channel','user',+ 'company',]),})),@@ -2144,6 +2219,7 @@ export const SetEntityProperty = z.object({'thread','channel','user',+ 'company',]),link_url: z.union([z.string(), z.null()]).default(null),link_urls: z.union([z.array(z.string()), z.null()]).default(null),diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts b/js/app/packages/service-clients/service-cognition/generated/tools/tool.tsindex ad7fdff409..680074939e 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/tool.ts@@ -28,6 +28,7 @@ type ToolParserMap = {call: types.EditDocument;response: types.EditDocumentResponse;};+ GetCompany: { call: types.GetCompany; response: types.GetCompanyResponse };GetEntityProperties: {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;@@ -37,6 +38,10 @@ type ToolParserMap = {call: types.ListCallRecords;response: types.ListCallRecordsResponse;};+ ListCompanies: {+ call: types.ListCompanies;+ response: types.ListCompaniesResponse;+ };ListEntities: {call: types.ListEntities;response: types.ListEntitiesResponse;@@ -136,6 +141,10 @@ const toolParserMap = {call: schemas.EditDocument,response: schemas.EditDocumentResponse,},+ GetCompany: {+ call: schemas.GetCompany,+ response: schemas.GetCompanyResponse,+ },GetEntityProperties: {call: schemas.GetEntityProperties,response: schemas.GetEntityPropertiesResponse,@@ -145,6 +154,10 @@ const toolParserMap = {call: schemas.ListCallRecords,response: schemas.ListCallRecordsResponse,},+ ListCompanies: {+ call: schemas.ListCompanies,+ response: schemas.ListCompaniesResponse,+ },ListEntities: {call: schemas.ListEntities,response: schemas.ListEntitiesResponse,@@ -267,6 +280,7 @@ type ToolDataMap = {call: types.EditDocument;response: types.EditDocumentResponse;};+ GetCompany: { call: types.GetCompany; response: types.GetCompanyResponse };GetEntityProperties: {call: types.GetEntityProperties;response: types.GetEntityPropertiesResponse;@@ -276,6 +290,10 @@ type ToolDataMap = {call: types.ListCallRecords;response: types.ListCallRecordsResponse;};+ ListCompanies: {+ call: types.ListCompanies;+ response: types.ListCompaniesResponse;+ };ListEntities: {call: types.ListEntities;response: types.ListEntitiesResponse;diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 9ffa0cd33a..110faa17cb 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -246,7 +246,8 @@ export type ToolEntityType =| 'chat'| 'thread'| 'channel'- | 'user';+ | 'user'+ | 'company';/*** Entity types that can be returned by the list entities AI tool.*/@@ -852,6 +853,127 @@ export interface Thread {*/updatedAt?: string | null;}+/**+ * A contact belonging to the company.+ */+export interface CompanyContactItem {+ /**+ * The contact's email address.+ */+ email: string;+ /**+ * The CRM contact id.+ */+ id: string;+ /**+ * Most recent known interaction with this contact.+ */+ lastInteraction: string;+ /**+ * The contact's display name, when known.+ */+ name?: string | null;+}+/**+ * A CRM company row returned by [`ListCompanies`].+ */+export interface CompanyListItem {+ /**+ * The company's email domains, primary domain first.+ */+ domains: string[];+ /**+ * Whether the company is hidden from the team's CRM listings.+ */+ hidden: boolean;+ /**+ * The CRM company id. Use with GetCompany, GetEntityProperties /+ * SetEntityProperty (entity_type=company).+ */+ id: string;+ /**+ * Most recent known email interaction with this company.+ */+ lastInteraction: string;+ /**+ * Company display name, when resolved.+ */+ name?: string | null;+ /**+ * Macro user id of the company's owner, if set.+ */+ ownerUserId?: string | null;+ /**+ * The company's revenue (dollars), if set.+ */+ revenue?: number | null;+ /**+ * The company's pipeline stage, if set.+ */+ stage?: ToolCompanyStage | null;+}+/**+ * A company's pipeline stage: the select option id currently set plus its+ * human-readable label.+ */+export interface ToolCompanyStage {+ /**+ * The stage's display label (e.g. "Lead", "Customer").+ */+ label: string;+ /**+ * The stage property option id (usable with SetEntityProperty).+ */+ optionId: string;+}+/**+ * A property attached to the company (builtin or custom).+ */+export interface CompanyPropertyItem {+ /**+ * The current value, if set.+ */+ currentValue?: {+ [k: string]: unknown;+ };+ /**+ * The data type (boolean, date, number, string, select_string, select_number, tag, entity, link).+ */+ dataType: string;+ /**+ * Human-readable property name.+ */+ displayName: string;+ /**+ * Whether the property supports multiple values.+ */+ isMultiSelect: boolean;+ /**+ * Whether this is a system-defined property.+ */+ isSystem: boolean;+ /**+ * Available options for select-type properties.+ */+ options: CompanyPropertyOption[];+ /**+ * The property definition id. Use with SetEntityProperty (entity_type=company).+ */+ propertyDefinitionId: string;+}+/**+ * An option available on a select-type company property.+ */+export interface CompanyPropertyOption {+ /**+ * The option's display value.+ */+ displayValue: string;+ /**+ * The option id to use when setting select values via SetEntityProperty.+ */+ id: string;+}/*** Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. This is keyword search, not semantic search: queries only match literal words/tokens, prefixes, or exact quoted terms that appear in the indexed content. Use this for targeted keyword/content lookup, not for activity-summary questions like "what happened today", "what's going on", "catch me up", or "what happened in standup today"; those should start with ListEntities using time/type/channel filters. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Matching defaults to prefix; set matchType to 'exact' to match whole tokens/phrases with no prefix expansion (e.g. an exact word, identifier, or full email address). Wrap a multi-word phrase in double quotes to keep it together as one adjacent phrase. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.*/@@ -1213,7 +1335,78 @@ export interface EmailSearchResult {sent_at?: string | null;}/**- * Get all properties attached to an entity (document, task, project, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first.+ * Fetch one of the team's CRM companies by id, with its domains, contacts, pipeline Stage / Owner / Revenue, and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change a property (move stage, set owner/revenue, or edit a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response.+ */+export interface GetCompany {+ /**+ * The CRM company id (UUID), e.g. from ListCompanies.+ */+ company_id: string;+}+/**+ * Response from the [`GetCompany`] tool.+ */+export interface GetCompanyResponse {+ /**+ * Contacts attached to this company.+ */+ contacts: CompanyContactItem[];+ /**+ * Short company description, when resolved.+ */+ description?: string | null;+ /**+ * The company's email domains, primary domain first.+ */+ domains: string[];+ /**+ * Whether team-wide email sharing is enabled for this company.+ */+ emailSync: boolean;+ /**+ * Earliest known email interaction with this company.+ */+ firstInteraction: string;+ /**+ * Whether the company is hidden from the team's CRM listings.+ */+ hidden: boolean;+ /**+ * The CRM company id.+ */+ id: string;+ /**+ * Most recent known email interaction with this company.+ */+ lastInteraction: string;+ /**+ * Company display name, when resolved.+ */+ name?: string | null;+ /**+ * Macro user id of the company's owner, if set.+ */+ ownerUserId?: string | null;+ /**+ * All properties attached to this company (builtin Stage / Owner /+ * Revenue plus custom ones), with current values and select options.+ */+ properties: CompanyPropertyItem[];+ /**+ * The company's revenue (dollars), if set.+ */+ revenue?: number | null;+ /**+ * The company's pipeline stage, if set.+ */+ stage?: ToolCompanyStage | null;+ /**+ * Human-readable summary.+ */+ summary: string;+}+/**+ * Get all properties attached to an entity (document, task, project, CRM company, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first. For CRM companies (entity_type=company, entity_id=the company UUID), this returns the builtin Stage / Owner / Revenue properties (with the team's stage options) plus any custom company properties.*/export interface GetEntityProperties {/**@@ -1402,6 +1595,44 @@ export interface ListCallRecordsResponse {*/records: CallRecordSummary[];}+/**+ * List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and its pipeline Stage / Owner / Revenue properties when set. Use the filters to narrow results: `search` for name/domain text, `stage` for pipeline stage, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to move stages or update owner/revenue/custom properties.+ */+export interface ListCompanies {+ /**+ * Also include companies hidden from the CRM. Defaults to false. Requires team admin or owner role.+ */+ include_hidden?: boolean | null;+ /**+ * Maximum number of companies to return. Defaults to 50; max 200.+ */+ limit?: number | null;+ /**+ * Filter to companies whose Owner property is this Macro user id (e.g. "macro|[email protected]"). Use ListTeamMembers to find user ids.+ */+ owner_user_id?: string | null;+ /**+ * Case-insensitive substring matched against company names and domains (e.g. "acme" matches "Acme Corp" and "acme.com").+ */+ search?: string | null;+ /**+ * Filter to companies in this pipeline stage. Accepts a stage label matched case-insensitively (e.g. "lead", "Customer" — teams may have custom stage names) or a stage option UUID.+ */+ stage?: string | null;+}+/**+ * Response from the [`ListCompanies`] tool.+ */+export interface ListCompaniesResponse {+ /**+ * The matching CRM companies.+ */+ companies: CompanyListItem[];+ /**+ * Human-readable summary of the results.+ */+ summary: string;+}/*** Browse the user's Macro workspace to see recent items they have access to. Returns Macro documents, AI conversations, projects, emails, chat channels, call records, and foreign entities. Use this to get an overview of what the user has been working on or to find items by type. Start here for activity-summary questions such as "what happened today", "what's going on", "catch me up", or "what happened in standup today"; apply precise time, type, channel, or mailbox filters when the user gives that scope. For Macro task requests such as "list my tasks", "tasks assigned to me", or "tasks I completed yesterday", prefer this tool over external task trackers such as Linear unless the user explicitly asks for Linear. Macro tasks are document items with df subtype {"l":{"dst":"task"}} and includeTypes ["document"]. Filter task Status and Assignees through propf using entity_type TASK: Status property 00000001-0000-0000-0000-000000000002, Completed option 00000001-0000-0000-0002-000000000004, Assignees property 00000001-0000-0000-0000-000000000001. The current user's assignee entity id is their Macro user id, usually macro|<their email address from context>. For "completed yesterday", combine status Completed, assigned-to-me, and a df updatedAt yesterday window with ua gte/lt ISO timestamps. For finding specific items by name or content, use the search tool instead.*/@@ -2727,6 +2958,12 @@ export interface SendEmail {* - Subtasks (00000001-0000-0000-0000-000000000006): entity, multi. Use entity_refs with entity_type='task'.* - Story Points (00000001-0000-0000-0000-000000000009): number, single. Use number_value.*+ * CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties:+ * - Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids.+ * - Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'.+ * - Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars).+ * Editing company properties requires the caller to be a team admin or owner.+ ** For non-system or custom properties, call GetEntityProperties first to discover property_definition_id values and options.*/export interface SetEntityProperty {diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex f143cdef4c..6ec35a6032 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3277,7 +3277,9 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"name = "crm"version = "0.1.0"dependencies = [+ "ai_toolset","anyhow",+ "async-trait","axum","chrono","entity_access",@@ -3285,10 +3287,14 @@ dependencies = ["macro_uuid","model-error-response","model_user",+ "models_properties",+ "properties","reqwest 0.13.4",+ "schemars 1.2.1","serde","serde_json","sqlx",+ "system_properties","thiserror 2.0.18","tokio","tracing",diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex 605bb082a6..18fef7c9b9 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -356,6 +356,7 @@ pub async fn build_tool_service_context_from_env(chat_tool_context,channel_tool_context,team_tool_context: crate::tool_context::build_team_tool_context(pool.clone()),+ crm_tool_context: crate::tool_context::build_crm_tool_context(pool.clone()),schedule_tool_context: crate::NoOpScheduleContext,anthropic_tool_context,recorder: ai_usage::pg_recorder(pool.clone()),diff --git a/rust/cloud-storage/ai_tools/src/lib.rs b/rust/cloud-storage/ai_tools/src/lib.rsindex 63210668c9..9dd28f822f 100644--- a/rust/cloud-storage/ai_tools/src/lib.rs+++ b/rust/cloud-storage/ai_tools/src/lib.rs@@ -21,6 +21,7 @@ use anthropic::toolset::anthropic_toolset;use call::inbound::toolset::call_toolset;use channels::inbound::toolset::channel_toolset;use chat::inbound::toolset::chat_toolset;+use crm::inbound::toolset::crm_toolset;use display_results::DisplayResults;use documents::inbound::toolset::document_toolset;use email::inbound::toolset::{email_toolset, mcp_toolset as email_mcp_toolset};@@ -45,14 +46,14 @@ pub use tool_context::{NoOpScheduleContext, NoOpSnsEndpointManager, NoOpTaskProperties, RequestContext,TaskPropertiesAdapter, ToolCallRecordQueryService, ToolCallService, ToolCallToolContext,ToolChannelEventDispatcher, ToolChannelMessagesService, ToolChannelToolContext,- ToolChatService, ToolChatToolContext, ToolCommsService, ToolDocumentService,- ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,+ ToolChatService, ToolChatToolContext, ToolCommsService, ToolCrmService, ToolCrmToolContext,+ ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,ToolEntityAccessManagementService, ToolEntityAccessService, ToolForeignEntityService,ToolFrecencyService, ToolNotificationQueue, ToolNotificationService,ToolNotificationToolContext, ToolPropertiesService, ToolPropertiesToolContext,ToolServiceContext, ToolSoupService, ToolSystemPropertiesService, ToolTeamService,ToolTeamToolContext, ToolUserEmailService, build_channel_tool_context,- build_channel_tool_context_with_dispatcher, build_properties_service,+ build_channel_tool_context_with_dispatcher, build_crm_tool_context, build_properties_service,build_properties_tool_context, build_task_properties_adapter, build_team_tool_context,};pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;@@ -84,6 +85,7 @@ pub(crate) fn subagent_toolset() -> AiToolSet {.add_subtoolset::<ToolChatToolContext>(chat_toolset()).add_subtoolset::<ToolChannelToolContext>(channel_toolset()).add_subtoolset::<ToolTeamToolContext>(team_toolset())+ .add_subtoolset::<ToolCrmToolContext>(crm_toolset()).add_subtoolset::<AnthropicToolContext>(anthropic_toolset())}diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex 3624f86128..339f827242 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -15,6 +15,7 @@ use chat::domain::service::ChatServiceImpl;use chat::inbound::toolset::ChatToolContext;use chat::outbound::postgres::PgChatRepo;use connection::domain::ports::ConnectionService;+use crm::inbound::toolset::CrmToolContext;use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToolContext};use email::{domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,@@ -125,6 +126,28 @@ pub fn build_channel_tool_context_with_dispatcher()}+/// Type alias for the CRM AI tool context.+pub type ToolCrmToolContext =+ CrmToolContext<ToolCrmService, ToolEntityAccessService, ToolPropertiesService>;++/// Build the CRM AI tool context from a Postgres pool.+pub fn build_crm_tool_context(pool: sqlx::PgPool) -> ToolCrmToolContext {+ let entity_access_service = Arc::new(+ entity_access::domain::service::EntityAccessServiceImpl::new(+ entity_access::outbound::PgAccessRepository::new(pool.clone()),+ ),+ );+ let properties = build_properties_service(pool.clone(), entity_access_service.clone());+ CrmToolContext {+ service: Arc::new(crm::domain::service::CrmServiceImpl::new(+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(pool.clone()),+ crm::outbound::no_op_resolver::NoOpCompanyMetadataResolver,+ )),+ entity_access_service,+ properties,+ }+}+/// Type alias for the team member listing service used by AI tools.pub type ToolTeamService = TeamRepositoryImpl;@@ -628,6 +651,7 @@ pub struct ToolServiceContext {pub chat_tool_context: ToolChatToolContext,pub channel_tool_context: ToolChannelToolContext,pub team_tool_context: ToolTeamToolContext,+ pub crm_tool_context: ToolCrmToolContext,pub schedule_tool_context: NoOpScheduleContext,pub anthropic_tool_context: AnthropicToolContext,/// Records token usage / cost for AI calls made with this context.diff --git a/rust/cloud-storage/crm/Cargo.toml b/rust/cloud-storage/crm/Cargo.tomlindex 08f827c4fe..d19330a03a 100644--- a/rust/cloud-storage/crm/Cargo.toml+++ b/rust/cloud-storage/crm/Cargo.toml@@ -5,6 +5,16 @@ publish = falseversion = "0.1.0"[features]+ai_tools = [+ "dep:ai_toolset",+ "dep:async-trait",+ "dep:models_properties",+ "dep:properties",+ "dep:schemars",+ "dep:system_properties",+ "entity_access/ports",+ "ports",+]axum = ["dep:axum","dep:macro_uuid",@@ -15,7 +25,7 @@ axum = ["entity_access/inbound","entity_access/ports",]-default = ["inbound", "outbound", "ports"]+default = ["ai_tools", "inbound", "outbound", "ports"]inbound = ["axum", "ports"]outbound = ["dep:reqwest", "dep:sqlx", "dep:unfurl", "ports"]ports = []@@ -34,6 +44,16 @@ uuid = { workspace = true }entity_access = { path = "../entity_access", default-features = false }+# AI toolset dependencies+ai_toolset = { path = "../ai_toolset", optional = true }+async-trait = { workspace = true, optional = true }+models_properties = { path = "../models_properties", optional = true }+properties = { path = "../properties", default-features = false, features = [+ "ports",+], optional = true }+schemars = { workspace = true, optional = true }+system_properties = { path = "../system_properties", optional = true }+# Axum / inbound dependenciesaxum = { workspace = true, optional = true }macro_uuid = { path = "../macro_uuid", optional = true }diff --git a/rust/cloud-storage/crm/src/domain/model.rs b/rust/cloud-storage/crm/src/domain/model.rsindex b669683417..15a6aaa2c8 100644--- a/rust/cloud-storage/crm/src/domain/model.rs+++ b/rust/cloud-storage/crm/src/domain/model.rs@@ -60,9 +60,13 @@ pub struct CrmCompany {/// `email_sync = false` (see/// [`crate::domain::service::CrmService::set_company_hidden`]).pub hidden: bool,- /// When the company was created+ /// Earliest known email interaction with this company. Repository+ /// read paths fill this from `crm_companies.first_interaction`, not+ /// the row's lifecycle `created_at`.pub created_at: DateTime<Utc>,- /// When the company was last updated+ /// Most recent known email interaction with this company. Repository+ /// read paths fill this from `crm_companies.last_interaction`, not+ /// the row's lifecycle `updated_at`.pub updated_at: DateTime<Utc>,/// All domains associated with this companypub domains: Vec<CrmDomain>,diff --git a/rust/cloud-storage/crm/src/inbound.rs b/rust/cloud-storage/crm/src/inbound.rsindex 299b52147a..201aa6e7f7 100644--- a/rust/cloud-storage/crm/src/inbound.rs+++ b/rust/cloud-storage/crm/src/inbound.rs@@ -4,3 +4,5 @@pub mod axum_extractors;#[cfg(feature = "axum")]pub mod axum_router;+#[cfg(feature = "ai_tools")]+pub mod toolset;diff --git a/rust/cloud-storage/crm/src/inbound/toolset/get_company.rs b/rust/cloud-storage/crm/src/inbound/toolset/get_company.rsnew file mode 100644index 0000000000..301e285272--- /dev/null+++ b/rust/cloud-storage/crm/src/inbound/toolset/get_company.rs@@ -0,0 +1,309 @@+//! GetCompany tool for reading a single CRM company's details.++use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use entity_access::domain::{+ models::{AccessError, Entity, EntityAccessReceipt, EntityType, ViewAccessLevel},+ ports::EntityAccessService,+};+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::property_option::PropertyOptionValue;+use models_properties::{DataType, EntityType as PropertyEntityType};+use properties::PropertiesService;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::domain::{+ auth::CrmCompanyReceipt,+ model::{CrmContact, CrmError},+ service::CrmService,+};++use super::{+ CrmToolContext, ToolCompanyStage, crm_error, extract_company_crm_props,+ load_stage_option_catalog,+};++/// A contact belonging to the company.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CompanyContactItem {+ /// The CRM contact id.+ pub id: Uuid,+ /// The contact's email address.+ pub email: String,+ /// The contact's display name, when known.+ pub name: Option<String>,+ /// Most recent known interaction with this contact.+ pub last_interaction: DateTime<Utc>,+}++impl From<CrmContact> for CompanyContactItem {+ fn from(contact: CrmContact) -> Self {+ Self {+ id: contact.id,+ email: contact.email,+ name: contact.name,+ last_interaction: contact.last_interaction,+ }+ }+}++/// An option available on a select-type company property.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CompanyPropertyOption {+ /// The option id to use when setting select values via SetEntityProperty.+ pub id: Uuid,+ /// The option's display value.+ pub display_value: String,+}++/// A property attached to the company (builtin or custom).+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CompanyPropertyItem {+ /// The property definition id. Use with SetEntityProperty (entity_type=company).+ pub property_definition_id: Uuid,+ /// Human-readable property name.+ pub display_name: String,+ /// The data type (boolean, date, number, string, select_string, select_number, tag, entity, link).+ pub data_type: String,+ /// Whether the property supports multiple values.+ pub is_multi_select: bool,+ /// Whether this is a system-defined property.+ pub is_system: bool,+ /// The current value, if set.+ pub current_value: Option<serde_json::Value>,+ /// Available options for select-type properties.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub options: Vec<CompanyPropertyOption>,+}++/// Response from the [`GetCompany`] tool.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct GetCompanyResponse {+ /// The CRM company id.+ pub id: Uuid,+ /// Company display name, when resolved.+ pub name: Option<String>,+ /// Short company description, when resolved.+ pub description: Option<String>,+ /// The company's email domains, primary domain first.+ pub domains: Vec<String>,+ /// Whether the company is hidden from the team's CRM listings.+ pub hidden: bool,+ /// Whether team-wide email sharing is enabled for this company.+ pub email_sync: bool,+ /// Earliest known email interaction with this company.+ pub first_interaction: DateTime<Utc>,+ /// Most recent known email interaction with this company.+ pub last_interaction: DateTime<Utc>,+ /// The company's pipeline stage, if set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub stage: Option<ToolCompanyStage>,+ /// Macro user id of the company's owner, if set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub owner_user_id: Option<String>,+ /// The company's revenue (dollars), if set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub revenue: Option<f64>,+ /// Contacts attached to this company.+ pub contacts: Vec<CompanyContactItem>,+ /// All properties attached to this company (builtin Stage / Owner /+ /// Revenue plus custom ones), with current values and select options.+ pub properties: Vec<CompanyPropertyItem>,+ /// Human-readable summary.+ pub summary: String,+}++/// Fetch one CRM company by id.+#[derive(Debug, Clone, Deserialize, JsonSchema)]+#[schemars(+ title = "GetCompany",+ description = "Fetch one of the team's CRM companies by id, with its domains, contacts, pipeline Stage / Owner / Revenue, and all attached property values (including custom properties and the valid stage options). Use ListCompanies to find company ids. To change a property (move stage, set owner/revenue, or edit a custom property) call SetEntityProperty with entity_type=company, the company id, and a property_definition_id / option id from this response."+)]+pub struct GetCompany {+ /// The CRM company id to fetch.+ #[schemars(description = "The CRM company id (UUID), e.g. from ListCompanies.")]+ pub company_id: Uuid,+}++#[async_trait]+impl<CSvc, ESvc, PSvc> AsyncTool<CrmToolContext<CSvc, ESvc, PSvc>> for GetCompany+where+ CSvc: CrmService,+ ESvc: EntityAccessService,+ PSvc: PropertiesService,+{+ type Output = GetCompanyResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, company_id=%self.company_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<CrmToolContext<CSvc, ESvc, PSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!(params=?self, "Get CRM company");++ let company_id = self.company_id.to_string();++ // Resolve the caller's permission on this company (derived from+ // their role on the owning team). Access failures collapse to+ // "not found" so company ids can't be probed across teams.+ let (permission, team_id) = match service_context+ .entity_access_service+ .get_crm_entity_permission_with_team(+ Some(&request_context.user_id),+ &company_id,+ EntityType::CrmCompany,+ )+ .await+ {+ Ok(pair) => pair,+ Err(+ AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::NotFound(_),+ ) => return Err(not_found()),+ Err(e) => {+ return Err(ToolCallError {+ description: "failed to verify access to the CRM company".to_string(),+ internal_error: e.into(),+ });+ }+ };++ if !permission.satisfies::<ViewAccessLevel>() {+ return Err(not_found());+ }++ let receipt = EntityAccessReceipt::try_new_authenticated_user(+ request_context.user_id.clone(),+ Entity {+ entity_id: company_id.clone(),+ entity_type: EntityType::CrmCompany,+ },+ permission,+ )+ .map_err(|e| ToolCallError {+ description: "failed to verify access to the CRM company".to_string(),+ internal_error: e.into(),+ })?;+ let receipt = CrmCompanyReceipt::new(receipt, team_id);++ let record = service_context+ .service+ .get_company_for_team(&receipt)+ .await+ .map_err(crm_error)?+ .ok_or_else(|| crm_error(CrmError::CompanyNotFoundForTeam))?;++ let properties = service_context+ .properties+ .get_entity_properties_with_definitions(&company_id, PropertyEntityType::Company)+ .await+ .map_err(|e| ToolCallError {+ description: "failed to load company properties".to_string(),+ internal_error: e.into(),+ })?;++ let stage_catalog =+ load_stage_option_catalog(&*service_context.properties, team_id).await?;+ let crm_props = extract_company_crm_props(&properties, &stage_catalog);++ let name = record.name.clone();+ let summary = format!(+ "CRM company {}{} with {} contact{}, {} propert{}.",+ name.as_deref().unwrap_or("(unnamed)"),+ crm_props+ .stage+ .as_ref()+ .map(|s| format!(" in stage {}", s.label))+ .unwrap_or_default(),+ record.contacts.len(),+ if record.contacts.len() == 1 { "" } else { "s" },+ properties.len(),+ if properties.len() == 1 { "y" } else { "ies" },+ );++ Ok(GetCompanyResponse {+ id: record.company.id,+ name,+ description: record.description,+ domains: record+ .company+ .domains+ .iter()+ .map(|d| d.domain.clone())+ .collect(),+ hidden: record.company.hidden,+ email_sync: record.company.email_sync,+ // The repo fills `company.created_at` / `updated_at` from+ // `crm_companies.first_interaction` / `last_interaction`, so+ // these really are the interaction endpoints, not+ // row-lifecycle timestamps.+ first_interaction: record.company.created_at,+ last_interaction: record.company.updated_at,+ stage: crm_props.stage,+ owner_user_id: crm_props.owner_user_id,+ revenue: crm_props.revenue,+ contacts: record.contacts.into_iter().map(Into::into).collect(),+ properties: properties.into_iter().map(to_property_item).collect(),+ summary,+ })+ }+}++fn not_found() -> ToolCallError {+ ToolCallError {+ description: "CRM company not found or not accessible to the caller's team".to_string(),+ internal_error: anyhow::anyhow!("crm company not found or not accessible"),+ }+}++fn to_property_item(prop: EntityPropertyWithDefinition) -> CompanyPropertyItem {+ let data_type = match prop.definition.data_type {+ DataType::Boolean => "boolean",+ DataType::Date => "date",+ DataType::Number => "number",+ DataType::String => "string",+ DataType::SelectNumber => "select_number",+ DataType::SelectString => "select_string",+ DataType::Tag => "tag",+ DataType::Entity => "entity",+ DataType::Link => "link",+ }+ .to_string();++ let current_value = prop+ .value+ .as_ref()+ .map(|v| serde_json::to_value(v).unwrap_or(serde_json::Value::Null));++ let options = prop+ .options+ .unwrap_or_default()+ .into_iter()+ .map(|option| CompanyPropertyOption {+ id: option.id,+ display_value: match option.value {+ PropertyOptionValue::String(s) => s,+ PropertyOptionValue::Number(n) => n.to_string(),+ },+ })+ .collect();++ CompanyPropertyItem {+ property_definition_id: prop.property.property_definition_id,+ display_name: prop.definition.display_name,+ data_type,+ is_multi_select: prop.definition.is_multi_select,+ is_system: prop.definition.is_system,+ current_value,+ options,+ }+}diff --git a/rust/cloud-storage/crm/src/inbound/toolset/list_companies.rs b/rust/cloud-storage/crm/src/inbound/toolset/list_companies.rsnew file mode 100644index 0000000000..21340d0ee6--- /dev/null+++ b/rust/cloud-storage/crm/src/inbound/toolset/list_companies.rs@@ -0,0 +1,337 @@+//! ListCompanies tool for browsing the caller team's CRM companies.++use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use chrono::{DateTime, Utc};+use entity_access::domain::{models::TeamRole, ports::EntityAccessService};+use models_properties::EntityType as PropertyEntityType;+use properties::{EntityPropertiesKey, PropertiesService};+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use system_properties::SystemPropertyKey;+use uuid::Uuid;++use crate::domain::{+ companies_repo::CrmCompanyListSort, model::CrmCompanyForSoup, service::CrmService,+};++use super::{+ CrmToolContext, ToolCompanyStage, caller_team_receipt, company_entity_refs, crm_error,+ extract_company_crm_props, load_stage_option_catalog,+};++/// Default number of companies returned when `limit` is omitted.+const DEFAULT_LIMIT: u16 = 50;+/// Maximum number of companies a single call can return.+const MAX_LIMIT: u16 = 200;+/// How many companies are pulled from the repository before in-memory+/// filtering. Matches the CRM request cap used by the app (a team's CRM+/// list is capped around 500 rows per page).+const FETCH_LIMIT: i64 = 500;++/// A CRM company row returned by [`ListCompanies`].+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CompanyListItem {+ /// The CRM company id. Use with GetCompany, GetEntityProperties /+ /// SetEntityProperty (entity_type=company).+ pub id: Uuid,+ /// Company display name, when resolved.+ pub name: Option<String>,+ /// The company's email domains, primary domain first.+ pub domains: Vec<String>,+ /// Whether the company is hidden from the team's CRM listings.+ pub hidden: bool,+ /// Most recent known email interaction with this company.+ pub last_interaction: DateTime<Utc>,+ /// The company's pipeline stage, if set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub stage: Option<ToolCompanyStage>,+ /// Macro user id of the company's owner, if set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub owner_user_id: Option<String>,+ /// The company's revenue (dollars), if set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub revenue: Option<f64>,+}++/// Response from the [`ListCompanies`] tool.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListCompaniesResponse {+ /// The matching CRM companies.+ pub companies: Vec<CompanyListItem>,+ /// Human-readable summary of the results.+ pub summary: String,+}++/// List the caller team's CRM companies.+#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]+#[schemars(+ title = "ListCompanies",+ description = "List the CRM companies tracked by the authenticated user's team, sorted by most recent interaction. Each row includes the company id, name, domains, last interaction time, and its pipeline Stage / Owner / Revenue properties when set. Use the filters to narrow results: `search` for name/domain text, `stage` for pipeline stage, `owner_user_id` for companies owned by a user. Use GetCompany for one company's full details (contacts + all properties), and SetEntityProperty with entity_type=company to move stages or update owner/revenue/custom properties."+)]+pub struct ListCompanies {+ /// Case-insensitive substring matched against company names and domains.+ #[schemars(+ description = "Case-insensitive substring matched against company names and domains (e.g. \"acme\" matches \"Acme Corp\" and \"acme.com\")."+ )]+ #[serde(default)]+ pub search: Option<String>,++ /// Filter to companies in this pipeline stage (label or option id).+ #[schemars(+ description = "Filter to companies in this pipeline stage. Accepts a stage label matched case-insensitively (e.g. \"lead\", \"Customer\" — teams may have custom stage names) or a stage option UUID."+ )]+ #[serde(default)]+ pub stage: Option<String>,++ /// Filter to companies owned by this Macro user id.+ #[schemars(+ description = "Filter to companies whose Owner property is this Macro user id (e.g. \"macro|[email protected]\"). Use ListTeamMembers to find user ids."+ )]+ #[serde(default)]+ pub owner_user_id: Option<String>,++ /// Also include hidden companies (team admin/owner only).+ #[schemars(+ description = "Also include companies hidden from the CRM. Defaults to false. Requires team admin or owner role."+ )]+ #[serde(default)]+ pub include_hidden: Option<bool>,++ /// Maximum number of companies to return (default 50, max 200).+ #[schemars(description = "Maximum number of companies to return. Defaults to 50; max 200.")]+ #[serde(default)]+ pub limit: Option<u16>,+}++#[async_trait]+impl<CSvc, ESvc, PSvc> AsyncTool<CrmToolContext<CSvc, ESvc, PSvc>> for ListCompanies+where+ CSvc: CrmService,+ ESvc: EntityAccessService,+ PSvc: PropertiesService,+{+ type Output = ListCompaniesResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ async fn call(+ &self,+ service_context: ServiceContext<CrmToolContext<CSvc, ESvc, PSvc>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!(params=?self, "List CRM companies");++ let (team_receipt, role) =+ caller_team_receipt(&*service_context.entity_access_service, &request_context).await?;+ let team_id = team_receipt.team_id();++ let include_hidden = self.include_hidden.unwrap_or(false);+ if include_hidden && !matches!(role, TeamRole::Admin | TeamRole::Owner) {+ return Err(ToolCallError {+ description: "include_hidden requires team admin or owner role".to_string(),+ internal_error: anyhow::anyhow!("caller is not a team admin/owner"),+ });+ }++ let limit = usize::from(self.limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT));+ let user_id: &str = request_context.user_id.0.as_ref();++ // Fetch visible companies (and hidden ones when requested), most+ // recently active first, then filter in memory.+ let mut companies = service_context+ .service+ .list_companies_for_soup(+ &team_receipt,+ user_id,+ &[],+ Some(false),+ CrmCompanyListSort::UpdatedAt,+ None,+ FETCH_LIMIT,+ )+ .await+ .map_err(crm_error)?;+ if include_hidden {+ let hidden = service_context+ .service+ .list_companies_for_soup(+ &team_receipt,+ user_id,+ &[],+ Some(true),+ CrmCompanyListSort::UpdatedAt,+ None,+ FETCH_LIMIT,+ )+ .await+ .map_err(crm_error)?;+ companies.extend(hidden);+ companies.sort_by(|a, b| {+ b.company+ .updated_at+ .cmp(&a.company.updated_at)+ .then_with(|| b.company.id.cmp(&a.company.id))+ });+ }++ // Text filter first so the property fetch only covers candidates.+ if let Some(search) = self+ .search+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ {+ let needle = search.to_lowercase();+ companies.retain(|c| matches_search(c, &needle));+ }++ let stage_catalog =+ load_stage_option_catalog(&*service_context.properties, team_id).await?;++ // Resolve the stage filter to option ids up front so an unknown+ // stage fails with an actionable error instead of an empty list.+ let stage_option_ids = match self+ .stage+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ {+ Some(stage) => {+ let ids = stage_catalog.matching_option_ids(stage);+ if ids.is_empty() {+ return Err(ToolCallError {+ description: format!(+ "unknown stage '{stage}'. Known stages for this team: {}",+ stage_catalog.known_labels().join(", ")+ ),+ internal_error: anyhow::anyhow!("unknown stage filter"),+ });+ }+ Some(ids)+ }+ None => None,+ };++ // Attach Stage / Owner / Revenue for the remaining candidates.+ // Teams with customized pipelines store stage values under a+ // team-scoped "Stage" definition rather than the system one, so+ // include those definition ids in the fetch filter too.+ let entity_refs = company_entity_refs(companies.iter().map(|c| c.company.id));+ let mut property_ids = vec![+ SystemPropertyKey::STAGE_UUID,+ SystemPropertyKey::COMPANY_OWNER_UUID,+ SystemPropertyKey::REVENUE_UUID,+ ];+ property_ids.extend_from_slice(stage_catalog.team_stage_definition_ids());+ let properties_map = service_context+ .properties+ .get_bulk_entity_properties(entity_refs, property_ids)+ .await+ .map_err(|e| ToolCallError {+ description: "failed to load company properties".to_string(),+ internal_error: e.into(),+ })?;++ let mut items: Vec<CompanyListItem> = Vec::new();+ let mut total_matching = 0usize;+ for company in companies {+ let props_key = EntityPropertiesKey {+ entity_id: company.company.id.to_string(),+ entity_type: PropertyEntityType::Company,+ };+ let props = properties_map+ .get(&props_key)+ .map(Vec::as_slice)+ .unwrap_or(&[]);+ let crm_props = extract_company_crm_props(props, &stage_catalog);++ if let Some(stage_ids) = &stage_option_ids {+ let matches_stage = crm_props+ .stage+ .as_ref()+ .is_some_and(|stage| stage_ids.contains(&stage.option_id));+ if !matches_stage {+ continue;+ }+ }+ if let Some(owner_filter) = self+ .owner_user_id+ .as_deref()+ .map(str::trim)+ .filter(|s| !s.is_empty())+ {+ let matches_owner = crm_props+ .owner_user_id+ .as_deref()+ .is_some_and(|owner| owner.eq_ignore_ascii_case(owner_filter));+ if !matches_owner {+ continue;+ }+ }++ total_matching += 1;+ if items.len() < limit {+ items.push(to_list_item(company, crm_props));+ }+ }++ let summary = if items.is_empty() {+ "No CRM companies match the given filters.".to_string()+ } else if total_matching > items.len() {+ format!(+ "Showing {} of {} matching CRM companies (sorted by most recent interaction). Narrow with search/stage/owner filters or raise limit.",+ items.len(),+ total_matching+ )+ } else {+ format!(+ "Found {} CRM compan{} (sorted by most recent interaction).",+ items.len(),+ if items.len() == 1 { "y" } else { "ies" }+ )+ };++ Ok(ListCompaniesResponse {+ companies: items,+ summary,+ })+ }+}++fn matches_search(company: &CrmCompanyForSoup, needle: &str) -> bool {+ if company+ .name+ .as_deref()+ .is_some_and(|name| name.to_lowercase().contains(needle))+ {+ return true;+ }+ company+ .company+ .domains+ .iter()+ .any(|d| d.domain.to_lowercase().contains(needle))+}++fn to_list_item(company: CrmCompanyForSoup, props: super::CompanyCrmProps) -> CompanyListItem {+ CompanyListItem {+ id: company.company.id,+ name: company.name,+ domains: company+ .company+ .domains+ .iter()+ .map(|d| d.domain.clone())+ .collect(),+ hidden: company.company.hidden,+ // The repo fills `company.updated_at` from+ // `crm_companies.last_interaction`, so this really is the latest+ // email interaction, not a row-lifecycle timestamp.+ last_interaction: company.company.updated_at,+ stage: props.stage,+ owner_user_id: props.owner_user_id,+ revenue: props.revenue,+ }+}diff --git a/rust/cloud-storage/crm/src/inbound/toolset/mod.rs b/rust/cloud-storage/crm/src/inbound/toolset/mod.rsnew file mode 100644index 0000000000..eec1d3b159--- /dev/null+++ b/rust/cloud-storage/crm/src/inbound/toolset/mod.rs@@ -0,0 +1,388 @@+//! Toolset inbound adapter for the CRM domain.+//!+//! Exposes team-scoped CRM company tools (`ListCompanies`, `GetCompany`)+//! to AI agents. Property writes (stage moves, revenue, owner, custom+//! properties) go through the properties toolset's `SetEntityProperty`+//! with `entity_type = company`.++mod get_company;+mod list_companies;++use std::collections::HashMap;+use std::sync::Arc;++use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};+use entity_access::domain::{+ models::{+ AccessError, Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole,+ TeamRole,+ },+ ports::EntityAccessService,+};+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::property_option::PropertyOptionValue;+use models_properties::service::property_value::PropertyValue;+use models_properties::{DataType, EntityType as PropertyEntityType};+use properties::PropertiesService;+use schemars::JsonSchema;+use serde::Serialize;+use system_properties::{StageOption, SystemPropertyKey};+use uuid::Uuid;++use crate::domain::{auth::CrmTeamReceipt, model::CrmError, service::CrmService};++pub use get_company::{GetCompany, GetCompanyResponse};+pub use list_companies::{ListCompanies, ListCompaniesResponse};++/// Service context for CRM AI tools.+pub struct CrmToolContext<CSvc, ESvc, PSvc>+where+ CSvc: CrmService,+ ESvc: EntityAccessService,+ PSvc: PropertiesService,+{+ /// The CRM service used to read company records.+ pub service: Arc<CSvc>,+ /// The entity access service used to resolve the caller's team+ /// membership and CRM entity permissions.+ pub entity_access_service: Arc<ESvc>,+ /// The properties domain service used to read company property values+ /// (Stage / Owner / Revenue plus custom properties) and the team's+ /// property definitions.+ pub properties: Arc<PSvc>,+}++impl<CSvc, ESvc, PSvc> Clone for CrmToolContext<CSvc, ESvc, PSvc>+where+ CSvc: CrmService,+ ESvc: EntityAccessService,+ PSvc: PropertiesService,+{+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ entity_access_service: self.entity_access_service.clone(),+ properties: self.properties.clone(),+ }+ }+}++impl<CSvc, ESvc, PSvc> CrmToolContext<CSvc, ESvc, PSvc>+where+ CSvc: CrmService,+ ESvc: EntityAccessService,+ PSvc: PropertiesService,+{+ /// Create a new CRM tool context.+ pub fn new(service: CSvc, entity_access_service: ESvc, properties: Arc<PSvc>) -> Self {+ Self {+ service: Arc::new(service),+ entity_access_service: Arc::new(entity_access_service),+ properties,+ }+ }+}++/// Create the CRM toolset.+pub fn crm_toolset<CSvc, ESvc, PSvc>() -> AsyncToolCollection<CrmToolContext<CSvc, ESvc, PSvc>>+where+ CSvc: CrmService,+ ESvc: EntityAccessService,+ PSvc: PropertiesService,+{+ AsyncToolCollection::new()+ .add_tool::<ListCompanies, CrmToolContext<CSvc, ESvc, PSvc>>()+ .add_tool::<GetCompany, CrmToolContext<CSvc, ESvc, PSvc>>()+}++/// A company's pipeline stage: the select option id currently set plus its+/// human-readable label.+#[derive(Debug, Clone, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct ToolCompanyStage {+ /// The stage property option id (usable with SetEntityProperty).+ pub option_id: Uuid,+ /// The stage's display label (e.g. "Lead", "Customer").+ pub label: String,+}++/// The builtin CRM company property values extracted from a company's+/// entity properties.+#[derive(Debug, Default)]+pub(crate) struct CompanyCrmProps {+ pub(crate) stage: Option<ToolCompanyStage>,+ pub(crate) owner_user_id: Option<String>,+ pub(crate) revenue: Option<f64>,+}++/// The catalog of stage options available to a team: the system Stage+/// definition's options plus any team-scoped definition named "Stage"+/// (teams can customize their pipeline stages).+#[derive(Debug, Default)]+pub(crate) struct StageOptionCatalog {+ /// option id -> label+ labels: HashMap<Uuid, String>,+ /// Ids of team-scoped select definitions named "Stage". Teams with a+ /// customized pipeline store their stage values under one of these+ /// definitions instead of the system Stage definition, so property+ /// fetches filtered by definition id must include them.+ team_stage_definition_ids: Vec<Uuid>,+}++impl StageOptionCatalog {+ /// Resolve a stage option id to its label. Falls back to the builtin+ /// [`StageOption`] constants when the id isn't in the catalog.+ pub(crate) fn label_for(&self, option_id: Uuid) -> Option<String> {+ self.labels+ .get(&option_id)+ .cloned()+ .or_else(|| StageOption::from_uuid(option_id).map(|s| s.display_value().to_string()))+ }++ /// Resolve a user-supplied `stage` filter (an option id or a label,+ /// matched case-insensitively) to the set of matching option ids.+ pub(crate) fn matching_option_ids(&self, stage: &str) -> Vec<Uuid> {+ let trimmed = stage.trim();+ if let Ok(id) = Uuid::parse_str(trimmed) {+ return vec![id];+ }+ self.labels+ .iter()+ .filter(|(_, label)| label.eq_ignore_ascii_case(trimmed))+ .map(|(id, _)| *id)+ .collect()+ }++ /// Ids of the team-scoped "Stage" definitions (empty when the team+ /// only uses the system Stage definition).+ pub(crate) fn team_stage_definition_ids(&self) -> &[Uuid] {+ &self.team_stage_definition_ids+ }++ /// The distinct stage labels known to this team, for actionable error+ /// messages.+ pub(crate) fn known_labels(&self) -> Vec<String> {+ let mut labels: Vec<String> = self.labels.values().cloned().collect();+ labels.sort();+ labels.dedup();+ labels+ }+}++/// Load the stage option catalog for `team_id`: options of the system+/// Stage definition (id `00000001-0000-0000-0000-000000000010`) plus any+/// team-scoped select definition named "Stage".+pub(crate) async fn load_stage_option_catalog<PSvc>(+ properties: &PSvc,+ team_id: Uuid,+) -> Result<StageOptionCatalog, ToolCallError>+where+ PSvc: PropertiesService,+{+ let defs = properties+ .list_property_definitions_with_options(Some(team_id), None, true, None)+ .await+ .map_err(|e| ToolCallError {+ description: "failed to load the team's stage options".to_string(),+ internal_error: e.into(),+ })?;++ let mut labels = HashMap::new();+ let mut team_stage_definition_ids = Vec::new();+ for def in defs {+ let is_stage_definition = def.definition.id == SystemPropertyKey::STAGE_UUID+ || (def.definition.display_name.eq_ignore_ascii_case("stage")+ && matches!(+ def.definition.data_type,+ DataType::SelectString | DataType::SelectNumber+ ));+ if !is_stage_definition {+ continue;+ }+ if def.definition.id != SystemPropertyKey::STAGE_UUID {+ team_stage_definition_ids.push(def.definition.id);+ }+ for option in def.property_options {+ let label = match option.value {+ PropertyOptionValue::String(s) => s,+ PropertyOptionValue::Number(n) => n.to_string(),+ };+ labels.insert(option.id, label);+ }+ }++ // Make sure the builtin defaults are always resolvable, even if the+ // seed rows are missing from this environment.+ for stage in [+ StageOption::Lead,+ StageOption::Qualified,+ StageOption::Demo,+ StageOption::Trial,+ StageOption::Negotiation,+ StageOption::Customer,+ StageOption::Churned,+ ] {+ labels+ .entry(stage.uuid())+ .or_insert_with(|| stage.display_value().to_string());+ }++ Ok(StageOptionCatalog {+ labels,+ team_stage_definition_ids,+ })+}++/// Extract the builtin CRM props (Stage / Owner / Revenue) from a+/// company's entity properties. The stage may live on the system Stage+/// definition or on a team-scoped select definition named "Stage";+/// teams with customized pipelines use the latter, so its value wins+/// over one set under the system definition.+pub(crate) fn extract_company_crm_props(+ props: &[EntityPropertyWithDefinition],+ stages: &StageOptionCatalog,+) -> CompanyCrmProps {+ let mut out = CompanyCrmProps::default();+ let mut system_stage: Option<ToolCompanyStage> = None;+ let mut team_stage: Option<ToolCompanyStage> = None;+ for prop in props {+ let definition_id = prop.property.property_definition_id;+ if definition_id == SystemPropertyKey::COMPANY_OWNER_UUID {+ if let Some(PropertyValue::EntityRef(refs)) = &prop.value {+ out.owner_user_id = refs.first().map(|r| r.entity_id.clone());+ }+ continue;+ }+ if definition_id == SystemPropertyKey::REVENUE_UUID {+ if let Some(PropertyValue::Num(n)) = prop.value {+ out.revenue = Some(n);+ }+ continue;+ }+ let is_system_stage = definition_id == SystemPropertyKey::STAGE_UUID;+ let is_team_stage = !is_system_stage+ && (stages.team_stage_definition_ids.contains(&definition_id)+ || prop.definition.display_name.eq_ignore_ascii_case("stage"));+ let slot = if is_system_stage {+ &mut system_stage+ } else if is_team_stage {+ &mut team_stage+ } else {+ continue;+ };+ if slot.is_none()+ && let Some(PropertyValue::SelectOption(option_ids)) = &prop.value+ && let Some(option_id) = option_ids.first().copied()+ {+ // Prefer the options attached to the property itself, then+ // the team catalog / builtin defaults.+ let label = prop+ .options+ .as_ref()+ .and_then(|options| {+ options+ .iter()+ .find(|o| o.id == option_id)+ .map(|o| match &o.value {+ PropertyOptionValue::String(s) => s.clone(),+ PropertyOptionValue::Number(n) => n.to_string(),+ })+ })+ .or_else(|| stages.label_for(option_id))+ .unwrap_or_else(|| option_id.to_string());+ *slot = Some(ToolCompanyStage { option_id, label });+ }+ }+ out.stage = team_stage.or(system_stage);+ out+}++/// Entity references for a batch of company ids, in `entity_properties`+/// terms (`entity_type = company`).+pub(crate) fn company_entity_refs(+ company_ids: impl IntoIterator<Item = Uuid>,+) -> Vec<models_properties::shared::EntityReference> {+ company_ids+ .into_iter()+ .map(|id| models_properties::shared::EntityReference {+ entity_type: PropertyEntityType::Company,+ entity_id: id.to_string(),+ specific_message_id: None,+ })+ .collect()+}++/// Resolve the caller's team and mint a member-level team receipt for+/// CRM listing calls. Errors with an actionable message when the caller+/// has no team.+pub(crate) async fn caller_team_receipt<ESvc>(+ entity_access_service: &ESvc,+ request_context: &RequestContext,+) -> Result<(CrmTeamReceipt<MemberTeamRole>, TeamRole), ToolCallError>+where+ ESvc: EntityAccessService,+{+ let team_info = entity_access_service+ .get_user_team(&request_context.user_id)+ .await+ .map_err(team_access_error)?;++ let Some(team_info) = team_info else {+ return Err(ToolCallError {+ description: "user is not in a team, so there is no team CRM to query".to_string(),+ internal_error: anyhow::anyhow!("user is not in a team"),+ });+ };++ let receipt = EntityAccessReceipt::try_new_authenticated_user(+ request_context.user_id.clone(),+ Entity {+ entity_id: team_info.team_id.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole {+ role: team_info.role,+ },+ )+ .map_err(team_access_error)?;++ let receipt = CrmTeamReceipt::from_team_receipt(receipt).map_err(crm_error)?;++ Ok((receipt, team_info.role))+}++/// Map an [`AccessError`] into an actionable tool error.+pub(crate) fn team_access_error(err: AccessError) -> ToolCallError {+ let description = match err {+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {+ "user is not a member of a team"+ }+ AccessError::NotFound(_) => "team not found",+ AccessError::BadRequest(_) => "invalid team membership",+ AccessError::DatabaseError(_) | AccessError::Internal => "failed to verify team membership",+ };++ ToolCallError {+ description: description.to_string(),+ internal_error: err.into(),+ }+}++/// Map a [`CrmError`] into an actionable tool error.+pub(crate) fn crm_error(err: CrmError) -> ToolCallError {+ let description = match &err {+ CrmError::CompanyNotFoundForTeam => {+ "CRM company not found for the caller's team".to_string()+ }+ CrmError::ContactNotFoundForTeam => {+ "CRM contact not found for the caller's team".to_string()+ }+ CrmError::InvalidRequest(msg) => msg.clone(),+ _ => "CRM request failed".to_string(),+ };++ ToolCallError {+ description,+ internal_error: err.into(),+ }+}diff --git a/rust/cloud-storage/crm/src/lib.rs b/rust/cloud-storage/crm/src/lib.rsindex ee7d79f321..acbba244d1 100644--- a/rust/cloud-storage/crm/src/lib.rs+++ b/rust/cloud-storage/crm/src/lib.rs@@ -14,7 +14,7 @@pub mod domain;/// The inbound module contains the inbound adapters for CRM-#[cfg(feature = "inbound")]+#[cfg(any(feature = "inbound", feature = "ai_tools"))]pub mod inbound;/// The outbound module contains the outbound adapters for CRMdiff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex a1b196e20e..5cc6eb08fa 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -343,6 +343,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Archat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),team_tool_context: ai_tools::build_team_tool_context(pool.clone()),+ crm_tool_context: ai_tools::build_crm_tool_context(pool.clone()),schedule_tool_context: ai_tools::no_op_schedule_context(),anthropic_tool_context: ai_tools::build_anthropic_tool_context_test(),recorder: ai_usage::pg_recorder(pool.clone()),diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 918fdfc091..129c58c177 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -410,6 +410,7 @@ async fn main() -> anyhow::Result<()> {chat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),team_tool_context: ai_tools::build_team_tool_context(db.clone()),+ crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),schedule_tool_context: ai_tools::NoOpScheduleContext,anthropic_tool_context: ai_tools::build_anthropic_tool_context(),recorder: ai_usage::pg_recorder(db.clone()),diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex 4107184d03..49224695b9 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -322,6 +322,7 @@ async fn build_tool_context(chat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(db.clone()),team_tool_context: ai_tools::build_team_tool_context(db.clone()),+ crm_tool_context: ai_tools::build_crm_tool_context(db.clone()),schedule_tool_context: NoOpScheduleContext,anthropic_tool_context: ai_tools::build_anthropic_tool_context(),recorder: ai_usage::pg_recorder(db.clone()),diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex 42c037e01a..57025052af 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -234,6 +234,7 @@ pub async fn build_tool_service_context(chat_tool_context,channel_tool_context: ai_tools::build_channel_tool_context(pool.clone()),team_tool_context: ai_tools::build_team_tool_context(pool.clone()),+ crm_tool_context: ai_tools::build_crm_tool_context(pool.clone()),schedule_tool_context: ai_tools::NoOpScheduleContext,anthropic_tool_context: ai_tools::build_anthropic_tool_context(),recorder: ai_usage::pg_recorder(pool.clone()),diff --git a/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs b/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rsindex f95b85cf09..e25a4e3a29 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/get_entity_properties.rs@@ -23,6 +23,7 @@ pub enum ToolEntityType {Thread,Channel,User,+ Company,}impl From<ToolEntityType> for EntityType {@@ -35,6 +36,7 @@ impl From<ToolEntityType> for EntityType {ToolEntityType::Thread => EntityType::Thread,ToolEntityType::Channel => EntityType::Channel,ToolEntityType::User => EntityType::User,+ ToolEntityType::Company => EntityType::Company,}}}@@ -42,7 +44,7 @@ impl From<ToolEntityType> for EntityType {#[derive(Debug, Deserialize, JsonSchema)]#[schemars(title = "GetEntityProperties",- description = "Get all properties attached to an entity (document, task, project, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first."+ description = "Get all properties attached to an entity (document, task, project, CRM company, etc.). Returns property definitions with their current values and available options for select-type properties. Use this to discover custom properties on an entity. For tasks, system properties (Assignees, Status, Priority, Due Date, etc.) are always present — you can update them directly with SetEntityProperty using well-known IDs without calling this first. For CRM companies (entity_type=company, entity_id=the company UUID), this returns the builtin Stage / Owner / Revenue properties (with the team's stage options) plus any custom company properties.")]pub struct GetEntityProperties {#[schemars(description = "The ID of the entity to get properties for.")]diff --git a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rsindex 7b2dafdf0b..4c28f9100f 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs@@ -47,6 +47,12 @@ Tasks always have these system properties (use these property_definition_id valu- Subtasks (00000001-0000-0000-0000-000000000006): entity, multi. Use entity_refs with entity_type='task'.- Story Points (00000001-0000-0000-0000-000000000009): number, single. Use number_value.+CRM companies (entity_type='company', entity_id=the company UUID) always have these system properties:+- Stage (00000001-0000-0000-0000-000000000010): select_string, single. Use option_id. Default options: Lead (00000001-0000-0000-0010-000000000001), Qualified (...0002), Demo (...0003), Trial (...0004), Negotiation (...0005), Customer (...0006), Churned (...0007). Teams can customize their stages, so prefer calling GetCompany or GetEntityProperties first to get the valid stage option ids.+- Owner (00000001-0000-0000-0000-000000000011): entity, single. Use entity_ref with entity_type='user' and entity_id='macro|[email protected]'.+- Revenue (00000001-0000-0000-0000-000000000012): number, single. Use number_value (dollars).+Editing company properties requires the caller to be a team admin or owner.+For non-system or custom properties, call GetEntityProperties first to discover property_definition_id values and options.")]#[serde(rename_all = "snake_case")]