Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(crm): add pipelines using shared database storage (#7454)

teo11203c917de9
diff --git a/.agents/skills/database-core/SKILL.md b/.agents/skills/database-core/SKILL.md
index 6fee319198..726a9cbb77 100644
--- a/.agents/skills/database-core/SKILL.md
+++ b/.agents/skills/database-core/SKILL.md
@@ -104,8 +104,10 @@ capabilities. `DatabaseRecords` wires the standard schema controls once. Read th
[provider](../../../apps/web/src/features/database/context/database.tsx) when adding
a host. `DatabaseGrid` composes the Macro app with its SQL cache and inference
source; ordinary API hosts use the provider's paginated source. Keep host-specific
-optimizations behind the same data-source contract. CRM can adopt this boundary
-without importing the Macro app adapter.
+optimizations behind the same data-source contract. CRM uses `createPipelineApi`
+in `features/crm/queries/pipeline-data.ts` with the same provider and controller.
+Its adapter converts transport values and calls pipeline-authorized endpoints;
+it does not own pagination or mutation planning.
Verify the same editor against a small fake API without app providers, then test
the Macro and CRM adapters against the same behavioral contract. Cover a failed
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 8e5c7a0a3d..61e4414a48 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -72,6 +72,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -112,6 +114,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -123,6 +126,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -176,6 +180,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -224,6 +230,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_toolset",
"crates/mention_utils",
@@ -237,6 +244,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -317,6 +325,8 @@
"crates/cursor_api_key",
"crates/cursor_cloud_agents",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
@@ -366,6 +376,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_toolset",
"crates/mention_utils",
@@ -379,6 +390,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -824,6 +836,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -861,6 +875,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -872,6 +887,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -923,6 +939,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -960,6 +978,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -971,6 +990,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -1022,6 +1042,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/email",
@@ -1060,6 +1082,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -1071,6 +1094,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -1123,6 +1147,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/email",
@@ -1163,6 +1189,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -1174,6 +1201,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -1224,6 +1252,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -1259,6 +1289,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -1270,6 +1301,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -1478,6 +1510,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -1514,6 +1548,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -1525,6 +1560,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -1760,6 +1796,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -1795,6 +1833,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -1806,6 +1845,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -1871,6 +1911,8 @@
"crates/cursor_api_key",
"crates/cursor_cloud_agents",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/decode_jwt",
"crates/document_storage_service_client",
"crates/document_sub_type",
@@ -1934,6 +1976,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_select",
"crates/mcp_toolset",
@@ -1950,6 +1993,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -2153,6 +2197,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -2209,6 +2255,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_grouping",
@@ -2306,6 +2353,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -2342,6 +2391,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -2353,6 +2403,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -2401,6 +2452,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -2442,6 +2495,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -2453,6 +2507,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -2940,6 +2995,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -2977,6 +3034,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -2988,6 +3046,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -3040,6 +3099,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3077,6 +3138,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -3088,6 +3150,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -3152,6 +3215,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
@@ -3202,6 +3267,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -3213,6 +3279,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -3429,6 +3496,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -3496,6 +3565,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -3507,6 +3577,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -3739,6 +3810,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3782,6 +3855,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -3793,6 +3867,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -3844,6 +3919,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
@@ -3871,6 +3948,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -3881,6 +3959,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -3931,6 +4010,8 @@
"crates/crm",
"crates/cursor_cloud_agents",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -3968,6 +4049,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -3979,6 +4061,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -4038,15 +4121,18 @@
"crates/connection_gateway_models",
"crates/cowlike",
"crates/database_env_vars",
+ "crates/database_sql",
"crates/databases",
"crates/document_sub_type",
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/filter_ast",
"crates/genai_telemetry",
"crates/harness_id",
"crates/harness_token",
"crates/invite_email",
+ "crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
"crates/macro_auth",
@@ -4060,6 +4146,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -4273,6 +4360,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -4321,6 +4410,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -4332,6 +4422,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -4866,6 +4957,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -4913,6 +5006,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -4924,6 +5018,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -4986,6 +5081,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -5032,6 +5129,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5043,6 +5141,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -5104,6 +5203,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -5144,6 +5245,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5155,6 +5257,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -5217,6 +5320,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -5250,6 +5355,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5260,6 +5366,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -5359,6 +5466,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -5393,6 +5502,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5404,6 +5514,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -5449,6 +5560,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -5483,6 +5596,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5494,6 +5608,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -5539,6 +5654,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/email",
@@ -5585,6 +5702,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5596,6 +5714,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -5647,6 +5766,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_service_client",
@@ -5681,6 +5802,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5691,6 +5813,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -5733,6 +5856,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -5767,6 +5892,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -5778,6 +5904,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -6131,6 +6258,7 @@
"crates/connection_gateway_models",
"crates/cowlike",
"crates/database_env_vars",
+ "crates/database_sql",
"crates/databases",
"crates/document_sub_type",
"crates/entity_access",
@@ -6139,6 +6267,7 @@
"crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
+ "crates/filter_ast",
"crates/folds/agent_fold",
"crates/forms",
"crates/genai_telemetry",
@@ -6146,6 +6275,7 @@
"crates/harness_token",
"crates/initiative",
"crates/invite_email",
+ "crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
"crates/lexical_client",
@@ -6162,6 +6292,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -6253,6 +6384,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -6301,6 +6434,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -6312,6 +6446,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -6646,6 +6781,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -6681,6 +6818,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -6691,6 +6829,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -6740,6 +6879,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -6795,6 +6936,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -6806,6 +6948,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -6879,6 +7022,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -6935,6 +7080,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -6946,6 +7092,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -7019,6 +7166,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -7075,6 +7224,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -7086,6 +7236,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -7295,6 +7446,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -7346,6 +7499,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -7357,6 +7511,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -7423,6 +7578,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -7477,6 +7634,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -7488,6 +7646,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -7778,6 +7937,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -7814,6 +7975,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_select",
"crates/mcp_toolset",
@@ -7828,6 +7990,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -9176,6 +9339,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -9209,6 +9374,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -9219,6 +9385,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -9274,6 +9441,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -9307,6 +9476,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -9317,6 +9487,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -9639,6 +9810,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -9675,6 +9848,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_select",
"crates/mcp_toolset",
@@ -9689,6 +9863,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -9748,6 +9923,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -9782,6 +9959,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -9793,6 +9971,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -9838,6 +10017,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -9872,6 +10053,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -9883,6 +10065,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -9962,6 +10145,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -10013,6 +10198,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_toolset",
"crates/mention_utils",
@@ -10026,6 +10212,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -10089,6 +10276,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -10136,6 +10325,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -10147,6 +10337,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -10363,6 +10554,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -10396,6 +10589,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -10406,6 +10600,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_entity_access_management",
"crates/models_pagination",
"crates/models_permissions",
@@ -10503,6 +10698,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -10553,6 +10750,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -10564,6 +10762,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -10629,6 +10828,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -10683,6 +10884,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -10694,6 +10896,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -10764,6 +10967,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_db_client",
@@ -10803,6 +11008,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -10814,6 +11020,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -10873,6 +11080,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -10906,6 +11115,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -10916,6 +11126,7 @@
"crates/model_owner",
"crates/model_user",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_entity_access_management",
"crates/models_opensearch",
"crates/models_pagination",
@@ -11148,6 +11359,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/email",
@@ -11195,6 +11408,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -11206,6 +11420,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -11275,6 +11490,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -11314,6 +11531,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_select",
"crates/mcp_toolset",
@@ -11328,6 +11546,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -11379,6 +11598,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -11416,6 +11637,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mcp_client",
"crates/mcp_select",
"crates/mcp_toolset",
@@ -11430,6 +11652,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -11487,6 +11710,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -11528,6 +11753,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -11539,6 +11765,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_grouping",
@@ -11595,6 +11822,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -11651,6 +11880,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_grouping",
@@ -11709,6 +11939,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -11751,6 +11983,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -11762,6 +11995,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_grouping",
@@ -11819,6 +12053,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/documents",
"crates/dynamodb_client",
@@ -11866,6 +12102,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -11877,6 +12114,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
@@ -11936,6 +12174,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -11969,6 +12209,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -11980,6 +12221,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -12237,6 +12479,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/email",
"crates/email_utils",
@@ -12272,6 +12516,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -12283,6 +12528,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -12348,6 +12594,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/dynamodb_client",
@@ -12384,6 +12632,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -12395,6 +12644,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -12440,6 +12690,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_sub_type",
"crates/dynamodb_client",
"crates/email",
@@ -12475,6 +12727,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -12486,6 +12739,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_email",
"crates/models_entity_access_management",
"crates/models_pagination",
@@ -12628,6 +12882,8 @@
"crates/cowlike",
"crates/crm",
"crates/database_env_vars",
+ "crates/database_sql",
+ "crates/databases",
"crates/document_storage_service_client",
"crates/document_sub_type",
"crates/documents",
@@ -12675,6 +12931,7 @@
"crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/maybe_send",
"crates/mention_utils",
"crates/messages",
"crates/model",
@@ -12686,6 +12943,7 @@
"crates/model_user",
"crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_databases",
"crates/models_dcs",
"crates/models_email",
"crates/models_entity_access_management",
diff --git a/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json b/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json
deleted file mode 100644
index dd105edbe3..0000000000
--- a/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE entity SET deleted_at = $2 WHERE id = $1\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Timestamptz"
- ]
- },
- "nullable": []
- },
- "hash": "0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34"
-}
diff --git a/.sqlx/query-0b1d927c5e5efd2e044109d4d0b3feab9015b4928f79b1b8986e6509d3398b04.json b/.sqlx/query-0b1d927c5e5efd2e044109d4d0b3feab9015b4928f79b1b8986e6509d3398b04.json
deleted file mode 100644
index 210effa1d4..0000000000
--- a/.sqlx/query-0b1d927c5e5efd2e044109d4d0b3feab9015b4928f79b1b8986e6509d3398b04.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n DELETE FROM entity WHERE id = $1\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "0b1d927c5e5efd2e044109d4d0b3feab9015b4928f79b1b8986e6509d3398b04"
-}
diff --git a/.sqlx/query-15feb261ed4a7a3a72639eb0ed1edf6d597d02112697b9e361af66502d867836.json b/.sqlx/query-15feb261ed4a7a3a72639eb0ed1edf6d597d02112697b9e361af66502d867836.json
deleted file mode 100644
index a11f41b87d..0000000000
--- a/.sqlx/query-15feb261ed4a7a3a72639eb0ed1edf6d597d02112697b9e361af66502d867836.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, 'agent_session', $2, 'user', 'owner')\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "15feb261ed4a7a3a72639eb0ed1edf6d597d02112697b9e361af66502d867836"
-}
diff --git a/.sqlx/query-1ac95ce3231ecad2ab682a8c026c7c46856c031226d176cb9078869e66b394fa.json b/.sqlx/query-1ac95ce3231ecad2ab682a8c026c7c46856c031226d176cb9078869e66b394fa.json
deleted file mode 100644
index 0ae4aa70d1..0000000000
--- a/.sqlx/query-1ac95ce3231ecad2ab682a8c026c7c46856c031226d176cb9078869e66b394fa.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT access_level AS \"access_level: AccessLevel\" FROM entity_access\n WHERE entity_id = $1 AND entity_type = 'document' AND source_id = $2\n AND source_type = 'channel' AND granted_from_project_id IS NULL",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "1ac95ce3231ecad2ab682a8c026c7c46856c031226d176cb9078869e66b394fa"
-}
diff --git a/.sqlx/query-200c23797d6058b842c1b2e3756c8ec605652b8a249332583fcf1494ea7bf2b3.json b/.sqlx/query-200c23797d6058b842c1b2e3756c8ec605652b8a249332583fcf1494ea7bf2b3.json
deleted file mode 100644
index a7489866a4..0000000000
--- a/.sqlx/query-200c23797d6058b842c1b2e3756c8ec605652b8a249332583fcf1494ea7bf2b3.json
+++ /dev/null
@@ -1,35 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT csp.access_level AS \"access_level: AccessLevel\"\n FROM \"ChannelSharePermission\" csp\n JOIN \"DocumentPermission\" dp ON dp.\"sharePermissionId\" = csp.share_permission_id\n WHERE dp.\"documentId\" = $1 AND csp.channel_id = $2",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level: AccessLevel",
- "type_info": {
- "Custom": {
- "name": "\"AccessLevel\"",
- "kind": {
- "Enum": [
- "view",
- "comment",
- "edit",
- "owner"
- ]
- }
- }
- }
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "200c23797d6058b842c1b2e3756c8ec605652b8a249332583fcf1494ea7bf2b3"
-}
diff --git a/.sqlx/query-252d6b852991aa5edc6949a0ff54488024dd607b5b4ce8c9a872a4e8ed626498.json b/.sqlx/query-252d6b852991aa5edc6949a0ff54488024dd607b5b4ce8c9a872a4e8ed626498.json
new file mode 100644
index 0000000000..0d48933ac6
--- /dev/null
+++ b/.sqlx/query-252d6b852991aa5edc6949a0ff54488024dd607b5b4ce8c9a872a4e8ed626498.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO database_column_protections (column_id, capability) VALUES ($1, $2) ON CONFLICT DO NOTHING",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "252d6b852991aa5edc6949a0ff54488024dd607b5b4ce8c9a872a4e8ed626498"
+}
diff --git a/.sqlx/query-276db648e050d5dd82ef6720085ad799b760f8a67f0b4ba8c845762b30ca379f.json b/.sqlx/query-276db648e050d5dd82ef6720085ad799b760f8a67f0b4ba8c845762b30ca379f.json
new file mode 100644
index 0000000000..45f1c7dbae
--- /dev/null
+++ b/.sqlx/query-276db648e050d5dd82ef6720085ad799b760f8a67f0b4ba8c845762b30ca379f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id FROM crm_pipeline_entities WHERE id = $1 AND trashed_at IS NULL FOR SHARE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "276db648e050d5dd82ef6720085ad799b760f8a67f0b4ba8c845762b30ca379f"
+}
diff --git a/.sqlx/query-279a2193c14cb465d9617eac135ac98b10eea9a8c5194ce7d83761d1b6d65715.json b/.sqlx/query-279a2193c14cb465d9617eac135ac98b10eea9a8c5194ce7d83761d1b6d65715.json
deleted file mode 100644
index ce6913009c..0000000000
--- a/.sqlx/query-279a2193c14cb465d9617eac135ac98b10eea9a8c5194ce7d83761d1b6d65715.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT enabled, completed_at FROM reminder WHERE id = $1",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "enabled",
- "type_info": "Bool"
- },
- {
- "ordinal": 1,
- "name": "completed_at",
- "type_info": "Timestamptz"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- false,
- true
- ]
- },
- "hash": "279a2193c14cb465d9617eac135ac98b10eea9a8c5194ce7d83761d1b6d65715"
-}
diff --git a/.sqlx/query-28dd992e64ffb3f4c7a089097e1dd57eb14603a848cdd8baee04f66f06256a8f.json b/.sqlx/query-28dd992e64ffb3f4c7a089097e1dd57eb14603a848cdd8baee04f66f06256a8f.json
deleted file mode 100644
index 0f938da04a..0000000000
--- a/.sqlx/query-28dd992e64ffb3f4c7a089097e1dd57eb14603a848cdd8baee04f66f06256a8f.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE \"Document\" SET \"deletedAt\" = NOW() WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "28dd992e64ffb3f4c7a089097e1dd57eb14603a848cdd8baee04f66f06256a8f"
-}
diff --git a/.sqlx/query-2cb555310b164293c928ee081ac4f596fa0ff5721a5a1eb048c98da0336dca56.json b/.sqlx/query-2cb555310b164293c928ee081ac4f596fa0ff5721a5a1eb048c98da0336dca56.json
deleted file mode 100644
index 837d97828b..0000000000
--- a/.sqlx/query-2cb555310b164293c928ee081ac4f596fa0ff5721a5a1eb048c98da0336dca56.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata) VALUES ($1, $2, $3, 'email_thread', 'reminders', $4)",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Varchar",
- "Text",
- "Jsonb"
- ]
- },
- "nullable": []
- },
- "hash": "2cb555310b164293c928ee081ac4f596fa0ff5721a5a1eb048c98da0336dca56"
-}
diff --git a/.sqlx/query-34dacf3327fb4ec4c93acbb8db279da87797c240b1ff866ec353b832b151717d.json b/.sqlx/query-34dacf3327fb4ec4c93acbb8db279da87797c240b1ff866ec353b832b151717d.json
deleted file mode 100644
index da6d17672e..0000000000
--- a/.sqlx/query-34dacf3327fb4ec4c93acbb8db279da87797c240b1ff866ec353b832b151717d.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE user_notification SET state = 'done' WHERE notification_id = ANY($1::uuid[])",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "UuidArray"
- ]
- },
- "nullable": []
- },
- "hash": "34dacf3327fb4ec4c93acbb8db279da87797c240b1ff866ec353b832b151717d"
-}
diff --git a/.sqlx/query-3793304d31fcad7fef324f70c049c08c528519a0f1a68571ca291a67f7d33344.json b/.sqlx/query-3793304d31fcad7fef324f70c049c08c528519a0f1a68571ca291a67f7d33344.json
deleted file mode 100644
index 559cdf04fa..0000000000
--- a/.sqlx/query-3793304d31fcad7fef324f70c049c08c528519a0f1a68571ca291a67f7d33344.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE reminder_email_followup SET payload = $2 WHERE reminder_id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Jsonb"
- ]
- },
- "nullable": []
- },
- "hash": "3793304d31fcad7fef324f70c049c08c528519a0f1a68571ca291a67f7d33344"
-}
diff --git a/.sqlx/query-652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55.json b/.sqlx/query-652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55.json
new file mode 100644
index 0000000000..28a04c2a98
--- /dev/null
+++ b/.sqlx/query-652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55.json
@@ -0,0 +1,82 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT p.id, p.team_id, p.record_type, p.database_id, p.table_id,\n p.name, p.user_id, p.created_at, p.trashed_at, p.primary_column_id,\n EXISTS (SELECT 1 FROM entity_access ea WHERE ea.entity_id = p.id\n AND ea.entity_type = 'crm_pipeline' AND ea.source_type = 'team'\n AND ea.source_id = p.team_id::text) AS \"team_shared!\"\n FROM crm_pipeline_entities p\n WHERE p.id = ANY($1) ORDER BY p.id",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "record_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "database_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "table_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 5,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "trashed_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "primary_column_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 10,
+ "name": "team_shared!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ null
+ ]
+ },
+ "hash": "652bbe1537469bf4b32115c6e4ff23ef6f105f52b3395b115e235b371c7b4a55"
+}
diff --git a/.sqlx/query-6a18325302f4c68619c189edc7c73d1c36945d9ec3c9cac0a6bacb85aeb1a50e.json b/.sqlx/query-6a18325302f4c68619c189edc7c73d1c36945d9ec3c9cac0a6bacb85aeb1a50e.json
deleted file mode 100644
index 35d033dd1b..0000000000
--- a/.sqlx/query-6a18325302f4c68619c189edc7c73d1c36945d9ec3c9cac0a6bacb85aeb1a50e.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES (\n gen_random_uuid(), 'two', 'TASK', $1,\n jsonb_build_object('type', 'EntityReference', 'value', jsonb_build_array(\n jsonb_build_object('entity_id', $2::text, 'entity_type', 'INITIATIVE'),\n jsonb_build_object('entity_id', $3::text, 'entity_type', 'INITIATIVE')\n ))\n ), (\n gen_random_uuid(), 'extra', 'TASK', $1,\n jsonb_build_object('type', 'EntityReference', 'value', jsonb_build_array(\n jsonb_build_object(\n 'entity_id', $2::text,\n 'entity_type', 'INITIATIVE',\n 'specific_message_id', 'x'\n )\n ))\n ), (\n gen_random_uuid(), 'empty', 'TASK', $1,\n '{\"type\": \"EntityReference\", \"value\": []}'::jsonb\n )\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "6a18325302f4c68619c189edc7c73d1c36945d9ec3c9cac0a6bacb85aeb1a50e"
-}
diff --git a/.sqlx/query-6f9c0940daebc47036fa96633e0daf147e62a2aec101b7d6e776edb8928e5d85.json b/.sqlx/query-6f9c0940daebc47036fa96633e0daf147e62a2aec101b7d6e776edb8928e5d85.json
deleted file mode 100644
index cdacb10828..0000000000
--- a/.sqlx/query-6f9c0940daebc47036fa96633e0daf147e62a2aec101b7d6e776edb8928e5d85.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM database_tables WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "6f9c0940daebc47036fa96633e0daf147e62a2aec101b7d6e776edb8928e5d85"
-}
diff --git a/.sqlx/query-752103a5ccaabd7a370f902f7451782e8eebc938558dcdfe5963557569592050.json b/.sqlx/query-752103a5ccaabd7a370f902f7451782e8eebc938558dcdfe5963557569592050.json
new file mode 100644
index 0000000000..a62bc0dbb8
--- /dev/null
+++ b/.sqlx/query-752103a5ccaabd7a370f902f7451782e8eebc938558dcdfe5963557569592050.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT id, position FROM database_rows WHERE table_id = $1 AND ($2::uuid IS NULL OR id > $2) ORDER BY id LIMIT $3",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "position",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "752103a5ccaabd7a370f902f7451782e8eebc938558dcdfe5963557569592050"
+}
diff --git a/.sqlx/query-fd7f4012b9812a2698f003914f471411289a31e4a92d30bf35bb4beb8faea182.json b/.sqlx/query-7d5ce21fddd9d966885a4bcd58ae6f18b6214cbbc9260a885adc2761646bd6f7.json
similarity index 66%
rename from .sqlx/query-fd7f4012b9812a2698f003914f471411289a31e4a92d30bf35bb4beb8faea182.json
rename to .sqlx/query-7d5ce21fddd9d966885a4bcd58ae6f18b6214cbbc9260a885adc2761646bd6f7.json
index 39f972f2dd..a1d9a667e4 100644
--- a/.sqlx/query-fd7f4012b9812a2698f003914f471411289a31e4a92d30bf35bb4beb8faea182.json
+++ b/.sqlx/query-7d5ce21fddd9d966885a4bcd58ae6f18b6214cbbc9260a885adc2761646bd6f7.json
@@ -1,17 +1,16 @@
{
"db_name": "PostgreSQL",
- "query": "INSERT INTO database_tables (id, database_id, name, position) VALUES ($1, $2, $3, $4)",
+ "query": "INSERT INTO database_tables (id, database_id, name, position) VALUES ($1, $2, 'Records', $3)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Uuid",
- "Text",
"Text"
]
},
"nullable": []
},
- "hash": "fd7f4012b9812a2698f003914f471411289a31e4a92d30bf35bb4beb8faea182"
+ "hash": "7d5ce21fddd9d966885a4bcd58ae6f18b6214cbbc9260a885adc2761646bd6f7"
}
diff --git a/.sqlx/query-80417d0c840c1ccfd92f5fd0f275baaad5573434a9bbef0abecb776f41c848e1.json b/.sqlx/query-80417d0c840c1ccfd92f5fd0f275baaad5573434a9bbef0abecb776f41c848e1.json
new file mode 100644
index 0000000000..8f9dbf02b9
--- /dev/null
+++ b/.sqlx/query-80417d0c840c1ccfd92f5fd0f275baaad5573434a9bbef0abecb776f41c848e1.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT p.id, ea.access_level AS \"access_level!: AccessLevel\"\n FROM crm_pipeline_entities p JOIN entity_access ea ON ea.entity_id = p.id AND ea.entity_type = 'crm_pipeline'\n WHERE ea.source_id = ANY($1)",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "access_level!: AccessLevel",
+ "type_info": {
+ "Custom": {
+ "name": "\"AccessLevel\"",
+ "kind": {
+ "Enum": [
+ "view",
+ "comment",
+ "edit",
+ "owner"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "80417d0c840c1ccfd92f5fd0f275baaad5573434a9bbef0abecb776f41c848e1"
+}
diff --git a/.sqlx/query-85a57d92e88596827b11f67bc1952b61f0b2a098b60916f58ac7cddc7f6c7f06.json b/.sqlx/query-85a57d92e88596827b11f67bc1952b61f0b2a098b60916f58ac7cddc7f6c7f06.json
new file mode 100644
index 0000000000..2a2bd02ed1
--- /dev/null
+++ b/.sqlx/query-85a57d92e88596827b11f67bc1952b61f0b2a098b60916f58ac7cddc7f6c7f06.json
@@ -0,0 +1,21 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "INSERT INTO crm_pipeline_entities (id, team_id, database_id, table_id, record_type, name, user_id, primary_column_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "85a57d92e88596827b11f67bc1952b61f0b2a098b60916f58ac7cddc7f6c7f06"
+}
diff --git a/.sqlx/query-877738d82663c922ef1fc204c34b41d0256600233b8a92db7ec4aa125f6d41d9.json b/.sqlx/query-877738d82663c922ef1fc204c34b41d0256600233b8a92db7ec4aa125f6d41d9.json
new file mode 100644
index 0000000000..2e39000c8e
--- /dev/null
+++ b/.sqlx/query-877738d82663c922ef1fc204c34b41d0256600233b8a92db7ec4aa125f6d41d9.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_pipeline_entities SET trashed_at = CASE WHEN $2 THEN now() ELSE NULL END, updated_at = now() WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "877738d82663c922ef1fc204c34b41d0256600233b8a92db7ec4aa125f6d41d9"
+}
diff --git a/.sqlx/query-97e6ebd22b021145300b88d79714a3f0cd99ac43c4a30f8923cd4a1e61dc92e7.json b/.sqlx/query-97e6ebd22b021145300b88d79714a3f0cd99ac43c4a30f8923cd4a1e61dc92e7.json
new file mode 100644
index 0000000000..55f9ba0ca9
--- /dev/null
+++ b/.sqlx/query-97e6ebd22b021145300b88d79714a3f0cd99ac43c4a30f8923cd4a1e61dc92e7.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT access_level::text FROM entity_access WHERE entity_id = $1 AND entity_type = 'crm_pipeline' AND source_id = ANY($2)",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "access_level",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "97e6ebd22b021145300b88d79714a3f0cd99ac43c4a30f8923cd4a1e61dc92e7"
+}
diff --git a/.sqlx/query-a6fe35d3b49cd46116ea15a05abd8f3d40d3825fccf9fd96dde66a7558d34d9e.json b/.sqlx/query-a6fe35d3b49cd46116ea15a05abd8f3d40d3825fccf9fd96dde66a7558d34d9e.json
deleted file mode 100644
index 40834987ee..0000000000
--- a/.sqlx/query-a6fe35d3b49cd46116ea15a05abd8f3d40d3825fccf9fd96dde66a7558d34d9e.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE user_notification SET state = 'done' WHERE notification_id = $1::uuid",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "a6fe35d3b49cd46116ea15a05abd8f3d40d3825fccf9fd96dde66a7558d34d9e"
-}
diff --git a/.sqlx/query-b4f1e9ac4501010c2cbecccaf4faba434b691842674a395e8d8aabc8bfb84167.json b/.sqlx/query-b4f1e9ac4501010c2cbecccaf4faba434b691842674a395e8d8aabc8bfb84167.json
new file mode 100644
index 0000000000..504ba78aac
--- /dev/null
+++ b/.sqlx/query-b4f1e9ac4501010c2cbecccaf4faba434b691842674a395e8d8aabc8bfb84167.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE crm_pipeline_entities SET name = $2, updated_at = now() WHERE id = $1 AND trashed_at IS NULL",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "b4f1e9ac4501010c2cbecccaf4faba434b691842674a395e8d8aabc8bfb84167"
+}
diff --git a/.sqlx/query-bc1e9d8e508c811bce59fe8cf6dacc0ea5d79591486fda8d857666ca63e0171c.json b/.sqlx/query-bc1e9d8e508c811bce59fe8cf6dacc0ea5d79591486fda8d857666ca63e0171c.json
deleted file mode 100644
index 89a4967610..0000000000
--- a/.sqlx/query-bc1e9d8e508c811bce59fe8cf6dacc0ea5d79591486fda8d857666ca63e0171c.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n VALUES ($1, 'agent_session', $2, 'user', 'owner')\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "bc1e9d8e508c811bce59fe8cf6dacc0ea5d79591486fda8d857666ca63e0171c"
-}
diff --git a/.sqlx/query-c601fa1db0539963c0a34da61b1cd955b3840952c75f107092904cb02879e8e3.json b/.sqlx/query-c601fa1db0539963c0a34da61b1cd955b3840952c75f107092904cb02879e8e3.json
new file mode 100644
index 0000000000..8e56f062c7
--- /dev/null
+++ b/.sqlx/query-c601fa1db0539963c0a34da61b1cd955b3840952c75f107092904cb02879e8e3.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE database_columns SET nullable = $2 WHERE id = $1",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c601fa1db0539963c0a34da61b1cd955b3840952c75f107092904cb02879e8e3"
+}
diff --git a/.sqlx/query-c659c62e75a1483f2205b35f6fc6f7dcc47e4f5b57ed7382f036ddd451db33cb.json b/.sqlx/query-c659c62e75a1483f2205b35f6fc6f7dcc47e4f5b57ed7382f036ddd451db33cb.json
deleted file mode 100644
index 0e8a5972e1..0000000000
--- a/.sqlx/query-c659c62e75a1483f2205b35f6fc6f7dcc47e4f5b57ed7382f036ddd451db33cb.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM database_columns WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "c659c62e75a1483f2205b35f6fc6f7dcc47e4f5b57ed7382f036ddd451db33cb"
-}
diff --git a/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json b/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json
deleted file mode 100644
index c0be316d98..0000000000
--- a/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity (id, entity_type, owner_type, owner_id, created_at, updated_at)\n VALUES ($1, $2, $3, $4, COALESCE($5::timestamptz, now()), COALESCE($6::timestamptz, now()))\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- {
- "Custom": {
- "name": "entity_owner_type",
- "kind": {
- "Enum": [
- "user",
- "bot",
- "team"
- ]
- }
- }
- },
- "Text",
- "Timestamptz",
- "Timestamptz"
- ]
- },
- "nullable": []
- },
- "hash": "d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e"
-}
diff --git a/.sqlx/query-e4249559e31e3234e0d4a69d2f44330e5a961e36af70ddbff65b1cd3ee2fcfb0.json b/.sqlx/query-e4249559e31e3234e0d4a69d2f44330e5a961e36af70ddbff65b1cd3ee2fcfb0.json
deleted file mode 100644
index 9c95a122e1..0000000000
--- a/.sqlx/query-e4249559e31e3234e0d4a69d2f44330e5a961e36af70ddbff65b1cd3ee2fcfb0.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM database_rows WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "e4249559e31e3234e0d4a69d2f44330e5a961e36af70ddbff65b1cd3ee2fcfb0"
-}
diff --git a/.sqlx/query-f041d69f00f7fd1e4b1489ecc7a4c25494eb147af43fdf0fca7a1e3ac8ae3159.json b/.sqlx/query-f041d69f00f7fd1e4b1489ecc7a4c25494eb147af43fdf0fca7a1e3ac8ae3159.json
deleted file mode 100644
index 0315438491..0000000000
--- a/.sqlx/query-f041d69f00f7fd1e4b1489ecc7a4c25494eb147af43fdf0fca7a1e3ac8ae3159.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM calls WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "f041d69f00f7fd1e4b1489ecc7a4c25494eb147af43fdf0fca7a1e3ac8ae3159"
-}
diff --git a/.sqlx/query-fab904148c8f97ebd0f2727e7caf3e85ffbf681e825f39c7d222e02430fbae82.json b/.sqlx/query-fab904148c8f97ebd0f2727e7caf3e85ffbf681e825f39c7d222e02430fbae82.json
deleted file mode 100644
index 692cae3559..0000000000
--- a/.sqlx/query-fab904148c8f97ebd0f2727e7caf3e85ffbf681e825f39c7d222e02430fbae82.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "DELETE FROM call_records WHERE id = $1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "fab904148c8f97ebd0f2727e7caf3e85ffbf681e825f39c7d222e02430fbae82"
-}
diff --git a/.sqlx/query-5607ac5fc23dc1e34964e32f7025bb89f1daa1226100cf1a46ac9c525bbd0f36.json b/.sqlx/query-ff292b3f040309ae5eaeec8fef20556a4ed9d2051ed450fb048d740d781e69b0.json
similarity index 54%
rename from .sqlx/query-5607ac5fc23dc1e34964e32f7025bb89f1daa1226100cf1a46ac9c525bbd0f36.json
rename to .sqlx/query-ff292b3f040309ae5eaeec8fef20556a4ed9d2051ed450fb048d740d781e69b0.json
index 5381067963..553afd5de9 100644
--- a/.sqlx/query-5607ac5fc23dc1e34964e32f7025bb89f1daa1226100cf1a46ac9c525bbd0f36.json
+++ b/.sqlx/query-ff292b3f040309ae5eaeec8fef20556a4ed9d2051ed450fb048d740d781e69b0.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "SELECT id FROM notification ORDER BY id",
+ "query": "SELECT id FROM crm_pipeline_entities WHERE id = $1 FOR UPDATE",
"describe": {
"columns": [
{
@@ -10,11 +10,13 @@
}
],
"parameters": {
- "Left": []
+ "Left": [
+ "Uuid"
+ ]
},
"nullable": [
false
]
},
- "hash": "5607ac5fc23dc1e34964e32f7025bb89f1daa1226100cf1a46ac9c525bbd0f36"
+ "hash": "ff292b3f040309ae5eaeec8fef20556a4ed9d2051ed450fb048d740d781e69b0"
}
diff --git a/Cargo.lock b/Cargo.lock
index 344ea537b2..b19112bcae 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5013,7 +5013,9 @@ dependencies = [
"axum",
"call",
"chrono",
+ "databases",
"entity_access",
+ "entity_access_db_utils",
"filter_ast",
"item_filters",
"kafka_util",
@@ -5024,6 +5026,7 @@ dependencies = [
"macro_uuid",
"messages",
"model-error-response",
+ "models_databases",
"models_properties",
"properties",
"rdkafka",
@@ -5570,6 +5573,7 @@ dependencies = [
"bot_id",
"chrono",
"connection_gateway_client",
+ "database_sql",
"entity_access",
"entity_access_db_utils",
"entity_mutation",
@@ -21836,6 +21840,7 @@ dependencies = [
"indexmap 2.14.0",
"indicatif",
"indoc",
+ "jsonwebtoken 10.3.0",
"libc",
"macro_aws_config",
"macro_env_var",
diff --git a/apps/web/src/features/block-database/queries/table-rows.ts b/apps/web/src/features/block-database/queries/table-rows.ts
index 22add2e708..d75ff1f22b 100644
--- a/apps/web/src/features/block-database/queries/table-rows.ts
+++ b/apps/web/src/features/block-database/queries/table-rows.ts
@@ -1,3 +1,7 @@
+import { toViewColumn } from '../../database/queries/column-detail';
+
+export { toViewColumn } from '../../database/queries/column-detail';
+
import { databaseSqlSchema } from '@core/database-sql/catalog';
import type { DatabaseOp } from '@core/database-sql/generated/types';
import type { DatabaseSqlReadReason } from '@core/database-sql/trace';
@@ -43,10 +47,7 @@ import {
type DatabaseColumnType,
inferDatabaseNumber,
} from '../../database/core/column-inference';
-import type {
- DatabaseCellValue,
- DatabaseViewColumn,
-} from '../../database/core/database-view';
+import type { DatabaseCellValue } from '../../database/core/database-view';
import { gridRows } from '../../database/core/grid-cells';
import { writeDatabaseRow } from '../../database/core/row-write';
import type {
@@ -65,36 +66,6 @@ import {
type TableChangesCapabilities,
} from './table-changes';
-export function toViewColumn(column: ColumnDetail): DatabaseViewColumn {
- const relation =
- column.column.config?.kind === 'link' ? column.column.config : undefined;
- return {
- id: column.column.id,
- name:
- column.column.display_name ?? column.definition.definition.display_name,
- dataType: column.definition.definition.data_type,
- isMultiSelect: !!relation || column.definition.definition.is_multi_select,
- options: column.definition.property_options.map((option) => ({
- id: option.id,
- label: String(option.value.value),
- color: option.color,
- })),
- writable: column.writable,
- sharedOutsideDatabase: column.shared_outside_database,
- ...(relation
- ? {
- relation: {
- databaseId: relation.database_id,
- tableId: relation.table_id,
- },
- }
- : {}),
- specificEntityType: column.definition.definition.specific_entity_type,
- inferType: column.column.infer_type,
- protections: column.column.protections,
- };
-}
-
/** A stale table or column name, which a refreshed schema may resolve. */
function isStaleSchema(
failure: DatabaseReadFailure | DatabaseWriteFailure
diff --git a/apps/web/src/features/crm/browser-test/editor.browser.e2e.ts b/apps/web/src/features/crm/browser-test/editor.browser.e2e.ts
new file mode 100644
index 0000000000..8a31785adf
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/editor.browser.e2e.ts
@@ -0,0 +1,48 @@
+import { expect, test } from '@playwright/test';
+
+test('the pipeline API powers the shared editor and respects column protections and grants', async ({
+ page,
+}) => {
+ await page.routeWebSocket('**', (socket) => socket.close());
+ await page.route('https://**', (route) => route.abort());
+ await page.route('**/__macro_dev/**', (route) => route.abort());
+ // Local container network changes can cancel Vite's initial module requests.
+ // Retry only that startup failure, never an editor interaction.
+ let networkChanged = false;
+ page.on('requestfailed', (request) => {
+ if (request.failure()?.errorText === 'net::ERR_NETWORK_CHANGED')
+ networkChanged = true;
+ });
+ for (let attempt = 0; attempt < 3; attempt++) {
+ networkChanged = false;
+ await page.goto('/src/features/crm/browser-test/editor.html');
+ await page.waitForLoadState('networkidle');
+ if (!networkChanged) break;
+ }
+ await expect(page.getByRole('grid', { name: 'Renewals' })).toBeVisible({
+ timeout: 30000,
+ });
+ await expect(page.getByText('Acme', { exact: true })).toBeVisible();
+ await page.getByRole('button', { name: /^Notes: Follow up\./ }).dblclick();
+ const editor = page.getByRole('textbox', { name: 'Edit Notes' });
+ await editor.fill('Renew in October');
+ await editor.press('Tab');
+ await expect(page.getByLabel('Pipeline writes')).toHaveText('1');
+ await page.getByRole('button', { name: 'Add column', exact: true }).click();
+ await expect(
+ page.getByRole('columnheader', { name: 'Unnamed', exact: true })
+ ).toBeVisible();
+ await expect(page.getByLabel('Pipeline writes')).toHaveText('2');
+ await page.keyboard.press('Escape');
+ await page
+ .getByRole('columnheader', { name: 'Company', exact: true })
+ .press('Shift+F10');
+ await expect(
+ page.getByRole('menuitem', { name: 'Delete column' })
+ ).toBeDisabled();
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { name: 'Toggle editing' }).click();
+ await expect(
+ page.getByRole('button', { name: 'Add column', exact: true })
+ ).toHaveCount(0);
+});
diff --git a/apps/web/src/features/crm/browser-test/editor.html b/apps/web/src/features/crm/browser-test/editor.html
new file mode 100644
index 0000000000..c46c499915
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/editor.html
@@ -0,0 +1 @@
+<!doctype html><html><head><meta charset="UTF-8" /><title>Pipeline editor fixture</title></head><body><div id="root"></div><script type="module" src="./editor.tsx"></script></body></html>
diff --git a/apps/web/src/features/crm/browser-test/editor.tsx b/apps/web/src/features/crm/browser-test/editor.tsx
new file mode 100644
index 0000000000..bca9ac5145
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/editor.tsx
@@ -0,0 +1,214 @@
+import '@app/index.css';
+import type { DatabaseOp } from '@core/database-sql/generated/types';
+import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
+import type { OpResult } from '@service-storage/generated/schemas/opResult';
+import type { StorageRow } from '@service-storage/generated/schemas/storageRow';
+import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { errAsync, okAsync } from 'neverthrow';
+import { createSignal } from 'solid-js';
+import { render } from 'solid-js/web';
+import { DatabaseProvider } from '../../database/context/database';
+import type { DatabaseViewState } from '../../database/core/view-state';
+import { DatabaseRecords } from '../../database/views/database-records';
+import type { Pipeline } from '../core/pipeline';
+import { createPipelineApi } from '../queries/pipeline-data';
+
+const id = (n: number) =>
+ `00000000-0000-0000-0000-${String(n).padStart(12, '0')}`;
+const pipeline: Pipeline = {
+ id: id(1),
+ databaseId: id(2),
+ tableId: id(3),
+ primaryColumnId: id(4),
+ teamId: id(5),
+ userId: 'macro|[email protected]',
+ name: 'Renewals',
+ recordType: 'company',
+ sharing: 'private',
+ grant: 'owner',
+ createdAt: '2026-10-01T00:00:00Z',
+ trashedAt: null,
+};
+function column(columnId: string, name: string, company = false): ColumnDetail {
+ return {
+ sql_name: name,
+ writable: true,
+ shared_outside_database: false,
+ column: {
+ id: columnId,
+ table_id: pipeline.tableId,
+ property_definition_id: columnId,
+ position: 'a0',
+ config: null,
+ display_name: null,
+ infer_type: false,
+ nullable: !company,
+ protections: company ? ['delete', 'change_type'] : [],
+ },
+ definition: {
+ definition: {
+ id: columnId,
+ display_name: name,
+ data_type: company ? 'ENTITY' : 'STRING',
+ specific_entity_type: company ? 'COMPANY' : null,
+ is_multi_select: false,
+ is_system: false,
+ is_metadata: false,
+ owner: { scope: 'database', database_id: pipeline.databaseId },
+ created_at: pipeline.createdAt,
+ updated_at: pipeline.createdAt,
+ },
+ property_options: [],
+ },
+ };
+}
+function Fixture() {
+ const [editable, setEditable] = createSignal(true);
+ const [writes, setWrites] = createSignal(0);
+ const [view, setView] = createSignal<DatabaseViewState>({
+ query: { filter: null },
+ layout: { kind: 'table', columns: [] },
+ });
+ let table: TableDetail = {
+ table: {
+ id: pipeline.tableId,
+ database_id: pipeline.databaseId,
+ name: 'Records',
+ position: 'a0',
+ version: 1,
+ },
+ sql_name: 'Records',
+ columns: [column(id(4), 'Company', true), column(id(6), 'Notes')],
+ views: [],
+ };
+ let rows: StorageRow[] = [
+ {
+ rowId: id(7),
+ cells: {
+ [id(4)]: {
+ type: 'EntityReference',
+ value: [
+ {
+ entity_id: id(8),
+ entity_type: 'COMPANY',
+ specific_message_id: null,
+ },
+ ],
+ },
+ [id(6)]: { type: 'String', value: 'Follow up' },
+ },
+ },
+ ];
+ const api = createPipelineApi(
+ {
+ getCrmPipelineTable: async () => okAsync(table),
+ queryCrmPipelineRows: async () =>
+ okAsync({ rows, version: table.table.version, next: null }),
+ applyCrmPipelineOps: (
+ _pipelineId: string,
+ batch: { ops: DatabaseOp[] }
+ ) => {
+ const version = table.table.version + 1;
+ const results: OpResult[] = [];
+ for (const op of batch.ops) {
+ if (
+ op.kind === 'rows' &&
+ op.change.kind === 'update' &&
+ op.change.changes.kind === 'per_row'
+ ) {
+ for (const change of op.change.changes.rows)
+ rows = rows.map((row) =>
+ row.rowId !== change.row
+ ? row
+ : {
+ ...row,
+ cells: {
+ ...row.cells,
+ ...Object.fromEntries(
+ change.cells.flatMap((cell) =>
+ cell.value.type === 'text'
+ ? [
+ [
+ cell.column,
+ { type: 'String', value: cell.value.value },
+ ],
+ ]
+ : []
+ )
+ ),
+ },
+ }
+ );
+ results.push({
+ kind: 'rows',
+ table: pipeline.tableId,
+ tableVersion: version,
+ change: { kind: 'updated', affected: 1 },
+ });
+ } else if (
+ op.kind === 'column' &&
+ op.change.kind === 'create' &&
+ op.change.definition.source === 'new'
+ ) {
+ table = {
+ ...table,
+ columns: [
+ ...table.columns,
+ column(op.column, op.change.definition.name),
+ ],
+ };
+ results.push({
+ kind: 'column',
+ table: pipeline.tableId,
+ tableVersion: version,
+ column: op.column,
+ change: { kind: 'created' },
+ });
+ } else
+ return errAsync([
+ {
+ code: 'INVALID_OP' as const,
+ message: 'Unsupported fixture operation',
+ refusal: null,
+ },
+ ]);
+ }
+ table = { ...table, table: { ...table.table, version } };
+ setWrites((value) => value + 1);
+ return okAsync({ results, changes: [] });
+ },
+ },
+ pipeline
+ );
+ return (
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ }
+ >
+ <main class="flex h-screen flex-col bg-panel text-ink">
+ <button onClick={() => setEditable((value) => !value)}>
+ Toggle editing
+ </button>
+ <output aria-label="Pipeline writes">{writes()}</output>
+ <DatabaseProvider
+ api={api}
+ tableId={pipeline.tableId}
+ view={view()}
+ capabilities={{ editRows: editable(), editColumns: editable() }}
+ >
+ <DatabaseRecords
+ view={view()}
+ stored={false}
+ onViewChange={(change) =>
+ setView((view) => ({ ...view, ...change }))
+ }
+ renderMentionValue={() => <span>Acme</span>}
+ />
+ </DatabaseProvider>
+ </main>
+ </QueryClientProvider>
+ );
+}
+render(Fixture, document.getElementById('root')!);
diff --git a/apps/web/src/features/crm/browser-test/pipelines.browser.e2e.ts b/apps/web/src/features/crm/browser-test/pipelines.browser.e2e.ts
new file mode 100644
index 0000000000..0a3d73fb3e
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/pipelines.browser.e2e.ts
@@ -0,0 +1,77 @@
+import { expect, test } from '@playwright/test';
+
+const fixture = '/src/features/crm/browser-test/pipelines.html';
+
+test('create a private company pipeline and customize a column', async ({
+ page,
+}) => {
+ await page.routeWebSocket('**', (socket) => socket.close());
+ await page.route('https://**', (route) => route.abort());
+ await page.route('**/__macro_dev/**', (route) => route.abort());
+ await page.goto(fixture, { waitUntil: 'domcontentloaded' });
+ await page.getByRole('button', { name: 'New pipeline', exact: true }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog.getByRole('radio', { name: 'Just me' })).toBeChecked();
+ await dialog.getByRole('textbox', { name: 'Pipeline name' }).fill('Renewals');
+ await dialog.getByRole('button', { name: 'Create pipeline' }).click();
+ await expect(dialog).not.toBeVisible();
+ await expect(
+ page.getByRole('textbox', { name: 'Pipeline name' })
+ ).toHaveValue('Renewals');
+ await expect(
+ page.getByRole('navigation', { name: 'CRM pipelines' })
+ ).toContainText('Private');
+ await page
+ .getByRole('columnheader', { name: 'Company', exact: true })
+ .press('Shift+F10');
+ await expect(
+ page.getByRole('menuitem', { name: 'Delete column' })
+ ).toBeDisabled();
+ await page.keyboard.press('Escape');
+ await expect(
+ page.getByRole('columnheader', { name: 'Company', exact: true })
+ ).toBeFocused();
+ await page
+ .getByRole('columnheader', { name: 'Stage', exact: true })
+ .press('F2');
+ await page.getByRole('textbox', { name: 'Column name' }).fill('Status');
+ await page.keyboard.press('Tab');
+ await expect(
+ page.getByRole('columnheader', { name: 'Status', exact: true })
+ ).toBeVisible();
+ await expect(page.getByLabel('Create requests')).toHaveText('1');
+ await page.screenshot({ path: '/tmp/pipeline-ui.png' });
+});
+
+test('contact pipeline preserves choices after a failed create', async ({
+ page,
+}) => {
+ await page.routeWebSocket('**', (socket) => socket.close());
+ await page.route('https://**', (route) => route.abort());
+ await page.route('**/__macro_dev/**', (route) => route.abort());
+ await page.goto(fixture, { waitUntil: 'domcontentloaded' });
+ await page.getByRole('button', { name: 'Fail next create' }).click();
+ await page.getByRole('button', { name: 'New pipeline', exact: true }).click();
+ const dialog = page.getByRole('dialog');
+ await dialog
+ .getByRole('textbox', { name: 'Pipeline name' })
+ .fill('Recruiting');
+ await dialog.getByRole('radio', { name: 'Contacts', exact: true }).check();
+ await dialog.getByRole('radio', { name: 'My team' }).check();
+ await dialog.getByRole('button', { name: 'Create pipeline' }).click();
+ await expect(dialog.getByRole('alert')).toBeVisible();
+ await expect(
+ dialog.getByRole('textbox', { name: 'Pipeline name' })
+ ).toHaveValue('Recruiting');
+ await expect(
+ dialog.getByRole('radio', { name: 'Contacts', exact: true })
+ ).toBeChecked();
+ await dialog.getByRole('button', { name: 'Create pipeline' }).click();
+ await expect(dialog).not.toBeVisible();
+ await expect(
+ page.getByRole('columnheader', { name: 'Contact', exact: true })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('navigation', { name: 'CRM pipelines' })
+ ).toContainText('Team');
+});
diff --git a/apps/web/src/features/crm/browser-test/pipelines.html b/apps/web/src/features/crm/browser-test/pipelines.html
new file mode 100644
index 0000000000..bfe6c6c860
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/pipelines.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="utf-8" /><title>CRM pipeline regression</title></head>
+ <body><div id="root"></div><script type="module" src="./pipelines.tsx"></script></body>
+</html>
diff --git a/apps/web/src/features/crm/browser-test/pipelines.tsx b/apps/web/src/features/crm/browser-test/pipelines.tsx
new file mode 100644
index 0000000000..02ae24a721
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/pipelines.tsx
@@ -0,0 +1,166 @@
+import '@app/index.css';
+import { Button } from '@ui';
+import { okAsync } from 'neverthrow';
+import { createSignal, For, Show } from 'solid-js';
+import { render } from 'solid-js/web';
+import { DatabaseColumnHeader } from '../../database/components/database-column-header';
+import type { DatabaseViewColumn } from '../../database/core/database-view';
+import { PipelineDialog } from '../components/pipeline-dialog';
+import { PipelineSidebar } from '../components/pipeline-sidebar';
+import type { PipelinesSource } from '../context/pipelines';
+import type { Pipeline } from '../core/pipeline';
+import { PipelineView } from '../views/pipeline';
+
+// Real creation, navigation and column-header controls. Persistence is
+// local; the Rust integration suite exercises the same contract against Postgres.
+function Editor(props: { pipeline: Pipeline }) {
+ const [columns, setColumns] = createSignal<DatabaseViewColumn[]>([
+ {
+ id: 'primary',
+ name: props.pipeline.recordType === 'company' ? 'Company' : 'Contact',
+ dataType: 'ENTITY',
+ specificEntityType:
+ props.pipeline.recordType === 'company' ? 'COMPANY' : 'CONTACT',
+ primary: true,
+ protections: ['delete', 'change_type'],
+ nullable: false,
+ writable: true,
+ isMultiSelect: false,
+ options: [],
+ },
+ {
+ id: 'stage',
+ name: 'Stage',
+ dataType: 'STRING',
+ writable: true,
+ isMultiSelect: false,
+ options: [],
+ },
+ ]);
+ return (
+ <div class="flex border-b border-edge-muted" role="row">
+ <For each={columns()}>
+ {(column) => (
+ <div class="w-64">
+ <DatabaseColumnHeader
+ column={column}
+ canRename
+ onSort={() => {}}
+ onChangeType={() => okAsync(undefined)}
+ onDelete={(id) => {
+ setColumns((before) =>
+ before.filter((column) => column.id !== id)
+ );
+ return okAsync(undefined);
+ }}
+ onRename={(id, name) => {
+ setColumns((before) =>
+ before.map((column) =>
+ column.id === id ? { ...column, name } : column
+ )
+ );
+ return okAsync(undefined);
+ }}
+ />
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+function Fixture() {
+ const [pipelines, setPipelines] = createSignal<Pipeline[]>([]);
+ const [selected, setSelected] = createSignal<string>();
+ const [creating, setCreating] = createSignal(false);
+ const [failNext, setFailNext] = createSignal(false);
+ const [calls, setCalls] = createSignal(0);
+ const active = () =>
+ pipelines().find((pipeline) => pipeline.id === selected());
+ const source: PipelinesSource = {
+ pipelines,
+ loading: () => false,
+ error: () => false,
+ refresh: async () => {},
+ create: async (input) => {
+ setCalls((count) => count + 1);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ if (failNext()) {
+ setFailNext(false);
+ throw new Error('Test request failed');
+ }
+ const pipeline: Pipeline = {
+ ...input,
+ id: crypto.randomUUID(),
+ databaseId: crypto.randomUUID(),
+ tableId: crypto.randomUUID(),
+ primaryColumnId: 'primary',
+ teamId: 'team',
+ userId: 'macro|[email protected]',
+ grant: 'owner',
+ createdAt: new Date().toISOString(),
+ trashedAt: null,
+ };
+ setPipelines((before) => [...before, pipeline]);
+ return pipeline;
+ },
+ rename: async (id, name) => {
+ setPipelines((before) =>
+ before.map((p) => (p.id === id ? { ...p, name } : p))
+ );
+ },
+ trash: async (id) => {
+ setPipelines((before) => before.filter((p) => p.id !== id));
+ },
+ };
+ return (
+ <main class="flex h-screen flex-col bg-panel text-ink">
+ <div class="flex gap-3 p-2">
+ <Button onClick={() => setFailNext(true)}>Fail next create</Button>
+ <output aria-label="Create requests">{calls()}</output>
+ </div>
+ <div class="flex min-h-0 flex-1">
+ <aside class="w-60 shrink-0 border-r border-edge-muted">
+ <PipelineSidebar
+ pipelines={pipelines()}
+ activeId={selected()}
+ loading={false}
+ error={false}
+ canCreate
+ onCreate={() => setCreating(true)}
+ onSelect={setSelected}
+ onRetry={() => {}}
+ />
+ </aside>
+ <div class="min-w-0 flex-1">
+ <Show when={selected()} keyed>
+ {(_id) => (
+ <Show when={active()}>
+ {(pipeline) => (
+ <PipelineView
+ pipeline={pipeline()}
+ source={source}
+ Editor={Editor}
+ Sharing={() => null}
+ onCopyLink={() => {}}
+ onBack={() => setSelected(undefined)}
+ />
+ )}
+ </Show>
+ )}
+ </Show>
+ </div>
+ </div>
+ <Show when={creating()}>
+ <PipelineDialog
+ onClose={() => setCreating(false)}
+ onCreate={async (input) => {
+ const pipeline = await source.create(input);
+ setSelected(pipeline.id);
+ }}
+ />
+ </Show>
+ </main>
+ );
+}
+const root = document.getElementById('root');
+if (root) render(() => <Fixture />, root);
diff --git a/apps/web/src/features/crm/browser-test/playwright.config.ts b/apps/web/src/features/crm/browser-test/playwright.config.ts
new file mode 100644
index 0000000000..35e25d986b
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/playwright.config.ts
@@ -0,0 +1,26 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from '@playwright/test';
+
+const webDirectory = fileURLToPath(new URL('../../../../', import.meta.url));
+const port = process.env.CRM_PIPELINE_TEST_PORT ?? '3047';
+export default defineConfig({
+ testDir: fileURLToPath(new URL('.', import.meta.url)),
+ testMatch: '*.browser.e2e.ts',
+ workers: 1,
+ timeout: 60_000,
+ use: {
+ baseURL: `http://localhost:${port}`,
+ headless: true,
+ viewport: { width: 1280, height: 800 },
+ launchOptions: {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+ },
+ },
+ webServer: {
+ command: `MACRO_DEV_HTTPS=false bunx vite --port ${port} --strictPort`,
+ cwd: webDirectory,
+ url: `http://localhost:${port}/app/`,
+ reuseExistingServer: false,
+ timeout: 60_000,
+ },
+});
diff --git a/apps/web/src/features/crm/components/crm-sidebar.tsx b/apps/web/src/features/crm/components/crm-sidebar.tsx
index 56c1e43f61..8f2feb7350 100644
--- a/apps/web/src/features/crm/components/crm-sidebar.tsx
+++ b/apps/web/src/features/crm/components/crm-sidebar.tsx
@@ -10,12 +10,13 @@ import StackIcon from '@phosphor/stack.svg';
import ImportIcon from '@phosphor/upload-simple.svg';
import { Button, Tooltip } from '@ui';
import { tourTarget } from '@ui/components/Tour';
-import { createSignal, For, Show } from 'solid-js';
+import { createSignal, For, type JSX, Show } from 'solid-js';
import { CRM_VIEWS } from '../core/navigation';
import { COMPANIES_TOUR } from '../tour';
export function CrmSidebar(props: {
active: string;
+ pipelines?: JSX.Element;
viewMode: 'board' | 'list';
onViewModeChange: (mode: 'board' | 'list') => void;
lists: { id: string; name: string; count: number }[];
@@ -110,6 +111,7 @@ export function CrmSidebar(props: {
</ViewSidebar.Nav>
</CollapsibleSection.Content>
</CollapsibleSection.Root>
+ {props.pipelines}
<Show when={props.listsEnabled}>
<CollapsibleSection.Root
open={listsOpen()}
diff --git a/apps/web/src/features/crm/components/pipeline-dialog.tsx b/apps/web/src/features/crm/components/pipeline-dialog.tsx
new file mode 100644
index 0000000000..1f4f4bad45
--- /dev/null
+++ b/apps/web/src/features/crm/components/pipeline-dialog.tsx
@@ -0,0 +1,129 @@
+import { Button, Dialog, Panel } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import type { NewPipeline } from '../core/pipeline';
+
+/** One creation session; cancel preserves existing CRM data. */
+export function PipelineDialog(props: {
+ onCreate(input: NewPipeline): Promise<void>;
+ onClose(): void;
+}) {
+ const [name, setName] = createSignal('');
+ const [recordType, setRecordType] =
+ createSignal<NewPipeline['recordType']>('company');
+ const [sharing, setSharing] = createSignal<NewPipeline['sharing']>('private');
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal(false);
+ async function submit(event: SubmitEvent) {
+ event.preventDefault();
+ if (pending() || !name().trim()) return;
+ setPending(true);
+ setError(false);
+ try {
+ await props.onCreate({
+ name: name().trim(),
+ recordType: recordType(),
+ sharing: sharing(),
+ });
+ props.onClose();
+ } catch {
+ setError(true);
+ } finally {
+ setPending(false);
+ }
+ }
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => !open && !pending() && props.onClose()}
+ class="w-112 max-w-[calc(100vw-2rem)]"
+ >
+ <Panel>
+ <Panel.Body>
+ <form onSubmit={submit} class="flex flex-col gap-4 p-5">
+ <Dialog.Title class="text-base font-semibold">
+ New pipeline
+ </Dialog.Title>
+ <Dialog.Description class="text-sm text-ink-muted">
+ Track companies or contacts with columns you can customize.
+ </Dialog.Description>
+ <label class="flex flex-col gap-1.5 text-sm">
+ Pipeline name
+ <input
+ required
+ maxlength={200}
+ value={name()}
+ onInput={(event) => setName(event.currentTarget.value)}
+ disabled={pending()}
+ placeholder="e.g. Design partners"
+ class="rounded-lg border border-edge-muted bg-input px-3 py-2 outline-none focus:border-accent"
+ />
+ </label>
+ <fieldset disabled={pending()} class="flex flex-col gap-2 text-sm">
+ <legend class="mb-2 font-medium">Track</legend>
+ <label class="flex items-center gap-2">
+ <input
+ type="radio"
+ name="recordType"
+ checked={recordType() === 'company'}
+ onChange={() => setRecordType('company')}
+ />
+ Companies
+ </label>
+ <label class="flex items-center gap-2">
+ <input
+ type="radio"
+ name="recordType"
+ checked={recordType() === 'contact'}
+ onChange={() => setRecordType('contact')}
+ />
+ Contacts
+ </label>
+ </fieldset>
+ <fieldset disabled={pending()} class="flex flex-col gap-2 text-sm">
+ <legend class="mb-2 font-medium">Share with</legend>
+ <label class="flex items-center gap-2">
+ <input
+ type="radio"
+ name="sharing"
+ checked={sharing() === 'private'}
+ onChange={() => setSharing('private')}
+ />
+ Just me
+ </label>
+ <label class="flex items-center gap-2">
+ <input
+ type="radio"
+ name="sharing"
+ checked={sharing() === 'team'}
+ onChange={() => setSharing('team')}
+ />
+ My team
+ </label>
+ <p class="text-xs text-ink-muted">
+ You can change sharing later. Team members can edit shared
+ pipelines.
+ </p>
+ </fieldset>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure-ink">
+ Could not create this pipeline. Please try again.
+ </p>
+ </Show>
+ <div class="flex justify-end gap-2">
+ <Button
+ variant="ghost"
+ disabled={pending()}
+ onClick={props.onClose}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={pending() || !name().trim()}>
+ {pending() ? 'Creating…' : 'Create pipeline'}
+ </Button>
+ </div>
+ </form>
+ </Panel.Body>
+ </Panel>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/crm/components/pipeline-sidebar.tsx b/apps/web/src/features/crm/components/pipeline-sidebar.tsx
new file mode 100644
index 0000000000..e24b3e769b
--- /dev/null
+++ b/apps/web/src/features/crm/components/pipeline-sidebar.tsx
@@ -0,0 +1,64 @@
+import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';
+import PlusIcon from '@phosphor/plus.svg';
+import TableIcon from '@phosphor/table.svg';
+import { createSignal, For, Show } from 'solid-js';
+import type { Pipeline } from '../core/pipeline';
+
+export function PipelineSidebar(props: {
+ pipelines: Pipeline[];
+ activeId?: string;
+ loading: boolean;
+ error: boolean;
+ canCreate: boolean;
+ onCreate(): void;
+ onSelect(id: string): void;
+ onRetry(): void;
+}) {
+ const [open, setOpen] = createSignal(true);
+ return (
+ <CollapsibleSection.Root open={open()} onOpenChange={setOpen}>
+ <CollapsibleSection.Trigger>
+ <span>Pipelines</span>
+ <CollapsibleSection.Indicator />
+ </CollapsibleSection.Trigger>
+ <CollapsibleSection.Content>
+ <ViewSidebar.Nav aria-label="CRM pipelines">
+ <For each={props.pipelines}>
+ {(pipeline) => (
+ <ViewSidebar.Item
+ active={props.activeId === pipeline.id}
+ title={pipeline.name}
+ onClick={() => props.onSelect(pipeline.id)}
+ >
+ <ViewSidebar.Icon>
+ <TableIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="min-w-0 flex-1 truncate">{pipeline.name}</span>
+ <span class="text-xs text-ink-extra-muted">
+ {pipeline.sharing === 'team' ? 'Team' : 'Private'}
+ </span>
+ </ViewSidebar.Item>
+ )}
+ </For>
+ <Show when={props.loading}>
+ <p class="px-3 py-2 text-xs text-ink-muted">Loading pipelines…</p>
+ </Show>
+ <Show when={props.error}>
+ <ViewSidebar.Item onClick={props.onRetry}>
+ Could not load pipelines. Retry
+ </ViewSidebar.Item>
+ </Show>
+ <ViewSidebar.Item
+ disabled={!props.canCreate}
+ onClick={props.onCreate}
+ >
+ <ViewSidebar.Icon>
+ <PlusIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span>New pipeline</span>
+ </ViewSidebar.Item>
+ </ViewSidebar.Nav>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ );
+}
diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsx
index 8af3656bb4..ad025d8dea 100644
--- a/apps/web/src/features/crm/context/crm-context.tsx
+++ b/apps/web/src/features/crm/context/crm-context.tsx
@@ -30,8 +30,16 @@ import type {
TeamSource,
TeamViewsSource,
} from './crm-sources';
+import type {
+ PipelineEditor,
+ PipelineSharing,
+ PipelinesSource,
+} from './pipelines';
export type CrmContext = {
+ createPipelines(teamId: Accessor<string | undefined>): PipelinesSource;
+ PipelineEditor: PipelineEditor;
+ PipelineSharing: PipelineSharing;
downloadCsv(content: string, filename: string): Promise<{ saved: boolean }>;
contactInitials(name: string | null | undefined, email: string): string;
userEmail(id: string): string;
diff --git a/apps/web/src/features/crm/context/pipelines.ts b/apps/web/src/features/crm/context/pipelines.ts
new file mode 100644
index 0000000000..c5649c3969
--- /dev/null
+++ b/apps/web/src/features/crm/context/pipelines.ts
@@ -0,0 +1,19 @@
+import type { Accessor, Component } from 'solid-js';
+import type { NewPipeline, Pipeline } from '../core/pipeline';
+
+export type PipelinesSource = {
+ pipelines: Accessor<Pipeline[]>;
+ loading: Accessor<boolean>;
+ error: Accessor<boolean>;
+ refresh(): Promise<void>;
+ create(input: NewPipeline): Promise<Pipeline>;
+ rename(id: string, name: string): Promise<void>;
+ trash(id: string): Promise<void>;
+};
+
+export type PipelineEditor = Component<{ pipeline: Pipeline }>;
+
+export type PipelineSharing = Component<{
+ pipeline: Pipeline;
+ onCopyLink(): void;
+}>;
diff --git a/apps/web/src/features/crm/core/pipeline.ts b/apps/web/src/features/crm/core/pipeline.ts
new file mode 100644
index 0000000000..8943c02a93
--- /dev/null
+++ b/apps/web/src/features/crm/core/pipeline.ts
@@ -0,0 +1,17 @@
+/** Pipeline identity and sharing are independent of its customizable table. */
+export type Pipeline = {
+ id: string;
+ teamId: string;
+ name: string;
+ userId: string;
+ recordType: 'company' | 'contact';
+ databaseId: string;
+ tableId: string;
+ primaryColumnId: string;
+ sharing: 'private' | 'team';
+ grant: 'view' | 'comment' | 'edit' | 'owner';
+ createdAt: string;
+ trashedAt: string | null;
+};
+
+export type NewPipeline = Pick<Pipeline, 'name' | 'recordType' | 'sharing'>;
diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.ts
index 3e219be4fa..5c33b6870d 100644
--- a/apps/web/src/features/crm/crm-adapter.ts
+++ b/apps/web/src/features/crm/crm-adapter.ts
@@ -34,6 +34,7 @@ import {
copyCrmViewLink,
createAppCrmNavigation,
} from './navigation-adapter';
+import { PipelineDatabaseEditor, PipelineShare } from './pipeline-adapter';
import {
createClosedStageIds,
createCrmPermissions,
@@ -57,6 +58,7 @@ import {
import { fetchCrmExportCompanies } from './queries/export';
import { useCrmLists } from './queries/lists';
import { useCrmPeopleQuery } from './queries/people';
+import { createPipelinesSource } from './queries/pipelines';
import {
useRecordCallsQuery,
useRecordFilesQuery,
@@ -149,6 +151,9 @@ export function createAppCrmContext(): CrmContext {
const userId = useUserId();
const createSettings = () => useTeamCrmConfig(deps);
return {
+ createPipelines: (teamId) => createPipelinesSource(deps, teamId),
+ PipelineEditor: PipelineDatabaseEditor,
+ PipelineSharing: PipelineShare,
feedback: toast,
downloadCsv: downloadCrmCsv,
contactInitials: getInitialsFromName,
diff --git a/apps/web/src/features/crm/navigation-adapter.ts b/apps/web/src/features/crm/navigation-adapter.ts
index f84c6f7458..1d3173a4a2 100644
--- a/apps/web/src/features/crm/navigation-adapter.ts
+++ b/apps/web/src/features/crm/navigation-adapter.ts
@@ -2,6 +2,7 @@ import { useSplitLayout } from '@components/app/split-layout/layout';
import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
import { toast } from '@core/component/Toast/Toast';
import { buildSimpleEntityUrl } from '@core/util/url';
+import { getWebOrigin } from '@core/util/webOrigin';
import { openEntityInSplitFromUnifiedList } from '../next-soup/utils';
import type { CrmContext } from './context/crm-context';
import type { CrmViewConfig } from './core/saved-view';
@@ -9,18 +10,20 @@ import {
CRM_VIEW_URL_PARAM,
encodeCrmViewParam,
} from './queries/saved-view-codec';
-/** Share link for a view config: /companies?crmView=<encoded>. */
+/** Share link for a CRM view, including its selected pipeline. */
export function buildCrmViewShareUrl(config: CrmViewConfig): string {
- const url = new URL('/companies', window.location.origin);
+ const url = new URL('/app/companies', getWebOrigin());
url.searchParams.set(CRM_VIEW_URL_PARAM, encodeCrmViewParam(config));
return url.toString();
}
-export function copyCrmViewLink(config: CrmViewConfig) {
- navigator.clipboard
- .writeText(buildCrmViewShareUrl(config))
- .then(() => toast.success('Link copied to clipboard'))
- .catch(() => toast.failure('Failed to copy link'));
+export async function copyCrmViewLink(config: CrmViewConfig) {
+ try {
+ await navigator.clipboard.writeText(buildCrmViewShareUrl(config));
+ toast.success('Link copied to clipboard');
+ } catch {
+ toast.failure('Failed to copy link');
+ }
}
export async function copyCrmRecordLink(target: {
type: 'company' | 'contact';
diff --git a/apps/web/src/features/crm/pipeline-adapter.tsx b/apps/web/src/features/crm/pipeline-adapter.tsx
new file mode 100644
index 0000000000..31a07a1c38
--- /dev/null
+++ b/apps/web/src/features/crm/pipeline-adapter.tsx
@@ -0,0 +1,126 @@
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { getPermissions } from '@core/component/SharePermissions';
+import { ShareTrigger } from '@core/component/TopBar/ShareButton';
+import { useShareModal } from '@core/component/TopBar/shareModal';
+import { storageServiceClient } from '@service-storage/client';
+import { Button } from '@ui';
+import { createSignal, onCleanup, onMount, Show, Suspense } from 'solid-js';
+import {
+ DatabaseMentionPicker,
+ DatabaseMentionValue,
+ DatabaseTextEditor,
+ DatabaseTextValue,
+} from '../block-database/database-mentions';
+import { DatabaseProvider, useDatabase } from '../database/context/database';
+import type { DatabaseViewState } from '../database/core/view-state';
+import { DatabaseRecords } from '../database/views/database-records';
+import type { Pipeline } from './core/pipeline';
+import { createPipelineApi } from './queries/pipeline-data';
+
+/** Pipelines supply their own identity and owner to the existing share dialog. */
+export function PipelineShare(props: {
+ pipeline: Pipeline;
+ onCopyLink(): void;
+}) {
+ const openShare = useShareModal(() => ({
+ id: props.pipeline.id,
+ blockAlias: 'database',
+ itemType: 'crm_pipeline',
+ name: props.pipeline.name,
+ owner: props.pipeline.userId,
+ userPermissions: getPermissions(props.pipeline.grant),
+ copyLink: props.onCopyLink,
+ }));
+ return (
+ <ShareTrigger
+ id={props.pipeline.id}
+ blockType="database"
+ onClick={openShare}
+ copyLink={props.onCopyLink}
+ />
+ );
+}
+
+/** The CRM adapter supplies authorized data to the reusable records UI. */
+export function PipelineDatabaseEditor(props: { pipeline: Pipeline }) {
+ return (
+ <Suspense
+ fallback={<div class="p-4 text-sm text-ink-muted">Loading pipeline…</div>}
+ >
+ <Show when={props.pipeline.id} keyed>
+ {(_id) => <PipelineRecords pipeline={props.pipeline} />}
+ </Show>
+ </Suspense>
+ );
+}
+
+function PipelineRecords(props: { pipeline: Pipeline }) {
+ const [view, setView] = createSignal<DatabaseViewState>({
+ query: { filter: null },
+ layout: { kind: 'table', columns: [] },
+ });
+ const api = createPipelineApi(storageServiceClient, props.pipeline);
+ const canEdit = () =>
+ props.pipeline.grant === 'owner' || props.pipeline.grant === 'edit';
+ return (
+ <StaticMarkdownContext>
+ <DatabaseProvider
+ api={api}
+ tableId={props.pipeline.tableId}
+ view={view()}
+ capabilities={{ editRows: canEdit(), editColumns: canEdit() }}
+ >
+ <PipelineRefresh />
+ <DatabaseRecords
+ view={view()}
+ stored={false}
+ onViewChange={(change) =>
+ setView((previous) => ({ ...previous, ...change }))
+ }
+ renderTextEditor={(editor) => <DatabaseTextEditor {...editor} />}
+ renderTextValue={(value) => <DatabaseTextValue value={value} />}
+ renderMentionPicker={(picker) => (
+ <DatabaseMentionPicker {...picker} />
+ )}
+ renderMentionValue={(id, entityType) => (
+ <DatabaseMentionValue id={id} entityType={entityType} />
+ )}
+ renderToolbar={(actions) => (
+ <div class="flex items-center justify-between gap-3 border-b border-edge-muted px-4 py-2">
+ <span class="text-xs text-ink-muted">
+ {props.pipeline.recordType === 'company'
+ ? 'Companies'
+ : 'Contacts'}{' '}
+ · Customize columns from their headers
+ </span>
+ <Show when={canEdit()}>
+ <Button
+ size="sm"
+ disabled={actions.pending()}
+ onClick={() => void actions.createRecord()}
+ >
+ {props.pipeline.recordType === 'company'
+ ? 'Add company'
+ : 'Add contact'}
+ </Button>
+ </Show>
+ </div>
+ )}
+ />
+ </DatabaseProvider>
+ </StaticMarkdownContext>
+ );
+}
+
+/** CRM owns the polling subscription; the shared source owns invalidation. */
+function PipelineRefresh() {
+ const database = useDatabase();
+ onMount(() => {
+ const timer = setInterval(
+ () => void database.data.rows.refresh('refresh'),
+ 5000
+ );
+ onCleanup(() => clearInterval(timer));
+ });
+ return null;
+}
diff --git a/apps/web/src/features/crm/queries/keys.ts b/apps/web/src/features/crm/queries/keys.ts
index d78503f0fc..03f2e1f38e 100644
--- a/apps/web/src/features/crm/queries/keys.ts
+++ b/apps/web/src/features/crm/queries/keys.ts
@@ -2,6 +2,9 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
export const crmKeys = createQueryKeys('crm', {
lists: null,
+ pipelines: (teamId: string | undefined) => [teamId],
+ pipelineTable: (id: string) => [id],
+ pipelineRows: (id: string) => [id],
company: (companyId: string) => [companyId],
contact: (contactId: string) => [contactId],
contactByEmail: (teamId: string, email: string) => [teamId, email],
diff --git a/apps/web/src/features/crm/queries/pipeline-data.test.tsx b/apps/web/src/features/crm/queries/pipeline-data.test.tsx
new file mode 100644
index 0000000000..e750be357f
--- /dev/null
+++ b/apps/web/src/features/crm/queries/pipeline-data.test.tsx
@@ -0,0 +1,277 @@
+import type { StorageRowsQuery } from '@service-storage/generated/schemas/storageRowsQuery';
+import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';
+import { cleanup, render, waitFor } from '@solidjs/testing-library';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { errAsync, okAsync } from 'neverthrow';
+import { Suspense } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { createDatabaseApiSource } from '../../database/queries/api-source';
+import type { Pipeline } from '../core/pipeline';
+import { createPipelineApi, pipelineCell } from './pipeline-data';
+
+const pipeline: Pipeline = {
+ id: 'pipeline',
+ databaseId: 'storage-only',
+ tableId: 'records',
+ primaryColumnId: 'company',
+ name: 'Sales',
+ userId: 'macro|[email protected]',
+ teamId: 'team',
+ recordType: 'company',
+ sharing: 'private',
+ grant: 'owner',
+ createdAt: '2026-10-01T00:00:00Z',
+ trashedAt: null,
+};
+const table: TableDetail = {
+ sql_name: 'Records',
+ table: {
+ id: 'records',
+ database_id: 'storage-only',
+ name: 'Records',
+ position: 'a0',
+ version: 1,
+ },
+ views: [],
+ columns: [
+ {
+ sql_name: 'Company',
+ writable: true,
+ shared_outside_database: false,
+ column: {
+ id: 'company',
+ table_id: 'records',
+ property_definition_id: 'definition',
+ position: 'a0',
+ config: null,
+ display_name: null,
+ infer_type: false,
+ },
+ definition: {
+ definition: {
+ id: 'definition',
+ display_name: 'Company',
+ data_type: 'ENTITY',
+ specific_entity_type: 'COMPANY',
+ is_multi_select: false,
+ is_system: false,
+ is_metadata: false,
+ owner: { scope: 'database', database_id: 'storage-only' },
+ created_at: '2026-10-01T00:00:00Z',
+ updated_at: '2026-10-01T00:00:00Z',
+ },
+ property_options: [],
+ },
+ },
+ ],
+};
+const clients: QueryClient[] = [];
+afterEach(() => {
+ cleanup();
+ for (const client of clients.splice(0)) client.clear();
+});
+
+function setup(writable = true) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ clients.push(client);
+ const storage = {
+ getCrmPipelineTable: vi.fn(async () =>
+ okAsync({
+ ...table,
+ columns: table.columns.map((column) => ({ ...column, writable })),
+ })
+ ),
+ queryCrmPipelineRows: vi.fn(
+ async (_id: string, { after }: StorageRowsQuery) =>
+ okAsync({
+ rows: [
+ {
+ rowId: after ? 'row2' : 'row1',
+ cells: {
+ company: {
+ type: 'EntityReference' as const,
+ value: [
+ {
+ entity_id: after ? 'company2' : 'company1',
+ entity_type: 'COMPANY' as const,
+ specific_message_id: null,
+ },
+ ],
+ },
+ },
+ },
+ ],
+ next: after ? null : 'row1',
+ version: 1,
+ })
+ ),
+ applyCrmPipelineOps: vi.fn(() =>
+ okAsync({
+ results: [
+ {
+ kind: 'rows' as const,
+ table: 'records',
+ tableVersion: 2,
+ change: { kind: 'inserted' as const, rows: ['row3'] },
+ },
+ ],
+ changes: [],
+ })
+ ),
+ };
+ const api = createPipelineApi(storage, pipeline);
+ let data!: ReturnType<typeof createDatabaseApiSource>;
+ function Host() {
+ data = createDatabaseApiSource({
+ api,
+ client,
+ tableId: pipeline.tableId,
+ view: () => ({
+ query: { filter: null },
+ layout: { kind: 'table', columns: [] },
+ }),
+ });
+ return <div>{data.rows.snapshot()?.rows.length ?? 'loading'}</div>;
+ }
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Suspense fallback="loading">
+ <Host />
+ </Suspense>
+ </QueryClientProvider>
+ ));
+ return { storage, data: () => data, client, api };
+}
+
+it('reads all pages through pipeline identity and supplies primary references to the shared grid', async () => {
+ const host = setup();
+ await waitFor(() =>
+ expect(host.data().rows.snapshot()?.rows).toHaveLength(2)
+ );
+ expect(host.storage.getCrmPipelineTable).toHaveBeenCalledWith('pipeline');
+ expect(host.storage.queryCrmPipelineRows).toHaveBeenCalledWith('pipeline', {
+ after: 'row1',
+ query: { filter: null },
+ rowIds: undefined,
+ });
+ expect(host.data().rows.columns()[0].primary).toBe(true);
+ expect(host.data().rows.snapshot()?.rows[1].cells.company).toBe('company2');
+});
+
+it('writes references through the pipeline operation endpoint and returns the inserted row identity', async () => {
+ const host = setup();
+ await waitFor(() => expect(host.data().rows.snapshot()).toBeDefined());
+ const result = await host
+ .data()
+ .rows.write(
+ { kind: 'create', values: { company: 'company3' } },
+ undefined,
+ false
+ );
+ expect(result.isOk() && result.value.insertedRowIds).toEqual(['row3']);
+ expect(host.storage.applyCrmPipelineOps).toHaveBeenCalledWith('pipeline', {
+ ops: [
+ {
+ kind: 'rows',
+ table: 'records',
+ change: {
+ kind: 'insert',
+ rows: [
+ [
+ {
+ column: 'company',
+ value: {
+ type: 'entities',
+ value: [{ entityType: 'COMPANY', entityId: 'company3' }],
+ },
+ },
+ ],
+ ],
+ },
+ },
+ ],
+ });
+});
+
+it('refuses a write to a read-only source before calling storage', async () => {
+ const host = setup(false);
+ await waitFor(() => expect(host.data().rows.snapshot()).toBeDefined());
+ const result = await host
+ .data()
+ .rows.write(
+ { kind: 'cell', rowId: 'row1', columnId: 'company', value: 'other' },
+ undefined,
+ false
+ );
+ expect(result.isErr() && result.error.kind).toBe('read-only-column');
+ expect(host.storage.applyCrmPipelineOps).not.toHaveBeenCalled();
+});
+
+it('maps single and multiple entity values without leaking transport objects into cells', () => {
+ const column = table.columns[0];
+ const value = {
+ type: 'EntityReference' as const,
+ value: [
+ {
+ entity_id: 'one',
+ entity_type: 'COMPANY' as const,
+ specific_message_id: null,
+ },
+ ],
+ };
+ expect(pipelineCell(value, column)).toBe('one');
+ expect(
+ pipelineCell(value, {
+ ...column,
+ definition: {
+ ...column.definition,
+ definition: { ...column.definition.definition, is_multi_select: true },
+ },
+ })
+ ).toBe('["one"]');
+ expect(pipelineCell(undefined, column)).toBeNull();
+});
+
+it('forwards the complete query and retained row request to the pipeline endpoint', async () => {
+ const host = setup();
+ const query = {
+ filter: null,
+ sort: [{ column: 'company', direction: 'descending' as const }],
+ };
+ await host.api.readRows({
+ tableId: 'records',
+ query,
+ cursor: 'after',
+ rowIds: ['held'],
+ });
+ expect(host.storage.queryCrmPipelineRows).toHaveBeenCalledWith('pipeline', {
+ after: 'after',
+ query,
+ rowIds: ['held'],
+ });
+ const other = await host.api.readRows({ tableId: 'other-pipeline', query });
+ expect(other.isErr()).toBe(true);
+});
+
+it('preserves unknown insert outcomes through the shared writer', async () => {
+ const host = setup();
+ await waitFor(() => expect(host.data().rows.snapshot()).toBeDefined());
+ const apply = vi.spyOn(host.api, 'applyOps').mockReturnValueOnce(
+ errAsync({
+ code: 'NETWORK_ERROR',
+ refusal: null,
+ message: 'Connection lost',
+ })
+ );
+ const result = await host
+ .data()
+ .rows.write(
+ { kind: 'create', values: { company: 'company3' } },
+ undefined,
+ false
+ );
+ expect(result.isErr() && result.error.kind).toBe('outcome-unknown');
+ expect(apply).toHaveBeenCalledTimes(1);
+});
diff --git a/apps/web/src/features/crm/queries/pipeline-data.ts b/apps/web/src/features/crm/queries/pipeline-data.ts
new file mode 100644
index 0000000000..0fcc9597a6
--- /dev/null
+++ b/apps/web/src/features/crm/queries/pipeline-data.ts
@@ -0,0 +1,114 @@
+import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
+import type { PropertyValue } from '@service-storage/generated/schemas/propertyValue';
+import { err, errAsync, ok, ResultAsync } from 'neverthrow';
+import { match } from 'ts-pattern';
+import type { DatabaseApi } from '../../database/core/api';
+import type { DatabaseCellValue } from '../../database/core/database-view';
+import { UNAVAILABLE_OPTION } from '../../database/core/grid-cells';
+import { toViewColumn } from '../../database/queries/column-detail';
+import type { Pipeline } from '../core/pipeline';
+import type { CrmRecordDependencies } from './dependencies';
+
+/** Adapt stored properties to the shared editor's values. */
+export function pipelineCell(
+ value: PropertyValue | undefined,
+ column: ColumnDetail
+): DatabaseCellValue {
+ if (!value) return null;
+ const listed = (values: string[]) =>
+ column.definition.definition.is_multi_select
+ ? JSON.stringify(values)
+ : (values[0] ?? null);
+ return match(value)
+ .with({ type: 'Boolean' }, ({ value }) => (value ? 1 : 0))
+ .with(
+ { type: 'Number' },
+ { type: 'String' },
+ { type: 'Date' },
+ ({ value }) => value
+ )
+ .with({ type: 'Link' }, ({ value }) => listed(value))
+ .with({ type: 'EntityReference' }, ({ value }) =>
+ listed(value.map((ref) => ref.entity_id))
+ )
+ .with({ type: 'SelectOption' }, ({ value }) =>
+ listed(
+ value.map((id) => {
+ const option = column.definition.property_options.find(
+ (option) => option.id === id
+ );
+ return option ? String(option.value.value) : UNAVAILABLE_OPTION;
+ })
+ )
+ )
+ .exhaustive();
+}
+
+/** Transport adapter only; the shared provider owns queries and editing. */
+export function createPipelineApi(
+ storage: Pick<
+ CrmRecordDependencies['storage'],
+ 'getCrmPipelineTable' | 'queryCrmPipelineRows' | 'applyCrmPipelineOps'
+ >,
+ pipeline: Pipeline
+): DatabaseApi {
+ const failure = () => ({
+ kind: 'fetch' as const,
+ message: 'Could not read this pipeline.',
+ });
+ const table = () =>
+ new ResultAsync(storage.getCrmPipelineTable(pipeline.id)).mapErr(failure);
+ return {
+ key: ['crm', 'pipeline', pipeline.id],
+ readTable: (tableId) =>
+ tableId !== pipeline.tableId
+ ? errAsync(failure())
+ : table().map((detail) => ({
+ id: detail.table.id,
+ databaseId: detail.table.database_id,
+ name: pipeline.name,
+ version: detail.table.version,
+ columns: detail.columns.map((column) => ({
+ ...toViewColumn(column),
+ primary: column.column.id === pipeline.primaryColumnId,
+ })),
+ })),
+ readRows: (request) =>
+ request.tableId !== pipeline.tableId
+ ? errAsync(failure())
+ : table().andThen((schema) =>
+ new ResultAsync(
+ storage.queryCrmPipelineRows(pipeline.id, {
+ after: request.cursor,
+ query: {
+ ...request.query,
+ filter: request.query.filter ?? null,
+ },
+ rowIds: request.rowIds,
+ })
+ )
+ .mapErr(failure)
+ .andThen((page) => {
+ if (page.version !== schema.table.version)
+ return err(failure());
+ return ok({
+ tableVersion: page.version,
+ nextCursor: page.next ?? undefined,
+ rows: page.rows.map((row) => ({
+ rowId: row.rowId,
+ cells: Object.fromEntries(
+ schema.columns.map((column) => [
+ column.column.id,
+ pipelineCell(row.cells[column.column.id], column),
+ ])
+ ),
+ })),
+ });
+ })
+ ),
+ applyOps: (batch) =>
+ storage
+ .applyCrmPipelineOps(pipeline.id, batch)
+ .mapErr(([error]) => error),
+ };
+}
diff --git a/apps/web/src/features/crm/queries/pipeline-sharing.ts b/apps/web/src/features/crm/queries/pipeline-sharing.ts
new file mode 100644
index 0000000000..189cc711b6
--- /dev/null
+++ b/apps/web/src/features/crm/queries/pipeline-sharing.ts
@@ -0,0 +1,37 @@
+import { queryClient } from '@queries/client';
+import { storageServiceClient } from '@service-storage/client';
+import type { SharePermissionV2 } from '@service-storage/generated/schemas/sharePermissionV2';
+import type { Pipeline } from '../core/pipeline';
+import { crmKeys } from './keys';
+
+/** Adapt pipeline grants to the standard sharing dialog. */
+export async function fetchPipelineSharePermissions(id: string) {
+ const pipeline = await storageServiceClient.getCrmPipeline(id);
+ if (pipeline.isErr()) return pipeline;
+ return pipeline.map(
+ (value): SharePermissionV2 => ({
+ id,
+ owner: value.userId,
+ channelSharePermissions: [],
+ linkShare: null,
+ linkShareAccessLevel: null,
+ teamShareAccessLevel: value.sharing === 'team' ? 'edit' : null,
+ })
+ );
+}
+
+export async function updatePipelineTeamShare(id: string, shared: boolean) {
+ const sharing = shared ? 'team' : 'private';
+ const result = await storageServiceClient.shareCrmPipeline(id, sharing);
+ if (result.isOk()) {
+ queryClient.setQueriesData<Pipeline[]>(
+ { queryKey: crmKeys.pipelines._def },
+ (before) =>
+ before?.map((pipeline) =>
+ pipeline.id === id ? { ...pipeline, sharing } : pipeline
+ )
+ );
+ await queryClient.invalidateQueries({ queryKey: crmKeys.pipelines._def });
+ }
+ return result;
+}
diff --git a/apps/web/src/features/crm/queries/pipelines.ts b/apps/web/src/features/crm/queries/pipelines.ts
new file mode 100644
index 0000000000..f5d0762c6c
--- /dev/null
+++ b/apps/web/src/features/crm/queries/pipelines.ts
@@ -0,0 +1,75 @@
+import { throwOnErr } from '@core/util/result';
+import { queryReadyGate } from '@queries/gate';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import type { PipelinesSource } from '../context/pipelines';
+import type { Pipeline } from '../core/pipeline';
+import type { CrmQueryDependencies } from './dependencies';
+import { crmKeys } from './keys';
+
+export function createPipelinesSource(
+ deps: CrmQueryDependencies,
+ teamId: Accessor<string | undefined>
+): PipelinesSource {
+ const query = useQuery(
+ () => ({
+ queryKey: crmKeys.pipelines(teamId()).queryKey,
+ queryFn: () => throwOnErr(() => deps.storage.listCrmPipelines()),
+ enabled: !!teamId(),
+ }),
+ () => deps.client
+ );
+ const refresh = async () => {
+ await deps.client.invalidateQueries({
+ queryKey: crmKeys.pipelines(teamId()).queryKey,
+ });
+ };
+ async function refreshAfterSave() {
+ try {
+ await refresh();
+ } catch {
+ deps.feedback.failure(
+ 'Saved, but could not refresh pipelines. Please refresh the view.'
+ );
+ }
+ }
+ function update(id: string, change?: Partial<Pipeline>) {
+ deps.client.setQueryData<Pipeline[]>(
+ crmKeys.pipelines(teamId()).queryKey,
+ (before) =>
+ before?.flatMap((pipeline) =>
+ pipeline.id === id
+ ? change
+ ? [{ ...pipeline, ...change }]
+ : []
+ : [pipeline]
+ )
+ );
+ void refreshAfterSave();
+ }
+ return {
+ pipelines: () => (queryReadyGate(query) ? query.data : []),
+ loading: () => query.isLoading,
+ error: () => query.isError,
+ refresh,
+ create: async (input) => {
+ const pipeline = await throwOnErr(() =>
+ deps.storage.createCrmPipeline(input)
+ );
+ deps.client.setQueryData(
+ crmKeys.pipelines(pipeline.teamId).queryKey,
+ (old: (typeof pipeline)[] | undefined) => [...(old ?? []), pipeline]
+ );
+ void refreshAfterSave();
+ return pipeline;
+ },
+ rename: async (id, name) => {
+ await throwOnErr(() => deps.storage.renameCrmPipeline(id, name));
+ update(id, { name });
+ },
+ trash: async (id) => {
+ await throwOnErr(() => deps.storage.trashCrmPipeline(id));
+ update(id);
+ },
+ };
+}
diff --git a/apps/web/src/features/crm/sharing-adapter.ts b/apps/web/src/features/crm/sharing-adapter.ts
new file mode 100644
index 0000000000..97fca5801f
--- /dev/null
+++ b/apps/web/src/features/crm/sharing-adapter.ts
@@ -0,0 +1,5 @@
+/** Pipeline grant operations exposed to the app's shared sharing dialog. */
+export {
+ fetchPipelineSharePermissions,
+ updatePipelineTeamShare,
+} from './queries/pipeline-sharing';
diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsx
index 8fb78fc199..fa32cb4723 100644
--- a/apps/web/src/features/crm/views/crm-workspace.tsx
+++ b/apps/web/src/features/crm/views/crm-workspace.tsx
@@ -22,6 +22,8 @@ import { tourTarget } from '@ui/components/Tour';
import { createSignal, type JSX, onMount, Show, Suspense } from 'solid-js';
import { CrmListDialog } from '../components/company-list-dialog';
import { CrmSidebar } from '../components/crm-sidebar';
+import { PipelineDialog } from '../components/pipeline-dialog';
+import { PipelineSidebar } from '../components/pipeline-sidebar';
import { useCrmContext } from '../context/crm-context';
import { useCrmWorkspace } from '../context/workspace-context';
import { CRM_VIEWS } from '../core/navigation';
@@ -32,6 +34,7 @@ import { useApplyCrmView } from './apply-view';
import { CrmExport } from './export-companies';
import { CrmImport } from './import-companies';
import { CrmPeople } from './people';
+import { PipelineView } from './pipeline';
import { CrmCompanyDetail } from './record-detail';
import { CompanyDisplayMenu, CompanyViewsMenu } from './saved-views-menu';
import {
@@ -164,6 +167,8 @@ export function CrmWorkspaceView(props: {
const {
openCreateCompany: openCreateCompanyModal,
exportCompanies: fetchCrmExportCompanies,
+ PipelineEditor,
+ copyViewLink,
} = useCrmContext();
const view = useCrmWorkspace();
const [selectedCompany, setSelectedCompany] = createSignal<{
@@ -187,6 +192,20 @@ export function CrmWorkspaceView(props: {
const teamQuery = useCurrentTeamQuery();
const teamId = () =>
teamQuery.isSuccess ? teamQuery.data?.team.id : undefined;
+ const canCreatePipeline = () =>
+ teamQuery.isSuccess && teamQuery.data?.team.crm_enabled === true;
+ const pipelines = useCrmContext().createPipelines(teamId);
+ const [creatingPipeline, setCreatingPipeline] = createSignal(false);
+ const pipelineId = () =>
+ view.activeTab()?.startsWith('pipeline:')
+ ? view.activeTab()?.slice('pipeline:'.length)
+ : undefined;
+ const activePipeline = () =>
+ pipelines.pipelines().find((pipeline) => pipeline.id === pipelineId());
+ const selectPipeline = (id: string) => {
+ closeCompany();
+ view.setActiveTab(`pipeline:${id}`);
+ };
const listsEnabled = useCrmContext().listsEnabled();
const lists = useCrmLists(() => (listsEnabled() ? teamId() : undefined));
const personal = usePersonalCrmViews();
@@ -274,7 +293,19 @@ export function CrmWorkspaceView(props: {
});
const sidebar = () => (
<CrmSidebar
- active={active()}
+ pipelines={
+ <PipelineSidebar
+ pipelines={pipelines.pipelines()}
+ activeId={pipelineId()}
+ loading={pipelines.loading()}
+ error={pipelines.error()}
+ canCreate={canCreatePipeline()}
+ onCreate={() => setCreatingPipeline(true)}
+ onSelect={selectPipeline}
+ onRetry={() => void pipelines.refresh()}
+ />
+ }
+ active={pipelineId() ? `pipeline:${pipelineId()}` : active()}
viewMode={view.viewMode()}
onViewModeChange={(mode) => {
closeCompany();
@@ -323,7 +354,47 @@ export function CrmWorkspaceView(props: {
/>
)}
</Show>
- <Show when={!selectedCompany()}>
+ <Show when={pipelineId()} keyed>
+ {(id) => (
+ <Show when={activePipeline()}>
+ {(pipeline) => (
+ <PipelineView
+ pipeline={pipeline()}
+ source={pipelines}
+ Sharing={useCrmContext().PipelineSharing}
+ Editor={PipelineEditor}
+ onCopyLink={() =>
+ copyViewLink({
+ kind: 'crm',
+ activeTab: `pipeline:${id}`,
+ })
+ }
+ onBack={() => navigate('active')}
+ navigation={
+ <NavigationToggle onExpand={() => setCollapsed(false)}>
+ <Suspense>{sidebar()}</Suspense>
+ </NavigationToggle>
+ }
+ />
+ )}
+ </Show>
+ )}
+ </Show>
+ <Show when={pipelineId() && !activePipeline()}>
+ <div class="flex flex-col items-start gap-3 p-6 text-sm text-ink-muted">
+ <p>
+ {pipelines.loading()
+ ? 'Loading pipeline…'
+ : pipelines.error()
+ ? 'Could not load this pipeline.'
+ : 'This pipeline is unavailable or you no longer have access.'}
+ </p>
+ <Button variant="ghost" onClick={() => navigate('active')}>
+ Back to companies
+ </Button>
+ </div>
+ </Show>
+ <Show when={!selectedCompany() && !pipelineId()}>
<Show when={!isTouchDevice() || peopleActive()}>
<div class="flex h-12 shrink-0 items-center gap-3 px-4">
<NavigationToggle onExpand={() => setCollapsed(false)}>
@@ -398,6 +469,15 @@ export function CrmWorkspaceView(props: {
</div>
</Show>
</ViewShell.Main>
+ <Show when={creatingPipeline() && canCreatePipeline()}>
+ <PipelineDialog
+ onClose={() => setCreatingPipeline(false)}
+ onCreate={async (input) => {
+ const pipeline = await pipelines.create(input);
+ selectPipeline(pipeline.id);
+ }}
+ />
+ </Show>
<Show when={listsEnabled() && editing()}>
{(initial) => {
const companies = useQuickAccessCrmCompaniesQuery();
diff --git a/apps/web/src/features/crm/views/pipeline.tsx b/apps/web/src/features/crm/views/pipeline.tsx
new file mode 100644
index 0000000000..4a3eface01
--- /dev/null
+++ b/apps/web/src/features/crm/views/pipeline.tsx
@@ -0,0 +1,125 @@
+import { Button } from '@ui';
+import { DeleteDialog } from '@ui/components/DeleteDialog';
+import { createSignal, type JSX, Show } from 'solid-js';
+import type {
+ PipelineEditor,
+ PipelineSharing,
+ PipelinesSource,
+} from '../context/pipelines';
+import type { Pipeline } from '../core/pipeline';
+
+export function PipelineView(props: {
+ pipeline: Pipeline;
+ source: PipelinesSource;
+ navigation?: JSX.Element;
+ Editor: PipelineEditor;
+ Sharing: PipelineSharing;
+ onCopyLink(): void;
+ onBack(): void;
+}) {
+ const [draftName, setDraftName] = createSignal<string>();
+ const name = () => draftName() ?? props.pipeline.name;
+ const [pending, setPending] = createSignal(false);
+ const [error, setError] = createSignal('');
+ const [deleting, setDeleting] = createSignal(false);
+ async function save(action: () => Promise<void>) {
+ if (pending()) return;
+ setPending(true);
+ setError('');
+ try {
+ await action();
+ } catch {
+ setError('Could not save this change. Please try again.');
+ } finally {
+ setPending(false);
+ }
+ }
+ return (
+ <div class="flex size-full min-h-0 flex-col">
+ <div class="flex flex-wrap items-center gap-3 border-b border-edge-muted p-3">
+ {props.navigation}
+ <Button variant="ghost" size="sm" onClick={props.onBack}>
+ Back to companies
+ </Button>
+ <form
+ class="flex min-w-0 flex-1 items-center gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void save(async () => {
+ await props.source.rename(props.pipeline.id, name().trim());
+ setDraftName(undefined);
+ });
+ }}
+ >
+ <input
+ aria-label="Pipeline name"
+ value={name()}
+ maxlength={200}
+ required
+ disabled={
+ pending() || !['owner', 'edit'].includes(props.pipeline.grant)
+ }
+ onInput={(event) => setDraftName(event.currentTarget.value)}
+ class="min-w-0 flex-1 rounded border border-transparent bg-transparent px-2 py-1 text-sm font-semibold outline-none focus:border-accent"
+ />
+ <Show when={name().trim() !== props.pipeline.name}>
+ <Button
+ size="sm"
+ type="submit"
+ disabled={pending() || !name().trim()}
+ >
+ Save name
+ </Button>
+ </Show>
+ </form>
+ <props.Sharing
+ pipeline={props.pipeline}
+ onCopyLink={props.onCopyLink}
+ />
+ <Show
+ when={props.pipeline.grant === 'owner'}
+ fallback={
+ <span class="text-xs text-ink-muted">
+ {props.pipeline.sharing === 'team'
+ ? 'Shared with team'
+ : 'Private'}
+ </span>
+ }
+ >
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={pending()}
+ onClick={() => setDeleting(true)}
+ >
+ Trash pipeline
+ </Button>
+ </Show>
+ </div>
+ <Show when={error()}>
+ <p role="alert" class="px-4 py-2 text-sm text-failure-ink">
+ {error()}
+ </p>
+ </Show>
+ <props.Editor pipeline={props.pipeline} />
+ <DeleteDialog
+ open={deleting()}
+ onOpenChange={setDeleting}
+ pending={pending()}
+ title="Trash pipeline?"
+ body={
+ <p>
+ The pipeline and its entries will move to trash. The companies and
+ contacts remain in your CRM.
+ </p>
+ }
+ onDelete={() =>
+ void save(async () => {
+ await props.source.trash(props.pipeline.id);
+ props.onBack();
+ })
+ }
+ />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/database/README.md b/apps/web/src/features/database/README.md
index b811e161c7..26748f663f 100644
--- a/apps/web/src/features/database/README.md
+++ b/apps/web/src/features/database/README.md
@@ -71,5 +71,5 @@ sharing, navigation, Forms integration and concrete network clients in
The API-only browser fixture is in
`../block-database/browser-test/api.tsx`. It exercises pagination, row edits,
column creation, permission changes and board rendering without app providers
-beyond the query client. CRM wiring belongs in the CRM feature after it rebases
-on this extraction.
+beyond the query client. The CRM feature uses `createPipelineApi` and the same provider/controller; its
+browser fixture is `../crm/browser-test/editor.tsx`.
diff --git a/apps/web/src/features/database/components/database-column-header.tsx b/apps/web/src/features/database/components/database-column-header.tsx
index ab68bc3bcb..5ea4386b6a 100644
--- a/apps/web/src/features/database/components/database-column-header.tsx
+++ b/apps/web/src/features/database/components/database-column-header.tsx
@@ -132,7 +132,13 @@ export function DatabaseColumnHeader(props: DatabaseColumnHeaderProps) {
};
props.registerRename?.(rename);
async function changeType(change: DatabaseColumnTypeChange) {
- if (!canRename() || !props.onChangeType || pending()) return;
+ if (
+ !canRename() ||
+ props.column.protections?.includes('change_type') ||
+ !props.onChangeType ||
+ pending()
+ )
+ return;
setMenuOpen(false);
setError('');
setOperating(true);
@@ -156,7 +162,13 @@ export function DatabaseColumnHeader(props: DatabaseColumnHeaderProps) {
if (converted.isErr()) setError(columnSchemaMessage(converted.error));
}
async function remove() {
- if (!canRename() || !props.onDelete || pending()) return;
+ if (
+ !canRename() ||
+ props.column.protections?.includes('delete') ||
+ !props.onDelete ||
+ pending()
+ )
+ return;
setError('');
setOperating(true);
const deleted = await props.onDelete(props.column.id);
@@ -385,7 +397,7 @@ export function DatabaseColumnHeader(props: DatabaseColumnHeaderProps) {
}
>
<Dropdown.Item disabled>
- Protected column — required by its feature
+ This column cannot be deleted
</Dropdown.Item>
</Show>
<For
diff --git a/apps/web/src/features/database/core/database-view.ts b/apps/web/src/features/database/core/database-view.ts
index 516a17440b..194195a565 100644
--- a/apps/web/src/features/database/core/database-view.ts
+++ b/apps/web/src/features/database/core/database-view.ts
@@ -19,9 +19,13 @@ export type DatabaseViewColumn = {
isMultiSelect: boolean;
options: DatabaseOption[];
writable: boolean;
+ /** The preferred field for record titles and initial focus. */
+ primary?: boolean;
specificEntityType?: DatabaseEntityType | null;
/** A new, empty Text column may adopt the type of its first entry. */
inferType?: boolean;
+ /** Whether a row may omit this cell. Defaults to true for legacy sources. */
+ nullable?: boolean;
/** Schema actions reserved by the feature using this column. */
protections?: ('delete' | 'change_type')[];
/** The column's definition is used beyond this database, so its options change everywhere. */
diff --git a/apps/web/src/features/database/core/table.test.ts b/apps/web/src/features/database/core/table.test.ts
index 6126fa139e..5c0ba65eb5 100644
--- a/apps/web/src/features/database/core/table.test.ts
+++ b/apps/web/src/features/database/core/table.test.ts
@@ -50,6 +50,16 @@ describe('record title', () => {
[name, entity]
)
).toBe('Launch plan');
+ // Moving a custom column before a pipeline's primary reference keeps its identity.
+ expect(
+ rowTitle(
+ {
+ rowId: 'row',
+ cells: { person: 'macro|[email protected]', name: 'Launch plan' },
+ },
+ [name, { ...entity, primary: true }]
+ )
+ ).toBe('Linked record');
});
});
diff --git a/apps/web/src/features/database/core/table.ts b/apps/web/src/features/database/core/table.ts
index d6891cd525..a7ebee72f2 100644
--- a/apps/web/src/features/database/core/table.ts
+++ b/apps/web/src/features/database/core/table.ts
@@ -41,9 +41,9 @@ export function rowValue(
return row.cells[columnId] ?? null;
}
-/** The column a row is named by outside a board: the table's first. */
+/** Name rows by their primary reference, or by the first column otherwise. */
export function titleColumn(columns: readonly DatabaseViewColumn[]) {
- return columns[0];
+ return columns.find((column) => column.primary) ?? columns[0];
}
/** A row's name as `column` holds it, or `Unnamed` when it holds nothing. */
diff --git a/apps/web/src/features/database/primitives/record-actions.ts b/apps/web/src/features/database/primitives/record-actions.ts
index 3837505ef1..69a43ad18c 100644
--- a/apps/web/src/features/database/primitives/record-actions.ts
+++ b/apps/web/src/features/database/primitives/record-actions.ts
@@ -162,7 +162,8 @@ export function createRecordActions(options: {
controller.dismissFailure();
}
function focusBlankRow() {
- const field = options.visibleColumns().find(canEditCell);
+ const editable = options.visibleColumns().filter(canEditCell);
+ const field = editable.find((column) => column.primary) ?? editable[0];
if (!options.canEdit() || !field) return false;
options.editCell(draftRows.blankId(), field.id);
return true;
diff --git a/apps/web/src/features/database/queries/column-detail.ts b/apps/web/src/features/database/queries/column-detail.ts
new file mode 100644
index 0000000000..56511b3c0f
--- /dev/null
+++ b/apps/web/src/features/database/queries/column-detail.ts
@@ -0,0 +1,33 @@
+import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';
+import type { DatabaseViewColumn } from '../core/database-view';
+
+export function toViewColumn(column: ColumnDetail): DatabaseViewColumn {
+ const relation =
+ column.column.config?.kind === 'link' ? column.column.config : undefined;
+ return {
+ id: column.column.id,
+ name:
+ column.column.display_name ?? column.definition.definition.display_name,
+ dataType: column.definition.definition.data_type,
+ isMultiSelect: !!relation || column.definition.definition.is_multi_select,
+ options: column.definition.property_options.map((option) => ({
+ id: option.id,
+ label: String(option.value.value),
+ color: option.color,
+ })),
+ writable: column.writable,
+ sharedOutsideDatabase: column.shared_outside_database,
+ ...(relation
+ ? {
+ relation: {
+ databaseId: relation.database_id,
+ tableId: relation.table_id,
+ },
+ }
+ : {}),
+ specificEntityType: column.definition.definition.specific_entity_type,
+ inferType: column.column.infer_type,
+ protections: column.column.protections,
+ nullable: column.column.nullable,
+ };
+}
diff --git a/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx b/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx
index 2856b39121..22ee61f035 100644
--- a/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx
+++ b/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx
@@ -23,6 +23,7 @@ function toItemType(type: EntityRef['type']): ItemType | undefined {
'agent_session',
'scheduled_action',
'initiative',
+ 'crm_pipeline',
// A database and its rows are their own entity kinds, not cloud-storage
// items.
'database',
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
index b8ff927d41..21b1ddc664 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx
@@ -26,6 +26,8 @@ const mocks = vi.hoisted(() => ({
getDocumentPermissions: vi.fn(),
getDatabasePermissions: vi.fn(),
updateDatabasePermissions: vi.fn(),
+ getPipelinePermissions: vi.fn(),
+ updatePipelineTeamShare: vi.fn(),
getChatPermissions: vi.fn(),
updateChatPermissions: vi.fn(),
fetchCallSharePermission: vi.fn(),
@@ -42,6 +44,10 @@ const mocks = vi.hoisted(() => ({
blockEditPermissionEnabled: true,
inBlock: true,
}));
+vi.mock('@app/features/crm/sharing-adapter', () => ({
+ fetchPipelineSharePermissions: mocks.getPipelinePermissions,
+ updatePipelineTeamShare: mocks.updatePipelineTeamShare,
+}));
vi.mock('@queries/storage/databases', () => ({
getDatabaseSharePermissions: mocks.getDatabasePermissions,
updateDatabaseSharePermissions: mocks.updateDatabasePermissions,
@@ -1218,6 +1224,116 @@ describe('native project sharing', () => {
});
});
+describe('pipeline sharing', () => {
+ function mountPipeline(owner = ME) {
+ mocks.hasTeam = true;
+ mocks.getPipelinePermissions.mockResolvedValue(
+ ok({ id: 'pipeline-1', owner, teamShareAccessLevel: null })
+ );
+ render(() => (
+ <ShareModal
+ id="pipeline-1"
+ name="Sales"
+ owner={owner}
+ itemType="crm_pipeline"
+ blockAlias="database"
+ userPermissions={
+ owner === ME ? Permissions.OWNER : Permissions.CAN_VIEW
+ }
+ copyLink={mocks.copyLink}
+ open
+ onOpenChange={vi.fn()}
+ />
+ ));
+ }
+
+ it.each([false, true])(
+ 'changes the pipeline team grant using the shared dialog (mobile: %s)',
+ async (mobile) => {
+ mocks.mobile = mobile;
+ mocks.updatePipelineTeamShare.mockImplementation(async (_id, shared) => {
+ mocks.getPipelinePermissions.mockResolvedValue(
+ ok({
+ id: 'pipeline-1',
+ owner: ME,
+ teamShareAccessLevel: shared ? 'edit' : null,
+ })
+ );
+ return ok({});
+ });
+ mountPipeline();
+ if (mobile) fireEvent.click(screen.getByRole('tab', { name: 'Team' }));
+ const control = await screen.findByRole('group', {
+ name: 'Team access level',
+ });
+ expect(control.getAttribute('data-value')).toBe('NONE');
+ expect(
+ screen.queryByRole('button', { name: 'Set Team access level view' })
+ ).toBeNull();
+ expect(
+ screen.queryByRole('button', { name: 'Select channel' })
+ ).toBeNull();
+ expect(screen.queryByText('Anyone with the link')).toBeNull();
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Set Team access level edit' })
+ );
+ await vi.waitFor(() =>
+ expect(control.getAttribute('data-value')).toBe('edit')
+ );
+ expect(mocks.updatePipelineTeamShare).toHaveBeenCalledWith(
+ 'pipeline-1',
+ true
+ );
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Set Team access level NONE' })
+ );
+ await vi.waitFor(() =>
+ expect(control.getAttribute('data-value')).toBe('NONE')
+ );
+ expect(mocks.updatePipelineTeamShare).toHaveBeenCalledWith(
+ 'pipeline-1',
+ false
+ );
+ expect(mocks.blockPermissionsRead).not.toHaveBeenCalled();
+ expect(mocks.getDatabasePermissions).not.toHaveBeenCalled();
+ expect(mocks.updateDatabasePermissions).not.toHaveBeenCalled();
+ expect(mocks.editDocument).not.toHaveBeenCalled();
+ }
+ );
+
+ it('keeps the current grant when a pipeline sharing request fails', async () => {
+ mocks.updatePipelineTeamShare.mockResolvedValue(
+ err([{ code: 'FORBIDDEN', message: 'Not the owner' }])
+ );
+ mountPipeline();
+ const control = await screen.findByRole('group', {
+ name: 'Team access level',
+ });
+ fireEvent.click(
+ screen.getByRole('button', { name: 'Set Team access level edit' })
+ );
+ const { toast } = await import('@core/component/Toast/Toast');
+ await vi.waitFor(() =>
+ expect(toast.alert).toHaveBeenCalledWith('Failed to change team access', {
+ subtext: 'Please try again',
+ })
+ );
+ expect(control.getAttribute('data-value')).toBe('NONE');
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it('lets a non-owner copy the pipeline link without changing access', () => {
+ mountPipeline(SOMEONE_ELSE);
+ expect(
+ screen.queryByRole('group', { name: 'Team access level' })
+ ).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Select channel' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Copy Link' }));
+ expect(mocks.copyLink).toHaveBeenCalledOnce();
+ expect(mocks.updatePipelineTeamShare).not.toHaveBeenCalled();
+ });
+});
+
it('database sharing reads its block permissions and disables public links', () => {
mocks.blockPermissionsRead.mockReturnValue({
isErr: () => false,
diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
index 3a719c65e4..0d3c20ea9a 100644
--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx
@@ -1,3 +1,7 @@
+import {
+ fetchPipelineSharePermissions,
+ updatePipelineTeamShare,
+} from '@app/features/crm/sharing-adapter';
import { projectRouteId } from '@app/features/projects/core/route';
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { useChannelParticipants } from '@channel/use-channel-participants';
@@ -135,7 +139,8 @@ const isLinkSharingDisabledForItem = (itemType: ShareItemType): boolean =>
itemType === 'project' ||
itemType === 'database' ||
// A form's public link is its audience, set on the form, not a share permission.
- itemType === 'form';
+ itemType === 'form' ||
+ itemType === 'crm_pipeline';
/** Blocks, plus native entities that are shared without one. */
type ShareBlockType = BlockName | BlockAlias | 'initiative';
@@ -156,6 +161,7 @@ export function shareLevelsFor(
}
async function fetchSharePermissions(id: string, itemType: ShareItemType) {
+ if (itemType === 'crm_pipeline') return fetchPipelineSharePermissions(id);
if (itemType === 'agent_session') {
return fetchAgentSessionSharePermissions(id);
}
@@ -184,6 +190,8 @@ const SHARE_LINK_SUBTEXT =
// Only these owners can grant access, so only they may forward. Their links
// don't grant access to recipients either, so copying skips SHARE_LINK_SUBTEXT.
const OWNER_ONLY_SHARE_DESCRIPTIONS: Partial<Record<ShareItemType, string>> = {
+ crm_pipeline:
+ 'Only the owner can change team access. You can copy a link for people who already have access.',
agent_session:
'Only the owner can share access to this session. You can copy a link for people who already have access.',
initiative:
@@ -795,7 +803,8 @@ export function ShareModal(props: ShareModalProps) {
const isBlockContext =
isInBlock() &&
props.itemType !== 'agent_session' &&
- props.itemType !== 'initiative';
+ props.itemType !== 'initiative' &&
+ props.itemType !== 'crm_pipeline';
const [fallbackPermissionsResource, { refetch: refetchFallback }] =
createResource(
() => {
@@ -817,8 +826,9 @@ export function ShareModal(props: ShareModalProps) {
: refetchFallback;
const userId = useUserId();
const canForward = () =>
- !OWNER_ONLY_SHARE_DESCRIPTIONS[props.itemType] ||
- (Boolean(userId()) && props.owner === userId());
+ props.itemType !== 'crm_pipeline' &&
+ (!OWNER_ONLY_SHARE_DESCRIPTIONS[props.itemType] ||
+ (Boolean(userId()) && props.owner === userId()));
const userPermissions = () =>
props.itemType === 'agent_session' && !canForward()
? Permissions.CAN_VIEW
@@ -1180,7 +1190,9 @@ export function ShareModal(props: ShareModalProps) {
getTeamShareScope(sharePermission.teamShareAccessLevel) !== 'NONE';
let result: Result<unknown, ResultError<any>[]>;
- if (props.itemType === 'agent_session') {
+ if (props.itemType === 'crm_pipeline') {
+ result = await updatePipelineTeamShare(props.id, shared);
+ } else if (props.itemType === 'agent_session') {
result = await updateAgentSessionSharePermissions(
props.id,
sharePermission
diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.ts b/apps/web/src/lib/core/component/TopBar/linkShare.ts
index cdeb8c6f87..5d994b22a4 100644
--- a/apps/web/src/lib/core/component/TopBar/linkShare.ts
+++ b/apps/web/src/lib/core/component/TopBar/linkShare.ts
@@ -5,7 +5,7 @@ import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/
export const NO_LINK_SHARE = 'NONE' as const;
-export type ShareItemType = ItemType | 'initiative';
+export type ShareItemType = ItemType | 'initiative' | 'crm_pipeline';
const TEAM_SHAREABLE_ITEM_TYPES: ReadonlySet<ShareItemType> =
new Set<ShareItemType>([
@@ -15,6 +15,7 @@ const TEAM_SHAREABLE_ITEM_TYPES: ReadonlySet<ShareItemType> =
'project',
'agent_session',
'initiative',
+ 'crm_pipeline',
]);
export function isTeamShareSupportedForItem(itemType: ShareItemType): boolean {
@@ -32,6 +33,8 @@ export function getShareItemNoun(itemType: ShareItemType): string {
return 'folder';
case 'initiative':
return 'project';
+ case 'crm_pipeline':
+ return 'pipeline';
default:
return itemType;
}
@@ -115,6 +118,10 @@ export const CALL_TEAM_SHARE_SCOPE_OPTIONS = (
}));
export function teamShareScopeOptionsForItem(itemType: ShareItemType) {
+ if (itemType === 'crm_pipeline')
+ return TEAM_SHARE_SCOPE_OPTIONS.filter(
+ (option) => option.value === 'NONE' || option.value === 'edit'
+ );
return itemType === 'call'
? CALL_TEAM_SHARE_SCOPE_OPTIONS
: TEAM_SHARE_SCOPE_OPTIONS;
diff --git a/apps/web/src/lib/queries/notification/notification-soup.ts b/apps/web/src/lib/queries/notification/notification-soup.ts
index 3f7b877ea3..d7fbc55e15 100644
--- a/apps/web/src/lib/queries/notification/notification-soup.ts
+++ b/apps/web/src/lib/queries/notification/notification-soup.ts
@@ -32,6 +32,7 @@ function notificationEntityTypeToSoupTag(
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'skill',
'database',
'database_row',
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.ts
index 206f11cdf2..0d2909a520 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/entityType.ts
@@ -26,6 +26,7 @@ export const EntityType = {
static_file: 'static_file',
crm_company: 'crm_company',
crm_contact: 'crm_contact',
+ crm_pipeline: 'crm_pipeline',
reminder: 'reminder',
skill: 'skill',
agent_session: 'agent_session',
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index 450f6e65e9..cb22dea994 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -3152,6 +3152,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
diff --git a/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.ts b/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.ts
index 445bd4565e..c6e096b1b8 100644
--- a/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.ts
+++ b/apps/web/src/lib/service-clients/service-connection/generated/schemas/entityType.ts
@@ -26,6 +26,7 @@ export const EntityType = {
static_file: 'static_file',
crm_company: 'crm_company',
crm_contact: 'crm_contact',
+ crm_pipeline: 'crm_pipeline',
reminder: 'reminder',
skill: 'skill',
agent_session: 'agent_session',
diff --git a/apps/web/src/lib/service-clients/service-connection/openapi.json b/apps/web/src/lib/service-clients/service-connection/openapi.json
index 2468b35a51..190bdb67eb 100644
--- a/apps/web/src/lib/service-clients/service-connection/openapi.json
+++ b/apps/web/src/lib/service-clients/service-connection/openapi.json
@@ -259,6 +259,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.ts
index 85d3c9c1fe..a2b0912165 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/entityType.ts
@@ -26,6 +26,7 @@ export const EntityType = {
static_file: 'static_file',
crm_company: 'crm_company',
crm_contact: 'crm_contact',
+ crm_pipeline: 'crm_pipeline',
reminder: 'reminder',
skill: 'skill',
agent_session: 'agent_session',
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
index d9cf475672..c9f1205d93 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts
@@ -58,6 +58,7 @@ export const unsubscribeItemParams = zod.object({
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -102,6 +103,7 @@ export const removeUnsubscribeItemParams = zod.object({
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -211,6 +213,7 @@ export const listTypedNotificationsResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -2106,6 +2109,7 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -3995,6 +3999,7 @@ export const getTypedNotificationsByEventItemIdResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -5889,6 +5894,7 @@ export const getTypedNotificationByIdResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.json
index 839870ca93..e1f34e9b3d 100644
--- a/apps/web/src/lib/service-clients/service-notification/openapi.json
+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json
@@ -1758,6 +1758,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index d803a5e767..91c9b12ed3 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -13,6 +13,7 @@ import {
SYNC_PERMISSION_TOKEN_DSS_HOST,
SYNC_SERVICE_HOSTS,
} from '@core/constant/servers';
+import type { DatabaseOp } from '@core/database-sql/generated/types';
import type { FetchError } from '@core/service';
import { cache } from '@core/util/cache';
import {
@@ -28,6 +29,8 @@ import type { IDocumentStorageServiceFile } from '@filesystem/file';
import type { SerializedEditorState } from 'lexical';
import { err, ok, type Result } from 'neverthrow';
import type { ApiChannelListPage } from './channel-list-types';
+import { fetchDatabaseOps } from './databases';
+import type { AccessiblePipeline as PipelineResponse } from './generated/schemas/accessiblePipeline';
import type { AccessLevel } from './generated/schemas/accessLevel';
import type { AddFavoriteRequest } from './generated/schemas/addFavoriteRequest';
import type { AddParticipantsRequest } from './generated/schemas/addParticipantsRequest';
@@ -159,8 +162,11 @@ import type { SlackCreateRequest } from './generated/schemas/slackCreateRequest'
import type { SlackRegisterRequest } from './generated/schemas/slackRegisterRequest';
import type { SmartTagPreview } from './generated/schemas/smartTagPreview';
import type { SoupPage } from './generated/schemas/soupPage';
+import type { StorageRows } from './generated/schemas/storageRows';
+import type { StorageRowsQuery } from './generated/schemas/storageRowsQuery';
import type { StoredGithubPullRequest } from './generated/schemas/storedGithubPullRequest';
import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';
+import type { TableDetail } from './generated/schemas/tableDetail';
import type { TeamOutOfOfficeResponse } from './generated/schemas/teamOutOfOfficeResponse';
import type { TypedSuccessResponse } from './generated/schemas/typedSuccessResponse';
import type { UpdateAgentRequest } from './generated/schemas/updateAgentRequest';
@@ -396,6 +402,48 @@ export const DOCUMENT_NAME_TOO_LONG_CODE = 'DOCUMENT_NAME_TOO_LONG' as const;
type SlackImportJobArgs = { jobId: JobId; signal?: AbortSignal };
export const storageServiceClient = {
+ listCrmPipelines: () =>
+ dssFetch<PipelineResponse[]>('/crm/pipelines', { method: 'GET' }),
+ getCrmPipeline: (id: string) =>
+ dssFetch<PipelineResponse>(`/crm/pipelines/${id}`, { method: 'GET' }),
+ getCrmPipelineTable: (id: string) =>
+ dssFetch<TableDetail>(`/crm/pipelines/${id}/table`, { method: 'GET' }),
+ getCrmPipelineRows: (id: string, after?: string) =>
+ dssFetch<StorageRows>(
+ `/crm/pipelines/${id}/rows${after ? `?after=${encodeURIComponent(after)}` : ''}`,
+ { method: 'GET' }
+ ),
+ queryCrmPipelineRows: (id: string, request: StorageRowsQuery) =>
+ dssFetch<StorageRows>(`/crm/pipelines/${id}/rows`, {
+ method: 'POST',
+ body: JSON.stringify(request),
+ }),
+ applyCrmPipelineOps: (
+ id: string,
+ request: { ops: DatabaseOp[]; baseVersions?: Record<string, number> }
+ ) => fetchDatabaseOps(`/crm/pipelines/${id}/ops`, request),
+ createCrmPipeline: (
+ input: Pick<PipelineResponse, 'name' | 'recordType' | 'sharing'>
+ ) =>
+ dssFetch<PipelineResponse>('/crm/pipelines', {
+ method: 'POST',
+ body: JSON.stringify(input),
+ }),
+ renameCrmPipeline: (id: string, name: string) =>
+ dssFetch(`/crm/pipelines/${id}/name`, {
+ method: 'PUT',
+ body: JSON.stringify({ name }),
+ }),
+ shareCrmPipeline: (id: string, sharing: PipelineResponse['sharing']) =>
+ dssFetch(`/crm/pipelines/${id}/sharing`, {
+ method: 'PUT',
+ body: JSON.stringify({ sharing }),
+ }),
+ trashCrmPipeline: (id: string) =>
+ dssFetch(`/crm/pipelines/${id}/trash`, {
+ method: 'PUT',
+ body: JSON.stringify({ trashed: true }),
+ }),
/** Macro Databases — see `./databases.ts`. */
databases: databasesClient,
/** Macro Forms — see `./forms.ts`. */
diff --git a/apps/web/src/lib/service-clients/service-storage/databases.ts b/apps/web/src/lib/service-clients/service-storage/databases.ts
index 4780bc9703..8a4145bfd9 100644
--- a/apps/web/src/lib/service-clients/service-storage/databases.ts
+++ b/apps/web/src/lib/service-clients/service-storage/databases.ts
@@ -263,24 +263,7 @@ export const databasesClient = {
/** The engine's ops: the generated `ApplyOpsRequest` drops `null` from optional fields. */
request: { ops: DatabaseOp[]; baseVersions?: Record<string, number> };
}): ResultAsync<ApplyOpsResponse, DatabaseOpsError[]> {
- return new ResultAsync(
- fetchWithToken<ApplyOpsResponse, 'INVALID_OP'>(
- `${documentStorageHost}/databases/${id}/ops`,
- {
- method: 'POST',
- body: JSON.stringify(request),
- errorResponseHandler: async (response): Promise<DatabaseOpsError> => {
- const { body, message } = await errorBody(response);
- const code = statusCode(response.status, 'INVALID_OP');
- return {
- code,
- message,
- refusal: code === 'INVALID_OP' ? opRefusalOf(body) : null,
- };
- },
- }
- )
- ).mapErr((errors) => errors.map(withRefusal));
+ return fetchDatabaseOps(`/databases/${id}/ops`, request);
},
/**
@@ -325,3 +308,28 @@ export const databasesClient = {
});
},
};
+
+/** Typed database operations can be hosted by another entity’s authorized endpoint. */
+export function fetchDatabaseOps(
+ path: string,
+ request: { ops: DatabaseOp[]; baseVersions?: Record<string, number> }
+): ResultAsync<ApplyOpsResponse, DatabaseOpsError[]> {
+ return new ResultAsync(
+ fetchWithToken<ApplyOpsResponse, 'INVALID_OP'>(
+ `${documentStorageHost}${path}`,
+ {
+ method: 'POST',
+ body: JSON.stringify(request),
+ errorResponseHandler: async (response): Promise<DatabaseOpsError> => {
+ const { body, message } = await errorBody(response);
+ const code = statusCode(response.status, 'INVALID_OP');
+ return {
+ code,
+ message,
+ refusal: code === 'INVALID_OP' ? opRefusalOf(body) : null,
+ };
+ },
+ }
+ )
+ ).mapErr((errors) => errors.map(withRefusal));
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/accessiblePipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/accessiblePipeline.ts
new file mode 100644
index 0000000000..34f798e2d7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/accessiblePipeline.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { AccessiblePipelineAllOf } from './accessiblePipelineAllOf';
+import type { Pipeline } from './pipeline';
+
+/**
+ * Metadata together with the caller's effective grant.
+ */
+export type AccessiblePipeline = Pipeline & AccessiblePipelineAllOf;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/accessiblePipelineAllOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/accessiblePipelineAllOf.ts
new file mode 100644
index 0000000000..5c14f39804
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/accessiblePipelineAllOf.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AccessLevel } from './accessLevel';
+
+export type AccessiblePipelineAllOf = {
+ /** Highest effective access. */
+ grant: AccessLevel;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts
index fbcadbbca9..5fa4061822 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/addFavoriteRequestEntityType.ts
@@ -23,6 +23,7 @@ export type AddFavoriteRequestEntityType =
| 'static_file'
| 'crm_company'
| 'crm_contact'
+ | 'crm_pipeline'
| 'reminder'
| 'skill'
| 'agent_session'
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/appliedOps.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/appliedOps.ts
new file mode 100644
index 0000000000..2ceef641dd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/appliedOps.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CommittedChange } from './committedChange';
+import type { OpResult } from './opResult';
+
+/**
+ * What a committed batch answers: a result per op, and the journal's change
+for each table version it produced.
+ */
+export interface AppliedOps {
+ /** The journal's changes. */
+ changes: CommittedChange[];
+ /** One result per op, in order. */
+ results: OpResult[];
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponseParentEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponseParentEntityType.ts
index d367dc75ef..86c3839bcd 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponseParentEntityType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/collabSurfaceResponseParentEntityType.ts
@@ -23,6 +23,7 @@ export type CollabSurfaceResponseParentEntityType =
| 'static_file'
| 'crm_company'
| 'crm_contact'
+ | 'crm_pipeline'
| 'reminder'
| 'skill'
| 'agent_session'
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipeline.ts
new file mode 100644
index 0000000000..1dd2212438
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createPipeline.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PipelineRecordType } from './pipelineRecordType';
+import type { PipelineSharing } from './pipelineSharing';
+
+/**
+ * Request to create an empty pipeline with the standard CRM columns.
+ */
+export interface CreatePipeline {
+ /** Pipeline name. */
+ name: string;
+ /** Company or contact entries. */
+ recordType: PipelineRecordType;
+ /** Defaults to private. */
+ sharing?: PipelineSharing;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequestParentEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequestParentEntityType.ts
index cb603e70f2..fa000ac1c3 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequestParentEntityType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/ensureCollabSurfaceRequestParentEntityType.ts
@@ -23,6 +23,7 @@ export type EnsureCollabSurfaceRequestParentEntityType =
| 'static_file'
| 'crm_company'
| 'crm_contact'
+ | 'crm_pipeline'
| 'reminder'
| 'skill'
| 'agent_session'
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts
index 7efa7c905e..8c954a2b3f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityRefEntityType.ts
@@ -23,6 +23,7 @@ export type FavoriteEntityRefEntityType =
| 'static_file'
| 'crm_company'
| 'crm_contact'
+ | 'crm_pipeline'
| 'reminder'
| 'skill'
| 'agent_session'
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.ts
index d2442e7ab3..45d114b3c6 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/favoriteEntityType.ts
@@ -23,6 +23,7 @@ export type FavoriteEntityType =
| 'static_file'
| 'crm_company'
| 'crm_contact'
+ | 'crm_pipeline'
| 'reminder'
| 'skill'
| 'agent_session'
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/getCrmPipelineRowsParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/getCrmPipelineRowsParams.ts
new file mode 100644
index 0000000000..62ce3e221e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/getCrmPipelineRowsParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type GetCrmPipelineRowsParams = {
+ /**
+ * Continue after this row identity.
+ */
+ after?: string | null;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 919352e392..9957a13af0 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -5,6 +5,8 @@
* OpenAPI spec version: 0.1.0
*/
+export * from './accessiblePipeline';
+export * from './accessiblePipelineAllOf';
export * from './accessLevel';
export * from './activeCallSummary';
export * from './activeCallsResponse';
@@ -120,6 +122,7 @@ export * from './apiGroupMetaNextCursor';
export * from './apiParticipantListRole';
export * from './apiParticipantRole';
export * from './apiPropertyEntityType';
+export * from './appliedOps';
export * from './applyOpsRequest';
export * from './applyOpsRequestBaseVersions';
export * from './applyOpsResponse';
@@ -532,6 +535,7 @@ export * from './createPairingRequest';
export * from './createPairingRequestAllowPermissionBypass';
export * from './createPairingRequestHost';
export * from './createPairingRequestScope';
+export * from './createPipeline';
export * from './createProjectRequest';
export * from './createProjectRequestProjectParentId';
export * from './createProjectResponse';
@@ -920,6 +924,7 @@ export * from './getChannelsParams';
export * from './getContactByEmailParams';
export * from './getContactByEmailResponse';
export * from './getContactByEmailResponseContact';
+export * from './getCrmPipelineRowsParams';
export * from './getDatabaseTableChangesParams';
export * from './getDocumentKeyResponse';
export * from './getDocumentKeyResponseData';
@@ -1235,6 +1240,8 @@ export * from './newView';
export * from './notificationFilters';
export * from './notificationState';
export * from './numberOperator';
+export * from './opBatch';
+export * from './opBatchBaseVersions';
export * from './opRefusalResponse';
export * from './opRefusalResponseColumn';
export * from './opRefusalResponseRow';
@@ -1313,6 +1320,10 @@ export * from './pdfPlaceableCommentAnchorRootId';
export * from './pendingClaimResponse';
export * from './pinnedItem';
export * from './pinRequest';
+export * from './pipeline';
+export * from './pipelineRecordType';
+export * from './pipelineSharing';
+export * from './pipelineTrashedAt';
export * from './postActivityRequest';
export * from './postGroupedSoupAstGroupPageRequest';
export * from './postGroupedSoupAstInitialRequest';
@@ -1414,6 +1425,7 @@ export * from './registerUploads';
export * from './removeParticipantsRequest';
export * from './renameChannelLabelRequest';
export * from './renameChannelLabelRequestRule';
+export * from './renamePipeline';
export * from './reorderFavoritesRequest';
export * from './reorderPinRequest';
export * from './replaceCrmStagesRequest';
@@ -1440,6 +1452,7 @@ export * from './rowHistoryEntryActor';
export * from './rowHistoryEntryAfter';
export * from './rowHistoryEntryBefore';
export * from './rowHistoryResponse';
+export * from './rowId';
export * from './rowsChange';
export * from './rowsChangeOneOf';
export * from './rowsChangeOneOfFive';
@@ -1531,6 +1544,7 @@ export * from './sharePermissionV2ChannelSharePermissions';
export * from './sharePermissionV2LinkShare';
export * from './sharePermissionV2LinkShareAccessLevel';
export * from './sharePermissionV2TeamShareAccessLevel';
+export * from './sharePipeline';
export * from './shortIdResponse';
export * from './simpleMention';
export * from './skippedCell';
@@ -1743,6 +1757,13 @@ export * from './starterDatabaseDatabaseId';
export * from './starterDatabaseTableId';
export * from './starterDatabaseViewId';
export * from './starterDocumentsResponse';
+export * from './storageRow';
+export * from './storageRowCells';
+export * from './storageRows';
+export * from './storageRowsNext';
+export * from './storageRowsQuery';
+export * from './storageRowsQueryAfter';
+export * from './storageRowsQueryRowIds';
export * from './storedGithubPullRequest';
export * from './storedGithubPullRequestAdditions';
export * from './storedGithubPullRequestAuthorGithubUserId';
@@ -1848,6 +1869,7 @@ export * from './transcriptSegmentRequestDiarizedSpeakerId';
export * from './transcriptSegmentRequestEmbedding';
export * from './transcriptSegmentRequestEndedAt';
export * from './transcriptSegmentRequestStreamStartedAt';
+export * from './trashPipeline';
export * from './turnEndedMetadata';
export * from './turnEndedMetadataActor';
export * from './turnEndedMetadataAnnouncementMessageId';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesEntityTypeItem.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesEntityTypeItem.ts
index ed7b6bb2ea..9066ed7db5 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesEntityTypeItem.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesEntityTypeItem.ts
@@ -27,6 +27,7 @@ export const ListFavoritesEntityTypeItem = {
static_file: 'static_file',
crm_company: 'crm_company',
crm_contact: 'crm_contact',
+ crm_pipeline: 'crm_pipeline',
reminder: 'reminder',
skill: 'skill',
agent_session: 'agent_session',
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/opBatch.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/opBatch.ts
new file mode 100644
index 0000000000..f30db89b37
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/opBatch.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { DatabaseOp } from './databaseOp';
+import type { OpBatchBaseVersions } from './opBatchBaseVersions';
+
+/**
+ * A batch of ops for one database and the versions its tables must be at.
+ */
+export interface OpBatch {
+ /** The version each named table must still be at; the batch is refused
+as a conflict if one moved. Without one, ops are last-write-wins. */
+ baseVersions?: OpBatchBaseVersions;
+ /** The ops, in the order they apply. */
+ ops: DatabaseOp[];
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/opBatchBaseVersions.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/opBatchBaseVersions.ts
new file mode 100644
index 0000000000..975a54e9b4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/opBatchBaseVersions.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { TableVersion } from './tableVersion';
+
+/**
+ * The version each named table must still be at; the batch is refused
+as a conflict if one moved. Without one, ops are last-write-wins.
+ */
+export type OpBatchBaseVersions = { [key: string]: TableVersion };
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipeline.ts
new file mode 100644
index 0000000000..f50263e78a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipeline.ts
@@ -0,0 +1,37 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PipelineRecordType } from './pipelineRecordType';
+import type { PipelineSharing } from './pipelineSharing';
+import type { PipelineTrashedAt } from './pipelineTrashedAt';
+
+/**
+ * Pipeline metadata; table schema and data are read through the database service.
+ */
+export interface Pipeline {
+ /** Creation time. */
+ createdAt: string;
+ /** Dedicated backing database. */
+ databaseId: string;
+ /** Entity identity, used with `CrmPipeline` access receipts. */
+ id: string;
+ /** Pipeline display name. */
+ name: string;
+ /** Protected primary column. */
+ primaryColumnId: string;
+ /** Kind of the primary reference. */
+ recordType: PipelineRecordType;
+ /** Whether the pipeline has a team grant. */
+ sharing: PipelineSharing;
+ /** Table of entries. */
+ tableId: string;
+ /** Team owning the pipeline; references retain their own access controls. */
+ teamId: string;
+ /** Trashed pipelines are omitted from navigation. */
+ trashedAt: PipelineTrashedAt;
+ /** Owning user; sharing never changes ownership. */
+ userId: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineRecordType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineRecordType.ts
new file mode 100644
index 0000000000..ad89fd3632
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineRecordType.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Which CRM entity each row references. Fixed when a pipeline is created.
+ */
+export type PipelineRecordType =
+ (typeof PipelineRecordType)[keyof typeof PipelineRecordType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const PipelineRecordType = {
+ company: 'company',
+ contact: 'contact',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineSharing.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineSharing.ts
new file mode 100644
index 0000000000..ff94485663
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineSharing.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Initial sharing, or the desired team grant. Individual ownership is preserved.
+ */
+export type PipelineSharing =
+ (typeof PipelineSharing)[keyof typeof PipelineSharing];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const PipelineSharing = {
+ private: 'private',
+ team: 'team',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineTrashedAt.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineTrashedAt.ts
new file mode 100644
index 0000000000..d964f3705f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/pipelineTrashedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Trashed pipelines are omitted from navigation.
+ */
+export type PipelineTrashedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/renamePipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renamePipeline.ts
new file mode 100644
index 0000000000..27a3867da7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renamePipeline.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Rename input.
+ */
+export interface RenamePipeline {
+ /** New display name. */
+ name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/rowId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/rowId.ts
new file mode 100644
index 0000000000..67253f9248
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/rowId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Identifier of a row.
+ */
+export type RowId = string;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePipeline.ts
new file mode 100644
index 0000000000..d7ac232c70
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePipeline.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PipelineSharing } from './pipelineSharing';
+
+/**
+ * Sharing input.
+ */
+export interface SharePipeline {
+ /** Desired team grant. */
+ sharing: PipelineSharing;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRow.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRow.ts
new file mode 100644
index 0000000000..c85725f663
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRow.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { RowId } from './rowId';
+import type { StorageRowCells } from './storageRowCells';
+
+/**
+ * One storage row, with cells keyed by column placement.
+ */
+export interface StorageRow {
+ /** Populated cells. */
+ cells: StorageRowCells;
+ /** Row identity, independent of any referenced entity. */
+ rowId: RowId;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowCells.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowCells.ts
new file mode 100644
index 0000000000..adfb308df5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowCells.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PropertyValue } from './propertyValue';
+
+/**
+ * Populated cells.
+ */
+export type StorageRowCells = { [key: string]: PropertyValue };
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRows.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRows.ts
new file mode 100644
index 0000000000..cfcb057f7c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRows.ts
@@ -0,0 +1,21 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { StorageRow } from './storageRow';
+import type { StorageRowsNext } from './storageRowsNext';
+import type { TableVersion } from './tableVersion';
+
+/**
+ * A bounded page of rows at a table version.
+ */
+export interface StorageRows {
+ next?: StorageRowsNext;
+ /** Rows in the requested view's order. */
+ rows: StorageRow[];
+ /** Table version when the read began. */
+ version: TableVersion;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsNext.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsNext.ts
new file mode 100644
index 0000000000..11a7f1830c
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsNext.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { RowId } from './rowId';
+
+export type StorageRowsNext = null | RowId;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQuery.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQuery.ts
new file mode 100644
index 0000000000..19a95a88af
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQuery.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { StorageRowsQueryAfter } from './storageRowsQueryAfter';
+import type { StorageRowsQueryRowIds } from './storageRowsQueryRowIds';
+import type { ViewQuery } from './viewQuery';
+
+/**
+ * A query over one authorized storage table.
+ */
+export interface StorageRowsQuery {
+ after?: StorageRowsQueryAfter;
+ /** The common database filter and sort semantics. */
+ query?: ViewQuery;
+ /** Read these retained rows regardless of the active filter. */
+ rowIds?: StorageRowsQueryRowIds;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQueryAfter.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQueryAfter.ts
new file mode 100644
index 0000000000..dab7dd1617
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQueryAfter.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { RowId } from './rowId';
+
+export type StorageRowsQueryAfter = null | RowId;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQueryRowIds.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQueryRowIds.ts
new file mode 100644
index 0000000000..cd51cb6951
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRowsQueryRowIds.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { RowId } from './rowId';
+
+/**
+ * Read these retained rows regardless of the active filter.
+ */
+export type StorageRowsQueryRowIds = RowId[] | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/trashPipeline.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/trashPipeline.ts
new file mode 100644
index 0000000000..0d7b54e302
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/trashPipeline.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Trash/restore input.
+ */
+export interface TrashPipeline {
+ /** True to trash; false to restore. */
+ trashed: boolean;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index fbc0ff882a..a906069f48 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -3543,6 +3543,7 @@ export const getCollabSurfaceResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -3598,6 +3599,7 @@ export const ensureCollabSurfaceBody = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -3634,6 +3636,7 @@ export const ensureCollabSurfaceResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -4423,6 +4426,4301 @@ export const setCrmContactNameBody = zod
})
.describe('Request body for `PUT \/contacts\/{contact_id}\/name`.');
+/**
+ * @summary List the caller's live pipelines in their CRM.
+ */
+export const listCrmPipelinesResponseItem = zod
+ .object({
+ createdAt: zod.iso.datetime({}).describe('Creation time.'),
+ databaseId: zod.uuid().describe('Dedicated backing database.'),
+ id: zod
+ .uuid()
+ .describe('Entity identity, used with `CrmPipeline` access receipts.'),
+ name: zod.string().describe('Pipeline display name.'),
+ primaryColumnId: zod.uuid().describe('Protected primary column.'),
+ recordType: zod
+ .enum(['company', 'contact'])
+ .describe(
+ 'Which CRM entity each row references. Fixed when a pipeline is created.'
+ ),
+ sharing: zod
+ .enum(['private', 'team'])
+ .describe(
+ 'Initial sharing, or the desired team grant. Individual ownership is preserved.'
+ ),
+ tableId: zod.uuid().describe('Table of entries.'),
+ teamId: zod
+ .uuid()
+ .describe(
+ 'Team owning the pipeline; references retain their own access controls.'
+ ),
+ trashedAt: zod.iso
+ .datetime({})
+ .nullable()
+ .describe('Trashed pipelines are omitted from navigation.'),
+ userId: zod
+ .string()
+ .describe('Owning user; sharing never changes ownership.'),
+ })
+ .describe(
+ 'Pipeline metadata; table schema and data are read through the database service.'
+ )
+ .and(
+ zod.object({
+ grant: zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ })
+ )
+ .describe("Metadata together with the caller's effective grant.");
+export const listCrmPipelinesResponse = zod.array(listCrmPipelinesResponseItem);
+
+/**
+ * @summary Create a private or team-shared pipeline.
+ */
+export const createCrmPipelineBody = zod
+ .object({
+ name: zod.string().describe('Pipeline name.'),
+ recordType: zod
+ .enum(['company', 'contact'])
+ .describe(
+ 'Which CRM entity each row references. Fixed when a pipeline is created.'
+ ),
+ sharing: zod
+ .enum(['private', 'team'])
+ .optional()
+ .describe(
+ 'Initial sharing, or the desired team grant. Individual ownership is preserved.'
+ ),
+ })
+ .describe(
+ 'Request to create an empty pipeline with the standard CRM columns.'
+ );
+
+export const createCrmPipelineResponse = zod
+ .object({
+ createdAt: zod.iso.datetime({}).describe('Creation time.'),
+ databaseId: zod.uuid().describe('Dedicated backing database.'),
+ id: zod
+ .uuid()
+ .describe('Entity identity, used with `CrmPipeline` access receipts.'),
+ name: zod.string().describe('Pipeline display name.'),
+ primaryColumnId: zod.uuid().describe('Protected primary column.'),
+ recordType: zod
+ .enum(['company', 'contact'])
+ .describe(
+ 'Which CRM entity each row references. Fixed when a pipeline is created.'
+ ),
+ sharing: zod
+ .enum(['private', 'team'])
+ .describe(
+ 'Initial sharing, or the desired team grant. Individual ownership is preserved.'
+ ),
+ tableId: zod.uuid().describe('Table of entries.'),
+ teamId: zod
+ .uuid()
+ .describe(
+ 'Team owning the pipeline; references retain their own access controls.'
+ ),
+ trashedAt: zod.iso
+ .datetime({})
+ .nullable()
+ .describe('Trashed pipelines are omitted from navigation.'),
+ userId: zod
+ .string()
+ .describe('Owning user; sharing never changes ownership.'),
+ })
+ .describe(
+ 'Pipeline metadata; table schema and data are read through the database service.'
+ )
+ .and(
+ zod.object({
+ grant: zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ })
+ )
+ .describe("Metadata together with the caller's effective grant.");
+
+/**
+ * @summary Read one pipeline by its entity identity.
+ */
+export const getCrmPipelineParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const getCrmPipelineResponse = zod
+ .object({
+ createdAt: zod.iso.datetime({}).describe('Creation time.'),
+ databaseId: zod.uuid().describe('Dedicated backing database.'),
+ id: zod
+ .uuid()
+ .describe('Entity identity, used with `CrmPipeline` access receipts.'),
+ name: zod.string().describe('Pipeline display name.'),
+ primaryColumnId: zod.uuid().describe('Protected primary column.'),
+ recordType: zod
+ .enum(['company', 'contact'])
+ .describe(
+ 'Which CRM entity each row references. Fixed when a pipeline is created.'
+ ),
+ sharing: zod
+ .enum(['private', 'team'])
+ .describe(
+ 'Initial sharing, or the desired team grant. Individual ownership is preserved.'
+ ),
+ tableId: zod.uuid().describe('Table of entries.'),
+ teamId: zod
+ .uuid()
+ .describe(
+ 'Team owning the pipeline; references retain their own access controls.'
+ ),
+ trashedAt: zod.iso
+ .datetime({})
+ .nullable()
+ .describe('Trashed pipelines are omitted from navigation.'),
+ userId: zod
+ .string()
+ .describe('Owning user; sharing never changes ownership.'),
+ })
+ .describe(
+ 'Pipeline metadata; table schema and data are read through the database service.'
+ )
+ .and(
+ zod.object({
+ grant: zod
+ .enum(['view', 'comment', 'edit', 'owner'])
+ .describe('Ordered from least to most access top -> bottom'),
+ })
+ )
+ .describe("Metadata together with the caller's effective grant.");
+
+/**
+ * @summary Rename a pipeline.
+ */
+export const renameCrmPipelineParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const renameCrmPipelineBody = zod
+ .object({
+ name: zod.string().describe('New display name.'),
+ })
+ .describe('Rename input.');
+
+/**
+ * @summary Edit pipeline schema or records with the common typed operations.
+ */
+export const applyCrmPipelineOpsParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const applyCrmPipelineOpsBodyOpsItemChangeViewLayoutColumnsItemWidthMin = 0;
+
+export const applyCrmPipelineOpsBodyOpsItemChangeLayoutColumnsItemWidthMin = 0;
+
+export const applyCrmPipelineOpsBody = zod
+ .object({
+ baseVersions: zod
+ .record(
+ zod.string(),
+ zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ )
+ )
+ .optional()
+ .describe(
+ 'The version each named table must still be at; the batch is refused\nas a conflict if one moved. Without one, ops are last-write-wins.'
+ ),
+ ops: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['create']),
+ name: zod
+ .string()
+ .describe(
+ 'Its name, unique within the database ignoring case.'
+ ),
+ })
+ .describe(
+ "Add the table, after the database's other tables. It starts with no\ncolumns and no rows."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['rename']),
+ name: zod
+ .string()
+ .describe(
+ 'Its new name, unique within the database ignoring case.'
+ ),
+ previousName: zod
+ .string()
+ .optional()
+ .describe(
+ 'The name the caller saw. Given, the rename is refused if the\ntable goes by another one now, so a concurrent rename is not\noverwritten.'
+ ),
+ })
+ .describe(
+ 'Rename the table. Its id, columns and rows stay.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['delete']),
+ })
+ .describe(
+ "Remove the table with its columns, rows and views. A database keeps\nat least one table, and a table another table's relation points at\nstays until that relation goes."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['reorder_columns']),
+ order: zod
+ .array(zod.uuid())
+ .describe('Its columns, in their new order.'),
+ })
+ .describe(
+ "Set the order of the table's columns: `order` names every one of\nthem once."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['reorder_views']),
+ order: zod
+ .array(zod.uuid())
+ .describe('Its views, in their new order.'),
+ })
+ .describe(
+ "Set the order of the table's views: `order` names every one of them\nonce."
+ ),
+ ])
+ .describe('A change to a table itself.'),
+ kind: zod.enum(['table']),
+ table: zod
+ .uuid()
+ .describe(
+ 'The table; for a creation, its new id, minted by the client, which\nlater ops of the request may name.'
+ ),
+ })
+ .describe(
+ 'A change to a table itself: its creation, name, removal, or the\norder of its columns or views.'
+ ),
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ after: zod
+ .uuid()
+ .optional()
+ .describe(
+ "The column it goes right after; left out, it goes after the\ntable's last column."
+ ),
+ definition: zod
+ .union([
+ zod
+ .object({
+ inferType: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Let the column's first value settle its type: only for a plain\ntext column."
+ ),
+ name: zod
+ .string()
+ .describe(
+ "The column's name, unique within the table ignoring case."
+ ),
+ options: zod
+ .array(
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ 'Its id, minted by the client; later ops of the request may name it.'
+ ),
+ label: zod
+ .string()
+ .describe(
+ "Its label, unique within the column ignoring case. A numeric\nselect's labels are numbers."
+ ),
+ })
+ .describe(
+ 'A select or tag option to create.'
+ )
+ )
+ .optional()
+ .describe(
+ 'For a select or tag column, the options it starts with, in\norder, each under an id the client mints. A select column with\nnone accepts nothing until options are added.'
+ ),
+ source: zod.enum(['new']),
+ type: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['text']),
+ })
+ .describe('Free text.'),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ })
+ .describe('A number.'),
+ zod
+ .object({
+ type: zod.enum(['boolean']),
+ })
+ .describe('A checkbox.'),
+ zod
+ .object({
+ type: zod.enum(['date']),
+ })
+ .describe('A date-time.'),
+ zod
+ .object({
+ type: zod.enum(['link']),
+ })
+ .describe('A URL.'),
+ zod
+ .object({
+ multi: zod
+ .boolean()
+ .describe(
+ 'Whether a cell holds several options.'
+ ),
+ type: zod.enum(['select']),
+ })
+ .describe('Text options.'),
+ zod
+ .object({
+ multi: zod
+ .boolean()
+ .describe(
+ 'Whether a cell holds several options.'
+ ),
+ type: zod.enum(['select_number']),
+ })
+ .describe('Numeric options.'),
+ zod
+ .object({
+ type: zod.enum(['tag']),
+ })
+ .describe(
+ 'Colored labels; always several per cell.'
+ ),
+ zod
+ .object({
+ multi: zod
+ .boolean()
+ .describe(
+ 'Whether a cell holds several references.'
+ ),
+ target: zod
+ .enum([
+ 'USER',
+ 'DOCUMENT',
+ 'TASK',
+ 'COMPANY',
+ 'CONTACT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'PROJECT',
+ 'THREAD',
+ 'CALENDAR_EVENT',
+ 'INITIATIVE',
+ ])
+ .describe(
+ 'A kind of Macro entity a reference column can point at.'
+ ),
+ type: zod.enum(['entity']),
+ })
+ .describe(
+ 'References to Macro entities.'
+ ),
+ zod
+ .object({
+ database: zod
+ .uuid()
+ .describe(
+ 'The database of the related table.'
+ ),
+ table: zod
+ .uuid()
+ .describe('The related table.'),
+ type: zod.enum(['relation']),
+ })
+ .describe('Rows of another table.'),
+ ])
+ .describe('A type a column can have.'),
+ })
+ .describe('A new property the database owns.'),
+ zod
+ .object({
+ property: zod
+ .uuid()
+ .describe("The property's definition."),
+ source: zod.enum(['existing']),
+ })
+ .describe(
+ "An existing property, a person's, a team's or a system one, bound\ninto the table under its own name."
+ ),
+ ])
+ .describe('What a new column holds.'),
+ kind: zod.enum(['create']),
+ })
+ .describe(
+ 'Add the column to the table: a new property the database owns, or an\nexisting one bound into the table.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['rename']),
+ name: zod
+ .string()
+ .describe(
+ 'Its new name, unique within the table ignoring case.'
+ ),
+ previousName: zod
+ .string()
+ .optional()
+ .describe(
+ 'The name the caller saw. Given, the rename is refused if the\ncolumn goes by another one now.'
+ ),
+ })
+ .describe(
+ 'Rename the column. Its id, type and cells stay; SQL names it by its\nnew name.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['change_type']),
+ to: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['text']),
+ })
+ .describe('Free text.'),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ })
+ .describe('A number.'),
+ zod
+ .object({
+ type: zod.enum(['boolean']),
+ })
+ .describe('A checkbox.'),
+ zod
+ .object({
+ type: zod.enum(['date']),
+ })
+ .describe('A date-time.'),
+ zod
+ .object({
+ type: zod.enum(['link']),
+ })
+ .describe('A URL.'),
+ zod
+ .object({
+ multi: zod
+ .boolean()
+ .describe(
+ 'Whether a cell holds several options.'
+ ),
+ type: zod.enum(['select']),
+ })
+ .describe('Text options.'),
+ zod
+ .object({
+ multi: zod
+ .boolean()
+ .describe(
+ 'Whether a cell holds several options.'
+ ),
+ type: zod.enum(['select_number']),
+ })
+ .describe('Numeric options.'),
+ zod
+ .object({
+ type: zod.enum(['tag']),
+ })
+ .describe(
+ 'Colored labels; always several per cell.'
+ ),
+ zod
+ .object({
+ multi: zod
+ .boolean()
+ .describe(
+ 'Whether a cell holds several references.'
+ ),
+ target: zod
+ .enum([
+ 'USER',
+ 'DOCUMENT',
+ 'TASK',
+ 'COMPANY',
+ 'CONTACT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'PROJECT',
+ 'THREAD',
+ 'CALENDAR_EVENT',
+ 'INITIATIVE',
+ ])
+ .describe(
+ 'A kind of Macro entity a reference column can point at.'
+ ),
+ type: zod.enum(['entity']),
+ })
+ .describe('References to Macro entities.'),
+ zod
+ .object({
+ database: zod
+ .uuid()
+ .describe(
+ 'The database of the related table.'
+ ),
+ table: zod
+ .uuid()
+ .describe('The related table.'),
+ type: zod.enum(['relation']),
+ })
+ .describe('Rows of another table.'),
+ ])
+ .describe('A type a column can have.'),
+ })
+ .describe(
+ 'Convert the column to another type, converting its cells; its id\nsurvives the change. A value that does not fit refuses the change,\ncounting and quoting the misfits: a type change never empties a\ncell. To keep the original, create a column of the new type and\nwrite it the values that convert.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['delete']),
+ })
+ .describe(
+ 'Remove the column and its cells. The views naming it forget it; a\nboard grouped by it must go or regroup first. A property shared\nbeyond the database stays, unbound here.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['add_options']),
+ options: zod
+ .array(
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ 'Its id, minted by the client; later ops of the request may name it.'
+ ),
+ label: zod
+ .string()
+ .describe(
+ "Its label, unique within the column ignoring case. A numeric\nselect's labels are numbers."
+ ),
+ })
+ .describe('A select or tag option to create.')
+ )
+ .describe(
+ 'The options, each under an id the client mints.'
+ ),
+ })
+ .describe(
+ 'Add options to a select or tag column, after its others. An option\nwhose label the column already has, ignoring case, is left out, so\nre-sending a list adds only what is new. Like\n[`ColumnChange::UpdateOption`], an option of a property shared beyond\nthe database goes everywhere it is used.'
+ ),
+ zod
+ .object({
+ color: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Its new colour, a hex string like `#RRGGBB`, or `null` to clear\nit; left out, it keeps its own. A tag option always has one.'
+ ),
+ kind: zod.enum(['update_option']),
+ label: zod
+ .string()
+ .optional()
+ .describe(
+ 'Its new label; left out, it keeps its own. Labels are unique\nwithin a column, ignoring case.'
+ ),
+ option: zod.uuid().describe('The option.'),
+ })
+ .describe(
+ 'Relabel or recolour one option of a select or tag column. Every cell\nholding it keeps it. A column bound to a property shared outside the\ndatabase changes wherever that property is used, so it takes the\nright to edit that property.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['delete_option']),
+ option: zod.uuid().describe('The option.'),
+ })
+ .describe(
+ 'Remove one option of a select or tag column, and take it out of every\ncell holding it: a single-valued cell is emptied, a multi-valued one\nkeeps its other options. Like [`ColumnChange::UpdateOption`], an\noption of a shared property goes everywhere it is used.'
+ ),
+ ])
+ .describe('A change to one column.'),
+ column: zod
+ .uuid()
+ .describe(
+ 'The column; for a creation, its new id, minted by the client,\nwhich later ops of the request may name.'
+ ),
+ kind: zod.enum(['column']),
+ table: zod.uuid().describe('The table.'),
+ })
+ .describe(
+ 'A change to one column of a table: its creation, name, type, removal\nor options.'
+ ),
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['insert']),
+ rows: zod
+ .array(
+ zod.array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column placement.'),
+ value: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['text']),
+ value: zod
+ .string()
+ .describe('Free text.'),
+ })
+ .describe('Free text.'),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ value: zod
+ .number()
+ .describe('A finite number.'),
+ })
+ .describe('A finite number.'),
+ zod
+ .object({
+ type: zod.enum(['boolean']),
+ value: zod
+ .boolean()
+ .describe('A checkbox.'),
+ })
+ .describe('A checkbox.'),
+ zod
+ .object({
+ type: zod.enum(['date']),
+ value: zod.iso
+ .datetime({})
+ .describe('A date-time.'),
+ })
+ .describe('A date-time.'),
+ zod
+ .object({
+ type: zod.enum(['link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Complete http or https URLs; at most one for a single-valued column.'
+ ),
+ })
+ .describe(
+ 'Complete http or https URLs; at most one for a single-valued column.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['options']),
+ value: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ 'An option the column has.'
+ ),
+ })
+ .describe(
+ 'An option the column has.'
+ ),
+ zod
+ .object({
+ label: zod
+ .string()
+ .describe(
+ "An option's label, matched without regard to case. An unknown label\nis refused."
+ ),
+ })
+ .describe(
+ "An option's label, matched without regard to case. An unknown label\nis refused."
+ ),
+ ])
+ .describe(
+ 'A select option, by its id or by its label.'
+ )
+ )
+ .describe(
+ 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
+ ),
+ })
+ .describe(
+ 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['entities']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entityId: zod
+ .string()
+ .describe(
+ "The entity's id."
+ ),
+ entityType: zod
+ .enum([
+ 'USER',
+ 'DOCUMENT',
+ 'TASK',
+ 'COMPANY',
+ 'CONTACT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'PROJECT',
+ 'THREAD',
+ 'CALENDAR_EVENT',
+ 'INITIATIVE',
+ ])
+ .describe(
+ 'A kind of Macro entity a reference column can point at.'
+ ),
+ })
+ .describe(
+ 'A reference to one Macro entity.'
+ )
+ )
+ .describe(
+ 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
+ ),
+ })
+ .describe(
+ 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['rows']),
+ value: zod
+ .array(zod.uuid())
+ .describe(
+ 'Rows of the table a relation column points at.'
+ ),
+ })
+ .describe(
+ 'Rows of the table a relation column points at.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['clear']),
+ })
+ .describe(
+ 'No value: the cell is emptied.'
+ ),
+ ])
+ .describe(
+ "A cell's value. It must fit the column's type: text for a text column,\noptions of the column for a select, and so on."
+ ),
+ })
+ .describe(
+ 'One cell of a row: which column, and its new value.'
+ )
+ )
+ )
+ .describe(
+ 'One entry per new row: the cells it starts with. Columns left out\nstart empty.'
+ ),
+ })
+ .describe(
+ 'Append rows to the table, in order, each with the cells it starts\nwith.'
+ ),
+ zod
+ .object({
+ changes: zod
+ .union([
+ zod
+ .object({
+ cells: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column placement.'),
+ value: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['text']),
+ value: zod
+ .string()
+ .describe('Free text.'),
+ })
+ .describe('Free text.'),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ value: zod
+ .number()
+ .describe('A finite number.'),
+ })
+ .describe('A finite number.'),
+ zod
+ .object({
+ type: zod.enum(['boolean']),
+ value: zod
+ .boolean()
+ .describe('A checkbox.'),
+ })
+ .describe('A checkbox.'),
+ zod
+ .object({
+ type: zod.enum(['date']),
+ value: zod.iso
+ .datetime({})
+ .describe('A date-time.'),
+ })
+ .describe('A date-time.'),
+ zod
+ .object({
+ type: zod.enum(['link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Complete http or https URLs; at most one for a single-valued column.'
+ ),
+ })
+ .describe(
+ 'Complete http or https URLs; at most one for a single-valued column.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['options']),
+ value: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ 'An option the column has.'
+ ),
+ })
+ .describe(
+ 'An option the column has.'
+ ),
+ zod
+ .object({
+ label: zod
+ .string()
+ .describe(
+ "An option's label, matched without regard to case. An unknown label\nis refused."
+ ),
+ })
+ .describe(
+ "An option's label, matched without regard to case. An unknown label\nis refused."
+ ),
+ ])
+ .describe(
+ 'A select option, by its id or by its label.'
+ )
+ )
+ .describe(
+ 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
+ ),
+ })
+ .describe(
+ 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['entities']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entityId: zod
+ .string()
+ .describe(
+ "The entity's id."
+ ),
+ entityType: zod
+ .enum([
+ 'USER',
+ 'DOCUMENT',
+ 'TASK',
+ 'COMPANY',
+ 'CONTACT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'PROJECT',
+ 'THREAD',
+ 'CALENDAR_EVENT',
+ 'INITIATIVE',
+ ])
+ .describe(
+ 'A kind of Macro entity a reference column can point at.'
+ ),
+ })
+ .describe(
+ 'A reference to one Macro entity.'
+ )
+ )
+ .describe(
+ 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
+ ),
+ })
+ .describe(
+ 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['rows']),
+ value: zod
+ .array(zod.uuid())
+ .describe(
+ 'Rows of the table a relation column points at.'
+ ),
+ })
+ .describe(
+ 'Rows of the table a relation column points at.'
+ ),
+ zod
+ .object({
+ type: zod.enum(['clear']),
+ })
+ .describe(
+ 'No value: the cell is emptied.'
+ ),
+ ])
+ .describe(
+ "A cell's value. It must fit the column's type: text for a text column,\noptions of the column for a select, and so on."
+ ),
+ })
+ .describe(
+ 'One cell of a row: which column, and its new value.'
+ )
+ )
+ .describe('The cells each of them gets.'),
+ kind: zod.enum(['uniform']),
+ rows: zod
+ .array(zod.uuid())
+ .describe('The rows.'),
+ })
+ .describe('The same cells on every row.'),
+ zod
+ .object({
+ kind: zod.enum(['per_row']),
+ rows: zod
+ .array(
+ zod
+ .object({
+ cells: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe(
+ 'The column placement.'
+ ),
+ value: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum([
+ 'text',
+ ]),
+ value: zod
+ .string()
+ .describe(
+ 'Free text.'
+ ),
+ })
+ .describe('Free text.'),
+ zod
+ .object({
+ type: zod.enum([
+ 'number',
+ ]),
+ value: zod
+ .number()
+ .describe(
+ 'A finite number.'
+ ),
+ })
+ .describe(
+ 'A finite number.'
+ ),
+ zod
+ .object({
+ type: zod.enum([
+ 'boolean',
+ ]),
+ value: zod
+ .boolean()
+ .describe(
+ 'A checkbox.'
+ ),
+ })
+ .describe('A checkbox.'),
+ zod
+ .object({
+ type: zod.enum([
+ 'date',
+ ]),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'A date-time.'
+ ),
+ })
+ .describe('A date-time.'),
+ zod
+ .object({
+ type: zod.enum([
+ 'link',
+ ]),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Complete http or https URLs; at most one for a single-valued column.'
+ ),
+ })
+ .describe(
+ 'Complete http or https URLs; at most one for a single-valued column.'
+ ),
+ zod
+ .object({
+ type: zod.enum([
+ 'options',
+ ]),
+ value: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ 'An option the column has.'
+ ),
+ })
+ .describe(
+ 'An option the column has.'
+ ),
+ zod
+ .object({
+ label: zod
+ .string()
+ .describe(
+ "An option's label, matched without regard to case. An unknown label\nis refused."
+ ),
+ })
+ .describe(
+ "An option's label, matched without regard to case. An unknown label\nis refused."
+ ),
+ ])
+ .describe(
+ 'A select option, by its id or by its label.'
+ )
+ )
+ .describe(
+ 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
+ ),
+ })
+ .describe(
+ 'Options of a select or tag column; at most one for a single-valued\ncolumn.'
+ ),
+ zod
+ .object({
+ type: zod.enum([
+ 'entities',
+ ]),
+ value: zod
+ .array(
+ zod
+ .object({
+ entityId: zod
+ .string()
+ .describe(
+ "The entity's id."
+ ),
+ entityType: zod
+ .enum([
+ 'USER',
+ 'DOCUMENT',
+ 'TASK',
+ 'COMPANY',
+ 'CONTACT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'PROJECT',
+ 'THREAD',
+ 'CALENDAR_EVENT',
+ 'INITIATIVE',
+ ])
+ .describe(
+ 'A kind of Macro entity a reference column can point at.'
+ ),
+ })
+ .describe(
+ 'A reference to one Macro entity.'
+ )
+ )
+ .describe(
+ 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
+ ),
+ })
+ .describe(
+ 'References to Macro entities of the kind the column points at; at\nmost one for a single-valued column.'
+ ),
+ zod
+ .object({
+ type: zod.enum([
+ 'rows',
+ ]),
+ value: zod
+ .array(zod.uuid())
+ .describe(
+ 'Rows of the table a relation column points at.'
+ ),
+ })
+ .describe(
+ 'Rows of the table a relation column points at.'
+ ),
+ zod
+ .object({
+ type: zod.enum([
+ 'clear',
+ ]),
+ })
+ .describe(
+ 'No value: the cell is emptied.'
+ ),
+ ])
+ .describe(
+ "A cell's value. It must fit the column's type: text for a text column,\noptions of the column for a select, and so on."
+ ),
+ })
+ .describe(
+ 'One cell of a row: which column, and its new value.'
+ )
+ )
+ .describe('Its new cells.'),
+ row: zod.uuid().describe('The row.'),
+ })
+ .describe(
+ "One row's cells in a [`RowChanges::PerRow`] update."
+ )
+ )
+ .describe(
+ 'The rows and their cells, in order.'
+ ),
+ })
+ .describe('Each row its own cells.'),
+ ])
+ .describe(
+ 'Which rows an update writes, and with what.'
+ ),
+ kind: zod.enum(['update']),
+ })
+ .describe(
+ 'Write cells of existing rows. Last write wins: there is no version\ncheck.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['delete']),
+ rows: zod
+ .array(zod.uuid())
+ .describe('The rows, each named once.'),
+ })
+ .describe('Remove rows and their cells.'),
+ ])
+ .describe("A write to a table's rows."),
+ kind: zod.enum(['rows']),
+ table: zod.uuid().describe('The table the rows belong to.'),
+ })
+ .describe("A write to a table's rows."),
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['create']),
+ view: zod
+ .object({
+ layout: zod
+ .union([
+ zod
+ .object({
+ columns: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column.'),
+ width: zod
+ .number()
+ .min(
+ applyCrmPipelineOpsBodyOpsItemChangeViewLayoutColumnsItemWidthMin
+ )
+ .nullable()
+ .describe(
+ 'Its width in pixels; the default when unset.'
+ ),
+ })
+ .describe(
+ 'How one column shows in a table layout.'
+ )
+ )
+ .describe(
+ "How columns show, in display order. A column left out shows\nafter the listed ones, in the table's order."
+ ),
+ kind: zod.enum(['table']),
+ })
+ .describe('A grid with a row per row.'),
+ zod
+ .object({
+ cardFields: zod
+ .array(zod.uuid())
+ .describe(
+ 'The columns a card shows under its title, in order.'
+ ),
+ groupBy: zod
+ .uuid()
+ .describe(
+ 'The single-select or single-person column whose values are the\nlanes.'
+ ),
+ hideEmptyLanes: zod
+ .boolean()
+ .describe(
+ 'Whether a lane with no cards is hidden.'
+ ),
+ kind: zod.enum(['board']),
+ lanes: zod
+ .array(
+ zod
+ .object({
+ hidden: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether it is hidden.'
+ ),
+ key: zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ kind: zod.enum(['option']),
+ })
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ kind: zod.enum(['user']),
+ })
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['none']),
+ })
+ .describe(
+ 'The cards whose grouping cell is empty.'
+ ),
+ ])
+ .describe(
+ "A lane of a board, named by what its cards' grouping cells hold: one\noption of a select, one person, or nothing."
+ ),
+ })
+ .describe(
+ 'How one lane shows in a board layout.'
+ )
+ )
+ .describe(
+ 'How lanes show, in display order.'
+ ),
+ title: zod
+ .uuid()
+ .optional()
+ .describe(
+ "The column a card is titled by. Left out, a board keeps the\ntitle it has, and a new board takes the table's first column."
+ ),
+ })
+ .describe(
+ 'Cards in lanes, one per option of a single-select column or per\nperson of a single-person column, plus one for empty cells.'
+ ),
+ ])
+ .describe(
+ 'A layout as an op asks for it: a board may leave its card title out.'
+ ),
+ name: zod.string().describe('Its name.'),
+ query: zod
+ .object({
+ filter: zod.union([
+ zod.null(),
+ zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe(
+ 'The column tested.'
+ ),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum([
+ 'presence',
+ ]),
+ operator: zod
+ .enum([
+ 'isEmpty',
+ 'isNotEmpty',
+ ])
+ .describe(
+ 'Whether a cell is empty.'
+ ),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'text',
+ ]),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe(
+ 'A text or link column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'number',
+ ]),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe(
+ 'A number column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'date',
+ ]),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe(
+ 'A date column.'
+ ),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum([
+ 'checkbox',
+ ]),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'options',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe(
+ 'A select or tag column.'
+ ),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum([
+ 'entities',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe(
+ "A test of one column's cells."
+ )
+ .and(
+ zod.object({
+ kind: zod.enum([
+ 'condition',
+ ]),
+ })
+ )
+ .describe(
+ 'A test of one column.'
+ ),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe(
+ "How a group's conditions combine."
+ ),
+ })
+ .describe(
+ 'Conditions joined by one conjunction.'
+ ),
+ ]),
+ sort: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column sorted on.'),
+ direction: zod
+ .enum(['ascending', 'descending'])
+ .describe(
+ 'A sort direction. Empty cells sort last either way.'
+ ),
+ })
+ .describe('One sort key.')
+ )
+ .optional()
+ .describe(
+ "The sort keys, first key first. Rows the keys leave tied keep the\ntable's own order; with no keys, the table's order is the view's."
+ ),
+ })
+ .optional()
+ .describe(
+ 'Which rows of the table a view shows, and in what order: a filter and a\nsort, nothing that joins, groups or reshapes rows.'
+ ),
+ })
+ .describe(
+ "A view's contents as an op creates it; the server gives it its id,\nposition and times."
+ ),
+ })
+ .describe(
+ 'Add the view to the table, after its other views.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['update']),
+ layout: zod
+ .union([
+ zod
+ .object({
+ columns: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column.'),
+ width: zod
+ .number()
+ .min(
+ applyCrmPipelineOpsBodyOpsItemChangeLayoutColumnsItemWidthMin
+ )
+ .nullable()
+ .describe(
+ 'Its width in pixels; the default when unset.'
+ ),
+ })
+ .describe(
+ 'How one column shows in a table layout.'
+ )
+ )
+ .describe(
+ "How columns show, in display order. A column left out shows\nafter the listed ones, in the table's order."
+ ),
+ kind: zod.enum(['table']),
+ })
+ .describe('A grid with a row per row.'),
+ zod
+ .object({
+ cardFields: zod
+ .array(zod.uuid())
+ .describe(
+ 'The columns a card shows under its title, in order.'
+ ),
+ groupBy: zod
+ .uuid()
+ .describe(
+ 'The single-select or single-person column whose values are the\nlanes.'
+ ),
+ hideEmptyLanes: zod
+ .boolean()
+ .describe(
+ 'Whether a lane with no cards is hidden.'
+ ),
+ kind: zod.enum(['board']),
+ lanes: zod
+ .array(
+ zod
+ .object({
+ hidden: zod
+ .boolean()
+ .optional()
+ .describe('Whether it is hidden.'),
+ key: zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ kind: zod.enum(['option']),
+ })
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ kind: zod.enum(['user']),
+ })
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['none']),
+ })
+ .describe(
+ 'The cards whose grouping cell is empty.'
+ ),
+ ])
+ .describe(
+ "A lane of a board, named by what its cards' grouping cells hold: one\noption of a select, one person, or nothing."
+ ),
+ })
+ .describe(
+ 'How one lane shows in a board layout.'
+ )
+ )
+ .describe(
+ 'How lanes show, in display order.'
+ ),
+ title: zod
+ .uuid()
+ .optional()
+ .describe(
+ "The column a card is titled by. Left out, a board keeps the\ntitle it has, and a new board takes the table's first column."
+ ),
+ })
+ .describe(
+ 'Cards in lanes, one per option of a single-select column or per\nperson of a single-person column, plus one for empty cells.'
+ ),
+ ])
+ .optional()
+ .describe(
+ 'A layout as an op asks for it: a board may leave its card title out.'
+ ),
+ name: zod.string().optional().describe('Its new name.'),
+ query: zod
+ .object({
+ filter: zod.union([
+ zod.null(),
+ zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column tested.'),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum([
+ 'presence',
+ ]),
+ operator: zod
+ .enum([
+ 'isEmpty',
+ 'isNotEmpty',
+ ])
+ .describe(
+ 'Whether a cell is empty.'
+ ),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['text']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe(
+ 'A text or link column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'number',
+ ]),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe(
+ 'A number column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['date']),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe('A date column.'),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum([
+ 'checkbox',
+ ]),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'options',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe(
+ 'A select or tag column.'
+ ),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum([
+ 'entities',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe(
+ "A test of one column's cells."
+ )
+ .and(
+ zod.object({
+ kind: zod.enum(['condition']),
+ })
+ )
+ .describe('A test of one column.'),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe(
+ "How a group's conditions combine."
+ ),
+ })
+ .describe(
+ 'Conditions joined by one conjunction.'
+ ),
+ ]),
+ sort: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column sorted on.'),
+ direction: zod
+ .enum(['ascending', 'descending'])
+ .describe(
+ 'A sort direction. Empty cells sort last either way.'
+ ),
+ })
+ .describe('One sort key.')
+ )
+ .optional()
+ .describe(
+ "The sort keys, first key first. Rows the keys leave tied keep the\ntable's own order; with no keys, the table's order is the view's."
+ ),
+ })
+ .optional()
+ .describe(
+ 'Which rows of the table a view shows, and in what order: a filter and a\nsort, nothing that joins, groups or reshapes rows.'
+ ),
+ })
+ .describe(
+ "Change the view's name, query or layout; what is left out stays."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['delete']),
+ })
+ .describe('Remove the view, with where its cards were.'),
+ zod
+ .object({
+ after: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'The card that ends up just after it, if any. Given with `before`,\nit must be the card right after `before`; with neither, the card\ngoes to the end of the lane.'
+ ),
+ before: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'The card that ends up just before it (it lands right after this\none), if any.'
+ ),
+ kind: zod.enum(['move_card']),
+ lane: zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ kind: zod.enum(['option']),
+ })
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ kind: zod.enum(['user']),
+ })
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['none']),
+ })
+ .describe(
+ 'The cards whose grouping cell is empty.'
+ ),
+ ])
+ .describe(
+ "A lane of a board, named by what its cards' grouping cells hold: one\noption of a select, one person, or nothing."
+ ),
+ row: zod.uuid().describe("The card's row."),
+ })
+ .describe(
+ "Move one of the board's cards: into a lane, which sets the row's\ngrouping cell to the lane's option or person (or empties it for the\nlane of empty cells), and to a place there, between two of its\ncards. Only an unsorted board's cards move by hand."
+ ),
+ ])
+ .describe('A change to one view.'),
+ kind: zod.enum(['view']),
+ table: zod.uuid().describe("The view's table."),
+ view: zod
+ .uuid()
+ .describe(
+ 'The view; for a creation, its new id, minted by the client.'
+ ),
+ })
+ .describe('A change to one view of a table.'),
+ zod
+ .object({
+ kind: zod.enum(['reorder_tables']),
+ order: zod
+ .array(zod.uuid())
+ .describe('Every table, in its new order.'),
+ })
+ .describe(
+ "Set the order of the database's tables: `order` names every one of\nthem once."
+ ),
+ ])
+ .describe(
+ "One write to a database: its tables, columns, options, rows or views,\ngrouped by the resource it changes. A request's ops apply in order and\ntogether, or not at all, and every op names a table of the database the\nrequest is for (or, creating one, adds it there)."
+ )
+ )
+ .describe('The ops, in the order they apply.'),
+ })
+ .describe(
+ 'A batch of ops for one database and the versions its tables must be at.'
+ );
+
+export const applyCrmPipelineOpsResponseResultsItemChangeAffectedMin = 0;
+
+export const applyCrmPipelineOpsResponseResultsItemChangeAffectedMinOne = 0;
+
+export const applyCrmPipelineOpsResponseResultsItemChangeViewLayoutColumnsItemWidthMin = 0;
+
+export const applyCrmPipelineOpsResponseResultsItemChangeViewLayoutColumnsItemWidthMinOne = 0;
+
+export const applyCrmPipelineOpsResponse = zod
+ .object({
+ changes: zod
+ .array(
+ zod
+ .object({
+ change: zod.number().describe("The journal's id of the change."),
+ table: zod.uuid().describe('The table.'),
+ version: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe(
+ "One change a committed batch journaled: a table, the version the batch\nproduced, and the journal's id for it."
+ )
+ )
+ .describe("The journal's changes."),
+ results: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['created']),
+ })
+ .describe('It was added.'),
+ zod
+ .object({
+ kind: zod.enum(['renamed']),
+ })
+ .describe('It was renamed.'),
+ zod
+ .object({
+ kind: zod.enum(['deleted']),
+ })
+ .describe('It was removed.'),
+ zod
+ .object({
+ kind: zod.enum(['columns_reordered']),
+ })
+ .describe('Its columns were reordered.'),
+ zod
+ .object({
+ kind: zod.enum(['views_reordered']),
+ positions: zod
+ .array(
+ zod
+ .object({
+ position: zod.string().describe('Its key.'),
+ view: zod.uuid().describe('The view.'),
+ })
+ .describe(
+ "A view's place among its table's views."
+ )
+ )
+ .describe("Every view's key, in their new order."),
+ })
+ .describe('Its views were reordered.'),
+ ])
+ .describe('What happened to a table.'),
+ kind: zod.enum(['table']),
+ table: zod.uuid().describe('The table.'),
+ tableVersion: zod
+ .number()
+ .optional()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe('What a table op did.'),
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['created']),
+ })
+ .describe('It was added.'),
+ zod
+ .object({
+ kind: zod.enum(['renamed']),
+ })
+ .describe('It was renamed.'),
+ zod
+ .object({
+ kind: zod.enum(['type_changed']),
+ })
+ .describe('Its type changed, and its cells with it.'),
+ zod
+ .object({
+ kind: zod.enum(['deleted']),
+ })
+ .describe('It was removed.'),
+ zod
+ .object({
+ added: zod
+ .array(zod.uuid())
+ .describe(
+ 'The options created, in order: those sent, less any whose label\nthe column already had.'
+ ),
+ kind: zod.enum(['options_added']),
+ })
+ .describe('It gained options.'),
+ zod
+ .object({
+ kind: zod.enum(['option_updated']),
+ })
+ .describe(
+ 'One of its options was relabelled or recoloured.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['option_deleted']),
+ })
+ .describe('One of its options was removed.'),
+ ])
+ .describe('What happened to a column.'),
+ column: zod.uuid().describe('The column.'),
+ kind: zod.enum(['column']),
+ table: zod.uuid().describe('The table.'),
+ tableVersion: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe('What a column op did.'),
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['inserted']),
+ rows: zod
+ .array(zod.uuid())
+ .describe(
+ 'The new rows, in the order they were sent.'
+ ),
+ })
+ .describe('Rows were added.'),
+ zod
+ .object({
+ affected: zod
+ .number()
+ .min(
+ applyCrmPipelineOpsResponseResultsItemChangeAffectedMin
+ )
+ .describe('How many rows the op updated.'),
+ kind: zod.enum(['updated']),
+ })
+ .describe("Rows' cells were written."),
+ zod
+ .object({
+ affected: zod
+ .number()
+ .min(
+ applyCrmPipelineOpsResponseResultsItemChangeAffectedMinOne
+ )
+ .describe('How many rows the op deleted.'),
+ kind: zod.enum(['deleted']),
+ })
+ .describe('Rows were removed.'),
+ ])
+ .describe("What happened to a table's rows."),
+ kind: zod.enum(['rows']),
+ table: zod.uuid().describe('The table.'),
+ tableVersion: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe('What a rows op did.'),
+ zod
+ .object({
+ change: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['created']),
+ view: zod
+ .object({
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When it was created.'),
+ databaseId: zod
+ .uuid()
+ .describe('The database the table belongs to.'),
+ id: zod.uuid().describe('The view.'),
+ layout: zod
+ .union([
+ zod
+ .object({
+ columns: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column.'),
+ width: zod
+ .number()
+ .min(
+ applyCrmPipelineOpsResponseResultsItemChangeViewLayoutColumnsItemWidthMin
+ )
+ .nullable()
+ .describe(
+ 'Its width in pixels; the default when unset.'
+ ),
+ })
+ .describe(
+ 'How one column shows in a table layout.'
+ )
+ )
+ .describe(
+ "How columns show, in display order. A column left out shows\nafter the listed ones, in the table's order."
+ ),
+ kind: zod.enum(['table']),
+ })
+ .describe('A grid with a row per row.'),
+ zod
+ .object({
+ cardFields: zod
+ .array(zod.uuid())
+ .describe(
+ 'The columns a card shows under its title, in order.'
+ ),
+ groupBy: zod
+ .uuid()
+ .describe(
+ 'The single-select or single-person column whose values are the\nlanes; moving a card to another lane sets this column.'
+ ),
+ hideEmptyLanes: zod
+ .boolean()
+ .describe(
+ 'Whether a lane with no cards is hidden.'
+ ),
+ kind: zod.enum(['board']),
+ lanes: zod
+ .array(
+ zod
+ .object({
+ hidden: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether it is hidden.'
+ ),
+ key: zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ kind: zod.enum(['option']),
+ })
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ kind: zod.enum(['user']),
+ })
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['none']),
+ })
+ .describe(
+ 'The cards whose grouping cell is empty.'
+ ),
+ ])
+ .describe(
+ "A lane of a board, named by what its cards' grouping cells hold: one\noption of a select, one person, or nothing."
+ ),
+ })
+ .describe(
+ 'How one lane shows in a board layout.'
+ )
+ )
+ .describe(
+ "How lanes show, in display order. A lane left out shows after the\nlisted ones: the lane of empty cells first, then options in the\ncolumn's order, or people by id."
+ ),
+ title: zod
+ .uuid()
+ .describe(
+ "The column a card is titled by, of any type. Removing it titles\nthe cards by the table's first remaining column."
+ ),
+ })
+ .describe(
+ 'Cards in lanes: one lane per option of a single-select column, or\none per person a single-person column names, plus one for cards\nwith an empty cell. A multi-valued column cannot group a board: a\ncard is in exactly one lane, so a card in several would need a place\nin each.'
+ ),
+ ])
+ .describe('How a view draws its rows.'),
+ name: zod
+ .string()
+ .describe(
+ "Its name, unique among the table's views ignoring case."
+ ),
+ position: zod
+ .string()
+ .describe(
+ "Where it sorts among the table's views: a fractional key."
+ ),
+ query: zod
+ .object({
+ filter: zod.union([
+ zod.null(),
+ zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe(
+ 'The column tested.'
+ ),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum([
+ 'presence',
+ ]),
+ operator: zod
+ .enum([
+ 'isEmpty',
+ 'isNotEmpty',
+ ])
+ .describe(
+ 'Whether a cell is empty.'
+ ),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'text',
+ ]),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe(
+ 'A text or link column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'number',
+ ]),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe(
+ 'A number column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'date',
+ ]),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe(
+ 'A date column.'
+ ),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum([
+ 'checkbox',
+ ]),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'options',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe(
+ 'A select or tag column.'
+ ),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum([
+ 'entities',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe(
+ "A test of one column's cells."
+ )
+ .and(
+ zod.object({
+ kind: zod.enum([
+ 'condition',
+ ]),
+ })
+ )
+ .describe(
+ 'A test of one column.'
+ ),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe(
+ "How a group's conditions combine."
+ ),
+ })
+ .describe(
+ 'Conditions joined by one conjunction.'
+ ),
+ ]),
+ sort: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column sorted on.'),
+ direction: zod
+ .enum(['ascending', 'descending'])
+ .describe(
+ 'A sort direction. Empty cells sort last either way.'
+ ),
+ })
+ .describe('One sort key.')
+ )
+ .optional()
+ .describe(
+ "The sort keys, first key first. Rows the keys leave tied keep the\ntable's own order; with no keys, the table's order is the view's."
+ ),
+ })
+ .describe(
+ 'Which rows of the table a view shows, and in what order: a filter and a\nsort, nothing that joins, groups or reshapes rows.'
+ ),
+ tableId: zod.uuid().describe('The table it shows.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When it last changed.'),
+ })
+ .describe('A view of one table, as stored.'),
+ })
+ .describe('It was added.'),
+ zod
+ .object({
+ kind: zod.enum(['updated']),
+ view: zod
+ .object({
+ createdAt: zod.iso
+ .datetime({})
+ .describe('When it was created.'),
+ databaseId: zod
+ .uuid()
+ .describe('The database the table belongs to.'),
+ id: zod.uuid().describe('The view.'),
+ layout: zod
+ .union([
+ zod
+ .object({
+ columns: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column.'),
+ width: zod
+ .number()
+ .min(
+ applyCrmPipelineOpsResponseResultsItemChangeViewLayoutColumnsItemWidthMinOne
+ )
+ .nullable()
+ .describe(
+ 'Its width in pixels; the default when unset.'
+ ),
+ })
+ .describe(
+ 'How one column shows in a table layout.'
+ )
+ )
+ .describe(
+ "How columns show, in display order. A column left out shows\nafter the listed ones, in the table's order."
+ ),
+ kind: zod.enum(['table']),
+ })
+ .describe('A grid with a row per row.'),
+ zod
+ .object({
+ cardFields: zod
+ .array(zod.uuid())
+ .describe(
+ 'The columns a card shows under its title, in order.'
+ ),
+ groupBy: zod
+ .uuid()
+ .describe(
+ 'The single-select or single-person column whose values are the\nlanes; moving a card to another lane sets this column.'
+ ),
+ hideEmptyLanes: zod
+ .boolean()
+ .describe(
+ 'Whether a lane with no cards is hidden.'
+ ),
+ kind: zod.enum(['board']),
+ lanes: zod
+ .array(
+ zod
+ .object({
+ hidden: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether it is hidden.'
+ ),
+ key: zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ kind: zod.enum(['option']),
+ })
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ kind: zod.enum(['user']),
+ })
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['none']),
+ })
+ .describe(
+ 'The cards whose grouping cell is empty.'
+ ),
+ ])
+ .describe(
+ "A lane of a board, named by what its cards' grouping cells hold: one\noption of a select, one person, or nothing."
+ ),
+ })
+ .describe(
+ 'How one lane shows in a board layout.'
+ )
+ )
+ .describe(
+ "How lanes show, in display order. A lane left out shows after the\nlisted ones: the lane of empty cells first, then options in the\ncolumn's order, or people by id."
+ ),
+ title: zod
+ .uuid()
+ .describe(
+ "The column a card is titled by, of any type. Removing it titles\nthe cards by the table's first remaining column."
+ ),
+ })
+ .describe(
+ 'Cards in lanes: one lane per option of a single-select column, or\none per person a single-person column names, plus one for cards\nwith an empty cell. A multi-valued column cannot group a board: a\ncard is in exactly one lane, so a card in several would need a place\nin each.'
+ ),
+ ])
+ .describe('How a view draws its rows.'),
+ name: zod
+ .string()
+ .describe(
+ "Its name, unique among the table's views ignoring case."
+ ),
+ position: zod
+ .string()
+ .describe(
+ "Where it sorts among the table's views: a fractional key."
+ ),
+ query: zod
+ .object({
+ filter: zod.union([
+ zod.null(),
+ zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe(
+ 'The column tested.'
+ ),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum([
+ 'presence',
+ ]),
+ operator: zod
+ .enum([
+ 'isEmpty',
+ 'isNotEmpty',
+ ])
+ .describe(
+ 'Whether a cell is empty.'
+ ),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'text',
+ ]),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe(
+ 'A text or link column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'number',
+ ]),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe(
+ 'A number column.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'date',
+ ]),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe(
+ 'A date column.'
+ ),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum([
+ 'checkbox',
+ ]),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum([
+ 'options',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe(
+ 'A select or tag column.'
+ ),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum([
+ 'entities',
+ ]),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe(
+ "A test of one column's cells."
+ )
+ .and(
+ zod.object({
+ kind: zod.enum([
+ 'condition',
+ ]),
+ })
+ )
+ .describe(
+ 'A test of one column.'
+ ),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe(
+ "How a group's conditions combine."
+ ),
+ })
+ .describe(
+ 'Conditions joined by one conjunction.'
+ ),
+ ]),
+ sort: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column sorted on.'),
+ direction: zod
+ .enum(['ascending', 'descending'])
+ .describe(
+ 'A sort direction. Empty cells sort last either way.'
+ ),
+ })
+ .describe('One sort key.')
+ )
+ .optional()
+ .describe(
+ "The sort keys, first key first. Rows the keys leave tied keep the\ntable's own order; with no keys, the table's order is the view's."
+ ),
+ })
+ .describe(
+ 'Which rows of the table a view shows, and in what order: a filter and a\nsort, nothing that joins, groups or reshapes rows.'
+ ),
+ tableId: zod.uuid().describe('The table it shows.'),
+ updatedAt: zod.iso
+ .datetime({})
+ .describe('When it last changed.'),
+ })
+ .describe('A view of one table, as stored.'),
+ })
+ .describe('It was changed.'),
+ zod
+ .object({
+ kind: zod.enum(['deleted']),
+ })
+ .describe('It was removed.'),
+ zod
+ .object({
+ kind: zod.enum(['card_moved']),
+ positions: zod
+ .array(
+ zod
+ .object({
+ lane: zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ kind: zod.enum(['option']),
+ })
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ kind: zod.enum(['user']),
+ })
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['none']),
+ })
+ .describe(
+ 'The cards whose grouping cell is empty.'
+ ),
+ ])
+ .describe(
+ "A lane of a board, named by what its cards' grouping cells hold: one\noption of a select, one person, or nothing."
+ ),
+ position: zod
+ .string()
+ .describe("The card's key in that lane."),
+ row: zod.uuid().describe("The card's row."),
+ })
+ .describe(
+ 'Where one card sits on a board: its lane, and its fractional key there.\nA card whose row has since moved to another lane has no place until it is\nmoved again.'
+ )
+ )
+ .describe(
+ "The positions written, the moved card's last."
+ ),
+ })
+ .describe('One of its cards moved.'),
+ ])
+ .describe('What happened to a view.'),
+ kind: zod.enum(['view']),
+ table: zod.uuid().describe("The view's table."),
+ tableVersion: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ view: zod.uuid().describe('The view.'),
+ })
+ .describe('What a view op did.'),
+ zod
+ .object({
+ kind: zod.enum(['reorder_tables']),
+ tables: zod
+ .array(
+ zod
+ .object({
+ table: zod.uuid().describe('The table.'),
+ version: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe('A table and its version.')
+ )
+ .describe(
+ 'Every table, in its new order, with its version once the request\ncommitted.'
+ ),
+ })
+ .describe("The database's tables in their new order."),
+ ])
+ .describe(
+ "What one op did, in the order the ops were sent, grouped as the ops are:\na result's `kind` is its op's, naming the same resource, and its\n`change` says what happened to it."
+ )
+ )
+ .describe('One result per op, in order.'),
+ })
+ .describe(
+ "What a committed batch answers: a result per op, and the journal's change\nfor each table version it produced."
+ );
+
+/**
+ * @summary Read pipeline records through pipeline access.
+ */
+export const getCrmPipelineRowsParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const getCrmPipelineRowsQueryParams = zod.object({
+ after: zod.uuid().nullish().describe('Continue after this row identity.'),
+});
+
+export const getCrmPipelineRowsResponse = zod
+ .object({
+ next: zod
+ .union([zod.null(), zod.uuid().describe('Identifier of a row.')])
+ .optional(),
+ rows: zod
+ .array(
+ zod
+ .object({
+ cells: zod
+ .record(
+ zod.string(),
+ zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['Boolean']),
+ value: zod
+ .boolean()
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ })
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Number']),
+ value: zod
+ .number()
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ })
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['String']),
+ value: zod
+ .string()
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ })
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Date']),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ })
+ .describe(
+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['SelectOption']),
+ value: zod
+ .array(zod.uuid())
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['EntityReference']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod.string(),
+ entity_type: zod
+ .enum([
+ 'CALENDAR_EVENT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DATABASE_ROW',
+ 'CONTACT',
+ 'DOCUMENT',
+ 'INITIATIVE',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ specific_message_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'
+ ),
+ })
+ .describe(
+ 'Entity reference for entity-type property values.'
+ )
+ )
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'
+ ),
+ ])
+ .describe(
+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'
+ )
+ )
+ .describe('Populated cells.'),
+ rowId: zod.uuid().describe('Identifier of a row.'),
+ })
+ .describe('One storage row, with cells keyed by column placement.')
+ )
+ .describe("Rows in the requested view's order."),
+ version: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe('A bounded page of rows at a table version.');
+
+/**
+ * @summary Query rows through pipeline access using the shared view protocol.
+ */
+export const queryCrmPipelineRowsParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const queryCrmPipelineRowsBody = zod
+ .object({
+ after: zod
+ .union([zod.null(), zod.uuid().describe('Identifier of a row.')])
+ .optional(),
+ query: zod
+ .object({
+ filter: zod.union([
+ zod.null(),
+ zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod.uuid().describe('The column tested.'),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['presence']),
+ operator: zod
+ .enum(['isEmpty', 'isNotEmpty'])
+ .describe('Whether a cell is empty.'),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['text']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe('A text or link column.'),
+ zod
+ .object({
+ kind: zod.enum(['number']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe('A number column.'),
+ zod
+ .object({
+ kind: zod.enum(['date']),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe('A date column.'),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe('Whether the box is checked.'),
+ kind: zod.enum(['checkbox']),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['options']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe('A select or tag column.'),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum(['entities']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe('A reference or relation column.'),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe("A test of one column's cells.")
+ .and(
+ zod.object({
+ kind: zod.enum(['condition']),
+ })
+ )
+ .describe('A test of one column.'),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe("How a group's conditions combine."),
+ })
+ .describe('Conditions joined by one conjunction.'),
+ ]),
+ sort: zod
+ .array(
+ zod
+ .object({
+ column: zod.uuid().describe('The column sorted on.'),
+ direction: zod
+ .enum(['ascending', 'descending'])
+ .describe(
+ 'A sort direction. Empty cells sort last either way.'
+ ),
+ })
+ .describe('One sort key.')
+ )
+ .optional()
+ .describe(
+ "The sort keys, first key first. Rows the keys leave tied keep the\ntable's own order; with no keys, the table's order is the view's."
+ ),
+ })
+ .optional()
+ .describe(
+ 'Which rows of the table a view shows, and in what order: a filter and a\nsort, nothing that joins, groups or reshapes rows.'
+ ),
+ rowIds: zod
+ .array(zod.uuid().describe('Identifier of a row.'))
+ .nullish()
+ .describe('Read these retained rows regardless of the active filter.'),
+ })
+ .describe('A query over one authorized storage table.');
+
+export const queryCrmPipelineRowsResponse = zod
+ .object({
+ next: zod
+ .union([zod.null(), zod.uuid().describe('Identifier of a row.')])
+ .optional(),
+ rows: zod
+ .array(
+ zod
+ .object({
+ cells: zod
+ .record(
+ zod.string(),
+ zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['Boolean']),
+ value: zod
+ .boolean()
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ })
+ .describe(
+ 'Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Number']),
+ value: zod
+ .number()
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ })
+ .describe(
+ 'Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['String']),
+ value: zod
+ .string()
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ })
+ .describe(
+ 'String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Date']),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ })
+ .describe(
+ 'Date\/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'
+ ),
+ zod
+ .object({
+ type: zod.enum(['SelectOption']),
+ value: zod
+ .array(zod.uuid())
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['EntityReference']),
+ value: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod.string(),
+ entity_type: zod
+ .enum([
+ 'CALENDAR_EVENT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DATABASE_ROW',
+ 'CONTACT',
+ 'DOCUMENT',
+ 'INITIATIVE',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ specific_message_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread\/channel\/chat.'
+ ),
+ })
+ .describe(
+ 'Entity reference for entity-type property values.'
+ )
+ )
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'
+ ),
+ zod
+ .object({
+ type: zod.enum(['Link']),
+ value: zod
+ .array(zod.string())
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'
+ ),
+ })
+ .describe(
+ 'Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https:\/\/example.com\", \"https:\/\/other.com\"]} (length 0+)'
+ ),
+ ])
+ .describe(
+ 'Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to\/from JSONB in the database.'
+ )
+ )
+ .describe('Populated cells.'),
+ rowId: zod.uuid().describe('Identifier of a row.'),
+ })
+ .describe('One storage row, with cells keyed by column placement.')
+ )
+ .describe("Rows in the requested view's order."),
+ version: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe('A bounded page of rows at a table version.');
+
+/**
+ * @summary Update sharing.
+ */
+export const shareCrmPipelineParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const shareCrmPipelineBody = zod
+ .object({
+ sharing: zod
+ .enum(['private', 'team'])
+ .describe(
+ 'Initial sharing, or the desired team grant. Individual ownership is preserved.'
+ ),
+ })
+ .describe('Sharing input.');
+
+/**
+ * @summary Read the host-owned table schema.
+ */
+export const getCrmPipelineTableParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const getCrmPipelineTableResponseViewsItemLayoutColumnsItemWidthMin = 0;
+
+export const getCrmPipelineTableResponse = zod
+ .object({
+ columns: zod
+ .array(
+ zod
+ .object({
+ column: zod
+ .object({
+ config: zod.union([
+ zod.null(),
+ zod
+ .object({
+ database_id: zod.uuid().describe('Target database.'),
+ kind: zod.enum(['link']),
+ table_id: zod.uuid().describe('Target table.'),
+ })
+ .describe(
+ 'A relation column: its cells reference rows of another table.'
+ )
+ .describe(
+ 'Column-kind specific configuration stored on the placement.'
+ ),
+ ]),
+ display_name: zod
+ .string()
+ .nullable()
+ .describe(
+ "The placement's own label, which also names it in SQL; `None` shows\nthe definition's name."
+ ),
+ id: zod.uuid().describe('Identifier of the placement.'),
+ infer_type: zod
+ .boolean()
+ .describe(
+ "Whether the first nonempty value may settle this new text column's type."
+ ),
+ nullable: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether a row may omit this cell; empty collections also count as absent.'
+ ),
+ position: zod
+ .string()
+ .describe('Fractional index for column ordering.'),
+ property_definition_id: zod
+ .uuid()
+ .describe('The bound property definition.'),
+ protections: zod
+ .array(
+ zod
+ .enum(['delete', 'change_type'])
+ .describe(
+ 'A schema operation reserved by a feature using a column.'
+ )
+ )
+ .optional()
+ .describe(
+ 'Schema operations reserved by a feature; ordinary edits cannot clear them.'
+ ),
+ table_id: zod.uuid().describe('Table the column appears on.'),
+ })
+ .describe(
+ 'A column: the placement of a property definition on a table.\n\nThe definition carries name, [`DataType`], multi-select flag, and options;\nthis carries only where it appears and column-kind configuration.'
+ ),
+ definition: zod
+ .object({
+ definition: zod
+ .object({
+ created_at: zod.iso.datetime({}),
+ data_type: zod
+ .enum([
+ 'BOOLEAN',
+ 'DATE',
+ 'NUMBER',
+ 'STRING',
+ 'SELECT_NUMBER',
+ 'SELECT_STRING',
+ 'TAG',
+ 'ENTITY',
+ 'LINK',
+ ])
+ .describe(
+ 'Data type for property values, determining storage and validation.'
+ ),
+ display_name: zod.string(),
+ id: zod.uuid(),
+ is_metadata: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'
+ ),
+ is_multi_select: zod.boolean(),
+ is_system: zod
+ .boolean()
+ .describe(
+ 'Flag to indicate if this is a system property (stored in DB).'
+ ),
+ owner: zod
+ .union([
+ zod
+ .object({
+ scope: zod.enum(['user']),
+ user_id: zod.string(),
+ })
+ .describe('User-scoped property.'),
+ zod
+ .object({
+ scope: zod.enum(['team']),
+ team_id: zod.uuid(),
+ })
+ .describe('Team-scoped property.'),
+ zod
+ .object({
+ database_id: zod.uuid(),
+ scope: zod.enum(['database']),
+ })
+ .describe(
+ 'Database-scoped property: the definition is a column of one Macro\ndatabase and is invisible to the shared user\/team property namespace.'
+ ),
+ zod
+ .object({
+ scope: zod.enum(['system']),
+ })
+ .describe(
+ 'System-owned property (no user, team, or database owner).'
+ ),
+ ])
+ .describe(
+ 'Defines who owns a property - user-scoped, team-scoped, database-scoped, or system.'
+ ),
+ specific_entity_type: zod.union([
+ zod.null(),
+ zod
+ .enum([
+ 'CALENDAR_EVENT',
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DATABASE_ROW',
+ 'CONTACT',
+ 'DOCUMENT',
+ 'INITIATIVE',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Type of entity that can be referenced by entity properties.'
+ ),
+ ]),
+ updated_at: zod.iso.datetime({}),
+ })
+ .describe(
+ 'Property definition model (service representation).'
+ ),
+ property_options: zod.array(
+ zod
+ .object({
+ color: zod.string().nullable(),
+ created_at: zod.iso.datetime({}),
+ display_order: zod.number(),
+ id: zod.uuid(),
+ property_definition_id: zod.uuid(),
+ updated_at: zod.iso.datetime({}),
+ value: zod
+ .union([
+ zod
+ .object({
+ type: zod.enum(['string']),
+ value: zod
+ .string()
+ .describe(
+ 'String value for SelectString properties'
+ ),
+ })
+ .describe(
+ 'String value for SelectString properties'
+ ),
+ zod
+ .object({
+ type: zod.enum(['number']),
+ value: zod
+ .number()
+ .describe(
+ 'Number value for SelectNumber properties'
+ ),
+ })
+ .describe(
+ 'Number value for SelectNumber properties'
+ ),
+ ])
+ .describe(
+ 'The value of a property option - either a string or a number.'
+ ),
+ })
+ .describe(
+ 'A selectable option for select-type properties (service representation).'
+ )
+ ),
+ })
+ .describe(
+ 'Property definition with its associated options (service representation).'
+ ),
+ shared_outside_database: zod
+ .boolean()
+ .describe(
+ "Whether the definition belongs to something beyond this database (a\nperson's, a team's or a system property), so changing its options\nchanges them everywhere that property is used."
+ ),
+ sql_name: zod
+ .string()
+ .describe(
+ 'The name SQL refers to the column by: its display name, quoted.'
+ ),
+ writable: zod
+ .boolean()
+ .describe('Whether SQL may write this column.'),
+ })
+ .describe('One column placement with the definition behind it.')
+ )
+ .describe('Columns in display order.'),
+ sql_name: zod
+ .string()
+ .describe(
+ 'The name SQL refers to the table by: its display name quoted and\nqualified by the database\'s (`FROM \"Plans\".\"Table 1\"`).'
+ ),
+ table: zod
+ .object({
+ database_id: zod.uuid().describe('Owning database.'),
+ id: zod.uuid().describe('Identifier.'),
+ name: zod
+ .string()
+ .describe("Display name; also the basis of the table's SQL name."),
+ position: zod.string().describe('Fractional index for tab ordering.'),
+ version: zod
+ .number()
+ .describe(
+ "Monotonic per-table version, bumped once by every committed change to a\ntable's schema or rows. Schema edits name the version they were made\nagainst, and change events carry the new one."
+ ),
+ })
+ .describe('One table (tab) of a database.'),
+ views: zod
+ .array(
+ zod
+ .object({
+ createdAt: zod.iso.datetime({}).describe('When it was created.'),
+ databaseId: zod
+ .uuid()
+ .describe('The database the table belongs to.'),
+ id: zod.uuid().describe('The view.'),
+ layout: zod
+ .union([
+ zod
+ .object({
+ columns: zod
+ .array(
+ zod
+ .object({
+ column: zod.uuid().describe('The column.'),
+ width: zod
+ .number()
+ .min(
+ getCrmPipelineTableResponseViewsItemLayoutColumnsItemWidthMin
+ )
+ .nullable()
+ .describe(
+ 'Its width in pixels; the default when unset.'
+ ),
+ })
+ .describe('How one column shows in a table layout.')
+ )
+ .describe(
+ "How columns show, in display order. A column left out shows\nafter the listed ones, in the table's order."
+ ),
+ kind: zod.enum(['table']),
+ })
+ .describe('A grid with a row per row.'),
+ zod
+ .object({
+ cardFields: zod
+ .array(zod.uuid())
+ .describe(
+ 'The columns a card shows under its title, in order.'
+ ),
+ groupBy: zod
+ .uuid()
+ .describe(
+ 'The single-select or single-person column whose values are the\nlanes; moving a card to another lane sets this column.'
+ ),
+ hideEmptyLanes: zod
+ .boolean()
+ .describe('Whether a lane with no cards is hidden.'),
+ kind: zod.enum(['board']),
+ lanes: zod
+ .array(
+ zod
+ .object({
+ hidden: zod
+ .boolean()
+ .optional()
+ .describe('Whether it is hidden.'),
+ key: zod
+ .union([
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ kind: zod.enum(['option']),
+ })
+ .describe(
+ "The cards holding this option of the board's select column."
+ ),
+ zod
+ .object({
+ id: zod
+ .string()
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ kind: zod.enum(['user']),
+ })
+ .describe(
+ "The cards naming this person in the board's person column."
+ ),
+ zod
+ .object({
+ kind: zod.enum(['none']),
+ })
+ .describe(
+ 'The cards whose grouping cell is empty.'
+ ),
+ ])
+ .describe(
+ "A lane of a board, named by what its cards' grouping cells hold: one\noption of a select, one person, or nothing."
+ ),
+ })
+ .describe('How one lane shows in a board layout.')
+ )
+ .describe(
+ "How lanes show, in display order. A lane left out shows after the\nlisted ones: the lane of empty cells first, then options in the\ncolumn's order, or people by id."
+ ),
+ title: zod
+ .uuid()
+ .describe(
+ "The column a card is titled by, of any type. Removing it titles\nthe cards by the table's first remaining column."
+ ),
+ })
+ .describe(
+ 'Cards in lanes: one lane per option of a single-select column, or\none per person a single-person column names, plus one for cards\nwith an empty cell. A multi-valued column cannot group a board: a\ncard is in exactly one lane, so a card in several would need a place\nin each.'
+ ),
+ ])
+ .describe('How a view draws its rows.'),
+ name: zod
+ .string()
+ .describe(
+ "Its name, unique among the table's views ignoring case."
+ ),
+ position: zod
+ .string()
+ .describe(
+ "Where it sorts among the table's views: a fractional key."
+ ),
+ query: zod
+ .object({
+ filter: zod.union([
+ zod.null(),
+ zod
+ .object({
+ conditions: zod
+ .array(
+ zod
+ .union([
+ zod
+ .object({
+ column: zod
+ .uuid()
+ .describe('The column tested.'),
+ test: zod
+ .union([
+ zod
+ .object({
+ kind: zod.enum(['presence']),
+ operator: zod
+ .enum(['isEmpty', 'isNotEmpty'])
+ .describe(
+ 'Whether a cell is empty.'
+ ),
+ })
+ .describe(
+ 'Whether the cell is empty; fits a column of any type.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['text']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'contains',
+ 'doesNotContain',
+ 'startsWith',
+ 'endsWith',
+ ])
+ .describe(
+ 'How a text cell compares to a text.'
+ ),
+ value: zod
+ .string()
+ .describe(
+ 'The text compared against, ignoring case for the containment\ntests.'
+ ),
+ })
+ .describe('A text or link column.'),
+ zod
+ .object({
+ kind: zod.enum(['number']),
+ operator: zod
+ .enum([
+ 'is',
+ 'isNot',
+ 'greaterThan',
+ 'greaterThanOrEqual',
+ 'lessThan',
+ 'lessThanOrEqual',
+ ])
+ .describe(
+ 'How a number cell compares to a number.'
+ ),
+ value: zod
+ .number()
+ .describe(
+ 'The number compared against; finite.'
+ ),
+ })
+ .describe('A number column.'),
+ zod
+ .object({
+ kind: zod.enum(['date']),
+ operator: zod
+ .enum([
+ 'before',
+ 'after',
+ 'onOrBefore',
+ 'onOrAfter',
+ ])
+ .describe(
+ 'How a date cell compares to a date-time.'
+ ),
+ value: zod.iso
+ .datetime({})
+ .describe(
+ 'The date-time compared against.'
+ ),
+ })
+ .describe('A date column.'),
+ zod
+ .object({
+ checked: zod
+ .boolean()
+ .describe(
+ 'Whether the box is checked.'
+ ),
+ kind: zod.enum(['checkbox']),
+ })
+ .describe(
+ 'A checkbox column. An unchecked box and an empty cell are the same.'
+ ),
+ zod
+ .object({
+ kind: zod.enum(['options']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ options: zod
+ .array(zod.uuid())
+ .describe(
+ 'Options of the column; at least one.'
+ ),
+ })
+ .describe('A select or tag column.'),
+ zod
+ .object({
+ entities: zod
+ .array(zod.string())
+ .describe(
+ "Entity ids, or for a relation the related rows' ids; at least\none."
+ ),
+ kind: zod.enum(['entities']),
+ operator: zod
+ .enum([
+ 'isAnyOf',
+ 'isNoneOf',
+ 'hasAny',
+ 'hasAll',
+ 'hasNone',
+ ])
+ .describe(
+ "How a cell's options or references relate to a set of them. The first\ntwo fit a column holding one value, the last three one holding several."
+ ),
+ })
+ .describe(
+ 'A reference or relation column.'
+ ),
+ ])
+ .describe(
+ "What a column's cell must be, by the kind of value the column holds."
+ ),
+ })
+ .describe("A test of one column's cells.")
+ .and(
+ zod.object({
+ kind: zod.enum(['condition']),
+ })
+ )
+ .describe('A test of one column.'),
+ zod
+ .unknown()
+ .and(
+ zod.object({
+ kind: zod.enum(['group']),
+ })
+ )
+ .describe('A nested group.'),
+ ])
+ .describe(
+ 'One entry of a group: a condition, or a group of its own.'
+ )
+ )
+ .describe(
+ 'The conditions and nested groups. A group without any keeps every\nrow.'
+ ),
+ conjunction: zod
+ .enum(['and', 'or'])
+ .describe("How a group's conditions combine."),
+ })
+ .describe('Conditions joined by one conjunction.'),
+ ]),
+ sort: zod
+ .array(
+ zod
+ .object({
+ column: zod.uuid().describe('The column sorted on.'),
+ direction: zod
+ .enum(['ascending', 'descending'])
+ .describe(
+ 'A sort direction. Empty cells sort last either way.'
+ ),
+ })
+ .describe('One sort key.')
+ )
+ .optional()
+ .describe(
+ "The sort keys, first key first. Rows the keys leave tied keep the\ntable's own order; with no keys, the table's order is the view's."
+ ),
+ })
+ .describe(
+ 'Which rows of the table a view shows, and in what order: a filter and a\nsort, nothing that joins, groups or reshapes rows.'
+ ),
+ tableId: zod.uuid().describe('The table it shows.'),
+ updatedAt: zod.iso.datetime({}).describe('When it last changed.'),
+ })
+ .describe('A view of one table, as stored.')
+ )
+ .describe("The table's views, in their order."),
+ })
+ .describe('One table with its columns and SQL name.');
+
+/**
+ * @summary Trash or restore a pipeline.
+ */
+export const trashCrmPipelineParams = zod.object({
+ id: zod.uuid(),
+});
+
+export const trashCrmPipelineBody = zod
+ .object({
+ trashed: zod.boolean().describe('True to trash; false to restore.'),
+ })
+ .describe('Trash\/restore input.');
+
/**
* @summary Read the caller's team CRM configuration. Any team member may read;
teams without a settings row get the defaults.
@@ -13042,6 +17340,7 @@ export const listFavoritesQueryParams = zod.object({
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -13105,6 +17404,7 @@ export const listFavoritesResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -13156,6 +17456,7 @@ export const addFavoriteBody = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -13208,6 +17509,7 @@ export const addFavoriteResponse = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -13257,6 +17559,7 @@ export const reorderFavoritesBody = zod
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
@@ -13299,6 +17602,7 @@ export const removeFavoriteByEntityParams = zod.object({
'static_file',
'crm_company',
'crm_contact',
+ 'crm_pipeline',
'reminder',
'skill',
'agent_session',
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts b/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts
index e5fa538859..3ebbe88e59 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-favorites.ts
@@ -39,6 +39,7 @@ const FAVORITE_ENTITY_TYPE_TO_GRAPHQL = {
static_file: 'STATIC_FILE',
crm_company: 'CRM_COMPANY',
crm_contact: 'CRM_CONTACT',
+ crm_pipeline: 'CRM_PIPELINE',
reminder: 'REMINDER',
skill: 'SKILL',
agent_session: 'AGENT_SESSION',
@@ -58,6 +59,7 @@ const GRAPHQL_ENTITY_TYPE_TO_FAVORITE = {
CHAT: 'chat',
CRM_COMPANY: 'crm_company',
CRM_CONTACT: 'crm_contact',
+ CRM_PIPELINE: 'crm_pipeline',
DATABASE: 'database',
DATABASE_ROW: 'database_row',
DOCUMENT: 'document',
@@ -143,6 +145,7 @@ function favoriteSoupEffects(
team: undefined,
static_file: undefined,
crm_contact: undefined,
+ crm_pipeline: undefined,
skill: undefined,
scheduled_action: undefined,
initiative: 'GraphqlSoupInitiative',
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index 55743d0fac..571ae5a418 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -858,6 +858,8 @@ export type GraphqlEntityType =
| 'CRM_COMPANY'
/** CRM contact entity. */
| 'CRM_CONTACT'
+ /** CRM pipeline entity. */
+ | 'CRM_PIPELINE'
/** Macro Database entity (a collection of user-defined tables). */
| 'DATABASE'
/** Row of a Macro Database table. */
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 6b7343de18..d2ddc4e017 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -6017,6 +6017,332 @@
}
}
},
+ "/crm/pipelines": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "List the caller's live pipelines in their CRM.",
+ "operationId": "list_crm_pipelines",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AccessiblePipeline"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Create a private or team-shared pipeline.",
+ "operationId": "create_crm_pipeline",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreatePipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AccessiblePipeline"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Read one pipeline by its entity identity.",
+ "operationId": "get_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AccessiblePipeline"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/name": {
+ "put": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Rename a pipeline.",
+ "operationId": "rename_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RenamePipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/ops": {
+ "post": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Edit pipeline schema or records with the common typed operations.",
+ "operationId": "apply_crm_pipeline_ops",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OpBatch"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AppliedOps"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/rows": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Read pipeline records through pipeline access.",
+ "operationId": "get_crm_pipeline_rows",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "after",
+ "in": "query",
+ "description": "Continue after this row identity.",
+ "required": false,
+ "schema": {
+ "type": ["string", "null"],
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StorageRows"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Query rows through pipeline access using the shared view protocol.",
+ "operationId": "query_crm_pipeline_rows",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StorageRowsQuery"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StorageRows"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/sharing": {
+ "put": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Update sharing.",
+ "operationId": "share_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SharePipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/table": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Read the host-owned table schema.",
+ "operationId": "get_crm_pipeline_table",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TableDetail"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/trash": {
+ "put": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Trash or restore a pipeline.",
+ "operationId": "trash_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TrashPipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
"/crm/settings": {
"get": {
"tags": ["crm::inbound::axum_router::team_settings"],
@@ -10231,6 +10557,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -10449,6 +10776,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -16903,6 +17231,25 @@
"description": "Ordered from least to most access top -> bottom",
"enum": ["view", "comment", "edit", "owner"]
},
+ "AccessiblePipeline": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Pipeline",
+ "description": "Pipeline metadata."
+ },
+ {
+ "type": "object",
+ "required": ["grant"],
+ "properties": {
+ "grant": {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "Highest effective access."
+ }
+ }
+ }
+ ],
+ "description": "Metadata together with the caller's effective grant."
+ },
"ActiveCallSummary": {
"type": "object",
"description": "A currently active call, as returned by the batch active-calls listing.",
@@ -17021,6 +17368,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -18222,6 +18570,27 @@
"USER"
]
},
+ "AppliedOps": {
+ "type": "object",
+ "description": "What a committed batch answers: a result per op, and the journal's change\nfor each table version it produced.",
+ "required": ["results", "changes"],
+ "properties": {
+ "changes": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CommittedChange"
+ },
+ "description": "The journal's changes."
+ },
+ "results": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/OpResult"
+ },
+ "description": "One result per op, in order."
+ }
+ }
+ },
"ApplyOpsRequest": {
"type": "object",
"description": "A batch of ops for one database, applied in order, in one transaction,\ntogether or not at all.",
@@ -21014,6 +21383,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -22737,6 +23107,26 @@
}
}
},
+ "CreatePipeline": {
+ "type": "object",
+ "description": "Request to create an empty pipeline with the standard CRM columns.",
+ "required": ["name", "recordType"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Pipeline name."
+ },
+ "recordType": {
+ "$ref": "#/components/schemas/PipelineRecordType",
+ "description": "Company or contact entries."
+ },
+ "sharing": {
+ "$ref": "#/components/schemas/PipelineSharing",
+ "description": "Defaults to private."
+ }
+ },
+ "additionalProperties": false
+ },
"CreateProjectRequest": {
"type": "object",
"required": ["name"],
@@ -25389,6 +25779,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -25845,6 +26236,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -25898,6 +26290,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -31220,6 +31613,30 @@
"lessThanOrEqual"
]
},
+ "OpBatch": {
+ "type": "object",
+ "description": "A batch of ops for one database and the versions its tables must be at.",
+ "required": ["ops"],
+ "properties": {
+ "baseVersions": {
+ "type": "object",
+ "description": "The version each named table must still be at; the batch is refused\nas a conflict if one moved. Without one, ops are last-write-wins.",
+ "additionalProperties": {
+ "$ref": "#/components/schemas/TableVersion"
+ },
+ "propertyNames": {
+ "type": "string"
+ }
+ },
+ "ops": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/DatabaseOp"
+ },
+ "description": "The ops, in the order they apply."
+ }
+ }
+ },
"OpRefusalResponse": {
"type": "object",
"description": "Why an op of a batch was refused. Nothing in the batch was written.",
@@ -32023,6 +32440,86 @@
}
}
},
+ "Pipeline": {
+ "type": "object",
+ "description": "Pipeline metadata; table schema and data are read through the database service.",
+ "required": [
+ "id",
+ "teamId",
+ "userId",
+ "name",
+ "recordType",
+ "databaseId",
+ "tableId",
+ "primaryColumnId",
+ "sharing",
+ "createdAt",
+ "trashedAt"
+ ],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Creation time."
+ },
+ "databaseId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Dedicated backing database."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Entity identity, used with `CrmPipeline` access receipts."
+ },
+ "name": {
+ "type": "string",
+ "description": "Pipeline display name."
+ },
+ "primaryColumnId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Protected primary column."
+ },
+ "recordType": {
+ "$ref": "#/components/schemas/PipelineRecordType",
+ "description": "Kind of the primary reference."
+ },
+ "sharing": {
+ "$ref": "#/components/schemas/PipelineSharing",
+ "description": "Whether the pipeline has a team grant."
+ },
+ "tableId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Table of entries."
+ },
+ "teamId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Team owning the pipeline; references retain their own access controls."
+ },
+ "trashedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "Trashed pipelines are omitted from navigation."
+ },
+ "userId": {
+ "type": "string",
+ "description": "Owning user; sharing never changes ownership."
+ }
+ }
+ },
+ "PipelineRecordType": {
+ "type": "string",
+ "description": "Which CRM entity each row references. Fixed when a pipeline is created.",
+ "enum": ["company", "contact"]
+ },
+ "PipelineSharing": {
+ "type": "string",
+ "description": "Initial sharing, or the desired team grant. Individual ownership is preserved.",
+ "enum": ["private", "team"]
+ },
"PostActivityRequest": {
"type": "object",
"description": "Request body for `POST /channels/activity`.",
@@ -33008,6 +33505,18 @@
}
}
},
+ "RenamePipeline": {
+ "type": "object",
+ "description": "Rename input.",
+ "required": ["name"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "New display name."
+ }
+ },
+ "additionalProperties": false
+ },
"ReorderFavoritesRequest": {
"type": "object",
"description": "Request body for reordering favorites.",
@@ -33341,6 +33850,11 @@
}
}
},
+ "RowId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Identifier of a row."
+ },
"RowsChange": {
"oneOf": [
{
@@ -34169,6 +34683,18 @@
}
}
},
+ "SharePipeline": {
+ "type": "object",
+ "description": "Sharing input.",
+ "required": ["sharing"],
+ "properties": {
+ "sharing": {
+ "$ref": "#/components/schemas/PipelineSharing",
+ "description": "Desired team grant."
+ }
+ },
+ "additionalProperties": false
+ },
"SharedEmailFilter": {
"type": "string",
"description": "Controls whether shared email threads are included in results.",
@@ -36392,6 +36918,87 @@
}
}
},
+ "StorageRow": {
+ "type": "object",
+ "description": "One storage row, with cells keyed by column placement.",
+ "required": ["rowId", "cells"],
+ "properties": {
+ "cells": {
+ "type": "object",
+ "description": "Populated cells.",
+ "additionalProperties": {
+ "$ref": "#/components/schemas/PropertyValue"
+ },
+ "propertyNames": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Identifier of a column placement within a table."
+ }
+ },
+ "rowId": {
+ "$ref": "#/components/schemas/RowId",
+ "description": "Row identity, independent of any referenced entity."
+ }
+ }
+ },
+ "StorageRows": {
+ "type": "object",
+ "description": "A bounded page of rows at a table version.",
+ "required": ["rows", "version"],
+ "properties": {
+ "next": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/RowId",
+ "description": "Cursor for another page, if present."
+ }
+ ]
+ },
+ "rows": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/StorageRow"
+ },
+ "description": "Rows in the requested view's order."
+ },
+ "version": {
+ "$ref": "#/components/schemas/TableVersion",
+ "description": "Table version when the read began."
+ }
+ }
+ },
+ "StorageRowsQuery": {
+ "type": "object",
+ "description": "A query over one authorized storage table.",
+ "properties": {
+ "after": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/RowId",
+ "description": "Continue after this row in the filtered, sorted result."
+ }
+ ]
+ },
+ "query": {
+ "$ref": "#/components/schemas/ViewQuery",
+ "description": "The common database filter and sort semantics."
+ },
+ "rowIds": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/RowId"
+ },
+ "description": "Read these retained rows regardless of the active filter."
+ }
+ },
+ "additionalProperties": false
+ },
"StoredGithubPullRequest": {
"type": "object",
"description": "A GitHub pull request as Macro stores it, read through one of the caller's records.",
@@ -37458,6 +38065,18 @@
}
}
},
+ "TrashPipeline": {
+ "type": "object",
+ "description": "Trash/restore input.",
+ "required": ["trashed"],
+ "properties": {
+ "trashed": {
+ "type": "boolean",
+ "description": "True to trash; false to restore."
+ }
+ },
+ "additionalProperties": false
+ },
"TurnEndedMetadata": {
"type": "object",
"description": "The runtime answered a turn. Another prompt may follow at once; see\n[`SessionSettledMetadata`] for \"nothing left to do\".",
diff --git a/crates/activity/src/outbound/pg_activity_repo.rs b/crates/activity/src/outbound/pg_activity_repo.rs
index 4e46dbe0f7..d19fb9d261 100644
--- a/crates/activity/src/outbound/pg_activity_repo.rs
+++ b/crates/activity/src/outbound/pg_activity_repo.rs
@@ -450,6 +450,7 @@ const fn _rankable_entity_types_are_exhaustive(entity_type: EntityType) {
| EntityType::ScheduledAction
| EntityType::Initiative
| EntityType::Database
+ | EntityType::CrmPipeline
| EntityType::DatabaseRow
| EntityType::Form => {}
}
diff --git a/crates/ai_tools/src/display_results/schema.generated.json b/crates/ai_tools/src/display_results/schema.generated.json
index 356bc84e16..4a1d60e56c 100644
--- a/crates/ai_tools/src/display_results/schema.generated.json
+++ b/crates/ai_tools/src/display_results/schema.generated.json
@@ -94,6 +94,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -191,6 +192,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
diff --git a/crates/crm/Cargo.toml b/crates/crm/Cargo.toml
index 5270727cef..9b09d95ddc 100644
--- a/crates/crm/Cargo.toml
+++ b/crates/crm/Cargo.toml
@@ -45,6 +45,7 @@ inbound = ["axum", "ports"]
# Read-only company/contact identity for other domains. Pulls only sqlx + ports.
lookup = ["dep:messages", "dep:rootcause", "dep:sqlx", "ports"]
outbound = [
+ "dep:entity_access_db_utils",
"dep:macro_user_id",
"dep:models_properties",
"dep:properties",
@@ -53,12 +54,15 @@ outbound = [
"dep:unfurl",
"ports",
]
-ports = []
+ports = ["dep:databases", "dep:models_databases", "dep:models_properties", "dep:macro_user_id", "dep:macro_uuid", "dep:rootcause", "dep:utoipa", "entity_access/ports"]
# Read-only CRM search (name/domain). Pulls only sqlx + ports — no
# reqwest/unfurl/axum — so search consumers stay lightweight.
search = ["dep:sqlx", "ports"]
[dependencies]
+databases = { path = "../databases", default-features = false, features = ["ports"], optional = true }
+models_databases = { path = "../models_databases", optional = true }
+entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }
anyhow = { workspace = true }
chrono = { workspace = true }
filter_ast = { path = "../filter_ast" }
@@ -103,6 +107,10 @@ unfurl = { path = "../unfurl", features = ["ports"], optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+databases = { path = "../databases", features = ["postgres", "gateway"] }
+entity_access = { path = "../entity_access", default-features = false, features = ["outbound"] }
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
+
macro_db_migrator = { path = "../macro_db_migrator" }
messages = { path = "../messages", default-features = false, features = ["outbound", "test-utils"] }
macro_user_id = { path = "../macro_user_id" }
diff --git a/crates/crm/SALES_BACKFILL.md b/crates/crm/SALES_BACKFILL.md
new file mode 100644
index 0000000000..403b7f8515
--- /dev/null
+++ b/crates/crm/SALES_BACKFILL.md
@@ -0,0 +1,24 @@
+# Legacy CRM → Sales
+
+The normal SQLx migration runner copies existing CRM sales data automatically.
+There is no operator command, per-team checkpoint table, or separate deployment step.
+The migration record and complete copy commit together. Failure rolls everything
+back; rerunning completed migrations does not overwrite edits or recreate deleted pipelines.
+
+Each CRM-enabled team with visible companies receives a team-shared **Sales**
+pipeline owned by its team owner. Every visible company gets a row, including
+Customer, Churned, and unstaged companies. Stage, Owner, and Revenue are copied;
+custom stage order, labels, and legacy mappings are preserved in independent
+pipeline options. Invalid values or unmappable stages abort the migration.
+Hidden companies, disabled CRMs, and private custom properties are not copied.
+
+Source records and properties remain intact. The migration locks its source
+tables while taking the snapshot. Later legacy CRM writes do not update Sales;
+Sales is an independent workflow. Company details, contacts, and activity stay
+on the linked CRM entities. This does not retarget legacy CRM or AI writers.
+
+The data copy is forward-only: its down migration refuses to erase completion
+or user edits. Revert application code without undoing this additive migration.
+Column protections reuse the shared database engine used by Forms. Company
+cells are non-nullable, single-company references; CRM checks the editor's record
+access, without requiring the record and pipeline to belong to the same team.
diff --git a/crates/crm/src/domain.rs b/crates/crm/src/domain.rs
index a16d55b41b..13ba0f3ded 100644
--- a/crates/crm/src/domain.rs
+++ b/crates/crm/src/domain.rs
@@ -37,3 +37,6 @@ pub mod search_service;
/// Contact listing models shared by Soup and the CRM service.
#[cfg(feature = "ports")]
pub mod contact_listing;
+/// CRM pipelines and their lifecycle.
+#[cfg(feature = "ports")]
+pub mod pipelines;
diff --git a/crates/crm/src/domain/pipelines.rs b/crates/crm/src/domain/pipelines.rs
new file mode 100644
index 0000000000..65939d9f00
--- /dev/null
+++ b/crates/crm/src/domain/pipelines.rs
@@ -0,0 +1,721 @@
+//! Company/contact pipelines: CRM policy over reusable database storage.
+
+#[cfg(test)]
+mod test;
+
+use super::{auth::CrmTeamReceipt, stages::StageDefinitionStore};
+use chrono::{DateTime, Utc};
+use databases::domain::{
+ models::{
+ AppliedOps, ColumnId, ColumnProtection, DatabaseId, OpBatch, RowId, TableDetail, TableId,
+ Viewer,
+ },
+ provisioning::{ProvisionedColumn, StorageBlueprint},
+ storage::{DatabaseStorageService, StorageRows, StorageRowsQuery},
+};
+use entity_access::domain::{
+ models::{
+ AccessLevel, EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityType,
+ MemberTeamRole, OwnerAccessLevel, RequiredPermission, ViewAccessLevel,
+ },
+ ports::{AccessiblePipelines, EntityAccessService},
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use models_properties::service::property_option::PropertyOptionValue;
+use models_properties::{DataType, EntityType as PropertyEntityType};
+use serde::{Deserialize, Serialize};
+use std::{collections::HashMap, sync::Arc};
+use uuid::Uuid;
+
+/// Which CRM entity each row references. Fixed when a pipeline is created.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum PipelineRecordType {
+ /// Company memberships.
+ Company,
+ /// Contact memberships.
+ Contact,
+}
+
+impl PipelineRecordType {
+ /// Database representation.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Company => "company",
+ Self::Contact => "contact",
+ }
+ }
+ /// The primary reference's property type.
+ pub fn property_type(self) -> PropertyEntityType {
+ match self {
+ Self::Company => PropertyEntityType::Company,
+ Self::Contact => PropertyEntityType::Contact,
+ }
+ }
+}
+
+/// Initial sharing, or the desired team grant. Individual ownership is preserved.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum PipelineSharing {
+ /// Only the creator, by default.
+ #[default]
+ Private,
+ /// Creator owns; current team members may edit.
+ Team,
+}
+
+/// Request to create an empty pipeline with the standard CRM columns.
+#[derive(Debug, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct CreatePipeline {
+ /// Pipeline name.
+ pub name: String,
+ /// Company or contact entries.
+ pub record_type: PipelineRecordType,
+ /// Defaults to private.
+ #[serde(default)]
+ pub sharing: PipelineSharing,
+}
+
+/// Pipeline metadata; table schema and data are read through the database service.
+#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct Pipeline {
+ /// Entity identity, used with `CrmPipeline` access receipts.
+ pub id: Uuid,
+ /// Team owning the pipeline; references retain their own access controls.
+ pub team_id: Uuid,
+ /// Owning user; sharing never changes ownership.
+ pub user_id: String,
+ /// Pipeline display name.
+ pub name: String,
+ /// Kind of the primary reference.
+ pub record_type: PipelineRecordType,
+ /// Dedicated backing database.
+ #[schema(value_type = Uuid)]
+ pub database_id: DatabaseId,
+ /// Table of entries.
+ #[schema(value_type = Uuid)]
+ pub table_id: TableId,
+ /// Protected primary column.
+ #[schema(value_type = Uuid)]
+ pub primary_column_id: ColumnId,
+ /// Whether the pipeline has a team grant.
+ pub sharing: PipelineSharing,
+ /// Creation time.
+ pub created_at: DateTime<Utc>,
+ /// Trashed pipelines are omitted from navigation.
+ #[schema(required = true)]
+ pub trashed_at: Option<DateTime<Utc>>,
+}
+
+/// Metadata together with the caller's effective grant.
+#[derive(Debug, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AccessiblePipeline {
+ /// Pipeline metadata.
+ #[serde(flatten)]
+ pub pipeline: Pipeline,
+ /// Highest effective access.
+ pub grant: AccessLevel,
+}
+
+/// All records needed for atomic provisioning.
+pub struct PipelineBlueprint {
+ /// Pipeline identity.
+ pub id: Uuid,
+ /// CRM team.
+ pub team_id: Uuid,
+ /// Primary reference kind.
+ pub record_type: PipelineRecordType,
+ /// Initial grants.
+ pub sharing: PipelineSharing,
+ /// Schema owned by the database domain.
+ pub database: StorageBlueprint,
+ /// Pipeline-owned display name.
+ pub name: String,
+ /// Initial owner.
+ pub creator: MacroUserIdStr<'static>,
+ /// Protected company/contact reference.
+ pub primary_column_id: ColumnId,
+}
+
+/// Errors crossing the pipeline boundary.
+#[derive(Debug, thiserror::Error)]
+pub enum PipelineError {
+ /// Invalid user input.
+ #[error("{0}")]
+ Invalid(&'static str),
+ /// Missing or inaccessible pipeline.
+ #[error("Pipeline not found")]
+ NotFound,
+ /// Access-layer refusal.
+ #[error(transparent)]
+ Access(#[from] entity_access::domain::models::AccessError),
+ /// CRM policy failure.
+ #[error(transparent)]
+ Crm(#[from] super::model::CrmError),
+ /// Database operation failure.
+ #[error(transparent)]
+ Database(#[from] databases::domain::models::DatabaseError),
+ /// Persistence failure.
+ #[error("Pipeline storage failed: {0}")]
+ Storage(rootcause::Report),
+}
+
+/// Persistence contract. Transactions and grant writes belong to the adapter.
+pub trait PipelineRepo: Send + Sync + 'static {
+ /// Adapter error.
+ type Error: std::error::Error + Send + Sync + 'static;
+ /// Holds a live pipeline against concurrent trash/deletion.
+ type Guard: Send;
+ /// Acquire a lifecycle guard for reads and writes.
+ fn lock_live(
+ &self,
+ id: Uuid,
+ ) -> impl Future<Output = Result<Option<Self::Guard>, Self::Error>> + Send;
+ /// Rename pipeline metadata.
+ fn rename(&self, id: Uuid, name: &str) -> impl Future<Output = Result<(), Self::Error>> + Send;
+ /// Update pipeline lifecycle metadata.
+ fn set_trashed(
+ &self,
+ id: Uuid,
+ trashed: bool,
+ ) -> impl Future<Output = Result<(), Self::Error>> + Send;
+ /// Facts used by creation policy.
+ fn crm_enabled(&self, team: Uuid) -> impl Future<Output = Result<bool, Self::Error>> + Send;
+ /// Read pipeline metadata for a known set of accessible identities.
+ fn get_many(
+ &self,
+ ids: &[Uuid],
+ ) -> impl Future<Output = Result<Vec<Pipeline>, Self::Error>> + Send;
+ /// Insert metadata, backing database and grants atomically.
+ fn create(
+ &self,
+ blueprint: &PipelineBlueprint,
+ ) -> impl Future<Output = Result<(), Self::Error>> + Send;
+ /// Change the owning team's grant; ownership remains unchanged.
+ fn share(
+ &self,
+ pipeline: &Pipeline,
+ sharing: PipelineSharing,
+ ) -> impl Future<Output = Result<(), Self::Error>> + Send;
+}
+
+/// Pipeline use cases for HTTP and other driving adapters.
+pub trait PipelineService: Send + Sync + 'static {
+ /// Create for the authenticated team member.
+ fn create(
+ &self,
+ team: CrmTeamReceipt<MemberTeamRole>,
+ input: CreatePipeline,
+ ) -> impl Future<Output = Result<AccessiblePipeline, PipelineError>> + Send;
+ /// Visible, live pipelines of this CRM.
+ fn list(
+ &self,
+ team: CrmTeamReceipt<MemberTeamRole>,
+ ) -> impl Future<Output = Result<Vec<AccessiblePipeline>, PipelineError>> + Send;
+ /// Read a pipeline by identity.
+ fn get(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl Future<Output = Result<AccessiblePipeline, PipelineError>> + Send;
+ /// Read the pipeline's schema through its own access boundary.
+ fn table(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl Future<Output = Result<TableDetail, PipelineError>> + Send;
+ /// Read pipeline records, without database app or Soup access.
+ fn rows(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ after: Option<RowId>,
+ ) -> impl Future<Output = Result<StorageRows, PipelineError>> + Send;
+ /// Query pipeline rows with the shared database filter and sort semantics.
+ fn query_rows(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ query: StorageRowsQuery,
+ ) -> impl Future<Output = Result<StorageRows, PipelineError>> + Send;
+
+ /// Validate pipeline policy, then use the shared storage operation planner.
+ fn apply_ops(
+ &self,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
+ batch: OpBatch,
+ ) -> impl Future<Output = Result<AppliedOps, PipelineError>> + Send;
+ /// Rename pipeline metadata.
+ fn rename(
+ &self,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
+ name: String,
+ ) -> impl Future<Output = Result<(), PipelineError>> + Send;
+ /// Change team sharing.
+ fn share(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ sharing: PipelineSharing,
+ ) -> impl Future<Output = Result<(), PipelineError>> + Send;
+ /// Move to trash or restore.
+ fn set_trashed(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ trashed: bool,
+ ) -> impl Future<Output = Result<(), PipelineError>> + Send;
+}
+
+/// Pipeline policy, composed with the owning database and access services.
+pub struct PipelineServiceImpl<Repo, Databases, Access, Stages> {
+ repo: Repo,
+ databases: Arc<Databases>,
+ access: Arc<Access>,
+ stages: Stages,
+}
+
+fn storage(error: impl std::error::Error + Send + Sync + 'static) -> PipelineError {
+ PipelineError::Storage(rootcause::Report::new(error).into_dynamic())
+}
+
+fn actor<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+) -> Result<MacroUserIdStr<'static>, PipelineError> {
+ match receipt.auth() {
+ EntityAccessAuth::Authenticated(user) => Ok(user.clone()),
+ _ => Err(PipelineError::Invalid("An authenticated user is required")),
+ }
+}
+
+fn name(input: &str) -> Result<String, PipelineError> {
+ let input = input.trim();
+ if input.is_empty() || input.chars().count() > 200 {
+ return Err(PipelineError::Invalid(
+ "Use a pipeline name between 1 and 200 characters",
+ ));
+ }
+ Ok(input.to_string())
+}
+
+impl<R: PipelineRepo, D, A, S> PipelineServiceImpl<R, D, A, S> {
+ /// Compose the service from domain capabilities.
+ pub fn new(repo: R, databases: Arc<D>, access: Arc<A>, stages: S) -> Self {
+ Self {
+ repo,
+ databases,
+ access,
+ stages,
+ }
+ }
+
+ async fn pipeline<T: RequiredPermission>(
+ &self,
+ receipt: &EntityAccessReceipt<T>,
+ ) -> Result<Pipeline, PipelineError> {
+ if receipt.entity().entity_type != EntityType::CrmPipeline {
+ return Err(PipelineError::NotFound);
+ }
+ let id = receipt
+ .entity()
+ .entity_id
+ .parse()
+ .map_err(|_| PipelineError::NotFound)?;
+ self.repo
+ .get_many(&[id])
+ .await
+ .map_err(storage)?
+ .pop()
+ .ok_or(PipelineError::NotFound)
+ }
+}
+
+/// Build the common CRM schema without performing I/O. Callers validate the name.
+pub(crate) fn pipeline_blueprint(
+ team_id: Uuid,
+ creator: MacroUserIdStr<'static>,
+ input: CreatePipeline,
+ labels: Vec<String>,
+) -> PipelineBlueprint {
+ let id = macro_uuid::generate_uuid_v7();
+ let primary_column_id = ColumnId::new();
+ let primary = ProvisionedColumn {
+ id: primary_column_id,
+ name: match input.record_type {
+ PipelineRecordType::Company => "Company",
+ PipelineRecordType::Contact => "Contact",
+ }
+ .into(),
+ data_type: DataType::Entity,
+ entity_type: Some(input.record_type.property_type()),
+ options: vec![],
+ nullable: false,
+ protections: vec![ColumnProtection::Delete, ColumnProtection::ChangeType],
+ };
+ let columns = vec![
+ primary,
+ ProvisionedColumn {
+ id: ColumnId::new(),
+ nullable: true,
+ protections: vec![],
+ name: "Stage".into(),
+ data_type: DataType::SelectString,
+ entity_type: None,
+ options: labels
+ .into_iter()
+ .map(|label| {
+ (
+ macro_uuid::generate_uuid_v7(),
+ PropertyOptionValue::String(label),
+ )
+ })
+ .collect(),
+ },
+ ProvisionedColumn {
+ id: ColumnId::new(),
+ nullable: true,
+ protections: vec![],
+ name: "Owner".into(),
+ data_type: DataType::Entity,
+ entity_type: Some(PropertyEntityType::User),
+ options: vec![],
+ },
+ ProvisionedColumn {
+ id: ColumnId::new(),
+ nullable: true,
+ protections: vec![],
+ name: "Revenue".into(),
+ data_type: DataType::Number,
+ entity_type: None,
+ options: vec![],
+ },
+ ];
+ PipelineBlueprint {
+ id,
+ team_id,
+ record_type: input.record_type,
+ sharing: input.sharing,
+ name: input.name,
+ creator,
+ primary_column_id,
+ database: StorageBlueprint {
+ id: DatabaseId::new(),
+ table_id: TableId::new(),
+ columns,
+ },
+ }
+}
+
+impl<R, D, A, S> PipelineService for PipelineServiceImpl<R, D, A, S>
+where
+ R: PipelineRepo,
+ D: DatabaseStorageService,
+ A: EntityAccessService + AccessiblePipelines,
+ S: StageDefinitionStore,
+{
+ async fn create(
+ &self,
+ team: CrmTeamReceipt<MemberTeamRole>,
+ input: CreatePipeline,
+ ) -> Result<AccessiblePipeline, PipelineError> {
+ let name = name(&input.name)?;
+ let creator = actor(team.receipt())?;
+ if !self
+ .repo
+ .crm_enabled(team.team_id())
+ .await
+ .map_err(storage)?
+ {
+ return Err(super::model::CrmError::CrmDisabledForTeam.into());
+ }
+ let stages = self.stages.get_team_stage_set(&team).await?;
+ let labels = stages
+ .map(|set| {
+ set.stages
+ .into_iter()
+ .map(|stage| stage.label)
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_else(|| {
+ use system_properties::StageOption::*;
+ [Lead, Qualified, Demo, Trial, Negotiation, Customer, Churned]
+ .into_iter()
+ .map(|stage| stage.display_value().to_owned())
+ .collect()
+ });
+ let blueprint = pipeline_blueprint(
+ team.team_id(),
+ creator.clone(),
+ CreatePipeline { name, ..input },
+ labels,
+ );
+ let id = blueprint.id;
+ self.repo.create(&blueprint).await.map_err(storage)?;
+ let pipeline = self
+ .repo
+ .get_many(&[id])
+ .await
+ .map_err(storage)?
+ .pop()
+ .ok_or(PipelineError::NotFound)?;
+ Ok(AccessiblePipeline {
+ pipeline,
+ grant: AccessLevel::Owner,
+ })
+ }
+
+ async fn list(
+ &self,
+ team: CrmTeamReceipt<MemberTeamRole>,
+ ) -> Result<Vec<AccessiblePipeline>, PipelineError> {
+ let user = actor(team.receipt())?;
+ let grants: HashMap<_, _> = self
+ .access
+ .accessible_pipelines(&user)
+ .await?
+ .into_iter()
+ .collect();
+ let ids = grants.keys().copied().collect::<Vec<_>>();
+ Ok(self
+ .repo
+ .get_many(&ids)
+ .await
+ .map_err(storage)?
+ .into_iter()
+ .filter(|p| p.team_id == team.team_id() && p.trashed_at.is_none())
+ .map(|pipeline| AccessiblePipeline {
+ grant: grants[&pipeline.id],
+ pipeline,
+ })
+ .collect())
+ }
+
+ async fn get(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<AccessiblePipeline, PipelineError> {
+ let pipeline = self.pipeline(&receipt).await?;
+ if pipeline.trashed_at.is_some() {
+ return Err(PipelineError::NotFound);
+ }
+ let grant = match receipt.entity_permission() {
+ entity_access::domain::models::EntityPermission::AccessLevel { access_level } => {
+ *access_level
+ }
+ _ => AccessLevel::View,
+ };
+ Ok(AccessiblePipeline { pipeline, grant })
+ }
+
+ async fn rename(
+ &self,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
+ input: String,
+ ) -> Result<(), PipelineError> {
+ let name = name(&input)?;
+ let pipeline = self.pipeline(&receipt).await?;
+ if pipeline.trashed_at.is_some() {
+ return Err(PipelineError::NotFound);
+ }
+ self.repo.rename(pipeline.id, &name).await.map_err(storage)
+ }
+
+ async fn share(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ sharing: PipelineSharing,
+ ) -> Result<(), PipelineError> {
+ let pipeline = self.pipeline(&receipt).await?;
+ if pipeline.trashed_at.is_some() {
+ return Err(PipelineError::NotFound);
+ }
+ self.repo.share(&pipeline, sharing).await.map_err(storage)
+ }
+
+ async fn set_trashed(
+ &self,
+ receipt: EntityAccessReceipt<OwnerAccessLevel>,
+ trashed: bool,
+ ) -> Result<(), PipelineError> {
+ let pipeline = self.pipeline(&receipt).await?;
+ self.repo
+ .set_trashed(pipeline.id, trashed)
+ .await
+ .map_err(storage)
+ }
+
+ async fn table(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<TableDetail, PipelineError> {
+ let pipeline = self.pipeline(&receipt).await?;
+ let _guard = self
+ .repo
+ .lock_live(pipeline.id)
+ .await
+ .map_err(storage)?
+ .ok_or(PipelineError::NotFound)?;
+ let mut table = self
+ .databases
+ .storage_tables(pipeline.database_id)
+ .await?
+ .into_iter()
+ .find(|table| table.table.id == pipeline.table_id)
+ .ok_or(PipelineError::NotFound)?;
+ let editable = matches!(
+ receipt.entity_permission(),
+ entity_access::domain::models::EntityPermission::AccessLevel {
+ access_level: AccessLevel::Edit | AccessLevel::Owner
+ }
+ );
+ for column in &mut table.columns {
+ column.writable &= editable;
+ }
+ Ok(table)
+ }
+
+ async fn rows(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ after: Option<RowId>,
+ ) -> Result<StorageRows, PipelineError> {
+ self.query_rows(
+ receipt,
+ StorageRowsQuery {
+ after,
+ ..Default::default()
+ },
+ )
+ .await
+ }
+
+ async fn query_rows(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ query: StorageRowsQuery,
+ ) -> Result<StorageRows, PipelineError> {
+ let pipeline = self.pipeline(&receipt).await?;
+ let _guard = self
+ .repo
+ .lock_live(pipeline.id)
+ .await
+ .map_err(storage)?
+ .ok_or(PipelineError::NotFound)?;
+ Ok(self
+ .databases
+ .storage_rows(pipeline.database_id, pipeline.table_id, query)
+ .await?)
+ }
+
+ async fn apply_ops(
+ &self,
+ receipt: EntityAccessReceipt<EditAccessLevel>,
+ batch: OpBatch,
+ ) -> Result<AppliedOps, PipelineError> {
+ use models_databases::{DatabaseOp, TableChange};
+ let pipeline = self.pipeline(&receipt).await?;
+ for op in &batch.ops {
+ let table = match op {
+ DatabaseOp::Rows { table, .. } | DatabaseOp::View { table, .. } => *table,
+ DatabaseOp::Column { table, .. } => *table,
+ DatabaseOp::Table {
+ table,
+ change: TableChange::ReorderColumns { .. },
+ } => *table,
+ _ => {
+ return Err(PipelineError::Invalid(
+ "A pipeline has one table; customize its columns and records",
+ ));
+ }
+ };
+ if table != pipeline.table_id {
+ return Err(PipelineError::NotFound);
+ }
+ }
+ let viewer = Viewer {
+ user_id: actor(&receipt)?,
+ acting_bot: None,
+ };
+ // A pipeline grant does not grant access to the records it references.
+ // The editor may reference records from any team they can access.
+ for id in primary_references(&pipeline, &batch)? {
+ self.access
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &viewer.user_id,
+ None,
+ &id.to_string(),
+ match pipeline.record_type {
+ PipelineRecordType::Company => EntityType::CrmCompany,
+ PipelineRecordType::Contact => EntityType::CrmContact,
+ },
+ )
+ .await?;
+ }
+ let _guard = self
+ .repo
+ .lock_live(pipeline.id)
+ .await
+ .map_err(storage)?
+ .ok_or(PipelineError::NotFound)?;
+ Ok(self
+ .databases
+ .apply_storage_ops(pipeline.database_id, viewer, batch)
+ .await?)
+ }
+}
+
+/// Distinct primary records explicitly written by this batch. Other cells and
+/// unchanged references do not require the editor to reselect the record.
+fn primary_references(
+ pipeline: &Pipeline,
+ batch: &OpBatch,
+) -> Result<std::collections::BTreeSet<Uuid>, PipelineError> {
+ use models_databases::{CellValue, CellWrite, DatabaseOp, RowChanges, RowsChange};
+ let mut references = std::collections::BTreeSet::new();
+ for op in &batch.ops {
+ let cells: Vec<&CellWrite> = match op {
+ DatabaseOp::Rows {
+ change: RowsChange::Insert { rows },
+ ..
+ } => rows.iter().flatten().collect(),
+ DatabaseOp::Rows {
+ change:
+ RowsChange::Update {
+ changes: RowChanges::Uniform { cells, .. },
+ },
+ ..
+ } => cells.iter().collect(),
+ DatabaseOp::Rows {
+ change:
+ RowsChange::Update {
+ changes: RowChanges::PerRow { rows },
+ },
+ ..
+ } => rows.iter().flat_map(|row| &row.cells).collect(),
+ _ => continue,
+ };
+ for cell in cells {
+ if cell.column != pipeline.primary_column_id {
+ continue;
+ }
+ if let CellValue::Entities(values) = &cell.value {
+ for value in values {
+ let expected = match pipeline.record_type {
+ PipelineRecordType::Company => models_databases::EntityKind::Company,
+ PipelineRecordType::Contact => models_databases::EntityKind::Contact,
+ };
+ if value.entity_type != expected {
+ return Err(PipelineError::Invalid(
+ "Choose the required CRM record type",
+ ));
+ }
+ references.insert(
+ value
+ .entity_id
+ .parse()
+ .map_err(|_| PipelineError::Invalid("Choose a valid CRM record"))?,
+ );
+ }
+ }
+ }
+ }
+ Ok(references)
+}
diff --git a/crates/crm/src/domain/pipelines/test.rs b/crates/crm/src/domain/pipelines/test.rs
new file mode 100644
index 0000000000..f320eb6727
--- /dev/null
+++ b/crates/crm/src/domain/pipelines/test.rs
@@ -0,0 +1,26 @@
+use super::*;
+
+#[test]
+fn creation_is_private_unless_requested_otherwise() {
+ let input: CreatePipeline = serde_json::from_value(serde_json::json!({
+ "name": "Renewals", "recordType": "company"
+ }))
+ .unwrap();
+ assert_eq!(input.sharing, PipelineSharing::Private);
+ assert_eq!(
+ input.record_type.property_type(),
+ PropertyEntityType::Company
+ );
+ assert_eq!(
+ PipelineRecordType::Contact.property_type(),
+ PropertyEntityType::Contact
+ );
+}
+
+#[test]
+fn names_are_trimmed_and_limited_by_characters() {
+ assert_eq!(name(" Renewals ").unwrap(), "Renewals");
+ assert!(name(" \n ").is_err());
+ assert!(name(&"あ".repeat(200)).is_ok());
+ assert!(name(&"あ".repeat(201)).is_err());
+}
diff --git a/crates/crm/src/inbound.rs b/crates/crm/src/inbound.rs
index 6ff68b7fe7..038aa36849 100644
--- a/crates/crm/src/inbound.rs
+++ b/crates/crm/src/inbound.rs
@@ -8,3 +8,7 @@ pub mod axum_router;
pub mod call_archived;
#[cfg(feature = "ai_tools")]
pub mod toolset;
+
+/// Pipeline routes.
+#[cfg(feature = "axum")]
+pub mod pipelines;
diff --git a/crates/crm/src/inbound/pipelines.rs b/crates/crm/src/inbound/pipelines.rs
new file mode 100644
index 0000000000..560cb97dc8
--- /dev/null
+++ b/crates/crm/src/inbound/pipelines.rs
@@ -0,0 +1,371 @@
+//! Thin HTTP adapters for pipeline creation, navigation, sharing and lifecycle.
+
+use crate::domain::{
+ auth::CrmTeamReceipt,
+ pipelines::{
+ AccessiblePipeline, CreatePipeline, PipelineError, PipelineService, PipelineSharing,
+ },
+};
+use axum::{
+ Json, Router,
+ extract::{FromRef, Path, Query, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+ routing::{get, post, put},
+};
+use entity_access::{
+ domain::{
+ models::{
+ EditAccessLevel, EntityAccessReceipt, EntityType, MemberTeamRole, OwnerAccessLevel,
+ RequiredPermission, ViewAccessLevel,
+ },
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::MacroUserTeamExtractorV2,
+};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
+};
+use serde::Deserialize;
+use std::sync::Arc;
+use uuid::Uuid;
+
+/// Services used by pipeline routes.
+pub struct PipelineRouterState<P, E, A> {
+ /// Pipeline domain service.
+ pub service: Arc<P>,
+ /// Entity access receipt issuer.
+ pub access: Arc<E>,
+ /// Authentication state.
+ pub authorization: MacroAuthorizationState<A>,
+}
+
+impl<P, E, A> Clone for PipelineRouterState<P, E, A> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ access: self.access.clone(),
+ authorization: self.authorization.clone(),
+ }
+ }
+}
+impl<P, E, A> FromRef<PipelineRouterState<P, E, A>> for Arc<E> {
+ fn from_ref(state: &PipelineRouterState<P, E, A>) -> Self {
+ state.access.clone()
+ }
+}
+impl<P, E, A> FromRef<PipelineRouterState<P, E, A>> for MacroAuthorizationState<A> {
+ fn from_ref(state: &PipelineRouterState<P, E, A>) -> Self {
+ state.authorization.clone()
+ }
+}
+
+/// Mount at `/crm/pipelines`.
+pub fn router<P, E, A, S>(state: PipelineRouterState<P, E, A>) -> Router<S>
+where
+ P: PipelineService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+ S: Send + Sync + 'static,
+{
+ Router::new()
+ .route("/", get(list::<P, E, A>).post(create::<P, E, A>))
+ .route("/{id}", get(read::<P, E, A>))
+ .route("/{id}/table", get(table::<P, E, A>))
+ .route(
+ "/{id}/rows",
+ get(rows::<P, E, A>).post(query_rows::<P, E, A>),
+ )
+ .route("/{id}/ops", post(apply_ops::<P, E, A>))
+ .route("/{id}/name", put(rename::<P, E, A>))
+ .route("/{id}/sharing", put(share::<P, E, A>))
+ .route("/{id}/trash", put(trash::<P, E, A>))
+ .with_state(state)
+}
+
+/// Create a private or team-shared pipeline.
+#[utoipa::path(post, path = "/crm/pipelines", operation_id = "create_crm_pipeline", request_body = CreatePipeline,
+ responses((status = 200, body = AccessiblePipeline)))]
+pub async fn create<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ team: MacroUserTeamExtractorV2<MemberTeamRole, E, A>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Json(input): Json<CreatePipeline>,
+) -> Result<Json<AccessiblePipeline>, PipelineError> {
+ Ok(Json(
+ state
+ .service
+ .create(
+ CrmTeamReceipt::from_team_receipt(team.entity_access_receipt)?,
+ input,
+ )
+ .await?,
+ ))
+}
+
+/// List the caller's live pipelines in their CRM.
+#[utoipa::path(get, path = "/crm/pipelines", operation_id = "list_crm_pipelines",
+ responses((status = 200, body = Vec<AccessiblePipeline>)))]
+pub async fn list<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ team: MacroUserTeamExtractorV2<MemberTeamRole, E, A>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+) -> Result<Json<Vec<AccessiblePipeline>>, PipelineError> {
+ Ok(Json(
+ state
+ .service
+ .list(CrmTeamReceipt::from_team_receipt(
+ team.entity_access_receipt,
+ )?)
+ .await?,
+ ))
+}
+
+async fn receipt<T: RequiredPermission, E: EntityAccessService, A: MacroAuthorizationService>(
+ access: &E,
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ id: Uuid,
+) -> Result<EntityAccessReceipt<T>, PipelineError> {
+ Ok(access
+ .generate_entity_access_receipt::<T>(
+ &auth.authorization.user.macro_user_id,
+ None,
+ &id.to_string(),
+ EntityType::CrmPipeline,
+ )
+ .await?)
+}
+
+/// Read one pipeline by its entity identity.
+#[utoipa::path(get, path = "/crm/pipelines/{id}", operation_id = "get_crm_pipeline",
+ params(("id" = Uuid, Path)), responses((status = 200, body = AccessiblePipeline)))]
+pub async fn read<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<AccessiblePipeline>, PipelineError> {
+ Ok(Json(
+ state
+ .service
+ .get(receipt::<ViewAccessLevel, _, _>(&*state.access, auth, id).await?)
+ .await?,
+ ))
+}
+
+/// Read the host-owned table schema.
+#[utoipa::path(get, path = "/crm/pipelines/{id}/table", operation_id = "get_crm_pipeline_table",
+ params(("id" = Uuid, Path)), responses((status = 200, body = databases::domain::models::TableDetail)))]
+pub async fn table<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+) -> Result<Json<databases::domain::models::TableDetail>, PipelineError> {
+ Ok(Json(
+ state
+ .service
+ .table(receipt::<ViewAccessLevel, _, _>(&*state.access, auth, id).await?)
+ .await?,
+ ))
+}
+
+/// Pagination through pipeline records.
+#[derive(Deserialize, utoipa::IntoParams)]
+pub struct RowsQuery {
+ /// Continue after this row identity.
+ pub after: Option<Uuid>,
+}
+
+/// Read pipeline records through pipeline access.
+#[utoipa::path(get, path = "/crm/pipelines/{id}/rows", operation_id = "get_crm_pipeline_rows",
+ params(("id" = Uuid, Path), RowsQuery), responses((status = 200, body = databases::domain::storage::StorageRows)))]
+pub async fn rows<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+ Query(query): Query<RowsQuery>,
+) -> Result<Json<databases::domain::storage::StorageRows>, PipelineError> {
+ Ok(Json(
+ state
+ .service
+ .rows(
+ receipt::<ViewAccessLevel, _, _>(&*state.access, auth, id).await?,
+ query.after.map(models_databases::RowId::from_uuid),
+ )
+ .await?,
+ ))
+}
+
+/// Query rows through pipeline access using the shared view protocol.
+#[utoipa::path(post, path = "/crm/pipelines/{id}/rows", operation_id = "query_crm_pipeline_rows",
+ request_body = databases::domain::storage::StorageRowsQuery, params(("id" = Uuid, Path)), responses((status = 200, body = databases::domain::storage::StorageRows)))]
+pub async fn query_rows<
+ P: PipelineService,
+ E: EntityAccessService,
+ A: MacroAuthorizationService,
+>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+ Json(query): Json<databases::domain::storage::StorageRowsQuery>,
+) -> Result<Json<databases::domain::storage::StorageRows>, PipelineError> {
+ Ok(Json(
+ state
+ .service
+ .query_rows(
+ receipt::<ViewAccessLevel, _, _>(&*state.access, auth, id).await?,
+ query,
+ )
+ .await?,
+ ))
+}
+
+/// Edit pipeline schema or records with the common typed operations.
+#[utoipa::path(post, path = "/crm/pipelines/{id}/ops", operation_id = "apply_crm_pipeline_ops",
+ request_body = databases::domain::models::OpBatch, params(("id" = Uuid, Path)), responses((status = 200, body = databases::domain::models::AppliedOps)))]
+pub async fn apply_ops<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+ Json(batch): Json<databases::domain::models::OpBatch>,
+) -> Result<Json<databases::domain::models::AppliedOps>, PipelineError> {
+ Ok(Json(
+ state
+ .service
+ .apply_ops(
+ receipt::<EditAccessLevel, _, _>(&*state.access, auth, id).await?,
+ batch,
+ )
+ .await?,
+ ))
+}
+
+/// Rename input.
+#[derive(Deserialize, utoipa::ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct RenamePipeline {
+ /// New display name.
+ pub name: String,
+}
+/// Sharing input.
+#[derive(Deserialize, utoipa::ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct SharePipeline {
+ /// Desired team grant.
+ pub sharing: PipelineSharing,
+}
+/// Trash/restore input.
+#[derive(Deserialize, utoipa::ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct TrashPipeline {
+ /// True to trash; false to restore.
+ pub trashed: bool,
+}
+
+/// Rename a pipeline.
+#[utoipa::path(put, path = "/crm/pipelines/{id}/name", operation_id = "rename_crm_pipeline", request_body = RenamePipeline,
+ params(("id" = Uuid, Path)), responses((status = 204)))]
+pub async fn rename<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+ Json(input): Json<RenamePipeline>,
+) -> Result<StatusCode, PipelineError> {
+ state
+ .service
+ .rename(
+ receipt::<EditAccessLevel, _, _>(&*state.access, auth, id).await?,
+ input.name,
+ )
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+/// Update sharing.
+#[utoipa::path(put, path = "/crm/pipelines/{id}/sharing", operation_id = "share_crm_pipeline", request_body = SharePipeline,
+ params(("id" = Uuid, Path)), responses((status = 204)))]
+pub async fn share<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+ Json(input): Json<SharePipeline>,
+) -> Result<StatusCode, PipelineError> {
+ state
+ .service
+ .share(
+ receipt::<OwnerAccessLevel, _, _>(&*state.access, auth, id).await?,
+ input.sharing,
+ )
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+/// Trash or restore a pipeline.
+#[utoipa::path(put, path = "/crm/pipelines/{id}/trash", operation_id = "trash_crm_pipeline", request_body = TrashPipeline,
+ params(("id" = Uuid, Path)), responses((status = 204)))]
+pub async fn trash<P: PipelineService, E: EntityAccessService, A: MacroAuthorizationService>(
+ auth: MacroAuthorizationExtractor<A, UserOrInternal>,
+ State(state): State<PipelineRouterState<P, E, A>>,
+ Path(id): Path<Uuid>,
+ Json(input): Json<TrashPipeline>,
+) -> Result<StatusCode, PipelineError> {
+ state
+ .service
+ .set_trashed(
+ receipt::<OwnerAccessLevel, _, _>(&*state.access, auth, id).await?,
+ input.trashed,
+ )
+ .await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
+impl IntoResponse for PipelineError {
+ fn into_response(self) -> Response {
+ match self {
+ Self::Invalid(message) => (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({"message": message})),
+ )
+ .into_response(),
+ Self::NotFound => StatusCode::NOT_FOUND.into_response(),
+ Self::Access(error) => {
+ entity_access::inbound::axum_extractors::ExtractorError::from(error).into_response()
+ }
+ Self::Crm(error) => error.into_response(),
+ Self::Database(error) => {
+ use databases::domain::models::DatabaseError;
+ let status = match error {
+ DatabaseError::InvalidOp(refusal) => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "message": refusal.reason,
+ "op": refusal.op,
+ "row": refusal.row,
+ "column": refusal.column,
+ "taken": refusal.taken,
+ })),
+ )
+ .into_response();
+ }
+ DatabaseError::NotFound => StatusCode::NOT_FOUND,
+ DatabaseError::Unauthorized => StatusCode::FORBIDDEN,
+ DatabaseError::InvalidSchemaOperation(_) | DatabaseError::InvalidSharing(_) => {
+ StatusCode::BAD_REQUEST
+ }
+ DatabaseError::RowInUse
+ | DatabaseError::OptionInUse
+ | DatabaseError::VersionConflict => StatusCode::CONFLICT,
+ DatabaseError::Repo(error) => {
+ tracing::error!(error = ?error, "pipeline database request failed");
+ return StatusCode::INTERNAL_SERVER_ERROR.into_response();
+ }
+ };
+ (
+ status,
+ Json(serde_json::json!({"message": error.to_string()})),
+ )
+ .into_response()
+ }
+ error => {
+ tracing::error!(error = ?error, "pipeline request failed");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ }
+ }
+ }
+}
diff --git a/crates/crm/src/outbound.rs b/crates/crm/src/outbound.rs
index eb9406ed2f..0146528440 100644
--- a/crates/crm/src/outbound.rs
+++ b/crates/crm/src/outbound.rs
@@ -22,3 +22,7 @@ pub mod stage_definitions;
/// Unfurl-backed implementation of the company metadata resolver
#[cfg(feature = "outbound")]
pub mod unfurl_resolver;
+
+/// Atomic pipeline storage over the databases domain writer.
+#[cfg(feature = "outbound")]
+pub mod pipelines;
diff --git a/crates/crm/src/outbound/pipelines.rs b/crates/crm/src/outbound/pipelines.rs
new file mode 100644
index 0000000000..b6350d3e40
--- /dev/null
+++ b/crates/crm/src/outbound/pipelines.rs
@@ -0,0 +1,211 @@
+//! Pipeline metadata and grants, composed with the database domain's writer.
+
+use crate::domain::pipelines::{
+ Pipeline, PipelineBlueprint, PipelineRecordType, PipelineRepo, PipelineSharing,
+};
+use databases::domain::provisioning::DatabaseStorageProvisioner;
+use entity_access_db_utils::{AccessLevel, EntityAccessSourceType, EntityType};
+use models_databases::{ColumnId, DatabaseId, TableId};
+use sqlx::{PgPool, Postgres, Transaction};
+use uuid::Uuid;
+
+/// Pipeline persistence errors.
+#[derive(Debug, thiserror::Error)]
+pub enum PipelineRepoError {
+ /// SQL failure rolls back the entire operation.
+ #[error(transparent)]
+ Sqlx(#[from] sqlx::Error),
+ /// Database provisioning failure.
+ #[error("Database provisioning failed: {0}")]
+ Database(#[source] Box<dyn std::error::Error + Send + Sync>),
+}
+
+/// Owns only CRM metadata; database storage is accessed through its domain port.
+pub struct PgPipelineRepo<Database> {
+ pool: PgPool,
+ database: Database,
+}
+
+impl<Database> PgPipelineRepo<Database> {
+ /// Construct at the application's composition root.
+ pub fn new(pool: PgPool, database: Database) -> Self {
+ Self { pool, database }
+ }
+}
+
+impl<Database> PgPipelineRepo<Database>
+where
+ Database: DatabaseStorageProvisioner<Transaction = Transaction<'static, Postgres>>,
+{
+ async fn create_in(
+ &self,
+ transaction: &mut Transaction<'static, Postgres>,
+ blueprint: &PipelineBlueprint,
+ ) -> Result<(), PipelineRepoError> {
+ self.database
+ .create_storage_in(transaction, &blueprint.database)
+ .await
+ .map_err(|error| PipelineRepoError::Database(Box::new(error)))?;
+ sqlx::query!(
+ "INSERT INTO crm_pipeline_entities (id, team_id, database_id, table_id, record_type, name, user_id, primary_column_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ blueprint.id, blueprint.team_id, blueprint.database.id.into_uuid(),
+ blueprint.database.table_id.into_uuid(), blueprint.record_type.as_str(), &blueprint.name, blueprint.creator.as_ref(), blueprint.primary_column_id.into_uuid(),
+ ).execute(&mut **transaction).await?;
+ entity_access_db_utils::insert_entity_access_row(
+ transaction,
+ &blueprint.id,
+ EntityType::CrmPipeline,
+ blueprint.creator.as_ref(),
+ EntityAccessSourceType::User,
+ AccessLevel::Owner,
+ )
+ .await?;
+ if blueprint.sharing == PipelineSharing::Team {
+ entity_access_db_utils::team_share::upsert_direct(
+ transaction,
+ &blueprint.id,
+ EntityType::CrmPipeline,
+ blueprint.team_id,
+ AccessLevel::Edit,
+ )
+ .await?;
+ }
+ Ok(())
+ }
+}
+
+impl<Database> PipelineRepo for PgPipelineRepo<Database>
+where
+ Database: DatabaseStorageProvisioner<Transaction = Transaction<'static, Postgres>>,
+{
+ type Error = PipelineRepoError;
+
+ async fn crm_enabled(&self, team: Uuid) -> Result<bool, Self::Error> {
+ Ok(sqlx::query_scalar!(
+ "SELECT crm_enabled FROM team_crm_settings WHERE team_id = $1",
+ team
+ )
+ .fetch_optional(&self.pool)
+ .await?
+ .unwrap_or(false))
+ }
+
+ async fn get_many(&self, ids: &[Uuid]) -> Result<Vec<Pipeline>, Self::Error> {
+ let rows = sqlx::query!(
+ r#"SELECT p.id, p.team_id, p.record_type, p.database_id, p.table_id,
+ p.name, p.user_id, p.created_at, p.trashed_at, p.primary_column_id,
+ EXISTS (SELECT 1 FROM entity_access ea WHERE ea.entity_id = p.id
+ AND ea.entity_type = 'crm_pipeline' AND ea.source_type = 'team'
+ AND ea.source_id = p.team_id::text) AS "team_shared!"
+ FROM crm_pipeline_entities p
+ WHERE p.id = ANY($1) ORDER BY p.id"#,
+ ids,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+ rows.into_iter()
+ .map(|row| {
+ let record_type = match row.record_type.as_str() {
+ "company" => PipelineRecordType::Company,
+ "contact" => PipelineRecordType::Contact,
+ _ => {
+ return Err(
+ sqlx::Error::Decode("Invalid pipeline record type".into()).into()
+ );
+ }
+ };
+ Ok(Pipeline {
+ id: row.id,
+ team_id: row.team_id,
+ name: row.name,
+ user_id: row.user_id,
+ record_type,
+ database_id: DatabaseId::from_uuid(row.database_id),
+ table_id: TableId::from_uuid(row.table_id),
+ primary_column_id: ColumnId::from_uuid(row.primary_column_id),
+ created_at: row.created_at,
+ trashed_at: row.trashed_at,
+ sharing: if row.team_shared {
+ PipelineSharing::Team
+ } else {
+ PipelineSharing::Private
+ },
+ })
+ })
+ .collect()
+ }
+
+ type Guard = Transaction<'static, Postgres>;
+
+ async fn lock_live(&self, id: Uuid) -> Result<Option<Self::Guard>, Self::Error> {
+ let mut tx = self.pool.begin().await?;
+ let row = sqlx::query!(
+ "SELECT id FROM crm_pipeline_entities WHERE id = $1 AND trashed_at IS NULL FOR SHARE",
+ id
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+ Ok(row.map(|_| tx))
+ }
+
+ async fn rename(&self, id: Uuid, name: &str) -> Result<(), Self::Error> {
+ sqlx::query!("UPDATE crm_pipeline_entities SET name = $2, updated_at = now() WHERE id = $1 AND trashed_at IS NULL", id, name)
+ .execute(&self.pool).await?;
+ Ok(())
+ }
+
+ async fn set_trashed(&self, id: Uuid, trashed: bool) -> Result<(), Self::Error> {
+ sqlx::query!("UPDATE crm_pipeline_entities SET trashed_at = CASE WHEN $2 THEN now() ELSE NULL END, updated_at = now() WHERE id = $1", id, trashed)
+ .execute(&self.pool).await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(skip_all, err)]
+ async fn create(&self, blueprint: &PipelineBlueprint) -> Result<(), Self::Error> {
+ let mut transaction = self.pool.begin().await?;
+ entity_access_db_utils::team_share::acquire_guard(&mut transaction).await?;
+ self.create_in(&mut transaction, blueprint).await?;
+ transaction.commit().await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(skip_all, err)]
+ async fn share(
+ &self,
+ pipeline: &Pipeline,
+ sharing: PipelineSharing,
+ ) -> Result<(), Self::Error> {
+ let mut transaction = self.pool.begin().await?;
+ entity_access_db_utils::team_share::acquire_guard(&mut transaction).await?;
+ // Serialize sharing with pipeline deletion.
+ sqlx::query!(
+ "SELECT id FROM crm_pipeline_entities WHERE id = $1 FOR UPDATE",
+ pipeline.id
+ )
+ .fetch_one(&mut *transaction)
+ .await?;
+ match sharing {
+ PipelineSharing::Team => {
+ entity_access_db_utils::team_share::upsert_direct(
+ &mut transaction,
+ &pipeline.id,
+ EntityType::CrmPipeline,
+ pipeline.team_id,
+ AccessLevel::Edit,
+ )
+ .await?
+ }
+ PipelineSharing::Private => {
+ entity_access_db_utils::team_share::delete_direct(
+ &mut transaction,
+ &pipeline.id,
+ EntityType::CrmPipeline,
+ pipeline.team_id,
+ )
+ .await?
+ }
+ }
+ transaction.commit().await?;
+ Ok(())
+ }
+}
diff --git a/crates/crm/tests/pipelines.rs b/crates/crm/tests/pipelines.rs
new file mode 100644
index 0000000000..f15396de78
--- /dev/null
+++ b/crates/crm/tests/pipelines.rs
@@ -0,0 +1,931 @@
+//! Pipeline policy and access boundaries, exercised through real domain services.
+#![cfg(feature = "outbound")]
+
+use crm::domain::{auth::CrmTeamReceipt, model::CrmError, pipelines::*, stages::*};
+use crm::outbound::pipelines::PgPipelineRepo;
+use databases::domain::models::DatabaseError;
+use databases::outbound::{
+ gateway_event_publisher::NoOpTableEventPublisher, pg_cell_store::PgCellStore,
+};
+use databases::wiring::{PgDatabasesService, build_service};
+use entity_access::{
+ domain::{
+ models::*,
+ ports::{AccessibleDatabases, EntityAccessService},
+ service::EntityAccessServiceImpl,
+ },
+ outbound::PgAccessRepository,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_event_broker::NoopMacroEventBroker;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_databases::*;
+use properties::PropertiesPgRepo;
+use serde_json::json;
+use sqlx::PgPool;
+use std::sync::Arc;
+use uuid::Uuid;
+
+const OWNER: &str = "macro|[email protected]";
+const MEMBER: &str = "macro|[email protected]";
+const OUTSIDER: &str = "macro|[email protected]";
+type Access = EntityAccessServiceImpl<PgAccessRepository>;
+type DatabaseService = PgDatabasesService<NoOpTableEventPublisher, NoopMacroEventBroker, Access>;
+type Service = PipelineServiceImpl<
+ PgPipelineRepo<PgCellStore<PropertiesPgRepo>>,
+ DatabaseService,
+ Access,
+ Stages,
+>;
+
+// A customized team template: the pipeline must copy it without sharing option IDs.
+struct Stages;
+impl StageDefinitionStore for Stages {
+ async fn get_team_stage_set(
+ &self,
+ _: &CrmTeamReceipt<MemberTeamRole>,
+ ) -> Result<Option<TeamStageSet>, CrmError> {
+ Ok(Some(TeamStageSet {
+ definition_id: Uuid::nil(),
+ stages: vec![
+ TeamStage {
+ id: Uuid::nil(),
+ label: "Prospect".into(),
+ display_order: 0,
+ },
+ TeamStage {
+ id: Uuid::nil(),
+ label: "Won".into(),
+ display_order: 1,
+ },
+ ],
+ }))
+ }
+ async fn create_team_stage_set(
+ &self,
+ _: &CrmTeamReceipt<MemberTeamRole>,
+ _: &[String],
+ ) -> Result<TeamStageSet, CrmError> {
+ panic!("pipeline creation must not edit the template")
+ }
+ async fn replace_stages(
+ &self,
+ _: &CrmTeamReceipt<MemberTeamRole>,
+ _: Uuid,
+ _: StageReplacePlan,
+ ) -> Result<TeamStageSet, CrmError> {
+ panic!("must not edit the template")
+ }
+ async fn delete_team_stage_set(
+ &self,
+ _: &CrmTeamReceipt<MemberTeamRole>,
+ _: Uuid,
+ ) -> Result<(), CrmError> {
+ panic!("must not edit the template")
+ }
+}
+fn user(id: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str(id).unwrap().into_owned()
+}
+fn team_receipt(team: Uuid, id: &str) -> CrmTeamReceipt<MemberTeamRole> {
+ CrmTeamReceipt::from_team_receipt(
+ EntityAccessReceipt::try_new_authenticated_user(
+ user(id),
+ Entity {
+ entity_id: team.to_string(),
+ entity_type: EntityType::Team,
+ },
+ EntityPermission::TeamRole {
+ role: TeamRole::Member,
+ },
+ )
+ .unwrap(),
+ )
+ .unwrap()
+}
+async fn access<T: RequiredPermission>(
+ a: &Access,
+ id: Uuid,
+ kind: EntityType,
+ actor: &str,
+) -> EntityAccessReceipt<T> {
+ a.generate_entity_access_receipt(&user(actor), None, &id.to_string(), kind)
+ .await
+ .unwrap()
+}
+async fn fixture(pool: &PgPool) -> (Service, Arc<DatabaseService>, Arc<Access>, Uuid, Uuid) {
+ for id in [OWNER, MEMBER, OUTSIDER] {
+ let uid = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$2)",
+ uid,
+ id
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1,$1,$2)"#,
+ id,
+ uid
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ }
+ let team = Uuid::now_v7();
+ sqlx::query!(
+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1,'Sales',$2)"#,
+ team,
+ OWNER
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ for id in [OWNER, MEMBER] {
+ sqlx::query!(
+ r#"INSERT INTO team_user (team_id,user_id,team_role) VALUES ($1,$2,'member')"#,
+ team,
+ id
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ }
+ sqlx::query!(
+ r#"INSERT INTO team_crm_settings (team_id,crm_enabled) VALUES ($1,true)"#,
+ team
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ let company = Uuid::now_v7();
+ sqlx::query!(r#"INSERT INTO crm_companies (id,team_id,first_interaction,last_interaction) VALUES ($1,$2,now(),now())"#, company, team).execute(pool).await.unwrap();
+ let a = Arc::new(Access::new(PgAccessRepository::new(pool.clone())));
+ let db = Arc::new(build_service(
+ pool.clone(),
+ a.clone(),
+ NoOpTableEventPublisher,
+ NoopMacroEventBroker,
+ ));
+ let svc = Service::new(
+ PgPipelineRepo::new(
+ pool.clone(),
+ PgCellStore::new(pool.clone(), PropertiesPgRepo::new(pool.clone())),
+ ),
+ db.clone(),
+ a.clone(),
+ Stages,
+ );
+ (svc, db, a, team, company)
+}
+async fn create(s: &Service, team: Uuid, record_type: PipelineRecordType) -> Pipeline {
+ s.create(
+ team_receipt(team, OWNER),
+ CreatePipeline {
+ name: " Renewals ".into(),
+ record_type,
+ sharing: PipelineSharing::Private,
+ },
+ )
+ .await
+ .unwrap()
+ .pipeline
+}
+fn insert(p: &Pipeline, entity: Uuid) -> DatabaseOp {
+ serde_json::from_value(json!({"kind":"rows", "table":p.table_id, "change":{"kind":"insert", "rows":[[{"column":p.primary_column_id, "value":{"type":"entities","value":[{"entityType":p.record_type.as_str().to_uppercase(),"entityId":entity.to_string()}]}}]]}})).unwrap()
+}
+async fn write(
+ s: &Service,
+ a: &Access,
+ p: &Pipeline,
+ ops: Vec<DatabaseOp>,
+) -> Result<Vec<OpResult>, PipelineError> {
+ s.apply_ops(
+ access(a, p.id, EntityType::CrmPipeline, OWNER).await,
+ ops.into(),
+ )
+ .await
+ .map(|applied| applied.results)
+}
+
+fn inserted(result: &[OpResult]) -> RowId {
+ match &result[0] {
+ OpResult::Rows {
+ change: RowsResult::Inserted { rows },
+ ..
+ } => rows[0],
+ other => panic!("{other:?}"),
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn private_defaults_team_sharing_and_revocation_cover_database_and_rows(pool: PgPool) {
+ let (s, _db, a, team, company) = fixture(&pool).await;
+ let p = create(&s, team, PipelineRecordType::Company).await;
+ assert_eq!(p.name, "Renewals");
+ assert_eq!(p.sharing, PipelineSharing::Private);
+ assert!(s.list(team_receipt(team, MEMBER)).await.unwrap().is_empty());
+ let detail = s
+ .table(access(&a, p.id, EntityType::CrmPipeline, OWNER).await)
+ .await
+ .unwrap();
+ assert_eq!(detail.columns.len(), 4);
+ let columns = &detail.columns;
+ assert_eq!(
+ columns
+ .iter()
+ .map(|c| c.definition.definition.display_name.as_str())
+ .collect::<Vec<_>>(),
+ vec!["Company", "Stage", "Owner", "Revenue"]
+ );
+ let stage = &columns[1].definition;
+ assert_eq!(
+ stage
+ .property_options
+ .iter()
+ .filter_map(|option| option.value.as_string())
+ .collect::<Vec<_>>(),
+ vec!["Prospect", "Won"]
+ );
+ assert!(
+ stage
+ .property_options
+ .iter()
+ .all(|option| option.id != Uuid::nil())
+ );
+ let row = inserted(&write(&s, &a, &p, vec![insert(&p, company)]).await.unwrap());
+ for actor in [MEMBER, OUTSIDER] {
+ for (id, kind) in [
+ (p.id, EntityType::CrmPipeline),
+ (p.database_id.into_uuid(), EntityType::Database),
+ (row.into_uuid(), EntityType::DatabaseRow),
+ ] {
+ assert_eq!(
+ a.get_access_level(Some(&user(actor)), &id.to_string(), kind)
+ .await
+ .unwrap(),
+ None
+ );
+ }
+ }
+ s.share(
+ access(&a, p.id, EntityType::CrmPipeline, OWNER).await,
+ PipelineSharing::Team,
+ )
+ .await
+ .unwrap();
+ assert_eq!(s.list(team_receipt(team, MEMBER)).await.unwrap().len(), 1);
+ assert_eq!(
+ a.get_access_level(
+ Some(&user(MEMBER)),
+ &p.id.to_string(),
+ EntityType::CrmPipeline
+ )
+ .await
+ .unwrap(),
+ Some(AccessLevel::Edit)
+ );
+ assert!(
+ a.generate_entity_access_receipt::<OwnerAccessLevel>(
+ &user(MEMBER),
+ None,
+ &p.id.to_string(),
+ EntityType::CrmPipeline
+ )
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ s.rows(
+ access(&a, p.id, EntityType::CrmPipeline, MEMBER).await,
+ None
+ )
+ .await
+ .unwrap()
+ .rows
+ .len(),
+ 1
+ );
+ for actor in [OWNER, MEMBER] {
+ for (id, kind) in [
+ (p.database_id.into_uuid(), EntityType::Database),
+ (row.into_uuid(), EntityType::DatabaseRow),
+ ] {
+ assert_eq!(
+ a.get_access_level(Some(&user(actor)), &id.to_string(), kind)
+ .await
+ .unwrap(),
+ None
+ );
+ }
+ assert!(
+ a.accessible_databases(&user(actor))
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM database_entities")
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ s.share(
+ access(&a, p.id, EntityType::CrmPipeline, OWNER).await,
+ PipelineSharing::Private,
+ )
+ .await
+ .unwrap();
+ assert!(
+ a.accessible_databases(&user(MEMBER))
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ a.get_access_level(
+ Some(&user(MEMBER)),
+ &row.to_string(),
+ EntityType::DatabaseRow
+ )
+ .await
+ .unwrap(),
+ None
+ );
+ assert_eq!(
+ a.get_access_level(
+ Some(&user(OWNER)),
+ &p.id.to_string(),
+ EntityType::CrmPipeline
+ )
+ .await
+ .unwrap(),
+ Some(AccessLevel::Owner)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn primary_record_is_required_and_protected_but_can_repeat(pool: PgPool) {
+ let (s, _db, a, team, company) = fixture(&pool).await;
+ let p = create(&s, team, PipelineRecordType::Company).await;
+ let row = inserted(&write(&s, &a, &p, vec![insert(&p, company)]).await.unwrap());
+ let duplicate = inserted(&write(&s, &a, &p, vec![insert(&p, company)]).await.unwrap());
+ assert_ne!(row, duplicate);
+ let blank = serde_json::from_value(
+ json!({"kind":"rows","table":p.table_id,"change":{"kind":"insert","rows":[[]]}}),
+ )
+ .unwrap();
+ assert!(matches!(
+ write(&s, &a, &p, vec![blank]).await,
+ Err(PipelineError::Database(DatabaseError::InvalidOp(_))) | Err(PipelineError::Invalid(_))
+ ));
+ let clear = serde_json::from_value(json!({"kind":"rows","table":p.table_id,"change":{"kind":"update","changes":{"kind":"uniform","rows":[row],"cells":[{"column":p.primary_column_id,"value":{"type":"clear"}}]}}})).unwrap();
+ assert!(matches!(
+ write(&s, &a, &p, vec![clear]).await,
+ Err(PipelineError::Database(DatabaseError::InvalidOp(_))) | Err(PipelineError::Invalid(_))
+ ));
+ let delete_column = serde_json::from_value(json!({"kind":"column","table":p.table_id,"column":p.primary_column_id,"change":{"kind":"delete"}})).unwrap();
+ assert!(matches!(
+ write(&s, &a, &p, vec![delete_column]).await,
+ Err(PipelineError::Database(DatabaseError::InvalidOp(_))) | Err(PipelineError::Invalid(_))
+ ));
+ assert!(matches!(
+ write(&s, &a, &p, vec![insert(&p, Uuid::now_v7())]).await,
+ Err(PipelineError::Access(_))
+ ));
+ for value in [
+ json!({"type": "entities", "value": []}),
+ json!({"type": "entities", "value": [
+ {"entityType": "COMPANY", "entityId": company},
+ {"entityType": "COMPANY", "entityId": company}
+ ]}),
+ json!({"type": "entities", "value": [{"entityType": "CONTACT", "entityId": company}]}),
+ json!({"type": "text", "value": "not a reference"}),
+ ] {
+ let operation = serde_json::from_value(json!({"kind": "rows", "table": p.table_id,
+ "change": {"kind": "insert", "rows": [[{"column": p.primary_column_id, "value": value}]]}})).unwrap();
+ assert!(matches!(
+ write(&s, &a, &p, vec![operation]).await,
+ Err(PipelineError::Database(DatabaseError::InvalidOp(_)))
+ | Err(PipelineError::Invalid(_))
+ ));
+ }
+ let second = create(&s, team, PipelineRecordType::Company).await;
+ // A receipt for one pipeline must never write another pipeline's storage.
+ assert!(matches!(
+ write(&s, &a, &p, vec![insert(&second, company)]).await,
+ Err(PipelineError::NotFound)
+ ));
+ let change_primary = DatabaseOp::Column {
+ table: second.table_id,
+ column: second.primary_column_id,
+ change: ColumnChange::ChangeType {
+ to: ColumnKind::Text,
+ },
+ };
+ assert!(matches!(
+ write(&s, &a, &second, vec![change_primary]).await,
+ Err(PipelineError::Database(DatabaseError::InvalidOp(_))) | Err(PipelineError::Invalid(_))
+ ));
+ write(&s, &a, &second, vec![insert(&second, company)])
+ .await
+ .unwrap();
+ let count: i64 = sqlx::query_scalar!(
+ r#"SELECT count(*) AS "count!" FROM database_rows WHERE table_id=$1"#,
+ p.table_id.into_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(count, 2);
+ // Removing one entry keeps the other entry and its CRM record.
+ let remove = DatabaseOp::Rows {
+ table: p.table_id,
+ change: RowsChange::Delete { rows: vec![row] },
+ };
+ write(&s, &a, &p, vec![remove]).await.unwrap();
+ let remaining = s
+ .rows(access(&a, p.id, EntityType::CrmPipeline, OWNER).await, None)
+ .await
+ .unwrap();
+ assert_eq!(remaining.rows.len(), 1);
+ assert_eq!(remaining.rows[0].row_id, duplicate);
+ write(&s, &a, &p, vec![insert(&p, company)]).await.unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn references_can_cross_teams_only_when_the_editor_has_record_access(pool: PgPool) {
+ let (s, _, a, team, _) = fixture(&pool).await;
+ let other_team = Uuid::now_v7();
+ let company = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Other CRM', $2)",
+ other_team,
+ OUTSIDER
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, true)",
+ other_team
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!("INSERT INTO crm_companies (id, team_id, first_interaction, last_interaction) VALUES ($1, $2, now(), now())", company, other_team).execute(&pool).await.unwrap();
+ let contact = Uuid::now_v7();
+ sqlx::query!("INSERT INTO crm_contacts (id, company_id, email, first_interaction, last_interaction) VALUES ($1, $2, '[email protected]', now(), now())", contact, company).execute(&pool).await.unwrap();
+ let companies = create(&s, team, PipelineRecordType::Company).await;
+ let contacts = create(&s, team, PipelineRecordType::Contact).await;
+ for (pipeline, record) in [(&companies, company), (&contacts, contact)] {
+ assert!(matches!(
+ write(&s, &a, pipeline, vec![insert(pipeline, record)]).await,
+ Err(PipelineError::Access(_))
+ ));
+ }
+ // Membership is currently limited to one team. Moving the editor preserves
+ // their pipeline owner grant while giving them access to the other CRM.
+ sqlx::query!(
+ "UPDATE team_user SET team_id = $1 WHERE user_id = $2",
+ other_team,
+ OWNER
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ for (pipeline, record) in [(&companies, company), (&contacts, contact)] {
+ write(&s, &a, pipeline, vec![insert(pipeline, record)])
+ .await
+ .unwrap();
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn custom_columns_use_core_validation_and_preserve_values(pool: PgPool) {
+ let (s, _, a, team, company) = fixture(&pool).await;
+ let p = create(&s, team, PipelineRecordType::Company).await;
+ let row = inserted(&write(&s, &a, &p, vec![insert(&p, company)]).await.unwrap());
+ let column = ColumnId::new();
+ let op = |value| serde_json::from_value::<DatabaseOp>(value).unwrap();
+ write(&s, &a, &p, vec![op(json!({
+ "kind": "column", "table": p.table_id, "column": column,
+ "change": {"kind": "create", "definition": {"source": "new", "name": "Notes", "type": {"type": "text"}}}
+ })), op(json!({
+ "kind": "rows", "table": p.table_id,
+ "change": {"kind": "update", "changes": {"kind": "uniform", "rows": [row], "cells": [{"column": column, "value": {"type": "text", "value": "Call next week"}}]}}
+ }))]).await.unwrap();
+ let rows = s
+ .rows(access(&a, p.id, EntityType::CrmPipeline, OWNER).await, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ serde_json::to_value(&rows.rows[0].cells[&column]).unwrap(),
+ json!({"type": "String", "value": "Call next week"})
+ );
+ assert!(matches!(
+ write(
+ &s,
+ &a,
+ &p,
+ vec![op(json!({
+ "kind": "column", "table": p.table_id, "column": column,
+ "change": {"kind": "change_type", "to": {"type": "number"}}
+ }))]
+ )
+ .await,
+ Err(PipelineError::Database(DatabaseError::InvalidOp(_)))
+ ));
+ let table = s
+ .table(access(&a, p.id, EntityType::CrmPipeline, OWNER).await)
+ .await
+ .unwrap();
+ assert_eq!(
+ table
+ .columns
+ .last()
+ .unwrap()
+ .definition
+ .definition
+ .data_type,
+ models_properties::DataType::String
+ );
+ // A consumer cannot bind another resource's property definition to bypass access.
+ assert!(matches!(write(&s, &a, &p, vec![op(json!({
+ "kind": "column", "table": p.table_id, "column": ColumnId::new(),
+ "change": {"kind": "create", "definition": {"source": "existing", "property": table.columns[0].column.property_definition_id}}
+ }))]).await, Err(PipelineError::Database(DatabaseError::InvalidOp(_)))));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn contact_pipelines_and_lifecycle_preserve_crm_records(pool: PgPool) {
+ let (s, _db, a, team, company) = fixture(&pool).await;
+ let contact = Uuid::now_v7();
+ sqlx::query!(r#"INSERT INTO crm_contacts (id,company_id,email,first_interaction,last_interaction) VALUES ($1,$2,'[email protected]',now(),now())"#, contact, company).execute(&pool).await.unwrap();
+ let p = create(&s, team, PipelineRecordType::Contact).await;
+ let row = inserted(&write(&s, &a, &p, vec![insert(&p, contact)]).await.unwrap());
+ let duplicate = inserted(&write(&s, &a, &p, vec![insert(&p, contact)]).await.unwrap());
+ assert_ne!(row, duplicate);
+ let rows = s
+ .rows(access(&a, p.id, EntityType::CrmPipeline, OWNER).await, None)
+ .await
+ .unwrap();
+ assert_eq!(rows.rows.len(), 2);
+ assert!(write(&s, &a, &p, vec![insert(&p, company)]).await.is_err());
+ s.rename(
+ access(&a, p.id, EntityType::CrmPipeline, OWNER).await,
+ "Hiring".into(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ s.get(access(&a, p.id, EntityType::CrmPipeline, OWNER).await)
+ .await
+ .unwrap()
+ .pipeline
+ .name,
+ "Hiring"
+ );
+ s.set_trashed(access(&a, p.id, EntityType::CrmPipeline, OWNER).await, true)
+ .await
+ .unwrap();
+ assert!(s.list(team_receipt(team, OWNER)).await.unwrap().is_empty());
+ assert!(write(&s, &a, &p, vec![insert(&p, contact)]).await.is_err());
+ s.set_trashed(
+ access(&a, p.id, EntityType::CrmPipeline, OWNER).await,
+ false,
+ )
+ .await
+ .unwrap();
+ assert_eq!(s.list(team_receipt(team, OWNER)).await.unwrap().len(), 1);
+ sqlx::query!(r#"DELETE FROM crm_pipeline_entities WHERE id=$1"#, p.id)
+ .execute(&pool)
+ .await
+ .unwrap();
+ let exists: bool = sqlx::query_scalar!(
+ r#"SELECT EXISTS(SELECT 1 FROM crm_contacts WHERE id=$1) AS "exists!""#,
+ contact
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(exists);
+ let exists: bool = sqlx::query_scalar!(
+ r#"SELECT EXISTS(SELECT 1 FROM databases WHERE id=$1) AS "exists!""#,
+ p.database_id.into_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert!(!exists);
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT count(*) FROM database_changes WHERE database_id = $1",
+ p.database_id.into_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn disabled_crm_cannot_create_pipeline_storage(pool: PgPool) {
+ let (s, _, _, team, _) = fixture(&pool).await;
+ sqlx::query!(
+ r#"UPDATE team_crm_settings SET crm_enabled=false WHERE team_id=$1"#,
+ team
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let result = s
+ .create(
+ team_receipt(team, OWNER),
+ CreatePipeline {
+ name: "Sales".into(),
+ record_type: PipelineRecordType::Company,
+ sharing: PipelineSharing::Team,
+ },
+ )
+ .await;
+ assert!(matches!(
+ result,
+ Err(PipelineError::Crm(CrmError::CrmDisabledForTeam))
+ ));
+ let count: i64 = sqlx::query_scalar!(r#"SELECT count(*) AS "count!" FROM databases"#)
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ assert_eq!(count, 0);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn migration_rollback_preserves_records_and_grants(pool: PgPool) {
+ let (s, _db, a, team, company) = fixture(&pool).await;
+ let p = create(&s, team, PipelineRecordType::Company).await;
+ let row = inserted(&write(&s, &a, &p, vec![insert(&p, company)]).await.unwrap());
+ s.share(
+ access(&a, p.id, EntityType::CrmPipeline, OWNER).await,
+ PipelineSharing::Team,
+ )
+ .await
+ .unwrap();
+ // Execute the actual rollback DDL in this disposable test database.
+ sqlx::raw_sql(include_str!(
+ "../../macro_db_client/migrations/20261007172434_crm_pipeline_entities.down.sql"
+ ))
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert!(
+ sqlx::query_scalar!(
+ r#"SELECT EXISTS(SELECT 1 FROM database_rows WHERE id = $1) AS "exists!""#,
+ row.into_uuid()
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap()
+ );
+ let grants = sqlx::query!(
+ "SELECT source_id, access_level::text AS level FROM entity_access WHERE entity_id = $1 AND entity_type = 'database' ORDER BY source_id",
+ p.database_id.into_uuid()
+ ).fetch_all(&pool).await.unwrap();
+ assert_eq!(grants.len(), 2);
+ assert!(
+ grants
+ .iter()
+ .any(|grant| grant.source_id == OWNER && grant.level.as_deref() == Some("owner"))
+ );
+ assert!(
+ grants
+ .iter()
+ .any(|grant| grant.source_id == team.to_string()
+ && grant.level.as_deref() == Some("edit"))
+ );
+}
+
+#[cfg(feature = "inbound")]
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn http_creation_listing_schema_and_records_use_pipeline_access(pool: PgPool) {
+ use axum::{
+ Router,
+ body::{Body, to_bytes},
+ http::{Request, StatusCode},
+ };
+ use crm::inbound::pipelines::{PipelineRouterState, router};
+ use macro_authorization::{
+ InternalAuthConfig, JwtValidator, MacroAuthorizationError, MacroAuthorizationServiceImpl,
+ MacroAuthorizationState, NoBotAuthorizer, NoUserApiKeyAuthorizer, ValidatedIdentity,
+ };
+ use tower::ServiceExt;
+ #[derive(Clone)]
+ struct Token;
+ impl JwtValidator for Token {
+ fn validate(
+ &self,
+ jwt: &str,
+ ) -> Result<ValidatedIdentity, rootcause::Report<MacroAuthorizationError>> {
+ if jwt != "owner" && jwt != "outsider" {
+ return Err(rootcause::Report::new(
+ MacroAuthorizationError::InvalidCredentials,
+ ));
+ }
+ Ok(ValidatedIdentity {
+ user_id: if jwt == "owner" { OWNER } else { OUTSIDER }.into(),
+ fusion_user_id: "test-fusion-user".into(),
+ organization_id: None,
+ permissions: None,
+ })
+ }
+ }
+ let (service, _, access, _, company) = fixture(&pool).await;
+ let app = Router::new().nest(
+ "/crm/pipelines",
+ router(PipelineRouterState {
+ service: Arc::new(service),
+ access,
+ authorization: MacroAuthorizationState::new(Arc::new(
+ MacroAuthorizationServiceImpl::new(
+ Token,
+ InternalAuthConfig {
+ api_key: "test-only".into(),
+ default_user_id: None,
+ },
+ NoBotAuthorizer,
+ NoUserApiKeyAuthorizer,
+ ),
+ )),
+ }),
+ );
+ let created = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/crm/pipelines")
+ .header("authorization", "Bearer owner")
+ .header("content-type", "application/json")
+ .body(Body::from(r#"{"name":"Renewals","recordType":"company"}"#))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(created.status(), StatusCode::OK);
+ let body: serde_json::Value =
+ serde_json::from_slice(&to_bytes(created.into_body(), 16384).await.unwrap()).unwrap();
+ assert_eq!(body["sharing"], "private");
+ assert_eq!(body["grant"], "owner");
+ assert_eq!(body["userId"], OWNER);
+ let pipeline_id = body["id"].as_str().unwrap();
+ let primary = body["primaryColumnId"].as_str().unwrap();
+ let table = body["tableId"].as_str().unwrap();
+ let operation = json!({"ops": [{"kind": "rows", "table": table, "change": {"kind": "insert", "rows": [[{"column": primary, "value": {"type": "entities", "value": [{"entityType": "COMPANY", "entityId": company}]}}]]}}]});
+ for (token, expected) in [
+ ("outsider", StatusCode::UNAUTHORIZED),
+ ("owner", StatusCode::OK),
+ ("owner", StatusCode::OK),
+ ] {
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri(format!("/crm/pipelines/{pipeline_id}/ops"))
+ .header("authorization", format!("Bearer {token}"))
+ .header("content-type", "application/json")
+ .body(Body::from(operation.to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), expected);
+ }
+ for route in ["table", "rows"] {
+ for (token, expected) in [
+ ("outsider", StatusCode::UNAUTHORIZED),
+ ("owner", StatusCode::OK),
+ ] {
+ let response = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri(format!("/crm/pipelines/{pipeline_id}/{route}"))
+ .header("authorization", format!("Bearer {token}"))
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), expected);
+ if route == "rows" && expected == StatusCode::OK {
+ let rows: serde_json::Value =
+ serde_json::from_slice(&to_bytes(response.into_body(), 16384).await.unwrap())
+ .unwrap();
+ let rows = rows["rows"].as_array().unwrap();
+ assert_eq!(rows.len(), 2);
+ assert_ne!(rows[0]["rowId"], rows[1]["rowId"]);
+ for row in rows {
+ assert_eq!(
+ row["cells"][primary]["value"][0]["entity_id"],
+ company.to_string()
+ );
+ }
+ }
+ }
+ }
+ let listed = app
+ .oneshot(
+ Request::builder()
+ .uri("/crm/pipelines")
+ .header("authorization", "Bearer owner")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(listed.status(), StatusCode::OK);
+ let body: serde_json::Value =
+ serde_json::from_slice(&to_bytes(listed.into_body(), 16384).await.unwrap()).unwrap();
+ assert_eq!(body.as_array().unwrap().len(), 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn queried_rows_filter_and_sort_before_paging_and_retain_hidden_records(pool: PgPool) {
+ use databases::domain::storage::StorageRowsQuery;
+ use models_properties::service::property_value::PropertyValue;
+ let (service, _, access_service, team, company) = fixture(&pool).await;
+ let pipeline = create(&service, team, PipelineRecordType::Company).await;
+ let schema = service
+ .table(access(&access_service, pipeline.id, EntityType::CrmPipeline, OWNER).await)
+ .await
+ .unwrap();
+ let revenue = schema
+ .columns
+ .iter()
+ .find(|column| column.definition.definition.display_name == "Revenue")
+ .unwrap()
+ .column
+ .id;
+ for range in [0..500, 500..502] {
+ let rows: Vec<_> = range.map(|number| json!([
+ {"column": pipeline.primary_column_id, "value": {"type":"entities", "value":[{"entityType":"COMPANY", "entityId":company.to_string()}]}},
+ {"column": revenue, "value": {"type":"number", "value":number}}
+ ])).collect();
+ let op = serde_json::from_value(json!({"kind":"rows", "table":pipeline.table_id, "change":{"kind":"insert", "rows":rows}})).unwrap();
+ write(&service, &access_service, &pipeline, vec![op])
+ .await
+ .unwrap();
+ }
+ let query = json!({"filter":{"conjunction":"and", "conditions":[{"kind":"condition", "column":revenue, "test":{"kind":"number","operator":"greaterThan", "value":0}}]}, "sort":[{"column":revenue, "direction":"descending"}]});
+ let first = service
+ .query_rows(
+ access(&access_service, pipeline.id, EntityType::CrmPipeline, OWNER).await,
+ serde_json::from_value(json!({"query":query})).unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(first.rows.len(), 500);
+ assert_eq!(first.rows[0].cells[&revenue], PropertyValue::Num(501.0));
+ assert_eq!(
+ first.rows.last().unwrap().cells[&revenue],
+ PropertyValue::Num(2.0)
+ );
+ let second = service
+ .query_rows(
+ access(&access_service, pipeline.id, EntityType::CrmPipeline, OWNER).await,
+ serde_json::from_value(json!({"query":query,"after":first.next})).unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(second.rows.len(), 1);
+ assert_eq!(second.rows[0].cells[&revenue], PropertyValue::Num(1.0));
+ assert_eq!(second.version, first.version);
+ assert!(second.next.is_none());
+ let all = service
+ .query_rows(
+ access(&access_service, pipeline.id, EntityType::CrmPipeline, OWNER).await,
+ StorageRowsQuery::default(),
+ )
+ .await
+ .unwrap();
+ let hidden = all
+ .rows
+ .iter()
+ .find(|row| row.cells[&revenue] == PropertyValue::Num(0.0))
+ .unwrap()
+ .row_id;
+ let retained = service
+ .query_rows(
+ access(&access_service, pipeline.id, EntityType::CrmPipeline, OWNER).await,
+ serde_json::from_value(json!({"query":query,"rowIds":[hidden]})).unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(retained.rows.len(), 1);
+ assert_eq!(retained.rows[0].row_id, hidden);
+}
diff --git a/crates/crm/tests/sales_backfill.rs b/crates/crm/tests/sales_backfill.rs
new file mode 100644
index 0000000000..49adeab975
--- /dev/null
+++ b/crates/crm/tests/sales_backfill.rs
@@ -0,0 +1,477 @@
+//! Migration coverage with real source properties, database constraints and access.
+#![cfg(feature = "outbound")]
+
+use entity_access::{
+ domain::{
+ models::{EntityType as AccessEntityType, ViewAccessLevel},
+ ports::EntityAccessService,
+ service::EntityAccessServiceImpl,
+ },
+ outbound::PgAccessRepository,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_properties::{EntityReference, EntityType, service::property_value::PropertyValue};
+use properties::{PropertiesPgRepo, domain::database_cell_writer::DatabaseCellWriter};
+use serde_json::json;
+use sqlx::PgPool;
+use system_properties::{StageOption, SystemPropertyKey};
+use uuid::Uuid;
+
+const OWNER: &str = "macro|[email protected]";
+const MEMBER: &str = "macro|[email protected]";
+const OUTSIDER: &str = "macro|[email protected]";
+
+async fn migrate(pool: &PgPool) -> Result<(), sqlx::migrate::MigrateError> {
+ MACRO_DB_MIGRATIONS.run(pool).await
+}
+
+async fn fixture(pool: &PgPool) -> Uuid {
+ // sqlx::test owns this disposable database; templates may already be migrated.
+ sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;")
+ .execute(pool)
+ .await
+ .unwrap();
+ let before_copy = sqlx::migrate::Migrator {
+ migrations: std::borrow::Cow::Owned(
+ MACRO_DB_MIGRATIONS
+ .iter()
+ .filter(|migration| migration.version < 20261007172435)
+ .cloned()
+ .collect(),
+ ),
+ ..sqlx::migrate::Migrator::DEFAULT
+ };
+ before_copy.run(pool).await.unwrap();
+ for id in [OWNER, MEMBER, OUTSIDER] {
+ let uid = macro_uuid::generate_uuid_v7();
+ sqlx::query!("INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)", uid, id).execute(pool).await.unwrap();
+ sqlx::query!(
+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#,
+ id,
+ uid
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ }
+ let team = macro_uuid::generate_uuid_v7();
+ sqlx::query!(
+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Migration team', $2)",
+ team,
+ OWNER
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ for id in [OWNER, MEMBER] {
+ sqlx::query!(
+ "INSERT INTO team_user (team_id, user_id, team_role) VALUES ($1, $2, 'member')",
+ team,
+ id
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ }
+ sqlx::query!(
+ "INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, true)",
+ team
+ )
+ .execute(pool)
+ .await
+ .unwrap();
+ team
+}
+
+async fn company(pool: &PgPool, team: Uuid, hidden: bool) -> Uuid {
+ let id = macro_uuid::generate_uuid_v7();
+ sqlx::query!("INSERT INTO crm_companies (id, team_id, hidden, first_interaction, last_interaction) VALUES ($1, $2, $3, now(), now())", id, team, hidden).execute(pool).await.unwrap();
+ id
+}
+
+async fn value(pool: &PgPool, company: Uuid, definition: Uuid, value: PropertyValue) {
+ let mut tx = pool.begin().await.unwrap();
+ PropertiesPgRepo::new(pool.clone())
+ .upsert_entity_property_in(
+ &mut tx,
+ &EntityReference {
+ entity_type: EntityType::Company,
+ entity_id: company.to_string(),
+ specific_message_id: None,
+ },
+ definition,
+ Some(value),
+ )
+ .await
+ .unwrap();
+ tx.commit().await.unwrap();
+}
+
+async fn stage(pool: &PgPool, company: Uuid, option: StageOption) {
+ value(
+ pool,
+ company,
+ SystemPropertyKey::Stage.uuid(),
+ PropertyValue::SelectOption(vec![option.uuid()]),
+ )
+ .await;
+}
+
+async fn pipeline(pool: &PgPool, team: Uuid) -> (Uuid, Uuid, Uuid) {
+ let row = sqlx::query!(
+ "SELECT id, database_id, table_id FROM crm_pipeline_entities WHERE team_id = $1",
+ team
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap();
+ (row.id, row.database_id, row.table_id)
+}
+
+async fn cell(pool: &PgPool, company: Uuid, column: &str) -> Option<serde_json::Value> {
+ sqlx::query_scalar!(
+ r#"SELECT ep.values FROM crm_pipeline_entities primary_column
+ JOIN database_columns primary_definition ON primary_definition.id = primary_column.primary_column_id
+ JOIN entity_properties primary_value ON primary_value.property_definition_id = primary_definition.property_definition_id
+ AND primary_value.entity_type = 'DATABASE_ROW'
+ JOIN database_columns c ON c.table_id = primary_column.table_id
+ JOIN property_definitions d ON d.id = c.property_definition_id
+ JOIN entity_properties ep ON ep.entity_id = primary_value.entity_id
+ AND ep.entity_type = 'DATABASE_ROW' AND ep.property_definition_id = d.id
+ WHERE primary_value.values -> 'value' -> 0 ->> 'entity_id' = $1 AND d.display_name = $2"#,
+ company.to_string(),
+ column,
+ )
+ .fetch_optional(pool)
+ .await
+ .unwrap()
+ .flatten()
+}
+
+async fn stage_label(pool: &PgPool, company: Uuid) -> Option<String> {
+ let value = cell(pool, company, "Stage").await?;
+ let id: Uuid = value["value"][0].as_str().unwrap().parse().unwrap();
+ sqlx::query_scalar!(
+ "SELECT string_value FROM property_options WHERE id = $1",
+ id
+ )
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+#[sqlx::test(migrations = false)]
+async fn copies_all_visible_companies_with_values_and_team_access(pool: PgPool) {
+ let team = fixture(&pool).await;
+ let open = company(&pool, team, false).await;
+ let won = company(&pool, team, false).await;
+ let lost = company(&pool, team, false).await;
+ let unstaged = company(&pool, team, false).await;
+ let hidden = company(&pool, team, true).await;
+ stage(&pool, open, StageOption::Demo).await;
+ stage(&pool, won, StageOption::Customer).await;
+ stage(&pool, lost, StageOption::Churned).await;
+ stage(&pool, hidden, StageOption::Lead).await;
+ let owner = PropertyValue::EntityRef(vec![EntityReference {
+ entity_type: EntityType::User,
+ entity_id: MEMBER.into(),
+ specific_message_id: None,
+ }]);
+ value(
+ &pool,
+ open,
+ SystemPropertyKey::CompanyOwner.uuid(),
+ owner.clone(),
+ )
+ .await;
+ value(
+ &pool,
+ open,
+ SystemPropertyKey::Revenue.uuid(),
+ PropertyValue::Num(1250.75),
+ )
+ .await;
+ migrate(&pool).await.unwrap();
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM database_rows")
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(4)
+ );
+ assert_eq!(stage_label(&pool, open).await.as_deref(), Some("Demo"));
+ assert_eq!(stage_label(&pool, won).await.as_deref(), Some("Customer"));
+ assert_eq!(stage_label(&pool, lost).await.as_deref(), Some("Churned"));
+ assert_eq!(stage_label(&pool, unstaged).await, None);
+ assert_eq!(cell(&pool, hidden, "Company").await, None);
+ assert_eq!(
+ cell(&pool, open, "Owner").await,
+ Some(serde_json::to_value(owner).unwrap())
+ );
+ assert_eq!(
+ cell(&pool, open, "Revenue").await,
+ Some(json!({"type":"Number", "value":1250.75}))
+ );
+ let original = sqlx::query_scalar!("SELECT values FROM entity_properties WHERE entity_type = 'COMPANY' AND entity_id = $1 AND property_definition_id = $2", open.to_string(), SystemPropertyKey::Stage.uuid()).fetch_one(&pool).await.unwrap();
+ assert_eq!(
+ original,
+ Some(json!({"type":"SelectOption", "value":[StageOption::Demo.uuid()]}))
+ );
+ let (pipeline, database, _) = pipeline(&pool, team).await;
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT name FROM crm_pipeline_entities WHERE database_id = $1",
+ database
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ "Sales"
+ );
+ let access = EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone()));
+ for actor in [OWNER, MEMBER, OUTSIDER] {
+ let user = MacroUserIdStr::parse_from_str(actor).unwrap().into_owned();
+ let result = access
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &user,
+ None,
+ &pipeline.to_string(),
+ AccessEntityType::CrmPipeline,
+ )
+ .await;
+ assert_eq!(result.is_ok(), actor != OUTSIDER);
+ let result = access
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &user,
+ None,
+ &database.to_string(),
+ AccessEntityType::Database,
+ )
+ .await;
+ assert!(
+ result.is_err(),
+ "core storage must not grant database app access"
+ );
+ }
+}
+
+#[sqlx::test(migrations = false)]
+async fn preserves_custom_stages_and_legacy_rename_mapping(pool: PgPool) {
+ let team = fixture(&pool).await;
+ let definition = macro_uuid::generate_uuid_v7();
+ sqlx::query!("INSERT INTO property_definitions (id, team_id, display_name, data_type, is_multi_select, is_system) VALUES ($1, $2, 'Deal Stage', 'SELECT_STRING', false, false)", definition, team).execute(&pool).await.unwrap();
+ let renamed = macro_uuid::generate_uuid_v7();
+ let won = macro_uuid::generate_uuid_v7();
+ let demo = macro_uuid::generate_uuid_v7();
+ for (order, (id, label)) in [(renamed, "Discovery"), (won, "Won"), (demo, "DEMO")]
+ .into_iter()
+ .enumerate()
+ {
+ sqlx::query!("INSERT INTO property_options (id, property_definition_id, string_value, display_order) VALUES ($1, $2, $3, $4)", id, definition, label, order as i32).execute(&pool).await.unwrap();
+ }
+ sqlx::query!(
+ "UPDATE team_crm_settings SET legacy_stage_ids = $2 WHERE team_id = $1",
+ team,
+ json!({StageOption::Lead.uuid().to_string(): renamed})
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let direct = company(&pool, team, false).await;
+ let mapped = company(&pool, team, false).await;
+ let by_label = company(&pool, team, false).await;
+ let empty = company(&pool, team, false).await;
+ value(
+ &pool,
+ direct,
+ definition,
+ PropertyValue::SelectOption(vec![won]),
+ )
+ .await;
+ stage(&pool, direct, StageOption::Lead).await;
+ stage(&pool, mapped, StageOption::Lead).await;
+ value(
+ &pool,
+ mapped,
+ definition,
+ PropertyValue::SelectOption(vec![]),
+ )
+ .await;
+ stage(&pool, by_label, StageOption::Demo).await;
+ value(
+ &pool,
+ empty,
+ definition,
+ PropertyValue::SelectOption(vec![]),
+ )
+ .await;
+ stage(&pool, empty, StageOption::Trial).await;
+ assert!(migrate(&pool).await.is_err());
+ value(
+ &pool,
+ empty,
+ SystemPropertyKey::Stage.uuid(),
+ PropertyValue::SelectOption(vec![]),
+ )
+ .await;
+ migrate(&pool).await.unwrap();
+ assert_eq!(stage_label(&pool, direct).await.as_deref(), Some("Won"));
+ assert_eq!(
+ stage_label(&pool, mapped).await.as_deref(),
+ Some("Discovery")
+ );
+ assert_eq!(stage_label(&pool, by_label).await.as_deref(), Some("DEMO"));
+ assert_eq!(stage_label(&pool, empty).await, None);
+ let copied = cell(&pool, direct, "Stage").await.unwrap();
+ assert_ne!(copied["value"][0], won.to_string());
+}
+
+#[sqlx::test(migrations = false)]
+async fn reruns_preserve_user_changes_and_deletions(pool: PgPool) {
+ let team = fixture(&pool).await;
+ let company = company(&pool, team, false).await;
+ migrate(&pool).await.unwrap();
+ let (pipeline, database, table) = pipeline(&pool, team).await;
+ sqlx::query!(
+ "UPDATE crm_pipeline_entities SET name = 'Renamed by user', trashed_at = now() WHERE database_id = $1",
+ database
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!("DELETE FROM database_rows WHERE table_id = $1", table)
+ .execute(&pool)
+ .await
+ .unwrap();
+ stage(&pool, company, StageOption::Customer).await;
+ migrate(&pool).await.unwrap();
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT name FROM crm_pipeline_entities WHERE database_id = $1",
+ database
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ "Renamed by user"
+ );
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT count(*) FROM database_rows WHERE table_id = $1",
+ table
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ sqlx::query!("DELETE FROM crm_pipeline_entities WHERE id = $1", pipeline)
+ .execute(&pool)
+ .await
+ .unwrap();
+ migrate(&pool).await.unwrap();
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM crm_pipeline_entities")
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+}
+
+#[sqlx::test(migrations = false)]
+async fn invalid_values_roll_back_the_entire_copy_and_can_retry(pool: PgPool) {
+ let team = fixture(&pool).await;
+ let ids = (0..251)
+ .map(|_| macro_uuid::generate_uuid_v7())
+ .collect::<Vec<_>>();
+ sqlx::query!("INSERT INTO crm_companies (id, team_id, first_interaction, last_interaction) SELECT id, $1, now(), now() FROM UNNEST($2::uuid[]) AS input(id)", team, &ids).execute(&pool).await.unwrap();
+ let last = *ids.iter().max().unwrap();
+ // Legacy property writes permit bad types; the migration must detect them.
+ value(
+ &pool,
+ last,
+ SystemPropertyKey::Revenue.uuid(),
+ PropertyValue::Str("not a number".into()),
+ )
+ .await;
+ assert!(migrate(&pool).await.is_err());
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM databases")
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+ value(
+ &pool,
+ last,
+ SystemPropertyKey::Revenue.uuid(),
+ PropertyValue::Num(42.0),
+ )
+ .await;
+ migrate(&pool).await.unwrap();
+ let (_, _, table) = pipeline(&pool, team).await;
+ let rows = sqlx::query!(
+ "SELECT id, position FROM database_rows WHERE table_id = $1 ORDER BY position",
+ table
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ for row in rows {
+ assert_eq!(row.id.get_version_num(), 7);
+ row.position
+ .parse::<models_databases::position::Position>()
+ .unwrap();
+ }
+
+ assert_eq!(
+ sqlx::query_scalar!(
+ "SELECT count(DISTINCT position) FROM database_rows WHERE table_id = $1",
+ table
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(251)
+ );
+}
+
+#[sqlx::test(migrations = false)]
+async fn disabled_and_empty_teams_are_untouched(pool: PgPool) {
+ let team = fixture(&pool).await;
+ company(&pool, team, false).await;
+ sqlx::query!(
+ "UPDATE team_crm_settings SET crm_enabled = false WHERE team_id = $1",
+ team
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let empty = Uuid::now_v7();
+ sqlx::query!(
+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'Empty CRM', $2)",
+ empty,
+ OUTSIDER
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES ($1, true)",
+ empty
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ migrate(&pool).await.unwrap();
+ assert_eq!(
+ sqlx::query_scalar!("SELECT count(*) FROM crm_pipeline_entities")
+ .fetch_one(&pool)
+ .await
+ .unwrap(),
+ Some(0)
+ );
+}
diff --git a/crates/databases/Cargo.toml b/crates/databases/Cargo.toml
index 928a0722f7..dc639e4ce2 100644
--- a/crates/databases/Cargo.toml
+++ b/crates/databases/Cargo.toml
@@ -44,6 +44,7 @@ postgres = [
]
[dependencies]
+database_sql = { path = "../database_sql" }
activity = { path = "../activity", default-features = false }
ai_toolset = { path = "../ai_toolset", optional = true }
anyhow = { workspace = true, optional = true }
diff --git a/crates/databases/README.md b/crates/databases/README.md
index 89ab5e0933..0aa7643726 100644
--- a/crates/databases/README.md
+++ b/crates/databases/README.md
@@ -25,8 +25,8 @@ Collaboration surfaces are a similar reusable resource; this change does not
turn them into entities or change their parent-based access model.
`DatabaseStorage` exposes allocation, validated storage batches, and deletion
-without app metadata. A future CRM domain can hold its own reference to a core
-database and authorize access through its own service. Its composition root
+without app metadata. The CRM pipeline domain holds its own reference to core
+storage and authorizes access through its own service. Its composition root
supplies the storage adapter. The port is trusted persistence, not a new public
API: consumers validate their own commands and authorize their own resources.
The Macro database service creates its entity and owner grant atomically through
@@ -34,6 +34,18 @@ its repository and uses `CellStore` to hold the entity's lifecycle lock during w
Both paths use the same transaction engine, table versions, cells and journal.
An app entity's foreign key prevents deleting its storage through the core port.
+`DatabaseStorageService` reuses the typed operation planner for hosts that accept
+`DatabaseOp` batches. It reads schema and paginated cells without app metadata,
+then writes through `DatabaseStorage::apply_storage_writes`; it does not mint
+app access receipts or publish app-entity events. The host holds its lifecycle
+guard while it calls the service. External property bindings and relations are
+refused unless a future host-specific capability authorizes them.
+
+`DatabaseStorageProvisioner` creates an initial schema in its host's transaction.
+CRM commits pipeline metadata, grants, and storage together through this port,
+without creating a `database_entities` row. The one-time legacy Sales copy runs
+through the normal SQLx migration runner.
+
The migration is a destructive cutover: it discards existing database content,
grants, saved queries, journal entries, and starter markers, then removes app
metadata from `databases`. Deploy it with the updated service; old binaries are
@@ -163,3 +175,11 @@ restores the column setting alongside its cells.
Enforcement belongs to the Rust database engine. Direct SQL and writes through
unrelated property APIs bypass it; the migration only adds the nullable flag.
+
+
+Host-owned storage reads accept the common `ViewQuery` and retained row IDs.
+The storage service reads bounded batches, evaluates the shared query compiler
+and fold over the complete table, then returns pages with table versions. This
+preserves filtering, option ordering, row positions and sorting across pages.
+The current implementation scans the table for each page; indexed query pushdown
+is a future optimization, not a different query language for each host.
diff --git a/crates/databases/src/domain.rs b/crates/databases/src/domain.rs
index bb65293b77..0ea8069a18 100644
--- a/crates/databases/src/domain.rs
+++ b/crates/databases/src/domain.rs
@@ -7,6 +7,9 @@ pub mod events;
pub mod journal;
pub mod models;
+#[cfg(feature = "ports")]
+pub mod storage;
+
#[cfg(feature = "entity_mutation")]
pub mod entity_mutation;
@@ -28,3 +31,7 @@ pub mod transfer;
/// Retry-safe first database provisioning.
#[cfg(feature = "ports")]
pub mod starter;
+
+/// Atomic provisioning for an entity that owns a database.
+#[cfg(feature = "ports")]
+pub mod provisioning;
diff --git a/crates/databases/src/domain/catalog.rs b/crates/databases/src/domain/catalog.rs
index d76bf6dd2d..9a80721609 100644
--- a/crates/databases/src/domain/catalog.rs
+++ b/crates/databases/src/domain/catalog.rs
@@ -32,6 +32,36 @@ pub struct TableEntry {
pub views: Vec<DatabaseView>,
}
+/// A storage table's schema, independent of app metadata and access grants.
+#[derive(Debug, Clone)]
+pub struct StorageTable {
+ /// Table identity, name, ordering and version.
+ pub table: Table,
+ /// Columns and their definitions in display order.
+ pub columns: Vec<ColumnEntry>,
+ /// Stored views, if the consumer uses them.
+ pub views: Vec<DatabaseView>,
+}
+
+impl From<TableEntry> for StorageTable {
+ fn from(entry: TableEntry) -> Self {
+ Self {
+ table: entry.table,
+ columns: entry.columns,
+ views: entry.views,
+ }
+ }
+}
+
+impl StorageTable {
+ /// The column bound to a definition.
+ pub fn column_for(&self, definition: PropertyDefinitionId) -> Option<&ColumnEntry> {
+ self.columns
+ .iter()
+ .find(|column| column.definition.definition.id == definition)
+ }
+}
+
/// One column placement with the definition behind it.
#[derive(Debug, Clone)]
pub struct ColumnEntry {
@@ -113,8 +143,12 @@ pub fn stored_data_type(data_type: DataType) -> StoredDataType {
/// A table's columns as a view's checks see them.
pub fn schema_columns(entry: &TableEntry) -> Vec<SchemaColumn> {
- entry
- .columns
+ storage_schema_columns(&entry.columns)
+}
+
+/// Column types used by the shared storage planner and view validator.
+pub fn storage_schema_columns(columns: &[ColumnEntry]) -> Vec<SchemaColumn> {
+ columns
.iter()
.map(|column| {
SchemaColumn::new(
@@ -296,22 +330,35 @@ pub fn column_kind(
/// The database's schema as a batch's journal keeps it: every table's
/// columns, with their options, and views, as `entries` has them.
pub fn schema_image(entries: &[TableEntry]) -> crate::domain::journal::SchemaImage {
+ storage_schema_image(entries.iter().map(|entry| {
+ (
+ &entry.table,
+ entry.columns.as_slice(),
+ entry.views.as_slice(),
+ )
+ }))
+}
+
+/// Journal schema without an app entity.
+pub fn storage_schema_image<'a>(
+ entries: impl IntoIterator<Item = (&'a Table, &'a [ColumnEntry], &'a [DatabaseView])>,
+) -> crate::domain::journal::SchemaImage {
use crate::domain::journal::{ColumnImage, OptionImage, SchemaImage, TableImage};
let mut image = SchemaImage::default();
- for entry in entries {
+ for (table, columns, views) in entries {
image.tables.push(TableImage {
- id: entry.table.id,
- name: entry.table.name.clone(),
- version: entry.table.version,
+ id: table.id,
+ name: table.name.clone(),
+ version: table.version,
});
- for column in &entry.columns {
+ for column in columns {
let mut options: Vec<_> = column.definition.property_options.iter().collect();
options.sort_by_key(|option| option.display_order);
image.columns.push(ColumnImage {
infer_type: column.column.infer_type,
nullable: column.column.nullable,
id: column.column.id,
- table: entry.table.id,
+ table: table.id,
name: column.name().to_owned(),
definition_name: column.definition.definition.display_name.clone(),
definition: column.definition.definition.id,
@@ -326,7 +373,7 @@ pub fn schema_image(entries: &[TableEntry]) -> crate::domain::journal::SchemaIma
.collect(),
});
}
- image.views.extend(entry.views.iter().cloned());
+ image.views.extend(views.iter().cloned());
}
image
}
diff --git a/crates/databases/src/domain/models.rs b/crates/databases/src/domain/models.rs
index ebef0c56be..b324953db5 100644
--- a/crates/databases/src/domain/models.rs
+++ b/crates/databases/src/domain/models.rs
@@ -778,7 +778,8 @@ pub struct CommittedChange {
/// What a committed batch answers: a result per op, and the journal's change
/// for each table version it produced.
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
pub struct AppliedOps {
/// One result per op, in order.
pub results: Vec<models_databases::OpResult>,
@@ -787,12 +788,15 @@ pub struct AppliedOps {
}
/// A batch of ops for one database and the versions its tables must be at.
-#[derive(Debug, Clone, PartialEq, Default)]
+#[derive(Debug, Clone, PartialEq, Default, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
pub struct OpBatch {
/// The ops, in the order they apply.
pub ops: Vec<DatabaseOp>,
/// The version each named table must still be at; the batch is refused
/// as a conflict if one moved. Without one, ops are last-write-wins.
+ #[serde(default)]
+ #[schema(value_type = HashMap<String, TableVersion>)]
pub base_versions: HashMap<TableId, TableVersion>,
}
diff --git a/crates/databases/src/domain/ports.rs b/crates/databases/src/domain/ports.rs
index b959d7f263..020e3b0ac0 100644
--- a/crates/databases/src/domain/ports.rs
+++ b/crates/databases/src/domain/ports.rs
@@ -181,6 +181,14 @@ pub trait DatabaseStorage: Send + Sync + 'static {
/// Allocate an empty core database without creating an app entity or grants.
fn create_storage(&self) -> impl Future<Output = Result<DatabaseId, Self::Error>> + Send;
+ /// A bounded page of identities from a host-authorized storage table.
+ fn storage_row_page(
+ &self,
+ table: TableId,
+ after: Option<RowId>,
+ limit: i64,
+ ) -> impl Future<Output = Result<Vec<RowRef>, Self::Error>> + Send;
+
/// Delete unbound storage, its tables, cells, definitions and journal.
/// An attached app entity prevents deletion through its foreign key.
fn delete_storage(
diff --git a/crates/databases/src/domain/provisioning.rs b/crates/databases/src/domain/provisioning.rs
new file mode 100644
index 0000000000..2ce24a64c4
--- /dev/null
+++ b/crates/databases/src/domain/provisioning.rs
@@ -0,0 +1,46 @@
+//! Atomic database provisioning for domains that own a database's lifecycle.
+
+use models_databases::{ColumnId, DatabaseId, TableId};
+use models_properties::service::property_option::PropertyOptionValue;
+use models_properties::{DataType, EntityType};
+use uuid::Uuid;
+
+/// A column to provision in core storage.
+pub struct ProvisionedColumn {
+ /// Stable placement identity.
+ pub id: ColumnId,
+ /// Display name.
+ pub name: String,
+ /// Cell type.
+ pub data_type: DataType,
+ /// Referenced entity type, for entity columns.
+ pub entity_type: Option<EntityType>,
+ /// Initial select options, copied into this database.
+ pub options: Vec<(Uuid, PropertyOptionValue)>,
+ /// Whether rows may omit this cell.
+ pub nullable: bool,
+ /// Schema operations reserved by the owning feature.
+ pub protections: Vec<super::models::ColumnProtection>,
+}
+
+/// A complete initial schema; the owning domain supplies the policy.
+pub struct StorageBlueprint {
+ /// Database identity.
+ pub id: DatabaseId,
+ /// Initial table identity.
+ pub table_id: TableId,
+ /// Initial column definitions in display order.
+ pub columns: Vec<ProvisionedColumn>,
+}
+
+/// Transactional port used by an owning domain's repository.
+pub trait DatabaseStorageProvisioner: super::ports::DatabaseStorage {
+ /// Opaque transaction supplied by the adapter.
+ type Transaction: Send;
+ /// Provision all database-owned storage in the caller's transaction.
+ fn create_storage_in(
+ &self,
+ transaction: &mut Self::Transaction,
+ database: &StorageBlueprint,
+ ) -> impl Future<Output = Result<(), Self::Error>> + Send;
+}
diff --git a/crates/databases/src/domain/service.rs b/crates/databases/src/domain/service.rs
index 1915212ff5..6a593dd92c 100644
--- a/crates/databases/src/domain/service.rs
+++ b/crates/databases/src/domain/service.rs
@@ -9,6 +9,7 @@ mod ops;
mod reads;
mod saved_queries;
mod sharing;
+mod storage;
#[cfg(test)]
mod test;
mod transfer;
diff --git a/crates/databases/src/domain/service/ops.rs b/crates/databases/src/domain/service/ops.rs
index 99ab05011f..39351ce1ba 100644
--- a/crates/databases/src/domain/service/ops.rs
+++ b/crates/databases/src/domain/service/ops.rs
@@ -20,7 +20,7 @@ use models_databases::{
use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;
use super::*;
-use crate::domain::catalog::ColumnEntry;
+use crate::domain::catalog::{ColumnEntry, StorageTable};
use crate::domain::journal::{JournalPlan, Restoration};
use crate::domain::models::{AppliedOps, CommittedChange};
use crate::domain::models::{
@@ -33,7 +33,7 @@ use chrono::DateTime;
const MAX_WRITTEN_ROWS: usize = 10_000;
/// How often a batch is planned again when a table whose schema it changes
/// moves between its planning and its locks.
-const MAX_PLANNING_ATTEMPTS: usize = 3;
+pub(super) const MAX_PLANNING_ATTEMPTS: usize = 3;
impl<Repository, Definitions, Cells, Events, Access, Broker>
DatabasesServiceImpl<Repository, Definitions, Cells, Events, Access, Broker>
@@ -87,17 +87,64 @@ where
batch: &OpBatch,
restoration: &Restoration,
) -> Result<Option<AppliedOps>, DatabaseError> {
- let OpBatch { ops, base_versions } = batch;
- let ops = ops.as_slice();
let database_id = receipt_database_id(receipt)?;
let grant = receipt_grant(receipt, AccessLevel::Edit);
- let entries = self
+ let entries: Vec<StorageTable> = self
.entries_for(&HashMap::from([(database_id, grant)]))
- .await?;
- let Some(database) = entries.first().map(|entry| entry.database.clone()) else {
+ .await?
+ .into_iter()
+ .map(StorageTable::from)
+ .collect();
+ if entries.is_empty() {
return Err(DatabaseError::NotFound);
- };
- refuse_foreign_tables(&entries, ops)?;
+ }
+ let attribution = receipt_attribution(receipt);
+ let ops = batch.ops.as_slice();
+ let (writes, planner) = self
+ .prepare_storage_batch(database_id, &entries, viewer, batch, restoration)
+ .await?;
+ let outcome = self
+ .cells
+ .apply_writes(&writes)
+ .await
+ .map_err(repository_error)?;
+ if let WritesOutcome::SchemaMoved(_) = outcome {
+ return Ok(None);
+ }
+ let committed = applied(outcome, ops, &planner.related)?;
+
+ let mut changes: Vec<(DatabaseId, TableId, TableVersion)> = committed
+ .table_versions
+ .iter()
+ .map(|(table, version)| {
+ let database = related_database(&writes, *table).unwrap_or(database_id);
+ (database, *table, *version)
+ })
+ .collect();
+ changes.extend(writes.writes.iter().filter_map(|write| match write {
+ Write::DeleteTable { table_id, version } => Some((database_id, *table_id, *version)),
+ _ => None,
+ }));
+ self.publish(attribution, &changes).await;
+ let journaled = committed.changes.clone();
+ Ok(Some(AppliedOps {
+ results: op_results(&entries, ops, &writes, committed)?,
+ changes: journaled,
+ }))
+ }
+
+ pub(super) async fn prepare_storage_batch(
+ &self,
+ database_id: DatabaseId,
+ entries: &[StorageTable],
+ viewer: &Viewer,
+ batch: &OpBatch,
+ restoration: &Restoration,
+ ) -> Result<(Writes, Planner), DatabaseError> {
+ let OpBatch { ops, base_versions } = batch;
+ let ops = ops.as_slice();
+ let grant = AccessLevel::Edit;
+ refuse_foreign_tables(entries, ops)?;
for (table, version) in base_versions {
let entry = entries
.iter()
@@ -107,9 +154,8 @@ where
return Err(DatabaseError::VersionConflict);
}
}
- let attribution = receipt_attribution(receipt);
- let mut found = self.found_for(&entries, viewer, ops).await?;
+ let mut found = self.found_for(database_id, entries, viewer, ops).await?;
let rebound: Vec<PropertyDefinitionId> = restoration.rebinds.values().copied().collect();
if !rebound.is_empty() {
found.rebound = self
@@ -122,12 +168,12 @@ where
.collect();
}
let editable = self
- .editable_shared_definitions(&entries, &found, database_id, viewer, ops)
+ .editable_shared_definitions(entries, &found, database_id, viewer, ops)
.await?;
- let boards = self.boards_moved_by(&entries, ops).await?;
+ let boards = self.boards_moved_by(entries, ops).await?;
let mut planner = Planner {
entries: entries.iter().cloned().map(Arc::new).collect(),
- database,
+ database_id,
grant,
editable,
found,
@@ -162,38 +208,15 @@ where
.collect(),
journal: JournalPlan {
ops: ops.to_vec(),
- schema: catalog::schema_image(&entries),
+ schema: catalog::storage_schema_image(
+ entries
+ .iter()
+ .map(|e| (&e.table, e.columns.as_slice(), e.views.as_slice())),
+ ),
acting_bot: viewer.acting_bot,
},
};
- let outcome = self
- .cells
- .apply_writes(&writes)
- .await
- .map_err(repository_error)?;
- if let WritesOutcome::SchemaMoved(_) = outcome {
- return Ok(None);
- }
- let committed = applied(outcome, ops, &planner.related)?;
-
- let mut changes: Vec<(DatabaseId, TableId, TableVersion)> = committed
- .table_versions
- .iter()
- .map(|(table, version)| {
- let database = related_database(&writes, *table).unwrap_or(database_id);
- (database, *table, *version)
- })
- .collect();
- changes.extend(writes.writes.iter().filter_map(|write| match write {
- Write::DeleteTable { table_id, version } => Some((database_id, *table_id, *version)),
- _ => None,
- }));
- self.publish(attribution, &changes).await;
- let journaled = committed.changes.clone();
- Ok(Some(AppliedOps {
- results: op_results(&entries, ops, &writes, committed)?,
- changes: journaled,
- }))
+ Ok((writes, planner))
}
/// What the batch's ops need read before they are planned: the
@@ -201,14 +224,11 @@ where
/// database, and the cells of every column it retypes.
async fn found_for(
&self,
- entries: &[TableEntry],
+ database_id: DatabaseId,
+ entries: &[StorageTable],
viewer: &Viewer,
ops: &[DatabaseOp],
) -> Result<Found, DatabaseError> {
- let database_id = entries
- .first()
- .map(|entry| entry.database.id)
- .ok_or(DatabaseError::NotFound)?;
let mut found = Found::default();
for op in ops {
let DatabaseOp::Column {
@@ -317,7 +337,7 @@ where
/// now, so the planner can place each move among them.
async fn boards_moved_by(
&self,
- entries: &[TableEntry],
+ entries: &[StorageTable],
ops: &[DatabaseOp],
) -> Result<HashMap<ViewId, views::Board>, DatabaseError> {
let mut boards = HashMap::new();
@@ -384,7 +404,7 @@ where
/// not enough on its own.
async fn editable_shared_definitions(
&self,
- entries: &[TableEntry],
+ entries: &[StorageTable],
found: &Found,
database_id: DatabaseId,
viewer: &Viewer,
@@ -466,7 +486,10 @@ fn option_columns(op: &DatabaseOp) -> Option<(TableId, Vec<ColumnId>)> {
/// Refuse a batch naming a table that is neither in the receipt's database
/// nor created by an earlier op of the batch.
-fn refuse_foreign_tables(entries: &[TableEntry], ops: &[DatabaseOp]) -> Result<(), DatabaseError> {
+fn refuse_foreign_tables(
+ entries: &[StorageTable],
+ ops: &[DatabaseOp],
+) -> Result<(), DatabaseError> {
let mut created: Vec<TableId> = Vec::new();
for (index, op) in ops.iter().enumerate() {
if let DatabaseOp::Table {
@@ -630,7 +653,7 @@ fn applied(
/// One result per op, in order, from what its write committed.
fn op_results(
- entries: &[TableEntry],
+ entries: &[StorageTable],
ops: &[DatabaseOp],
writes: &Writes,
committed: Committed,
@@ -875,10 +898,10 @@ struct Found {
/// Turns ops into writes against one database's catalog, as the ops before
/// each leave it, collecting the options they create and the rows their
/// relation cells point at.
-struct Planner {
+pub(super) struct Planner {
/// The database's tables as the ops so far leave them, in tab order.
- entries: Vec<Arc<TableEntry>>,
- database: Database,
+ entries: Vec<Arc<StorageTable>>,
+ database_id: DatabaseId,
grant: AccessLevel,
/// The shared definitions whose options the viewer may change.
editable: Vec<PropertyDefinitionId>,
@@ -920,6 +943,23 @@ impl Place {
}
}
+impl Planner {
+ pub(super) fn finish(
+ &self,
+ entries: &[StorageTable],
+ batch: &OpBatch,
+ writes: &Writes,
+ outcome: WritesOutcome,
+ ) -> Result<AppliedOps, DatabaseError> {
+ let committed = applied(outcome, &batch.ops, &self.related)?;
+ let changes = committed.changes.clone();
+ Ok(AppliedOps {
+ results: op_results(entries, &batch.ops, writes, committed)?,
+ changes,
+ })
+ }
+}
+
impl Planner {
/// The write one op makes: its target (the table, column or view) is
/// resolved once, and its change planned against it.
@@ -959,7 +999,7 @@ impl Planner {
&mut self,
index: usize,
table: TableId,
- entry: Result<Arc<TableEntry>, DatabaseError>,
+ entry: Result<Arc<StorageTable>, DatabaseError>,
change: &TableChange,
) -> Result<Write, DatabaseError> {
match change {
@@ -979,7 +1019,7 @@ impl Planner {
fn column_write(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
column: ColumnId,
change: &ColumnChange,
) -> Result<Write, DatabaseError> {
@@ -1025,7 +1065,7 @@ impl Planner {
}
/// The table an op names, as the ops so far leave it.
- fn entry(&self, index: usize, table: TableId) -> Result<Arc<TableEntry>, DatabaseError> {
+ fn entry(&self, index: usize, table: TableId) -> Result<Arc<StorageTable>, DatabaseError> {
self.entries
.iter()
.find(|entry| entry.table.id == table)
@@ -1034,7 +1074,7 @@ impl Planner {
}
/// The table an op changes, to change it in place.
- fn entry_mut(&mut self, table: TableId) -> Option<&mut TableEntry> {
+ fn entry_mut(&mut self, table: TableId) -> Option<&mut StorageTable> {
self.entries
.iter_mut()
.find(|entry| entry.table.id == table)
@@ -1058,7 +1098,7 @@ impl Planner {
/// Refuse a change to the options of a property shared beyond the
/// database unless the viewer may edit that property.
fn may_change_options(&self, place: Place, column: &ColumnEntry) -> Result<(), DatabaseError> {
- if column.shared_outside(self.database.id)
+ if column.shared_outside(self.database_id)
&& !self.editable.contains(&column.definition.definition.id)
{
return Err(place.refuse(
diff --git a/crates/databases/src/domain/service/ops/cells.rs b/crates/databases/src/domain/service/ops/cells.rs
index c52999bab6..8d797314b8 100644
--- a/crates/databases/src/domain/service/ops/cells.rs
+++ b/crates/databases/src/domain/service/ops/cells.rs
@@ -9,14 +9,14 @@ use models_properties::shared::{DataType, EntityReference};
use super::super::column_types::is_complete_url;
use super::super::{option_label_key, takes_options};
use super::{Place, Planner, RelatedRow};
-use crate::domain::catalog::{self, ColumnEntry, TableEntry, entity_type};
+use crate::domain::catalog::{self, ColumnEntry, StorageTable, entity_type};
use crate::domain::models::{CellChanges, ColumnConfig, DatabaseError};
impl Planner {
/// One row's cells as stored values; `None` empties a cell.
pub(super) fn cells(
&mut self,
- entry: &TableEntry,
+ entry: &StorageTable,
op: usize,
row: Option<usize>,
cells: &[CellWrite],
diff --git a/crates/databases/src/domain/service/ops/columns.rs b/crates/databases/src/domain/service/ops/columns.rs
index 34e7ef9d45..64417df6d8 100644
--- a/crates/databases/src/domain/service/ops/columns.rs
+++ b/crates/databases/src/domain/service/ops/columns.rs
@@ -20,7 +20,7 @@ use super::super::{
MAX_CONVERTED_ROWS, same_name, takes_options, validate_name, validate_option_labels,
};
use super::{ColumnCells, Place, Planner, refuse, refuse_taken, schema_refusal};
-use crate::domain::catalog::{self, ColumnEntry, PropertyType, TableEntry};
+use crate::domain::catalog::{self, ColumnEntry, PropertyType, StorageTable};
use crate::domain::models::{
Column, ColumnConfig, ColumnId, ColumnProtection, ColumnReplacement, DatabaseError, DatabaseId,
DatabaseView, NewDefinition, OptionId, PropertyDefinitionId, RowId, SchemaError, TableId,
@@ -31,7 +31,7 @@ impl Planner {
pub(super) fn create_column(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
definition: &NewColumn,
after: Option<ColumnId>,
) -> Result<Write, DatabaseError> {
@@ -82,7 +82,7 @@ impl Planner {
options,
};
(
- stored_definition(self.database.id, &created),
+ stored_definition(self.database_id, &created),
Some(created),
config,
*infer_type,
@@ -153,7 +153,7 @@ impl Planner {
pub(super) fn rename_column(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
column: &ColumnEntry,
name: &str,
previous_name: Option<&str>,
@@ -192,7 +192,7 @@ impl Planner {
pub(super) fn delete_column(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
column: &ColumnEntry,
) -> Result<Write, DatabaseError> {
let column_id = place.column;
@@ -241,7 +241,7 @@ impl Planner {
pub(super) fn order_columns(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
order: &[ColumnId],
) -> Result<Write, DatabaseError> {
let current: HashSet<ColumnId> = entry
@@ -282,7 +282,7 @@ impl Planner {
pub(super) fn add_options(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
column: &ColumnEntry,
options: &[NewOption],
) -> Result<Write, DatabaseError> {
@@ -318,7 +318,7 @@ impl Planner {
pub(super) fn change_type(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
column: &ColumnEntry,
to: ColumnKind,
) -> Result<Write, DatabaseError> {
@@ -466,7 +466,7 @@ impl Planner {
(!self.created_tables.contains(&entry.table.id)).then_some(entry.table.version);
self.store_views(entry.table.id, &views);
- let stored_definition = stored_definition(self.database.id, &definition);
+ let stored_definition = stored_definition(self.database_id, &definition);
if let Some(column) = self.column_mut(entry.table.id, column_id) {
column.column.property_definition_id = definition.id;
column.column.config = config;
@@ -495,7 +495,7 @@ impl Planner {
fn rebind(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
column: &ColumnEntry,
previous: PropertyDefinitionId,
relation: Option<(DatabaseId, TableId)>,
@@ -537,7 +537,7 @@ impl Planner {
pub(super) fn update_option(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
column: &ColumnEntry,
option: OptionId,
label: Option<&str>,
@@ -575,7 +575,7 @@ impl Planner {
pub(super) fn delete_option(
&mut self,
place: Place,
- entry: &TableEntry,
+ entry: &StorageTable,
column: &ColumnEntry,
option: OptionId,
) -> Result<Write, DatabaseError> {
@@ -670,7 +670,7 @@ impl Planner {
database: DatabaseId,
table: TableId,
) -> Result<(), DatabaseError> {
- if database == self.database.id {
+ if database == self.database_id {
return if self.entries.iter().any(|entry| entry.table.id == table) {
Ok(())
} else {
@@ -719,7 +719,7 @@ impl Planner {
/// Where a new column goes: right after `after`, or after the table's last.
fn column_position(
- entry: &TableEntry,
+ entry: &StorageTable,
place: Place,
after: Option<ColumnId>,
) -> Result<models_databases::position::Position, DatabaseError> {
diff --git a/crates/databases/src/domain/service/ops/rows.rs b/crates/databases/src/domain/service/ops/rows.rs
index 11cb581944..0f0ad387fc 100644
--- a/crates/databases/src/domain/service/ops/rows.rs
+++ b/crates/databases/src/domain/service/ops/rows.rs
@@ -5,7 +5,7 @@ use models_databases::views::LaneKey;
use models_databases::{RowChanges, RowsChange};
use super::{MAX_WRITTEN_ROWS, Place, Planner, refuse};
-use crate::domain::catalog::TableEntry;
+use crate::domain::catalog::StorageTable;
use crate::domain::journal::cell_value;
use crate::domain::models::{DatabaseError, Write};
@@ -13,7 +13,7 @@ impl Planner {
pub(super) fn rows_write(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
change: &RowsChange,
) -> Result<Write, DatabaseError> {
let table = entry.table.id;
diff --git a/crates/databases/src/domain/service/ops/tables.rs b/crates/databases/src/domain/service/ops/tables.rs
index 3d02bd2197..4db9c7befe 100644
--- a/crates/databases/src/domain/service/ops/tables.rs
+++ b/crates/databases/src/domain/service/ops/tables.rs
@@ -8,7 +8,7 @@ use models_databases::TakenId;
use models_databases::position::{key_between, keys_between};
use super::{Planner, refuse, refuse_taken};
-use crate::domain::catalog::TableEntry;
+use crate::domain::catalog::StorageTable;
use crate::domain::models::{
ColumnConfig, DatabaseError, SchemaError, Table, TableId, TableVersion, Write,
};
@@ -29,16 +29,14 @@ impl Planner {
// lock; this place only orders the batch's later reads.
let position = key_between(self.entries.last().map(|entry| &entry.table.position), None)
.map_err(|error| refuse(index, None, None, error.to_string()))?;
- self.entries.push(Arc::new(TableEntry {
- database: self.database.clone(),
+ self.entries.push(Arc::new(StorageTable {
table: Table {
id,
- database_id: self.database.id,
+ database_id: self.database_id,
name: name.clone(),
position,
version: TableVersion(0),
},
- grant: self.grant,
columns: Vec::new(),
views: Vec::new(),
}));
@@ -49,7 +47,7 @@ impl Planner {
pub(super) fn rename_table(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
name: &str,
previous_name: Option<&str>,
) -> Result<Write, DatabaseError> {
@@ -82,7 +80,7 @@ impl Planner {
pub(super) fn delete_table(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
) -> Result<Write, DatabaseError> {
let table = entry.table.id;
if self.entries.len() == 1 {
diff --git a/crates/databases/src/domain/service/ops/views.rs b/crates/databases/src/domain/service/ops/views.rs
index a3f9faa4a9..1164a54b13 100644
--- a/crates/databases/src/domain/service/ops/views.rs
+++ b/crates/databases/src/domain/service/ops/views.rs
@@ -12,7 +12,7 @@ use models_databases::{ColumnId, OptionId, TakenId, ViewChange};
use models_properties::service::property_value::PropertyValue;
use super::{Place, Planner, refuse, refuse_taken};
-use crate::domain::catalog::{TableEntry, schema_columns};
+use crate::domain::catalog::{StorageTable, storage_schema_columns};
use crate::domain::journal::cell_value;
use crate::domain::models::{DatabaseError, Position, PropertyDefinitionId, RowId, TableId, Write};
use crate::domain::service::{same_name, validate_name};
@@ -79,7 +79,7 @@ impl Planner {
pub(super) fn view_write(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
id: ViewId,
change: &ViewChange,
) -> Result<Write, DatabaseError> {
@@ -104,7 +104,7 @@ impl Planner {
.map_err(|error| refuse(index, None, None, error.to_string()))?;
let view = DatabaseView {
id,
- database_id: entry.database.id,
+ database_id: entry.table.database_id,
table_id: table,
name,
position,
@@ -173,7 +173,7 @@ impl Planner {
pub(super) fn order_views(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
order: &[ViewId],
) -> Result<Write, DatabaseError> {
let views = self.views_of(entry);
@@ -224,7 +224,7 @@ impl Planner {
fn move_card(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
board: DatabaseView,
CardMove {
row,
@@ -332,7 +332,7 @@ impl Planner {
}
/// The views of a table as the ops so far leave them, in their order.
- pub(super) fn views_of(&mut self, entry: &TableEntry) -> &mut Vec<DatabaseView> {
+ pub(super) fn views_of(&mut self, entry: &StorageTable) -> &mut Vec<DatabaseView> {
self.views
.entry(entry.table.id)
.or_insert_with(|| entry.views.clone())
@@ -341,7 +341,7 @@ impl Planner {
fn view(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
id: ViewId,
) -> Result<&DatabaseView, DatabaseError> {
self.views_of(entry)
@@ -350,7 +350,7 @@ impl Planner {
.ok_or_else(|| refuse(index, None, None, format!("no view {id} on this table")))
}
- fn replace_view(&mut self, entry: &TableEntry, view: DatabaseView) {
+ fn replace_view(&mut self, entry: &StorageTable, view: DatabaseView) {
if let Some(current) = self
.views_of(entry)
.iter_mut()
@@ -365,7 +365,7 @@ impl Planner {
fn view_name(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
view: Option<ViewId>,
name: &str,
) -> Result<String, DatabaseError> {
@@ -395,7 +395,7 @@ impl Planner {
fn check_view(
&mut self,
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
query: &ViewQuery,
layout: &ViewLayout,
) -> Result<(), DatabaseError> {
@@ -406,8 +406,8 @@ impl Planner {
/// A table's columns as a view's checks see them, with the options the
/// ops so far leave them.
- fn schema_of(&mut self, entry: &TableEntry) -> Vec<SchemaColumn> {
- let mut columns = schema_columns(entry);
+ fn schema_of(&mut self, entry: &StorageTable) -> Vec<SchemaColumn> {
+ let mut columns = storage_schema_columns(&entry.columns);
for (column, schema) in entry.columns.iter().zip(&mut columns) {
if !schema.options.is_empty() || column.takes_options() {
schema.options = self
@@ -457,7 +457,7 @@ impl Planner {
/// `current_title`, or takes the table's first column.
fn stored_layout(
index: usize,
- entry: &TableEntry,
+ entry: &StorageTable,
layout: &RequestedLayout,
current_title: Option<ColumnId>,
) -> Result<ViewLayout, DatabaseError> {
diff --git a/crates/databases/src/domain/service/storage.rs b/crates/databases/src/domain/service/storage.rs
new file mode 100644
index 0000000000..ad1e321944
--- /dev/null
+++ b/crates/databases/src/domain/service/storage.rs
@@ -0,0 +1,272 @@
+//! Core storage uses the same planner, definitions, cells and journal as the app.
+
+mod query;
+
+use super::*;
+use crate::domain::catalog::{ColumnEntry, StorageTable};
+use crate::domain::journal::Restoration;
+use crate::domain::models::{AppliedOps, WritesOutcome};
+use crate::domain::ports::DatabaseStorage;
+use crate::domain::storage::{DatabaseStorageService, StorageRow, StorageRows, StorageRowsQuery};
+use models_databases::{ColumnChange, ColumnKind, DatabaseOp, NewColumn};
+
+impl<R, D, C, E, A, B> DatabasesServiceImpl<R, D, C, E, A, B>
+where
+ R: DatabasesRepo,
+ D: ColumnDefinitionStore,
+ C: CellStore,
+ E: TableEventPublisher,
+ A: AccessDirectory,
+ B: MacroEventBroker,
+{
+ async fn storage_entries(&self, id: DatabaseId) -> Result<Vec<StorageTable>, DatabaseError> {
+ let tables = self
+ .repository
+ .tables_for_databases(&[id])
+ .await
+ .map_err(repository_error)?;
+ let ids: Vec<_> = tables.iter().map(|table| table.id).collect();
+ let columns = self
+ .repository
+ .columns_for_tables(&ids)
+ .await
+ .map_err(repository_error)?;
+ let definition_ids: Vec<_> = columns
+ .iter()
+ .map(|column| column.property_definition_id)
+ .collect();
+ let definitions: HashMap<_, _> = self
+ .definitions
+ .definitions(&definition_ids)
+ .await
+ .map_err(repository_error)?
+ .into_iter()
+ .map(|definition| (definition.definition.id, definition))
+ .collect();
+ let views = self
+ .repository
+ .views_for_tables(&ids)
+ .await
+ .map_err(repository_error)?;
+ tables
+ .into_iter()
+ .map(|table| {
+ let columns = columns
+ .iter()
+ .filter(|column| column.table_id == table.id)
+ .map(|column| {
+ Ok(ColumnEntry {
+ column: column.clone(),
+ definition: definitions
+ .get(&column.property_definition_id)
+ .cloned()
+ .ok_or(DatabaseError::NotFound)?,
+ writable: true,
+ })
+ })
+ .collect::<Result<_, DatabaseError>>()?;
+ let views = views
+ .iter()
+ .filter(|view| view.table_id == table.id)
+ .cloned()
+ .collect();
+ Ok(StorageTable {
+ table,
+ columns,
+ views,
+ })
+ })
+ .collect()
+ }
+}
+
+impl<R, D, C, E, A, B> DatabaseStorageService for DatabasesServiceImpl<R, D, C, E, A, B>
+where
+ R: DatabasesRepo,
+ D: ColumnDefinitionStore,
+ C: CellStore + DatabaseStorage,
+ E: TableEventPublisher,
+ A: AccessDirectory,
+ B: MacroEventBroker,
+{
+ async fn storage_tables(&self, id: DatabaseId) -> Result<Vec<TableDetail>, DatabaseError> {
+ Ok(self
+ .storage_entries(id)
+ .await?
+ .into_iter()
+ .map(|entry| TableDetail {
+ sql_name: catalog::sql_identifier(&entry.table.name),
+ table: entry.table,
+ columns: entry
+ .columns
+ .into_iter()
+ .map(|column| ColumnDetail {
+ sql_name: catalog::sql_identifier(column.name()),
+ shared_outside_database: column.shared_outside(id),
+ column: column.column,
+ definition: column.definition,
+ writable: true,
+ })
+ .collect(),
+ views: entry.views,
+ })
+ .collect())
+ }
+
+ async fn storage_rows(
+ &self,
+ id: DatabaseId,
+ table: TableId,
+ request: StorageRowsQuery,
+ ) -> Result<StorageRows, DatabaseError> {
+ const PAGE_SIZE: i64 = 500;
+ let entry = self
+ .storage_entries(id)
+ .await?
+ .into_iter()
+ .find(|entry| entry.table.id == table)
+ .ok_or(DatabaseError::NotFound)?;
+ // Scan in bounded batches, then let the shared SQL engine apply the complete
+ // view before paging. Sorting one fetched page would give incorrect results.
+ let mut after = None;
+ let mut source = Vec::new();
+ let mut values = HashMap::new();
+ loop {
+ let refs = self
+ .cells
+ .storage_row_page(table, after, PAGE_SIZE)
+ .await
+ .map_err(repository_error)?;
+ if refs.is_empty() {
+ break;
+ }
+ after = refs.last().map(|row| row.id);
+ let ids: Vec<_> = refs.iter().map(|row| row.id).collect();
+ let cells = self.cells.cells(&ids).await.map_err(repository_error)?;
+ for row in refs {
+ let cells = cells.get(&row.id).cloned().unwrap_or_default();
+ if request
+ .row_ids
+ .as_ref()
+ .is_some_and(|ids| !ids.contains(&row.id))
+ {
+ continue;
+ }
+ source.push(query::row(&row, &cells));
+ values.insert(row.id, cells);
+ }
+ }
+ let ordered = query::rows(&entry, source, &request)?;
+ let start = match request.after {
+ Some(after) => {
+ ordered
+ .iter()
+ .position(|id| *id == after)
+ .ok_or(DatabaseError::VersionConflict)?
+ + 1
+ }
+ None => 0,
+ };
+ let page: Vec<_> = ordered
+ .iter()
+ .skip(start)
+ .take(PAGE_SIZE as usize)
+ .copied()
+ .collect();
+ let next = (start + page.len() < ordered.len()).then(|| *page.last().unwrap());
+ let rows = page
+ .into_iter()
+ .map(|row_id| {
+ let cells = values.remove(&row_id).unwrap_or_default();
+ StorageRow {
+ row_id,
+ cells: entry
+ .columns
+ .iter()
+ .filter_map(|column| {
+ cells
+ .get(&column.column.property_definition_id)
+ .cloned()
+ .map(|value| (column.column.id, value))
+ })
+ .collect(),
+ }
+ })
+ .collect();
+ let version = self
+ .repository
+ .table_versions(&[table])
+ .await
+ .map_err(repository_error)?
+ .get(&table)
+ .copied()
+ .ok_or(DatabaseError::NotFound)?;
+ if version != entry.table.version {
+ return Err(DatabaseError::VersionConflict);
+ }
+ Ok(StorageRows {
+ rows,
+ next,
+ version,
+ })
+ }
+
+ async fn apply_storage_ops(
+ &self,
+ id: DatabaseId,
+ viewer: Viewer,
+ batch: OpBatch,
+ ) -> Result<AppliedOps, DatabaseError> {
+ for (index, op) in batch.ops.iter().enumerate() {
+ if matches!(
+ op,
+ DatabaseOp::Column {
+ change: ColumnChange::Create {
+ definition: NewColumn::Existing { .. },
+ ..
+ },
+ ..
+ } | DatabaseOp::Column {
+ change: ColumnChange::Create {
+ definition: NewColumn::New {
+ kind: ColumnKind::Relation { .. },
+ ..
+ },
+ ..
+ },
+ ..
+ } | DatabaseOp::Column {
+ change: ColumnChange::ChangeType {
+ to: ColumnKind::Relation { .. }
+ },
+ ..
+ }
+ ) {
+ return Err(DatabaseError::InvalidOp(crate::domain::models::OpRefusal {
+ op: index,
+ row: None,
+ column: None,
+ taken: None,
+ reason: "Storage consumers must authorize external bindings and relations"
+ .into(),
+ }));
+ }
+ }
+ for _ in 0..ops::MAX_PLANNING_ATTEMPTS {
+ let entries = self.storage_entries(id).await?;
+ let (writes, planner) = self
+ .prepare_storage_batch(id, &entries, &viewer, &batch, &Restoration::default())
+ .await?;
+ let outcome = self
+ .cells
+ .apply_storage_writes(&writes)
+ .await
+ .map_err(repository_error)?;
+ if matches!(outcome, WritesOutcome::SchemaMoved(_)) {
+ continue;
+ }
+ return planner.finish(&entries, &batch, &writes, outcome);
+ }
+ Err(DatabaseError::VersionConflict)
+ }
+}
diff --git a/crates/databases/src/domain/service/storage/query.rs b/crates/databases/src/domain/service/storage/query.rs
new file mode 100644
index 0000000000..8bad925604
--- /dev/null
+++ b/crates/databases/src/domain/service/storage/query.rs
@@ -0,0 +1,110 @@
+//! Reuse the database query compiler and fold for host-owned storage reads.
+use crate::domain::{
+ catalog::{PropertyType, StorageTable, option_labels},
+ models::{DatabaseError, RowRef},
+ storage::StorageRowsQuery,
+};
+use database_sql::{
+ Catalog, Cell, Row,
+ catalog::{Column, ColumnKind, SelectOption, Table, TableSource},
+};
+use models_databases::{
+ OptionId, RowId, ViewId,
+ views::{DatabaseView, ViewLayout},
+};
+use models_properties::service::property_value::PropertyValue;
+use std::collections::HashMap;
+
+pub(super) fn row(row: &RowRef, cells: &HashMap<uuid::Uuid, PropertyValue>) -> Row {
+ Row {
+ id: row.id,
+ position: Some(row.position.clone()),
+ cells: cells
+ .iter()
+ .map(|(id, value)| {
+ (
+ *id,
+ match value {
+ PropertyValue::Bool(value) => Cell::Bool(*value),
+ PropertyValue::Num(value) => Cell::Number(*value),
+ PropertyValue::Str(value) => Cell::Text(value.clone()),
+ PropertyValue::Date(value) => Cell::Date(*value),
+ PropertyValue::SelectOption(ids) => {
+ Cell::Options(ids.iter().copied().map(OptionId::from_uuid).collect())
+ }
+ PropertyValue::EntityRef(refs) => Cell::Entities(
+ refs.iter()
+ .map(|reference| reference.entity_id.clone())
+ .collect(),
+ ),
+ PropertyValue::Link(urls) => Cell::Text(urls.join(" ")),
+ },
+ )
+ })
+ .collect(),
+ }
+}
+
+pub(super) fn rows(
+ entry: &StorageTable,
+ rows: Vec<Row>,
+ request: &StorageRowsQuery,
+) -> Result<Vec<RowId>, DatabaseError> {
+ let catalog = Catalog {
+ tables: vec![Table {
+ id: entry.table.id,
+ database_id: entry.table.database_id,
+ database: String::new(),
+ name: entry.table.name.clone(),
+ source: TableSource::Database,
+ columns: entry
+ .columns
+ .iter()
+ .map(|column| Column {
+ id: column.column.property_definition_id,
+ placement: column.column.id,
+ name: column.name().to_owned(),
+ kind: ColumnKind::of(
+ PropertyType::of(&column.column, &column.definition).cast_kind(),
+ option_labels(&column.definition)
+ .into_iter()
+ .map(|(id, label)| SelectOption { id, label })
+ .collect(),
+ ),
+ })
+ .collect(),
+ }],
+ };
+ let query = if request.row_ids.is_some() {
+ Default::default()
+ } else {
+ request.query.clone()
+ };
+ let now = chrono::Utc::now();
+ let view = DatabaseView {
+ id: ViewId::new(),
+ database_id: entry.table.database_id,
+ table_id: entry.table.id,
+ name: String::new(),
+ position: entry.table.position.clone(),
+ query,
+ layout: ViewLayout::Table { columns: vec![] },
+ created_at: now,
+ updated_at: now,
+ };
+ let select = database_sql::compile_view(&view, &catalog).map_err(|error| {
+ DatabaseError::InvalidOp(crate::domain::models::OpRefusal {
+ op: 0,
+ row: None,
+ column: None,
+ taken: None,
+ reason: error.to_string(),
+ })
+ })?;
+ let filter = select.where_.clone();
+ let mut plan = database_sql::split(&catalog, select);
+ // Storage supplies unfiltered rows, so evaluate even predicates the SQL
+ // planner would normally push into its external row source.
+ plan.residual = filter;
+ Ok(database_sql::fold_relations(&catalog, &plan, vec![rows]).1)
+}
diff --git a/crates/databases/src/domain/storage.rs b/crates/databases/src/domain/storage.rs
new file mode 100644
index 0000000000..8b1a4f4b27
--- /dev/null
+++ b/crates/databases/src/domain/storage.rs
@@ -0,0 +1,72 @@
+//! Typed access to reusable storage for domains that own authorization and lifecycle.
+
+use std::collections::HashMap;
+
+use models_properties::service::property_value::PropertyValue;
+use serde::{Deserialize, Serialize};
+
+use super::models::{
+ AppliedOps, ColumnId, DatabaseError, DatabaseId, OpBatch, RowId, TableDetail, TableId,
+ TableVersion, Viewer,
+};
+
+/// One storage row, with cells keyed by column placement.
+#[derive(Debug, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct StorageRow {
+ /// Row identity, independent of any referenced entity.
+ pub row_id: RowId,
+ /// Populated cells.
+ pub cells: HashMap<ColumnId, PropertyValue>,
+}
+
+/// A bounded page of rows at a table version.
+#[derive(Debug, Serialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct StorageRows {
+ /// Rows in the requested view's order.
+ pub rows: Vec<StorageRow>,
+ /// Cursor for another page, if present.
+ pub next: Option<RowId>,
+ /// Table version when the read began.
+ pub version: TableVersion,
+}
+
+/// A query over one authorized storage table.
+#[derive(Debug, Default, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct StorageRowsQuery {
+ /// Continue after this row in the filtered, sorted result.
+ pub after: Option<RowId>,
+ /// The common database filter and sort semantics.
+ #[serde(default)]
+ pub query: models_databases::views::ViewQuery,
+ /// Read these retained rows regardless of the active filter.
+ pub row_ids: Option<Vec<RowId>>,
+}
+
+/// Trusted domain capability. Consumers enforce access and hold their own
+/// lifecycle guard through each call. This never creates a database app entity.
+pub trait DatabaseStorageService: Send + Sync + 'static {
+ /// Read schema from an authorized core resource.
+ fn storage_tables(
+ &self,
+ id: DatabaseId,
+ ) -> impl Future<Output = Result<Vec<TableDetail>, DatabaseError>> + Send;
+ /// Read a page from a table in the authorized resource.
+ fn storage_rows(
+ &self,
+ id: DatabaseId,
+ table: TableId,
+ query: StorageRowsQuery,
+ ) -> impl Future<Output = Result<StorageRows, DatabaseError>> + Send;
+ /// Validate typed operations with the shared planner, then commit through
+ /// `DatabaseStorage`. External property bindings and cross-resource relations
+ /// require a host capability and are not accepted by this entry point.
+ fn apply_storage_ops(
+ &self,
+ id: DatabaseId,
+ viewer: Viewer,
+ batch: OpBatch,
+ ) -> impl Future<Output = Result<AppliedOps, DatabaseError>> + Send;
+}
diff --git a/crates/databases/src/outbound/pg_cell_store.rs b/crates/databases/src/outbound/pg_cell_store.rs
index b2f40b1b90..acfbf8b861 100644
--- a/crates/databases/src/outbound/pg_cell_store.rs
+++ b/crates/databases/src/outbound/pg_cell_store.rs
@@ -3,6 +3,7 @@
//! options.
mod core;
+mod provisioning;
mod required;
mod transfer;
@@ -428,7 +429,7 @@ where
let refused = |outcome| Ok(Applied::Refused(outcome));
let database_id = writes.database_id;
// Schema planning is optimistic. Recheck protections under the same table
- // locks that serialize form registration before changing stored schema.
+ // locks that serialize protection registration before changing stored schema.
let protected_operation = match write {
Write::DeleteColumn { column_id, .. } => Some((*column_id, ColumnProtection::Delete)),
Write::ReplaceColumn { replacement, .. } => {
diff --git a/crates/databases/src/outbound/pg_cell_store/core.rs b/crates/databases/src/outbound/pg_cell_store/core.rs
index f6b296d103..74bc79d5ab 100644
--- a/crates/databases/src/outbound/pg_cell_store/core.rs
+++ b/crates/databases/src/outbound/pg_cell_store/core.rs
@@ -25,6 +25,26 @@ where
Ok(id)
}
+ async fn storage_row_page(
+ &self,
+ table: TableId,
+ after: Option<RowId>,
+ limit: i64,
+ ) -> Result<Vec<crate::domain::models::RowRef>, Self::Error> {
+ let rows = sqlx::query!(
+ "SELECT id, position FROM database_rows WHERE table_id = $1 AND ($2::uuid IS NULL OR id > $2) ORDER BY id LIMIT $3",
+ table.into_uuid(), after.map(RowId::into_uuid), limit,
+ ).fetch_all(&self.pool).await?;
+ rows.into_iter()
+ .map(|row| {
+ Ok(crate::domain::models::RowRef {
+ id: RowId::from_uuid(row.id),
+ position: row.position.parse().map_err(PgDatabasesRepoError::from)?,
+ })
+ })
+ .collect()
+ }
+
#[tracing::instrument(err, skip(self))]
async fn delete_storage(&self, id: DatabaseId) -> Result<(), Self::Error> {
let mut transaction = self.pool.begin().await?;
diff --git a/crates/databases/src/outbound/pg_cell_store/provisioning.rs b/crates/databases/src/outbound/pg_cell_store/provisioning.rs
new file mode 100644
index 0000000000..efb85e39d4
--- /dev/null
+++ b/crates/databases/src/outbound/pg_cell_store/provisioning.rs
@@ -0,0 +1,83 @@
+use super::*;
+use crate::domain::provisioning::{DatabaseStorageProvisioner, StorageBlueprint};
+use crate::outbound::pg_databases_repo::insert_column;
+use models_databases::position::key_between;
+use properties::domain::database_cell_writer::DatabaseCellWriter;
+
+impl<Properties> DatabaseStorageProvisioner for PgCellStore<Properties>
+where
+ Properties: PropertiesRepo<Err = anyhow::Error>
+ + DatabaseDefinitionWriter<Transaction = Transaction<'static, Postgres>>
+ + DatabaseCellWriter<Transaction = Transaction<'static, Postgres>>
+ + DatabaseOptionWriter
+ + Send
+ + Sync
+ + 'static,
+{
+ type Transaction = Transaction<'static, Postgres>;
+
+ #[tracing::instrument(skip_all, err)]
+ async fn create_storage_in(
+ &self,
+ transaction: &mut Self::Transaction,
+ database: &StorageBlueprint,
+ ) -> Result<(), Self::Error> {
+ sqlx::query!(
+ "INSERT INTO databases (id) VALUES ($1)",
+ database.id.into_uuid()
+ )
+ .execute(&mut **transaction)
+ .await?;
+ let position = key_between(None, None).map_err(PgDatabasesRepoError::from)?;
+ sqlx::query!(
+ "INSERT INTO database_tables (id, database_id, name, position) VALUES ($1, $2, 'Records', $3)",
+ database.table_id.into_uuid(), database.id.into_uuid(), position.as_str(),
+ ).execute(&mut **transaction).await?;
+ let positions =
+ models_databases::position::keys_between(None, None, database.columns.len())
+ .map_err(PgDatabasesRepoError::from)?;
+ for (column, position) in database.columns.iter().zip(positions) {
+ let definition = self
+ .properties
+ .create_database_definition_in(
+ transaction,
+ NewDatabaseDefinition {
+ id: macro_uuid::generate_uuid_v7(),
+ database_id: database.id.into_uuid(),
+ name: &column.name,
+ data_type: column.data_type,
+ is_multi_select: false,
+ specific_entity_type: column.entity_type,
+ options: &column.options,
+ },
+ )
+ .await
+ .map_err(|error| PgCellStoreError::Cells(Box::new(error)))?;
+ insert_column(
+ transaction,
+ column.id,
+ database.table_id,
+ definition.definition.id,
+ &position,
+ false,
+ )
+ .await?;
+ sqlx::query!(
+ "UPDATE database_columns SET nullable = $2 WHERE id = $1",
+ column.id.into_uuid(),
+ column.nullable
+ )
+ .execute(&mut **transaction)
+ .await?;
+ for capability in &column.protections {
+ sqlx::query!(
+ "INSERT INTO database_column_protections (column_id, capability) VALUES ($1, $2) ON CONFLICT DO NOTHING",
+ column.id.into_uuid(), capability.to_string(),
+ )
+ .execute(&mut **transaction)
+ .await?;
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/databases/src/outbound/pg_databases_repo/test/schema_ops.rs b/crates/databases/src/outbound/pg_databases_repo/test/schema_ops.rs
index 9e8021d676..909332e407 100644
--- a/crates/databases/src/outbound/pg_databases_repo/test/schema_ops.rs
+++ b/crates/databases/src/outbound/pg_databases_repo/test/schema_ops.rs
@@ -784,3 +784,45 @@ async fn a_type_change_converts_stored_cells_and_rewrites_views_testing_the_colu
}
);
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn protected_columns_refuse_direct_sql_but_allow_parent_deletion(pool: PgPool) {
+ let guests = guests(&pool).await;
+ sqlx::query!("INSERT INTO database_column_protections (column_id, capability) VALUES ($1, 'delete'), ($1, 'change_type')", guests.name.into_uuid()).execute(&pool).await.unwrap();
+ let error = sqlx::query!(
+ "DELETE FROM database_columns WHERE id = $1",
+ guests.name.into_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.as_database_error().unwrap().constraint(),
+ Some("database_column_protected")
+ );
+ let error = sqlx::query!(
+ "UPDATE property_definitions SET data_type = 'NUMBER' WHERE id = $1",
+ guests.name_definition
+ )
+ .execute(&pool)
+ .await
+ .unwrap_err();
+ assert_eq!(
+ error.as_database_error().unwrap().constraint(),
+ Some("database_column_protected")
+ );
+ sqlx::query!(
+ "UPDATE database_columns SET display_name = 'Renamed' WHERE id = $1",
+ guests.name.into_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ sqlx::query!(
+ "DELETE FROM database_entities WHERE database_id = $1",
+ guests.database_id.into_uuid()
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+}
diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rs
index 21384ad983..95965f9180 100644
--- a/crates/entity_access/src/domain/ports.rs
+++ b/crates/entity_access/src/domain/ports.rs
@@ -104,6 +104,19 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {
agent_session_id: &str,
) -> impl Future<Output = Result<Option<AgentSessionParent>, AccessError>> + Send;
+ /// Highest grant on a CRM pipeline.
+ fn get_pipeline_access(
+ &self,
+ id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> impl Future<Output = Result<Option<AccessLevel>, AccessError>> + Send;
+
+ /// All pipeline grants for the caller's current sharing sources.
+ fn list_pipeline_access(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Vec<(Uuid, AccessLevel)>, AccessError>> + Send;
+
/// Get the highest access level a user has for a database.
fn get_database_access(
&self,
@@ -717,3 +730,12 @@ impl EntityAccessService for NoOpEntityAccessService {
Ok(None)
}
}
+
+/// Directory of pipeline grants for CRM navigation.
+pub trait AccessiblePipelines: Clone + Send + Sync + 'static {
+ /// Highest effective grant on each accessible pipeline.
+ fn accessible_pipelines(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> impl Future<Output = Result<Vec<(Uuid, AccessLevel)>, AccessError>> + Send;
+}
diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rs
index 8511ccd285..2e4ea1ecff 100644
--- a/crates/entity_access/src/domain/service.rs
+++ b/crates/entity_access/src/domain/service.rs
@@ -9,8 +9,8 @@ use crate::domain::{
EntityPermission, EntityType, RequiredPermission, TeamRole, UserTeamInfo, ViewAccessLevel,
},
ports::{
- AccessRepository, AccessibleDatabases, AccessibleForms, EntityAccessService,
- ScheduledActionGrants,
+ AccessRepository, AccessibleDatabases, AccessibleForms, AccessiblePipelines,
+ EntityAccessService, ScheduledActionGrants,
},
};
use futures::{StreamExt, stream};
@@ -74,6 +74,7 @@ where
Ok(direct.max(parent_access.map(session_permission_from_parent)))
}
EntityType::Initiative => self.repo.get_initiative_access(entity_id, user_id).await,
+ EntityType::CrmPipeline => self.repo.get_pipeline_access(entity_id, user_id).await,
EntityType::Database => self.repo.get_database_access(entity_id, user_id).await,
EntityType::DatabaseRow => self.repo.get_database_row_access(entity_id, user_id).await,
EntityType::Form => self.repo.get_form_access(entity_id, user_id).await,
@@ -218,6 +219,7 @@ where
| EntityType::EmailThread
| EntityType::Call
| EntityType::Initiative
+ | EntityType::CrmPipeline
| EntityType::Database
| EntityType::DatabaseRow
| EntityType::Form => {
@@ -557,6 +559,7 @@ where
| EntityType::CalendarEvent
| EntityType::AgentSession
| EntityType::Initiative
+ | EntityType::CrmPipeline
| EntityType::Database
| EntityType::DatabaseRow
| EntityType::Form
@@ -641,6 +644,7 @@ where
| EntityType::CalendarEvent
| EntityType::AgentSession
| EntityType::Initiative
+ | EntityType::CrmPipeline
| EntityType::Database
| EntityType::DatabaseRow
| EntityType::Form
@@ -758,6 +762,7 @@ where
| EntityType::Initiative
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::Database
| EntityType::Form => {
let entity_id = Uuid::parse_str(entity_id).map_err(|_| {
@@ -860,3 +865,12 @@ fn session_permission_from_parent(level: AccessLevel) -> AccessLevel {
AccessLevel::View
}
}
+
+impl<R: AccessRepository> AccessiblePipelines for EntityAccessServiceImpl<R> {
+ async fn accessible_pipelines(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<(Uuid, AccessLevel)>, AccessError> {
+ self.repo.list_pipeline_access(user_id).await
+ }
+}
diff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rs
index b26847a8e1..5cf5e32492 100644
--- a/crates/entity_access/src/domain/service/test.rs
+++ b/crates/entity_access/src/domain/service/test.rs
@@ -35,6 +35,8 @@ struct MockRepo {
scheduled_action_access: Arc<Mutex<Option<AccessLevel>>>,
accessible_scheduled_action_ids: Arc<Mutex<Vec<Uuid>>>,
agent_session_parent: Arc<Mutex<Option<AgentSessionParent>>>,
+ pipeline_access: Arc<Mutex<Option<AccessLevel>>>,
+ pipeline_access_list: Arc<Mutex<Vec<(Uuid, AccessLevel)>>>,
database_access: Arc<Mutex<Option<AccessLevel>>>,
database_access_list: Arc<Mutex<Vec<(Uuid, AccessLevel)>>>,
database_row_access: Arc<Mutex<Option<AccessLevel>>>,
@@ -88,6 +90,8 @@ impl MockRepo {
scheduled_action_access: Arc::new(Mutex::new(None)),
accessible_scheduled_action_ids: Arc::new(Mutex::new(Vec::new())),
agent_session_parent: Arc::default(),
+ pipeline_access: Arc::default(),
+ pipeline_access_list: Arc::default(),
database_access: Arc::new(Mutex::new(None)),
database_access_list: Arc::new(Mutex::new(Vec::new())),
database_row_access: Arc::new(Mutex::new(None)),
@@ -412,6 +416,20 @@ impl AccessRepository for MockRepo {
Ok(*self.initiative_access.lock().await)
}
+ async fn get_pipeline_access(
+ &self,
+ _id: &str,
+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ Ok(*self.pipeline_access.lock().await)
+ }
+ async fn list_pipeline_access(
+ &self,
+ _user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<(Uuid, AccessLevel)>, AccessError> {
+ Ok(self.pipeline_access_list.lock().await.clone())
+ }
+
async fn get_database_access(
&self,
_database_id: &str,
@@ -2902,3 +2920,45 @@ async fn accessible_forms_are_the_repository_listing() {
vec![(shared, AccessLevel::View), (owned, AccessLevel::Owner)]
);
}
+
+#[tokio::test]
+async fn pipeline_receipts_use_their_own_grants() {
+ let repo = MockRepo::new().with_database_access(AccessLevel::Owner);
+ let service = EntityAccessServiceImpl::new(repo.clone());
+ let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let id = Uuid::now_v7().to_string();
+ assert!(
+ service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ &user,
+ None,
+ &id,
+ EntityType::CrmPipeline
+ )
+ .await
+ .is_err()
+ );
+ *repo.pipeline_access.lock().await = Some(AccessLevel::Edit);
+ assert!(
+ service
+ .generate_entity_access_receipt::<EditAccessLevel>(
+ &user,
+ None,
+ &id,
+ EntityType::CrmPipeline
+ )
+ .await
+ .is_ok()
+ );
+ assert!(
+ service
+ .generate_entity_access_receipt::<OwnerAccessLevel>(
+ &user,
+ None,
+ &id,
+ EntityType::CrmPipeline
+ )
+ .await
+ .is_err()
+ );
+}
diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rs
index ab33d5c278..40b96d777c 100644
--- a/crates/entity_access/src/outbound/pg_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo.rs
@@ -303,6 +303,30 @@ impl AccessRepository for PgAccessRepository {
.await?)
}
+ async fn get_pipeline_access(
+ &self,
+ id: &str,
+ user_id: Option<&MacroUserId<Lowercase<'_>>>,
+ ) -> Result<Option<AccessLevel>, AccessError> {
+ let id = id
+ .parse::<Uuid>()
+ .map_err(|_| AccessError::BadRequest("Invalid pipeline ID"))?;
+ let sources = queries::get_user_source_ids(&self.pool, user_id)
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(queries::pipeline_access::get_pipeline_access(&self.pool, id, &sources).await?)
+ }
+
+ async fn list_pipeline_access(
+ &self,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ ) -> Result<Vec<(Uuid, AccessLevel)>, AccessError> {
+ let sources = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(queries::pipeline_access::list_pipeline_access(&self.pool, &sources).await?)
+ }
+
#[tracing::instrument(err, skip(self, user_id))]
async fn get_database_access(
&self,
@@ -529,6 +553,9 @@ impl AccessRepository for PgAccessRepository {
)
.await
}
+ EntityType::CrmPipeline => {
+ queries::pipeline_access::get_pipeline_access(&self.pool, entity_uuid, &source_ids).await
+ }
EntityType::Database => {
queries::database_access::get_database_access(
&self.pool,
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries.rs b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
index 1acd87d8c9..8d749a2063 100644
--- a/crates/entity_access/src/outbound/pg_access_repo/queries.rs
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries.rs
@@ -36,6 +36,7 @@ pub mod document_access;
pub mod foreign_entity_access;
pub mod form_access;
pub mod initiative_access;
+pub mod pipeline_access;
pub mod project_access;
pub mod scheduled_action_access;
pub mod team_access;
diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/pipeline_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/pipeline_access.rs
new file mode 100644
index 0000000000..7e9245120b
--- /dev/null
+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/pipeline_access.rs
@@ -0,0 +1,41 @@
+//! Pipeline grants, resolved through the caller's current sharing sources.
+
+use super::SourceIds;
+use crate::domain::models::AccessLevel;
+use sqlx::PgPool;
+use std::collections::BTreeMap;
+use uuid::Uuid;
+
+/// Highest grant on each pipeline, including trashed pipelines for restoration.
+pub async fn list_pipeline_access(
+ pool: &PgPool,
+ sources: &SourceIds,
+) -> Result<Vec<(Uuid, AccessLevel)>, sqlx::Error> {
+ let rows = sqlx::query!(
+ r#"SELECT p.id, ea.access_level AS "access_level!: AccessLevel"
+ FROM crm_pipeline_entities p JOIN entity_access ea ON ea.entity_id = p.id AND ea.entity_type = 'crm_pipeline'
+ WHERE ea.source_id = ANY($1)"#,
+ &sources.0,
+ ).fetch_all(pool).await?;
+ let mut grants = BTreeMap::<Uuid, AccessLevel>::new();
+ for row in rows {
+ grants
+ .entry(row.id)
+ .and_modify(|level| *level = (*level).max(row.access_level))
+ .or_insert(row.access_level);
+ }
+ Ok(grants.into_iter().collect())
+}
+
+/// Resolve one pipeline without enumerating the caller's other pipelines.
+pub async fn get_pipeline_access(
+ pool: &PgPool,
+ id: Uuid,
+ sources: &SourceIds,
+) -> Result<Option<AccessLevel>, sqlx::Error> {
+ let levels = sqlx::query_scalar!(
+ "SELECT access_level::text FROM entity_access WHERE entity_id = $1 AND entity_type = 'crm_pipeline' AND source_id = ANY($2)",
+ id, &sources.0,
+ ).fetch_all(pool).await?;
+ super::database_access::highest_access_level(&levels)
+}
diff --git a/crates/entity_access/src/outbound/pg_explain_access_repo.rs b/crates/entity_access/src/outbound/pg_explain_access_repo.rs
index 924100f178..acda68256f 100644
--- a/crates/entity_access/src/outbound/pg_explain_access_repo.rs
+++ b/crates/entity_access/src/outbound/pg_explain_access_repo.rs
@@ -136,6 +136,19 @@ impl ExplainAccessRepository for PgExplainAccessRepository {
)
.await?)
}
+ EntityType::CrmPipeline => {
+ let pipeline_id = parse_uuid(entity_id, "Invalid pipeline ID format")?;
+ let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
+ .await
+ .map_err(anyhow_access_error)?;
+ Ok(queries::list_entity_access_grants(
+ &self.pool,
+ &pipeline_id,
+ EntityType::CrmPipeline,
+ &source_ids,
+ )
+ .await?)
+ }
EntityType::Form => {
let form_id = parse_uuid(entity_id, "Invalid form ID format")?;
let source_ids = queries::get_user_source_ids(&self.pool, Some(user_id))
diff --git a/crates/entity_access/src/outbound/pg_explain_access_repo/test.rs b/crates/entity_access/src/outbound/pg_explain_access_repo/test.rs
index 1427de039d..46180a1fdf 100644
--- a/crates/entity_access/src/outbound/pg_explain_access_repo/test.rs
+++ b/crates/entity_access/src/outbound/pg_explain_access_repo/test.rs
@@ -332,3 +332,38 @@ async fn form_explanation_lists_grants_and_the_public_audience(pool: PgPool) {
assert_eq!(members.effective_access_level(), None);
assert!(members.grants.is_empty());
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_team"))
+)]
+async fn pipeline_explanation_uses_pipeline_grants_without_database_grants(pool: PgPool) {
+ let pipeline_id = Uuid::now_v7();
+ let member = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ let outsider = MacroUserIdStr::try_from_email("[email protected]").unwrap();
+ sqlx::query!(
+ "INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+ VALUES ($1, 'crm_pipeline', $2, 'user', 'view'),
+ ($1, 'database', $2, 'user', 'owner')",
+ pipeline_id,
+ member.as_ref(),
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let service = ExplainAccessServiceImpl::new(PgExplainAccessRepository::new(pool));
+ let explanation = service
+ .explain_access(&member, &pipeline_id.to_string(), EntityType::CrmPipeline)
+ .await
+ .unwrap();
+ assert_eq!(
+ explanation.effective_access_level(),
+ Some(AccessLevel::View)
+ );
+ assert_eq!(explanation.grants.len(), 1);
+ let denied = service
+ .explain_access(&outsider, &pipeline_id.to_string(), EntityType::CrmPipeline)
+ .await
+ .unwrap();
+ assert!(denied.grants.is_empty());
+}
diff --git a/crates/entity_access_db_utils/src/lib.rs b/crates/entity_access_db_utils/src/lib.rs
index fd22791907..f66d7e852d 100644
--- a/crates/entity_access_db_utils/src/lib.rs
+++ b/crates/entity_access_db_utils/src/lib.rs
@@ -439,6 +439,7 @@ pub async fn update_entity_access_channel_share_permissions(
.await?;
}
EntityType::Database
+ | EntityType::CrmPipeline
| EntityType::Form
| EntityType::AgentSession
| EntityType::Chat
@@ -558,6 +559,7 @@ pub async fn update_entity_access_channel_share_permissions(
}
}
EntityType::Database
+ | EntityType::CrmPipeline
| EntityType::Form
| EntityType::AgentSession
| EntityType::Chat
diff --git a/crates/favorites/src/domain/mutation_service.rs b/crates/favorites/src/domain/mutation_service.rs
index ce66e3c629..1d1a05ef18 100644
--- a/crates/favorites/src/domain/mutation_service.rs
+++ b/crates/favorites/src/domain/mutation_service.rs
@@ -110,6 +110,7 @@ fn validate_favoritable(entity_type: EntityType) -> Result<(), FavoritesError> {
| EntityType::Initiative
// Databases and forms are not favoritable yet, and rows never are.
| EntityType::Database
+ | EntityType::CrmPipeline
| EntityType::DatabaseRow
| EntityType::Form => Err(FavoritesError::UnsupportedEntityType(entity_type)),
}
diff --git a/crates/graphql_common/src/entity_type.rs b/crates/graphql_common/src/entity_type.rs
index 8db5fee93b..cbb8e8fe1b 100644
--- a/crates/graphql_common/src/entity_type.rs
+++ b/crates/graphql_common/src/entity_type.rs
@@ -37,6 +37,8 @@ pub enum GraphqlSoupEntityType {
/// Canonical entity types accepted by cross-entity APIs.
#[derive(Enum, Copy, Clone, Eq, PartialEq, Hash)]
pub enum GraphqlEntityType {
+ /// CRM pipeline entity.
+ CrmPipeline,
/// Document entity.
Document,
/// Chat entity.
@@ -115,6 +117,7 @@ impl GraphqlSoupEntityType {
| EntityType::StaticFile
| EntityType::Skill
| EntityType::ScheduledAction
+ | EntityType::CrmPipeline
| EntityType::Database
| EntityType::Form => return None,
})
@@ -164,6 +167,7 @@ impl GraphqlEntityType {
EntityType::AgentSession => Self::AgentSession,
EntityType::ScheduledAction => Self::ScheduledAction,
EntityType::Initiative => Self::Initiative,
+ EntityType::CrmPipeline => Self::CrmPipeline,
EntityType::Database => Self::Database,
EntityType::DatabaseRow => Self::DatabaseRow,
EntityType::Form => Self::Form,
@@ -197,6 +201,7 @@ impl GraphqlEntityType {
Self::AgentSession => EntityType::AgentSession,
Self::ScheduledAction => EntityType::ScheduledAction,
Self::Initiative => EntityType::Initiative,
+ Self::CrmPipeline => EntityType::CrmPipeline,
Self::Database => EntityType::Database,
Self::DatabaseRow => EntityType::DatabaseRow,
Self::Form => EntityType::Form,
diff --git a/crates/graphql_soup/src/loaders.rs b/crates/graphql_soup/src/loaders.rs
index c61a054be9..5c87e359e8 100644
--- a/crates/graphql_soup/src/loaders.rs
+++ b/crates/graphql_soup/src/loaders.rs
@@ -389,6 +389,7 @@ fn entity_filter_ast(entities: &[Entity<'static>]) -> Result<EntityFilterAst, So
| EntityType::Skill
| EntityType::ScheduledAction
| EntityType::Reminder
+ | EntityType::CrmPipeline
| EntityType::Database
| EntityType::Form => {
return Err(rootcause::report!(
diff --git a/crates/macro_db_client/migrations/20261007172434_crm_pipeline_entities.down.sql b/crates/macro_db_client/migrations/20261007172434_crm_pipeline_entities.down.sql
new file mode 100644
index 0000000000..9bbd70afc9
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261007172434_crm_pipeline_entities.down.sql
@@ -0,0 +1,13 @@
+-- Preserve pipeline content as ordinary database app entities on rollback.
+INSERT INTO database_entities (database_id, name, user_id, created_at, updated_at, trashed_at)
+SELECT database_id, name, user_id, created_at, updated_at, trashed_at FROM crm_pipeline_entities
+ON CONFLICT DO NOTHING;
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+SELECT p.database_id, 'database', ea.source_id, ea.source_type, ea.access_level
+FROM crm_pipeline_entities p JOIN entity_access ea ON ea.entity_id = p.id AND ea.entity_type = 'crm_pipeline'
+ON CONFLICT DO NOTHING;
+DELETE FROM entity_access WHERE entity_type = 'crm_pipeline' AND entity_id IN (SELECT id FROM crm_pipeline_entities);
+DROP TRIGGER crm_pipeline_cleanup ON crm_pipeline_entities;
+DELETE FROM database_column_protections WHERE column_id IN (SELECT primary_column_id FROM crm_pipeline_entities);
+DROP TABLE crm_pipeline_entities;
+DROP FUNCTION clean_up_crm_pipeline();
diff --git a/crates/macro_db_client/migrations/20261007172434_crm_pipeline_entities.up.sql b/crates/macro_db_client/migrations/20261007172434_crm_pipeline_entities.up.sql
new file mode 100644
index 0000000000..7b110d343b
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261007172434_crm_pipeline_entities.up.sql
@@ -0,0 +1,25 @@
+-- CRM owns pipeline identity; reusable storage owns columns and cells.
+CREATE TABLE crm_pipeline_entities (
+ id UUID PRIMARY KEY,
+ team_id UUID NOT NULL REFERENCES team(id) ON DELETE CASCADE,
+ database_id UUID NOT NULL UNIQUE REFERENCES databases(id) ON DELETE RESTRICT,
+ name TEXT NOT NULL,
+ user_id TEXT NOT NULL REFERENCES "User"(id) ON DELETE CASCADE ON UPDATE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ trashed_at TIMESTAMPTZ,
+ table_id UUID NOT NULL UNIQUE REFERENCES database_tables(id) ON DELETE RESTRICT,
+ primary_column_id UUID NOT NULL UNIQUE REFERENCES database_columns(id) DEFERRABLE INITIALLY DEFERRED,
+ record_type TEXT NOT NULL CHECK (record_type IN ('company', 'contact'))
+);
+CREATE INDEX crm_pipeline_entities_team ON crm_pipeline_entities(team_id);
+
+CREATE FUNCTION clean_up_crm_pipeline() RETURNS TRIGGER LANGUAGE plpgsql AS $$
+BEGIN
+ DELETE FROM entity_access WHERE entity_id = OLD.id AND entity_type = 'crm_pipeline';
+ DELETE FROM database_changes WHERE database_id = OLD.database_id;
+ DELETE FROM databases WHERE id = OLD.database_id;
+ RETURN NULL;
+END $$;
+CREATE TRIGGER crm_pipeline_cleanup AFTER DELETE ON crm_pipeline_entities
+FOR EACH ROW EXECUTE FUNCTION clean_up_crm_pipeline();
diff --git a/crates/macro_db_client/migrations/20261007172435_copy_legacy_crm_sales.down.sql b/crates/macro_db_client/migrations/20261007172435_copy_legacy_crm_sales.down.sql
new file mode 100644
index 0000000000..9ab39437dd
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261007172435_copy_legacy_crm_sales.down.sql
@@ -0,0 +1,5 @@
+-- The copy may already contain user edits. Never delete it or allow the runner
+-- to forget completion and create duplicate Sales pipelines on the next deploy.
+DO $$ BEGIN
+ RAISE EXCEPTION 'The Sales data copy is forward-only; keep its migration record and pipeline data';
+END $$;
diff --git a/crates/macro_db_client/migrations/20261007172435_copy_legacy_crm_sales.up.sql b/crates/macro_db_client/migrations/20261007172435_copy_legacy_crm_sales.up.sql
new file mode 100644
index 0000000000..30adea9740
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261007172435_copy_legacy_crm_sales.up.sql
@@ -0,0 +1,149 @@
+-- A one-time snapshot. SQLx commits the copy and its migration record together.
+-- Keep legacy records/properties intact; subsequent pipeline edits are independent.
+SELECT pg_advisory_xact_lock(1413824845, 1);
+LOCK TABLE team, team_crm_settings, crm_companies, property_definitions,
+ property_options, entity_properties IN SHARE ROW EXCLUSIVE MODE;
+
+-- Migration-local UUIDv7 generation for PostgreSQL 16 (uuidv7() needs PG18).
+-- Runtime identities continue to be generated by the application.
+CREATE FUNCTION pg_temp.sales_uuid() RETURNS UUID LANGUAGE SQL VOLATILE AS $$
+ SELECT encode(set_byte(set_byte(bytes, 6, (get_byte(bytes, 6) & 15) | 112),
+ 8, (get_byte(bytes, 8) & 63) | 128), 'hex')::uuid
+ FROM (SELECT overlay(gen_random_bytes(16) placing
+ decode(lpad(to_hex((extract(epoch FROM clock_timestamp()) * 1000)::bigint), 12, '0'), 'hex')
+ FROM 1 FOR 6) AS bytes) random;
+$$;
+
+CREATE TEMP TABLE sales_teams ON COMMIT DROP AS
+SELECT t.id AS team_id, t.owner_id, s.legacy_stage_ids,
+ pg_temp.sales_uuid() AS pipeline_id, pg_temp.sales_uuid() AS database_id,
+ pg_temp.sales_uuid() AS table_id, d.id AS stage_definition
+FROM team t JOIN team_crm_settings s ON s.team_id = t.id AND s.crm_enabled
+LEFT JOIN property_definitions d ON d.team_id = t.id AND d.display_name = 'Deal Stage'
+WHERE EXISTS (SELECT 1 FROM crm_companies c WHERE c.team_id = t.id AND NOT c.hidden);
+ALTER TABLE sales_teams ADD PRIMARY KEY (team_id);
+
+DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM sales_teams t JOIN property_definitions d ON d.id = t.stage_definition
+ WHERE d.data_type <> 'SELECT_STRING' OR d.is_multi_select) THEN
+ RAISE EXCEPTION 'Sales migration requires a single-select Deal Stage definition';
+ END IF;
+END $$;
+
+CREATE TEMP TABLE sales_columns ON COMMIT DROP AS
+SELECT t.team_id, t.database_id, t.table_id, pg_temp.sales_uuid() AS column_id,
+ pg_temp.sales_uuid() AS definition_id, c.*
+FROM sales_teams t CROSS JOIN (VALUES
+ ('Company', 'ENTITY', 'COMPANY', '20', false),
+ ('Stage', 'SELECT_STRING', NULL, '40', true),
+ ('Owner', 'ENTITY', 'USER', '60', true),
+ ('Revenue', 'NUMBER', NULL, '80', true)
+) c(name, data_type, entity_type, position, nullable);
+
+CREATE TEMP TABLE sales_system_stages ON COMMIT DROP AS
+SELECT ('00000001-0000-0000-0010-' || lpad(n::text, 12, '0'))::uuid AS id, label, n - 1 AS position
+FROM (VALUES (1, 'Lead'), (2, 'Qualified'), (3, 'Demo'), (4, 'Trial'),
+ (5, 'Negotiation'), (6, 'Customer'), (7, 'Churned')) s(n, label);
+
+CREATE TEMP TABLE sales_options ON COMMIT DROP AS
+SELECT t.team_id, s.id AS source_id, pg_temp.sales_uuid() AS id, s.label, s.position::int
+FROM sales_teams t CROSS JOIN sales_system_stages s WHERE t.stage_definition IS NULL
+UNION ALL
+SELECT t.team_id, o.id, pg_temp.sales_uuid(), o.string_value,
+ (row_number() OVER (PARTITION BY t.team_id ORDER BY o.display_order, o.id) - 1)::int
+FROM sales_teams t JOIN property_options o ON o.property_definition_id = t.stage_definition;
+ALTER TABLE sales_options ALTER COLUMN label SET NOT NULL;
+
+CREATE TEMP TABLE sales_rows ON COMMIT DROP AS
+SELECT c.id AS company_id, t.team_id, t.table_id, t.owner_id, pg_temp.sales_uuid() AS row_id,
+ lpad(to_hex(row_number() OVER (PARTITION BY t.team_id ORDER BY c.id)), 16, '0') || '80' AS position,
+ direct.values AS stage, legacy.values AS legacy_stage, owner.values AS owner, revenue.values AS revenue
+FROM sales_teams t JOIN crm_companies c ON c.team_id = t.team_id AND NOT c.hidden
+LEFT JOIN entity_properties direct ON direct.entity_type = 'COMPANY' AND direct.entity_id = c.id::text
+ AND direct.property_definition_id = coalesce(t.stage_definition, '00000001-0000-0000-0000-000000000010'::uuid)
+LEFT JOIN entity_properties legacy ON legacy.entity_type = 'COMPANY' AND legacy.entity_id = c.id::text
+ AND legacy.property_definition_id = '00000001-0000-0000-0000-000000000010'
+LEFT JOIN entity_properties owner ON owner.entity_type = 'COMPANY' AND owner.entity_id = c.id::text
+ AND owner.property_definition_id = '00000001-0000-0000-0000-000000000011'
+LEFT JOIN entity_properties revenue ON revenue.entity_type = 'COMPANY' AND revenue.entity_id = c.id::text
+ AND revenue.property_definition_id = '00000001-0000-0000-0000-000000000012';
+
+-- Validate before copying so malformed legacy values cannot silently disappear.
+DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM sales_rows r CROSS JOIN LATERAL (VALUES (r.stage), (r.legacy_stage)) s(value)
+ WHERE value IS NOT NULL AND value <> 'null'::jsonb AND CASE
+ WHEN value ->> 'type' IS DISTINCT FROM 'SelectOption'
+ OR jsonb_typeof(value -> 'value') IS DISTINCT FROM 'array' THEN true
+ ELSE jsonb_array_length(value -> 'value') > 1
+ OR (jsonb_array_length(value -> 'value') = 1 AND jsonb_typeof(value -> 'value' -> 0) <> 'string') END) THEN
+ RAISE EXCEPTION 'Sales migration found an invalid single-select stage';
+ END IF;
+ IF EXISTS (SELECT 1 FROM sales_rows WHERE owner IS NOT NULL AND owner <> 'null'::jsonb AND CASE
+ WHEN owner ->> 'type' IS DISTINCT FROM 'EntityReference'
+ OR jsonb_typeof(owner -> 'value') IS DISTINCT FROM 'array' THEN true
+ ELSE jsonb_array_length(owner -> 'value') > 1 OR EXISTS (
+ SELECT 1 FROM jsonb_array_elements(owner -> 'value') ref
+ WHERE ref ->> 'entity_type' IS DISTINCT FROM 'USER'
+ OR coalesce(ref ->> 'entity_id', '') = '') END) THEN
+ RAISE EXCEPTION 'Sales migration found an invalid owner';
+ END IF;
+ IF EXISTS (SELECT 1 FROM sales_rows WHERE revenue IS NOT NULL AND revenue <> 'null'::jsonb
+ AND (revenue ->> 'type' IS DISTINCT FROM 'Number'
+ OR jsonb_typeof(revenue -> 'value') IS DISTINCT FROM 'number')) THEN
+ RAISE EXCEPTION 'Sales migration found invalid revenue';
+ END IF;
+END $$;
+
+ALTER TABLE sales_rows ADD COLUMN stage_option UUID;
+UPDATE sales_rows r SET stage_option = coalesce(
+ (SELECT o.id FROM sales_options o WHERE o.team_id = r.team_id AND o.source_id::text = r.stage -> 'value' ->> 0),
+ (SELECT o.id FROM sales_options o WHERE o.team_id = r.team_id
+ AND o.source_id::text = t.legacy_stage_ids ->> (r.legacy_stage -> 'value' ->> 0)),
+ (SELECT o.id FROM sales_options o JOIN sales_system_stages s ON lower(s.label) = lower(o.label)
+ WHERE o.team_id = r.team_id AND s.id::text = r.legacy_stage -> 'value' ->> 0
+ ORDER BY o.position LIMIT 1)
+) FROM sales_teams t WHERE t.team_id = r.team_id;
+DO $$ BEGIN
+ IF EXISTS (SELECT 1 FROM sales_rows WHERE stage_option IS NULL
+ AND (stage -> 'value' ->> 0 IS NOT NULL OR legacy_stage -> 'value' ->> 0 IS NOT NULL)) THEN
+ RAISE EXCEPTION 'Sales migration found an unmapped stage; repair the CRM stage mapping and retry';
+ END IF;
+END $$;
+
+INSERT INTO databases (id) SELECT database_id FROM sales_teams;
+INSERT INTO database_tables (id, database_id, name, position)
+SELECT table_id, database_id, 'Records', '80' FROM sales_teams;
+INSERT INTO property_definitions (id, database_id, display_name, data_type, is_multi_select, specific_entity_type)
+SELECT definition_id, database_id, name, data_type::property_data_type, false, entity_type::property_entity_type
+FROM sales_columns;
+INSERT INTO database_columns (id, table_id, property_definition_id, position, nullable)
+SELECT column_id, table_id, definition_id, position, nullable FROM sales_columns;
+INSERT INTO database_column_protections (column_id, capability)
+SELECT column_id, capability FROM sales_columns
+CROSS JOIN (VALUES ('delete'), ('change_type')) p(capability) WHERE name = 'Company';
+INSERT INTO property_options (id, property_definition_id, string_value, display_order, color)
+SELECT o.id, c.definition_id, o.label, o.position,
+ (ARRAY['#0091FF', '#46A758', '#8E4EC6', '#F76B15', '#E93D82', '#12A594',
+ '#FFB224', '#3E63DD', '#E5484D', '#F5D90A', '#889096', '#E54D2E'])[o.position % 12 + 1]
+FROM sales_options o JOIN sales_columns c ON c.team_id = o.team_id AND c.name = 'Stage';
+INSERT INTO crm_pipeline_entities (id, team_id, database_id, name, user_id, table_id, primary_column_id, record_type)
+SELECT t.pipeline_id, t.team_id, t.database_id, 'Sales', t.owner_id, t.table_id, c.column_id, 'company'
+FROM sales_teams t JOIN sales_columns c ON c.team_id = t.team_id AND c.name = 'Company';
+INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)
+SELECT pipeline_id, 'crm_pipeline', owner_id, 'user'::entity_access_source_type, 'owner'::"AccessLevel" FROM sales_teams
+UNION ALL
+SELECT pipeline_id, 'crm_pipeline', team_id::text, 'team', 'edit' FROM sales_teams;
+INSERT INTO database_rows (id, table_id, position, created_by)
+SELECT row_id, table_id, position, owner_id FROM sales_rows;
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+SELECT pg_temp.sales_uuid(), r.row_id::text, 'DATABASE_ROW', c.definition_id, v.value
+FROM sales_rows r JOIN sales_columns c ON c.team_id = r.team_id
+CROSS JOIN LATERAL (VALUES
+ ('Company', jsonb_build_object('type', 'EntityReference', 'value', jsonb_build_array(
+ jsonb_build_object('entity_type', 'COMPANY', 'entity_id', r.company_id::text, 'specific_message_id', NULL)))),
+ ('Stage', CASE WHEN r.stage_option IS NOT NULL THEN
+ jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array(r.stage_option)) END),
+ ('Owner', r.owner), ('Revenue', r.revenue)
+) v(name, value)
+WHERE c.name = v.name AND v.value IS NOT NULL AND v.value <> 'null'::jsonb;
+DROP FUNCTION pg_temp.sales_uuid();
diff --git a/crates/macro_db_client/src/item_access/delete.rs b/crates/macro_db_client/src/item_access/delete.rs
index 8fc528a134..8f99270968 100644
--- a/crates/macro_db_client/src/item_access/delete.rs
+++ b/crates/macro_db_client/src/item_access/delete.rs
@@ -73,6 +73,7 @@ pub async fn delete_user_entity_access_bulk(
| EntityType::Call
| EntityType::AgentSession
| EntityType::Initiative
+ | EntityType::CrmPipeline
| EntityType::Database
| EntityType::Form => {
sqlx::query!(
diff --git a/crates/macro_db_client/src/user/create_user.rs b/crates/macro_db_client/src/user/create_user.rs
index c32b5d6a8f..c449567bbf 100644
--- a/crates/macro_db_client/src/user/create_user.rs
+++ b/crates/macro_db_client/src/user/create_user.rs
@@ -2,7 +2,13 @@ use std::collections::HashSet;
use sqlx::{Pool, Postgres};
+#[cfg(test)]
+mod test;
+
/// Creates a new user in the database and attaches provided roles
+///
+/// `macro_user_customer_id` supplies the required legacy account key. Only an
+/// actual Stripe customer belongs in the optional profile billing field.
#[expect(clippy::too_many_arguments, reason = "too annoying to fix")]
#[tracing::instrument(skip(db))]
pub async fn create_user(
@@ -11,7 +17,8 @@ pub async fn create_user(
username: &str,
email: &str,
is_verified: bool,
- stripe_customer_id: &str,
+ macro_user_customer_id: &str,
+ stripe_customer_id: Option<&str>,
organization_id: Option<i32>,
roles: HashSet<String>,
) -> anyhow::Result<String> {
@@ -28,7 +35,7 @@ pub async fn create_user(
"#,
&id,
username,
- stripe_customer_id,
+ macro_user_customer_id,
email,
false // has_trialed
)
diff --git a/crates/macro_db_client/src/user/create_user/test.rs b/crates/macro_db_client/src/user/create_user/test.rs
new file mode 100644
index 0000000000..2fbe83d325
--- /dev/null
+++ b/crates/macro_db_client/src/user/create_user/test.rs
@@ -0,0 +1,53 @@
+use super::*;
+use crate::user::get::get_user_id_and_stripe_customer_id_by_email;
+
+#[sqlx::test]
+async fn a_local_placeholder_does_not_become_a_billing_customer(pool: sqlx::PgPool) {
+ let email = "[email protected]";
+ let user_id = create_user(
+ &pool,
+ &uuid::Uuid::new_v4().to_string(),
+ email,
+ email,
+ true,
+ None,
+ None,
+ HashSet::new(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ get_user_id_and_stripe_customer_id_by_email(&pool, email)
+ .await
+ .unwrap(),
+ (user_id, None)
+ );
+}
+
+#[sqlx::test]
+async fn a_real_stripe_customer_remains_available_for_billing(pool: sqlx::PgPool) {
+ let email = "[email protected]";
+ let customer_id = "cus_signup_test";
+ let user_id = create_user(
+ &pool,
+ &uuid::Uuid::new_v4().to_string(),
+ email,
+ email,
+ true,
+ customer_id,
+ Some(customer_id),
+ None,
+ HashSet::new(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ get_user_id_and_stripe_customer_id_by_email(&pool, email)
+ .await
+ .unwrap(),
+ (user_id, Some(customer_id.to_owned()))
+ );
+}
diff --git a/crates/model-entity/src/lib.rs b/crates/model-entity/src/lib.rs
index d1ac2216d2..033001ba47 100644
--- a/crates/model-entity/src/lib.rs
+++ b/crates/model-entity/src/lib.rs
@@ -60,6 +60,8 @@ pub enum EntityType {
CrmCompany,
/// The entity is a CRM contact tracked by a team
CrmContact,
+ /// A customizable company or contact pipeline with its own grants.
+ CrmPipeline,
/// The entity is a reminder set by a user
Reminder,
/// The entity is an AI skill: either a skill document or a built-in
@@ -106,6 +108,7 @@ impl EntityType {
// — they aren't rows in the `entity_access` table.
EntityType::CrmCompany => false,
EntityType::CrmContact => false,
+ EntityType::CrmPipeline => false,
// A reminder is private to the user who set it. Access resolves
// from its owner column, not from a row in the `entity_access`
// table — the same shape as channels and CRM entities.
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index 69f2a2b2f9..7a4d3c7cfd 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -54,6 +54,7 @@ pub fn storage_entity_type(entity_type: AccessEntityType) -> Option<EntityType>
AccessEntityType::DatabaseRow => Some(EntityType::DatabaseRow),
AccessEntityType::User => Some(EntityType::User),
AccessEntityType::ChannelMessage
+ | AccessEntityType::CrmPipeline
| AccessEntityType::Database
| AccessEntityType::Form
| AccessEntityType::Team
diff --git a/docs/AGENT_GUIDE/databases.md b/docs/AGENT_GUIDE/databases.md
index 50fb9ddf9d..f1cf4d13f2 100644
--- a/docs/AGENT_GUIDE/databases.md
+++ b/docs/AGENT_GUIDE/databases.md
@@ -56,6 +56,38 @@ PostHog unless the variable was set when it was built. With the flag off:
`showDatabaseSql` (`VITE_SHOW_DATABASE_SQL`) is separate and only hides SQL.
+## CRM pipelines
+
+Pipelines are created from the CRM sidebar's **New pipeline** action. Their
+records are read and edited through the pipeline's access; they are not standalone
+database app entities and do not appear in the Databases list. Use **Share → Team access**
+in the CRM to switch between **None** (private) and **Edit** (team). A pipeline's primary
+company/contact reference is required. The same company or contact can appear
+in multiple independent rows, including through the row menu's **Duplicate** action.
+The reference column and table are protected against removal or type changes. See
+[Customers (CRM)](surfaces.md#customers-crm--appcomponentcompanies) for the flow.
+
+Teams migrated from the legacy CRM have a team-shared **Sales** pipeline with
+their visible companies and copied Stage, Owner and Revenue values, including
+closed and unstaged companies. Hidden companies are excluded. The migration is
+a one-time copy: later edits to a company’s legacy properties do not synchronize
+with its pipeline row. The pipeline can be renamed, customized or trashed normally.
+
+Pipeline primary columns use the shared database column protections: their header
+must disable deletion and type changes. Renaming and reordering remain allowed.
+The primary column is non-nullable: inserting a row without its record, clearing
+its cell, or choosing an empty list fails without saving any of the batch.
+Company pipelines accept one company; contact pipelines accept one contact.
+The referenced record can belong to another team if the editor can access it;
+pipeline sharing does not grant access to the referenced record's details.
+
+Pipelines use the shared database editor. Verify that column-menu sorting orders
+all records, including records beyond the first page, and that opening a record
+keeps it available when a view filter excludes it. Cell edits and **Add column**
+use pipeline authorization. Viewer grants hide editing controls. The CRM editor
+fixture (`features/crm/browser-test/editor.html`) covers the real pipeline API
+adapter and shared provider against local test responses.
+
## Properties and records
An embedded records editor can allow cell edits while its host controls the
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 1e565fe3f6..ca5030d0f2 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1857,6 +1857,34 @@ editors without changing hosted data.
At narrow widths, `Show CRM navigation` opens the same navigation in a menu.
The sidebar's Views and Lists sections can also collapse independently.
+**Pipelines** in the CRM sidebar hold company or contact entries in the shared
+records editor. They have their own identity, ownership and sharing; their
+storage does not appear as a separate database in navigation.
+**New pipeline** is disabled until the team's CRM is enabled. For a new team,
+use **Open CRM settings** in the empty state to enable CRM, then return to
+Customers to create a pipeline. Verify this with a newly created team as well as
+an existing CRM-enabled team.
+Choose **New pipeline**, enter a name, choose **Companies** or **Contacts**, and
+choose **Just me** (the default) or **My team**. Creating opens the pipeline's
+editable table. Team members can edit shared pipelines; the creator owns them
+and can change access later through the standard **Share** dialog. Under
+**Team access**, choose **Edit** to share with the team or **None** to make the
+pipeline private. **Copy Link** copies a CRM link that opens this pipeline for
+anyone who has access. On mobile, team access is in the **Team** tab.
+
+The first column is a required company/contact reference. The same company or
+contact can occur in multiple rows in a pipeline and can also belong to other
+pipelines. Each row has its own field values; **Duplicate** copies a row into a new
+entry referencing the same company or contact. The reference column
+can be renamed but cannot be removed or changed to another type. Stage, Owner,
+and Revenue are independent pipeline fields; editing them does not modify the
+company's CRM fields. Use **Add column** or a column header's menu to customize
+columns. Pipeline Stage options initially copy the team's current deal stages. Open
+pipelines refresh other editors' changes periodically; a local edit refreshes
+immediately after saving.
+**Trash pipeline** removes its table from navigation without deleting the linked
+companies or contacts. **Back to companies** returns to the main CRM views.
+
CRM lists are currently disabled by `enableCrmLists` (default `false`). The sidebar
Lists section, list editor, and company membership controls only mount when enabled.
Existing list data is preserved; a restored list view returns to All companies while
@@ -2090,6 +2118,9 @@ Free-team joins do not create a paid subscription, bill a seat, or grant premium
roles. Teams with an existing paid subscription retain their per-seat billing;
enterprise teams retain their billing bypass.
+On a local stack started with `--no-doppler`, verify free-team creation from a
+fresh passwordless signup. It must work without Stripe credentials.
+
Under **Team**, owners/admins can turn **Auto-join on domain** off and can restrict
invitations to admins with **Members can invite**. These controls still apply.
To verify the membership flow, use a local free team with five members: invite
diff --git a/docs/RUNNING_LOCALLY.md b/docs/RUNNING_LOCALLY.md
index a1ab0c2f99..ece69fb015 100644
--- a/docs/RUNNING_LOCALLY.md
+++ b/docs/RUNNING_LOCALLY.md
@@ -109,6 +109,10 @@ just run_local --no-doppler
The local stack does not need Doppler. It uses the code-defined local configuration with dummy AWS credentials and fixed test secrets. Most contributors are not on the team, so this is the common path.
+Local authentication includes a working signing key pair for Macro API tokens,
+which settings actions such as enabling CRM require. New teams start with CRM
+disabled; enable it in Settings > CRM before creating pipelines.
+
The stack boots with stubbed values for every config the services require, including the third-party integrations (Google, GitHub, Stripe, CloudFront). Those flows do not work against real services with the stubs. The rest of the stack is fully functional: auth, documents, email, and search.
To use a real integration locally, supply its keys via `--env-file` — see [Integration Secrets](#integration-secrets) below.
@@ -215,7 +219,7 @@ A `--no-doppler` stack boots with deterministic stubs for every value the servic
| --- | --- | --- |
| Google login / Gmail | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET_KEY` | Google SSO and Gmail inbox linking are unavailable. Local signup still works. The email service reports no Gmail grant and skips inbox syncing. |
| GitHub login | `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_IDP_ID` | Login with GitHub is unavailable |
-| Stripe billing | `STRIPE_SECRET_KEY`, `STRIPE_PRICE_ID` | Checkout and subscription endpoints fail. Signup still works: the create-user webhook detects the stub key and skips the real Stripe call. It stores a placeholder customer id instead. |
+| Stripe billing | `STRIPE_SECRET_KEY`, `STRIPE_PRICE_ID` | Checkout and subscription endpoints fail. Signup skips Stripe and leaves profile billing unset, so free-team creation works. Only the required legacy account field stores a local placeholder. |
| CloudFront signed URLs | `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY` | Document download URLs are unsigned (fine against local S3) |
The other stubbed keys (`REDIS_HOST`, `MACRO_DB_URL`, `INTERNAL_API_KEY`, `AUTHENTICATION_SERVICE_SECRET_KEY`, `ACCOUNT_LINK_STATE_SECRET`, `OPENSEARCH_USERNAME`, `OPENSEARCH_PASSWORD`) are internal plumbing with correct local values — you never need to override them.
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index ce223c3a4b..6445845c2b 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -538,7 +538,7 @@ export type Entity = {
/**
* The type of an entity in Macro
*/
-export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
/**
* Error response body.
diff --git a/packages/sdk/generated/connection/types.gen.ts b/packages/sdk/generated/connection/types.gen.ts
index 0bc80ac332..07a622fb4d 100644
--- a/packages/sdk/generated/connection/types.gen.ts
+++ b/packages/sdk/generated/connection/types.gen.ts
@@ -40,7 +40,7 @@ export type Entity = {
/**
* The type of an entity in Macro
*/
-export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
export type GenericErrorResponse = {
/**
diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.ts
index 38930d51c1..5437733a4a 100644
--- a/packages/sdk/generated/notification/types.gen.ts
+++ b/packages/sdk/generated/notification/types.gen.ts
@@ -532,7 +532,7 @@ export type Entity = {
/**
* The type of an entity in Macro
*/
-export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+export type EntityType = 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
/**
* A plain old json error response for use with axum.
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index d2fba1172e..4f4336ccf8 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DataType, DateOperator, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessiblePipeline, AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DataType, DateOperator, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityRef, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmPipelineData, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.ts
index 4db7be13d2..8f2b702e4a 100644
--- a/packages/sdk/generated/storage/sdk.gen.ts
+++ b/packages/sdk/generated/storage/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, ServerSentEventsResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';
+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CollaborateFormData, CollaborateFormErrors, CollaborateFormResponses, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponses, ConvertDatabaseColumnData, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseErrors, CreateDatabaseResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateFormData, CreateFormErrors, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditMyFormResponseData, EditMyFormResponseErrors, EditMyFormResponseResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetBotOwnerProfilesData, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmPipelineData, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsErrors, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryErrors, GetDatabaseQueryResponses, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupErrors, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetFormData, GetFormErrors, GetFormPermissionsData, GetFormPermissionsErrors, GetFormPermissionsResponses, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryErrors, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyErrors, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMyFormResponseData, GetMyFormResponseErrors, GetMyFormResponseResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, ImportDatabaseTableData, ImportDatabaseTableErrors, ImportDatabaseTableResponses, InferDatabaseColumnTypeData, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAccessibleFormsData, ListAccessibleFormsErrors, ListAccessibleFormsResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesErrors, ListDatabasesResponses, ListEmailRemindersData, ListEmailRemindersErrors, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListFormsData, ListFormsErrors, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MeetingCancelData, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationErrors, MeetingCancelPreparationResponses, MeetingCancelResponses, MeetingCreateData, MeetingCreateErrors, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinErrors, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteErrors, MeetingInvitePermissionsData, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponses, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersErrors, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinErrors, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveErrors, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveErrors, MeetingListActiveResponses, MeetingListData, MeetingListErrors, MeetingListResponses, MeetingLookupData, MeetingLookupErrors, MeetingLookupResponses, MeetingParticipantsData, MeetingParticipantsErrors, MeetingParticipantsResponses, MeetingPrepareData, MeetingPrepareErrors, MeetingPrepareResponses, MeetingShareData, MeetingShareErrors, MeetingShareResponses, MeetingUpdateData, MeetingUpdateErrors, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutErrors, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, RenameCrmPipelineData, RenameCrmPipelineResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDatabaseQueryData, SaveDatabaseQueryErrors, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SearchContactsData, SearchContactsErrors, SearchContactsResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupErrors, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, ShareCrmPipelineData, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, SubmitFormResponseData, SubmitFormResponseErrors, SubmitFormResponseResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationErrors, TranscribeDictationResponses, TrashCrmPipelineData, TrashCrmPipelineResponses, UndoDatabaseChangeData, UndoDatabaseChangeErrors, UndoDatabaseChangeResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateDatabasePermissionsData, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponses, UpdateFormData, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsErrors, UpdateFormPermissionsResponses, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -1066,6 +1066,118 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * List the caller's live pipelines in their CRM.
+ */
+ public listCrmPipelines<ThrowOnError extends boolean = false>(options?: Options<ListCrmPipelinesData, ThrowOnError>): RequestResult<ListCrmPipelinesResponses, unknown, ThrowOnError> {
+ return (options?.client ?? this.client).get<ListCrmPipelinesResponses, unknown, ThrowOnError>({ url: '/crm/pipelines', ...options });
+ }
+
+ /**
+ * Create a private or team-shared pipeline.
+ */
+ public createCrmPipeline<ThrowOnError extends boolean = false>(options: Options<CreateCrmPipelineData, ThrowOnError>): RequestResult<CreateCrmPipelineResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).post<CreateCrmPipelineResponses, unknown, ThrowOnError>({
+ url: '/crm/pipelines',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Read one pipeline by its entity identity.
+ */
+ public getCrmPipeline<ThrowOnError extends boolean = false>(options: Options<GetCrmPipelineData, ThrowOnError>): RequestResult<GetCrmPipelineResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).get<GetCrmPipelineResponses, unknown, ThrowOnError>({ url: '/crm/pipelines/{id}', ...options });
+ }
+
+ /**
+ * Rename a pipeline.
+ */
+ public renameCrmPipeline<ThrowOnError extends boolean = false>(options: Options<RenameCrmPipelineData, ThrowOnError>): RequestResult<RenameCrmPipelineResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).put<RenameCrmPipelineResponses, unknown, ThrowOnError>({
+ url: '/crm/pipelines/{id}/name',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Edit pipeline schema or records with the common typed operations.
+ */
+ public applyCrmPipelineOps<ThrowOnError extends boolean = false>(options: Options<ApplyCrmPipelineOpsData, ThrowOnError>): RequestResult<ApplyCrmPipelineOpsResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).post<ApplyCrmPipelineOpsResponses, unknown, ThrowOnError>({
+ url: '/crm/pipelines/{id}/ops',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Read pipeline records through pipeline access.
+ */
+ public getCrmPipelineRows<ThrowOnError extends boolean = false>(options: Options<GetCrmPipelineRowsData, ThrowOnError>): RequestResult<GetCrmPipelineRowsResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).get<GetCrmPipelineRowsResponses, unknown, ThrowOnError>({ url: '/crm/pipelines/{id}/rows', ...options });
+ }
+
+ /**
+ * Query rows through pipeline access using the shared view protocol.
+ */
+ public queryCrmPipelineRows<ThrowOnError extends boolean = false>(options: Options<QueryCrmPipelineRowsData, ThrowOnError>): RequestResult<QueryCrmPipelineRowsResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).post<QueryCrmPipelineRowsResponses, unknown, ThrowOnError>({
+ url: '/crm/pipelines/{id}/rows',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Update sharing.
+ */
+ public shareCrmPipeline<ThrowOnError extends boolean = false>(options: Options<ShareCrmPipelineData, ThrowOnError>): RequestResult<ShareCrmPipelineResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).put<ShareCrmPipelineResponses, unknown, ThrowOnError>({
+ url: '/crm/pipelines/{id}/sharing',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Read the host-owned table schema.
+ */
+ public getCrmPipelineTable<ThrowOnError extends boolean = false>(options: Options<GetCrmPipelineTableData, ThrowOnError>): RequestResult<GetCrmPipelineTableResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).get<GetCrmPipelineTableResponses, unknown, ThrowOnError>({ url: '/crm/pipelines/{id}/table', ...options });
+ }
+
+ /**
+ * Trash or restore a pipeline.
+ */
+ public trashCrmPipeline<ThrowOnError extends boolean = false>(options: Options<TrashCrmPipelineData, ThrowOnError>): RequestResult<TrashCrmPipelineResponses, unknown, ThrowOnError> {
+ return (options.client ?? this.client).put<TrashCrmPipelineResponses, unknown, ThrowOnError>({
+ url: '/crm/pipelines/{id}/trash',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Read the caller's team CRM configuration. Any team member may read;
* teams without a settings row get the defaults.
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 55291f52be..703301ac6b 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -9,6 +9,16 @@ export type ClientOptions = {
*/
export type AccessLevel = 'view' | 'comment' | 'edit' | 'owner';
+/**
+ * Metadata together with the caller's effective grant.
+ */
+export type AccessiblePipeline = Pipeline & {
+ /**
+ * Highest effective access.
+ */
+ grant: AccessLevel;
+};
+
/**
* A currently active call, as returned by the batch active-calls listing.
*/
@@ -82,7 +92,7 @@ export type AddFavoriteRequest = {
/**
* The type of the entity to favorite.
*/
- entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+ entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
};
/**
@@ -869,6 +879,21 @@ export type ApiParticipantRole = 'owner' | 'admin' | 'member';
*/
export type ApiPropertyEntityType = 'CHANNEL' | 'CHAT' | 'COMPANY' | 'DOCUMENT' | 'PROJECT' | 'TASK' | 'THREAD' | 'USER';
+/**
+ * What a committed batch answers: a result per op, and the journal's change
+ * for each table version it produced.
+ */
+export type AppliedOps = {
+ /**
+ * The journal's changes.
+ */
+ changes: Array<CommittedChange>;
+ /**
+ * One result per op, in order.
+ */
+ results: Array<OpResult>;
+};
+
/**
* A batch of ops for one database, applied in order, in one transaction,
* together or not at all.
@@ -2856,7 +2881,7 @@ export type CollabSurfaceResponse = {
/**
* Type of the parent entity.
*/
- parentEntityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+ parentEntityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
/**
* Lifecycle state (`ready` for every surface visible via the API).
*/
@@ -4002,6 +4027,24 @@ export type CreatePairingRequest = {
scope?: null | RequestedHarnessScope;
};
+/**
+ * Request to create an empty pipeline with the standard CRM columns.
+ */
+export type CreatePipeline = {
+ /**
+ * Pipeline name.
+ */
+ name: string;
+ /**
+ * Company or contact entries.
+ */
+ recordType: PipelineRecordType;
+ /**
+ * Defaults to private.
+ */
+ sharing?: PipelineSharing;
+};
+
export type CreateProjectRequest = {
/**
* The name of the project.
@@ -5741,7 +5784,7 @@ export type EnsureCollabSurfaceRequest = {
/**
* Type of the parent entity access derives from.
*/
- parentEntityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+ parentEntityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
};
/**
@@ -6047,7 +6090,7 @@ export type Favorite = {
/**
* The type of the favorited entity.
*/
- entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+ entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
/**
* File type of the favorited document, when applicable.
*/
@@ -6069,7 +6112,7 @@ export type FavoriteEntityRef = {
/**
* The type of the favorited entity.
*/
- entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+ entityType: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
};
/**
@@ -9267,6 +9310,23 @@ export type NotificationState = 'unseen' | 'seen' | 'done';
*/
export type NumberOperator = 'is' | 'isNot' | 'greaterThan' | 'greaterThanOrEqual' | 'lessThan' | 'lessThanOrEqual';
+/**
+ * A batch of ops for one database and the versions its tables must be at.
+ */
+export type OpBatch = {
+ /**
+ * The version each named table must still be at; the batch is refused
+ * as a conflict if one moved. Without one, ops are last-write-wins.
+ */
+ baseVersions?: {
+ [key: string]: TableVersion;
+ };
+ /**
+ * The ops, in the order they apply.
+ */
+ ops: Array<DatabaseOp>;
+};
+
/**
* Why an op of a batch was refused. Nothing in the batch was written.
*/
@@ -9641,6 +9701,66 @@ export type PinnedItem = {
pinIndex: number;
};
+/**
+ * Pipeline metadata; table schema and data are read through the database service.
+ */
+export type Pipeline = {
+ /**
+ * Creation time.
+ */
+ createdAt: string;
+ /**
+ * Dedicated backing database.
+ */
+ databaseId: string;
+ /**
+ * Entity identity, used with `CrmPipeline` access receipts.
+ */
+ id: string;
+ /**
+ * Pipeline display name.
+ */
+ name: string;
+ /**
+ * Protected primary column.
+ */
+ primaryColumnId: string;
+ /**
+ * Kind of the primary reference.
+ */
+ recordType: PipelineRecordType;
+ /**
+ * Whether the pipeline has a team grant.
+ */
+ sharing: PipelineSharing;
+ /**
+ * Table of entries.
+ */
+ tableId: string;
+ /**
+ * Team owning the pipeline; references retain their own access controls.
+ */
+ teamId: string;
+ /**
+ * Trashed pipelines are omitted from navigation.
+ */
+ trashedAt: string | null;
+ /**
+ * Owning user; sharing never changes ownership.
+ */
+ userId: string;
+};
+
+/**
+ * Which CRM entity each row references. Fixed when a pipeline is created.
+ */
+export type PipelineRecordType = 'company' | 'contact';
+
+/**
+ * Initial sharing, or the desired team grant. Individual ownership is preserved.
+ */
+export type PipelineSharing = 'private' | 'team';
+
/**
* Request body for `POST /channels/activity`.
*/
@@ -10176,6 +10296,16 @@ export type RenameChannelLabelRequest = {
rule?: null | ChannelLabelRule;
};
+/**
+ * Rename input.
+ */
+export type RenamePipeline = {
+ /**
+ * New display name.
+ */
+ name: string;
+};
+
/**
* Request body for reordering favorites.
*/
@@ -10397,6 +10527,11 @@ export type RowHistoryResponse = {
changes: Array<RowHistoryEntry>;
};
+/**
+ * Identifier of a row.
+ */
+export type RowId = string;
+
/**
* A write to a table's rows.
*/
@@ -10877,6 +11012,16 @@ export type SharePermissionV2 = {
teamShareAccessLevel?: null | AccessLevel;
};
+/**
+ * Sharing input.
+ */
+export type SharePipeline = {
+ /**
+ * Desired team grant.
+ */
+ sharing: PipelineSharing;
+};
+
/**
* Controls whether shared email threads are included in results.
*/
@@ -12403,6 +12548,52 @@ export type StarterDocumentsResponse = {
how_to_guide_id: string;
};
+/**
+ * One storage row, with cells keyed by column placement.
+ */
+export type StorageRow = {
+ /**
+ * Populated cells.
+ */
+ cells: {
+ [key: string]: PropertyValue;
+ };
+ /**
+ * Row identity, independent of any referenced entity.
+ */
+ rowId: RowId;
+};
+
+/**
+ * A bounded page of rows at a table version.
+ */
+export type StorageRows = {
+ next?: null | RowId;
+ /**
+ * Rows in the requested view's order.
+ */
+ rows: Array<StorageRow>;
+ /**
+ * Table version when the read began.
+ */
+ version: TableVersion;
+};
+
+/**
+ * A query over one authorized storage table.
+ */
+export type StorageRowsQuery = {
+ after?: null | RowId;
+ /**
+ * The common database filter and sort semantics.
+ */
+ query?: ViewQuery;
+ /**
+ * Read these retained rows regardless of the active filter.
+ */
+ rowIds?: Array<RowId> | null;
+};
+
/**
* A GitHub pull request as Macro stores it, read through one of the caller's records.
*/
@@ -13098,6 +13289,16 @@ export type TranscriptSegmentRequest = {
streamStartedAt?: string | null;
};
+/**
+ * Trash/restore input.
+ */
+export type TrashPipeline = {
+ /**
+ * True to trash; false to restore.
+ */
+ trashed: boolean;
+};
+
/**
* The runtime answered a turn. Another prompt may follow at once; see
* [`SessionSettledMetadata`] for "nothing left to do".
@@ -16506,6 +16707,157 @@ export type SetCrmContactNameResponses = {
export type SetCrmContactNameResponse = SetCrmContactNameResponses[keyof SetCrmContactNameResponses];
+export type ListCrmPipelinesData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/crm/pipelines';
+};
+
+export type ListCrmPipelinesResponses = {
+ 200: Array<AccessiblePipeline>;
+};
+
+export type ListCrmPipelinesResponse = ListCrmPipelinesResponses[keyof ListCrmPipelinesResponses];
+
+export type CreateCrmPipelineData = {
+ body: CreatePipeline;
+ path?: never;
+ query?: never;
+ url: '/crm/pipelines';
+};
+
+export type CreateCrmPipelineResponses = {
+ 200: AccessiblePipeline;
+};
+
+export type CreateCrmPipelineResponse = CreateCrmPipelineResponses[keyof CreateCrmPipelineResponses];
+
+export type GetCrmPipelineData = {
+ body?: never;
+ path: {
+ id: string;
+ };
+ query?: never;
+ url: '/crm/pipelines/{id}';
+};
+
+export type GetCrmPipelineResponses = {
+ 200: AccessiblePipeline;
+};
+
+export type GetCrmPipelineResponse = GetCrmPipelineResponses[keyof GetCrmPipelineResponses];
+
+export type RenameCrmPipelineData = {
+ body: RenamePipeline;
+ path: {
+ id: string;
+ };
+ query?: never;
+ url: '/crm/pipelines/{id}/name';
+};
+
+export type RenameCrmPipelineResponses = {
+ 204: void;
+};
+
+export type RenameCrmPipelineResponse = RenameCrmPipelineResponses[keyof RenameCrmPipelineResponses];
+
+export type ApplyCrmPipelineOpsData = {
+ body: OpBatch;
+ path: {
+ id: string;
+ };
+ query?: never;
+ url: '/crm/pipelines/{id}/ops';
+};
+
+export type ApplyCrmPipelineOpsResponses = {
+ 200: AppliedOps;
+};
+
+export type ApplyCrmPipelineOpsResponse = ApplyCrmPipelineOpsResponses[keyof ApplyCrmPipelineOpsResponses];
+
+export type GetCrmPipelineRowsData = {
+ body?: never;
+ path: {
+ id: string;
+ };
+ query?: {
+ /**
+ * Continue after this row identity.
+ */
+ after?: string | null;
+ };
+ url: '/crm/pipelines/{id}/rows';
+};
+
+export type GetCrmPipelineRowsResponses = {
+ 200: StorageRows;
+};
+
+export type GetCrmPipelineRowsResponse = GetCrmPipelineRowsResponses[keyof GetCrmPipelineRowsResponses];
+
+export type QueryCrmPipelineRowsData = {
+ body: StorageRowsQuery;
+ path: {
+ id: string;
+ };
+ query?: never;
+ url: '/crm/pipelines/{id}/rows';
+};
+
+export type QueryCrmPipelineRowsResponses = {
+ 200: StorageRows;
+};
+
+export type QueryCrmPipelineRowsResponse = QueryCrmPipelineRowsResponses[keyof QueryCrmPipelineRowsResponses];
+
+export type ShareCrmPipelineData = {
+ body: SharePipeline;
+ path: {
+ id: string;
+ };
+ query?: never;
+ url: '/crm/pipelines/{id}/sharing';
+};
+
+export type ShareCrmPipelineResponses = {
+ 204: void;
+};
+
+export type ShareCrmPipelineResponse = ShareCrmPipelineResponses[keyof ShareCrmPipelineResponses];
+
+export type GetCrmPipelineTableData = {
+ body?: never;
+ path: {
+ id: string;
+ };
+ query?: never;
+ url: '/crm/pipelines/{id}/table';
+};
+
+export type GetCrmPipelineTableResponses = {
+ 200: TableDetail;
+};
+
+export type GetCrmPipelineTableResponse = GetCrmPipelineTableResponses[keyof GetCrmPipelineTableResponses];
+
+export type TrashCrmPipelineData = {
+ body: TrashPipeline;
+ path: {
+ id: string;
+ };
+ query?: never;
+ url: '/crm/pipelines/{id}/trash';
+};
+
+export type TrashCrmPipelineResponses = {
+ 204: void;
+};
+
+export type TrashCrmPipelineResponse = TrashCrmPipelineResponses[keyof TrashCrmPipelineResponses];
+
export type GetCrmTeamSettingsData = {
body?: never;
path?: never;
@@ -18267,7 +18619,7 @@ export type ListFavoritesData = {
/**
* Restrict to favorites whose entity is one of these types.
*/
- entityType?: Array<'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form'>;
+ entityType?: Array<'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form'>;
/**
* Restrict to favorites whose entity is one of these ids.
*/
@@ -18336,7 +18688,7 @@ export type RemoveFavoriteByEntityData = {
/**
* The type of an entity in Macro
*/
- entity_type: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
+ entity_type: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'crm_pipeline' | 'reminder' | 'skill' | 'agent_session' | 'scheduled_action' | 'initiative' | 'database' | 'database_row' | 'form';
/**
* The id of the favorited entity.
*/
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index 450f6e65e9..cb22dea994 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -3152,6 +3152,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
diff --git a/packages/sdk/specs/connection.json b/packages/sdk/specs/connection.json
index 2468b35a51..190bdb67eb 100644
--- a/packages/sdk/specs/connection.json
+++ b/packages/sdk/specs/connection.json
@@ -259,6 +259,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.json
index 839870ca93..e1f34e9b3d 100644
--- a/packages/sdk/specs/notification.json
+++ b/packages/sdk/specs/notification.json
@@ -1758,6 +1758,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 6b7343de18..d2ddc4e017 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -6017,6 +6017,332 @@
}
}
},
+ "/crm/pipelines": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "List the caller's live pipelines in their CRM.",
+ "operationId": "list_crm_pipelines",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/AccessiblePipeline"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Create a private or team-shared pipeline.",
+ "operationId": "create_crm_pipeline",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreatePipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AccessiblePipeline"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Read one pipeline by its entity identity.",
+ "operationId": "get_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AccessiblePipeline"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/name": {
+ "put": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Rename a pipeline.",
+ "operationId": "rename_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RenamePipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/ops": {
+ "post": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Edit pipeline schema or records with the common typed operations.",
+ "operationId": "apply_crm_pipeline_ops",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/OpBatch"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AppliedOps"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/rows": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Read pipeline records through pipeline access.",
+ "operationId": "get_crm_pipeline_rows",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "after",
+ "in": "query",
+ "description": "Continue after this row identity.",
+ "required": false,
+ "schema": {
+ "type": ["string", "null"],
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StorageRows"
+ }
+ }
+ }
+ }
+ }
+ },
+ "post": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Query rows through pipeline access using the shared view protocol.",
+ "operationId": "query_crm_pipeline_rows",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StorageRowsQuery"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/StorageRows"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/sharing": {
+ "put": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Update sharing.",
+ "operationId": "share_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SharePipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/table": {
+ "get": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Read the host-owned table schema.",
+ "operationId": "get_crm_pipeline_table",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TableDetail"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/crm/pipelines/{id}/trash": {
+ "put": {
+ "tags": ["crm::inbound::pipelines"],
+ "summary": "Trash or restore a pipeline.",
+ "operationId": "trash_crm_pipeline",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TrashPipeline"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ }
+ }
+ }
+ },
"/crm/settings": {
"get": {
"tags": ["crm::inbound::axum_router::team_settings"],
@@ -10231,6 +10557,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -10449,6 +10776,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -16903,6 +17231,25 @@
"description": "Ordered from least to most access top -> bottom",
"enum": ["view", "comment", "edit", "owner"]
},
+ "AccessiblePipeline": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Pipeline",
+ "description": "Pipeline metadata."
+ },
+ {
+ "type": "object",
+ "required": ["grant"],
+ "properties": {
+ "grant": {
+ "$ref": "#/components/schemas/AccessLevel",
+ "description": "Highest effective access."
+ }
+ }
+ }
+ ],
+ "description": "Metadata together with the caller's effective grant."
+ },
"ActiveCallSummary": {
"type": "object",
"description": "A currently active call, as returned by the batch active-calls listing.",
@@ -17021,6 +17368,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -18222,6 +18570,27 @@
"USER"
]
},
+ "AppliedOps": {
+ "type": "object",
+ "description": "What a committed batch answers: a result per op, and the journal's change\nfor each table version it produced.",
+ "required": ["results", "changes"],
+ "properties": {
+ "changes": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CommittedChange"
+ },
+ "description": "The journal's changes."
+ },
+ "results": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/OpResult"
+ },
+ "description": "One result per op, in order."
+ }
+ }
+ },
"ApplyOpsRequest": {
"type": "object",
"description": "A batch of ops for one database, applied in order, in one transaction,\ntogether or not at all.",
@@ -21014,6 +21383,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -22737,6 +23107,26 @@
}
}
},
+ "CreatePipeline": {
+ "type": "object",
+ "description": "Request to create an empty pipeline with the standard CRM columns.",
+ "required": ["name", "recordType"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Pipeline name."
+ },
+ "recordType": {
+ "$ref": "#/components/schemas/PipelineRecordType",
+ "description": "Company or contact entries."
+ },
+ "sharing": {
+ "$ref": "#/components/schemas/PipelineSharing",
+ "description": "Defaults to private."
+ }
+ },
+ "additionalProperties": false
+ },
"CreateProjectRequest": {
"type": "object",
"required": ["name"],
@@ -25389,6 +25779,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -25845,6 +26236,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -25898,6 +26290,7 @@
"static_file",
"crm_company",
"crm_contact",
+ "crm_pipeline",
"reminder",
"skill",
"agent_session",
@@ -31220,6 +31613,30 @@
"lessThanOrEqual"
]
},
+ "OpBatch": {
+ "type": "object",
+ "description": "A batch of ops for one database and the versions its tables must be at.",
+ "required": ["ops"],
+ "properties": {
+ "baseVersions": {
+ "type": "object",
+ "description": "The version each named table must still be at; the batch is refused\nas a conflict if one moved. Without one, ops are last-write-wins.",
+ "additionalProperties": {
+ "$ref": "#/components/schemas/TableVersion"
+ },
+ "propertyNames": {
+ "type": "string"
+ }
+ },
+ "ops": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/DatabaseOp"
+ },
+ "description": "The ops, in the order they apply."
+ }
+ }
+ },
"OpRefusalResponse": {
"type": "object",
"description": "Why an op of a batch was refused. Nothing in the batch was written.",
@@ -32023,6 +32440,86 @@
}
}
},
+ "Pipeline": {
+ "type": "object",
+ "description": "Pipeline metadata; table schema and data are read through the database service.",
+ "required": [
+ "id",
+ "teamId",
+ "userId",
+ "name",
+ "recordType",
+ "databaseId",
+ "tableId",
+ "primaryColumnId",
+ "sharing",
+ "createdAt",
+ "trashedAt"
+ ],
+ "properties": {
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Creation time."
+ },
+ "databaseId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Dedicated backing database."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Entity identity, used with `CrmPipeline` access receipts."
+ },
+ "name": {
+ "type": "string",
+ "description": "Pipeline display name."
+ },
+ "primaryColumnId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Protected primary column."
+ },
+ "recordType": {
+ "$ref": "#/components/schemas/PipelineRecordType",
+ "description": "Kind of the primary reference."
+ },
+ "sharing": {
+ "$ref": "#/components/schemas/PipelineSharing",
+ "description": "Whether the pipeline has a team grant."
+ },
+ "tableId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Table of entries."
+ },
+ "teamId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Team owning the pipeline; references retain their own access controls."
+ },
+ "trashedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "Trashed pipelines are omitted from navigation."
+ },
+ "userId": {
+ "type": "string",
+ "description": "Owning user; sharing never changes ownership."
+ }
+ }
+ },
+ "PipelineRecordType": {
+ "type": "string",
+ "description": "Which CRM entity each row references. Fixed when a pipeline is created.",
+ "enum": ["company", "contact"]
+ },
+ "PipelineSharing": {
+ "type": "string",
+ "description": "Initial sharing, or the desired team grant. Individual ownership is preserved.",
+ "enum": ["private", "team"]
+ },
"PostActivityRequest": {
"type": "object",
"description": "Request body for `POST /channels/activity`.",
@@ -33008,6 +33505,18 @@
}
}
},
+ "RenamePipeline": {
+ "type": "object",
+ "description": "Rename input.",
+ "required": ["name"],
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "New display name."
+ }
+ },
+ "additionalProperties": false
+ },
"ReorderFavoritesRequest": {
"type": "object",
"description": "Request body for reordering favorites.",
@@ -33341,6 +33850,11 @@
}
}
},
+ "RowId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Identifier of a row."
+ },
"RowsChange": {
"oneOf": [
{
@@ -34169,6 +34683,18 @@
}
}
},
+ "SharePipeline": {
+ "type": "object",
+ "description": "Sharing input.",
+ "required": ["sharing"],
+ "properties": {
+ "sharing": {
+ "$ref": "#/components/schemas/PipelineSharing",
+ "description": "Desired team grant."
+ }
+ },
+ "additionalProperties": false
+ },
"SharedEmailFilter": {
"type": "string",
"description": "Controls whether shared email threads are included in results.",
@@ -36392,6 +36918,87 @@
}
}
},
+ "StorageRow": {
+ "type": "object",
+ "description": "One storage row, with cells keyed by column placement.",
+ "required": ["rowId", "cells"],
+ "properties": {
+ "cells": {
+ "type": "object",
+ "description": "Populated cells.",
+ "additionalProperties": {
+ "$ref": "#/components/schemas/PropertyValue"
+ },
+ "propertyNames": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Identifier of a column placement within a table."
+ }
+ },
+ "rowId": {
+ "$ref": "#/components/schemas/RowId",
+ "description": "Row identity, independent of any referenced entity."
+ }
+ }
+ },
+ "StorageRows": {
+ "type": "object",
+ "description": "A bounded page of rows at a table version.",
+ "required": ["rows", "version"],
+ "properties": {
+ "next": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/RowId",
+ "description": "Cursor for another page, if present."
+ }
+ ]
+ },
+ "rows": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/StorageRow"
+ },
+ "description": "Rows in the requested view's order."
+ },
+ "version": {
+ "$ref": "#/components/schemas/TableVersion",
+ "description": "Table version when the read began."
+ }
+ }
+ },
+ "StorageRowsQuery": {
+ "type": "object",
+ "description": "A query over one authorized storage table.",
+ "properties": {
+ "after": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/RowId",
+ "description": "Continue after this row in the filtered, sorted result."
+ }
+ ]
+ },
+ "query": {
+ "$ref": "#/components/schemas/ViewQuery",
+ "description": "The common database filter and sort semantics."
+ },
+ "rowIds": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/RowId"
+ },
+ "description": "Read these retained rows regardless of the active filter."
+ }
+ },
+ "additionalProperties": false
+ },
"StoredGithubPullRequest": {
"type": "object",
"description": "A GitHub pull request as Macro stores it, read through one of the caller's records.",
@@ -37458,6 +38065,18 @@
}
}
},
+ "TrashPipeline": {
+ "type": "object",
+ "description": "Trash/restore input.",
+ "required": ["trashed"],
+ "properties": {
+ "trashed": {
+ "type": "boolean",
+ "description": "True to trash; false to restore."
+ }
+ },
+ "additionalProperties": false
+ },
"TurnEndedMetadata": {
"type": "object",
"description": "The runtime answered a turn. Another prompt may follow at once; see\n[`SessionSettledMetadata`] for \"nothing left to do\".",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 591507318c..bf07991aa2 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -391,6 +391,17 @@ export const storageBacklog = [
'getEmailFollowup',
'setEmailFollowup',
'listEmailReminders',
+ // CRM pipelines fit the crm namespace but are not wrapped yet.
+ 'createCrmPipeline',
+ 'applyCrmPipelineOps',
+ 'getCrmPipeline',
+ 'getCrmPipelineRows',
+ 'queryCrmPipelineRows',
+ 'getCrmPipelineTable',
+ 'listCrmPipelines',
+ 'renameCrmPipeline',
+ 'shareCrmPipeline',
+ 'trashCrmPipeline',
'approveHarnessPairing',
'claimHarnessPairing',
'createAgent',
diff --git a/services/authentication_service/src/service/user/create_user.rs b/services/authentication_service/src/service/user/create_user.rs
index 21e91fa5c0..ede1b35403 100644
--- a/services/authentication_service/src/service/user/create_user.rs
+++ b/services/authentication_service/src/service/user/create_user.rs
@@ -9,7 +9,7 @@ mod test;
/// The stub `STRIPE_SECRET_KEY` set by `run_local --no-doppler` (see
/// `tooling/xtask/crates/xtask_local/src/local/local_env.rs`). With this key a
/// real Stripe call would fail, so local signups skip it and store a
-/// deterministic placeholder id instead.
+/// deterministic placeholder only in the required legacy account field.
const LOCAL_STRIPE_SECRET_STUB: &str = "local-stripe-secret";
fn is_local_stripe_stub() -> bool {
@@ -42,14 +42,19 @@ pub async fn create_user(
let stripe_customer_id = if is_local_stripe_stub() {
// Local mode uses a stub key; don't call Stripe (it would 401 and
// abort the transactional user.create webhook, blocking all signups).
- local_stripe_customer_id(email)
+ None
} else {
// NOTE: stripe adds in ~400ms of latency to this request. We may want to update our
// requirement that each customer exists in stripe and create stripe customers as needed.
let stripe_customer = create_stripe_user(email, stripe_client).await?;
tracing::trace!(stripe_customer_id=?stripe_customer.id.to_string(), "created stripe customer");
- stripe_customer.id.to_string()
+ Some(stripe_customer.id.to_string())
};
+ // The legacy account key is required, but a profile without a real Stripe
+ // customer must leave billing absent so free team creation skips Stripe.
+ let macro_user_customer_id = stripe_customer_id
+ .clone()
+ .unwrap_or_else(|| local_stripe_customer_id(email));
let organization_id = match_user_to_organization(db, email).await?;
tracing::trace!(organization_id=?organization_id, "matched user to organization");
@@ -70,7 +75,8 @@ pub async fn create_user(
username,
email,
is_verified,
- &stripe_customer_id,
+ &macro_user_customer_id,
+ stripe_customer_id.as_deref(),
organization_id,
roles,
)
diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rs
index 410bb5a093..efd10996ce 100644
--- a/services/document_storage_service/src/api.rs
+++ b/services/document_storage_service/src/api.rs
@@ -312,7 +312,10 @@ fn api_router(state: ApiContext) -> Router {
)
.nest(
"/crm",
- crm::inbound::axum_router::crm_router(state.crm_state.clone()),
+ crm::inbound::axum_router::crm_router(state.crm_state.clone()).nest(
+ "/pipelines",
+ crm::inbound::pipelines::router(state.pipeline_state.clone()),
+ ),
)
.merge(
bots::inbound::channel_webhook_router::channel_bot_webhook_router(
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 6c002ada39..9d632deb13 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -187,6 +187,20 @@ pub(crate) type DssCrmStageService = crm::domain::stages::CrmStageServiceImpl<
crm::outbound::stage_definitions::PropertiesStageDefinitionStore<PropertiesService>,
>;
+pub(crate) type DssPipelineService = crm::domain::pipelines::PipelineServiceImpl<
+ crm::outbound::pipelines::PgPipelineRepo<
+ databases::outbound::pg_cell_store::PgCellStore<PropertiesPgRepo>,
+ >,
+ DatabasesServiceType,
+ EntityAccessService,
+ crm::outbound::stage_definitions::PropertiesStageDefinitionStore<PropertiesService>,
+>;
+pub(crate) type DssPipelineState = crm::inbound::pipelines::PipelineRouterState<
+ DssPipelineService,
+ EntityAccessService,
+ AuthorizationService,
+>;
+
pub(crate) type DssCrmState = crm::inbound::axum_router::CrmRouterState<
DssCrmService,
DssCrmStageService,
@@ -865,6 +879,7 @@ pub(crate) struct ApiContext {
pub entity_access_management_service: EntityAccessManagementService,
pub crm_state: DssCrmState,
pub owned_purge_state: DssOwnedPurgeState,
+ pub pipeline_state: DssPipelineState,
}
env_var! {
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 0338b07791..3db0e35849 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -500,6 +500,16 @@ use utoipa::OpenApi;
sync_service_hex::inbound::axum_router::bulk_wakeup_handler,
// /crm
+ crm::inbound::pipelines::create,
+ crm::inbound::pipelines::list,
+ crm::inbound::pipelines::read,
+ crm::inbound::pipelines::table,
+ crm::inbound::pipelines::rows,
+ crm::inbound::pipelines::query_rows,
+ crm::inbound::pipelines::apply_ops,
+ crm::inbound::pipelines::rename,
+ crm::inbound::pipelines::share,
+ crm::inbound::pipelines::trash,
crm::inbound::axum_router::set_email_sync::handler,
crm::inbound::axum_router::set_company_hidden::handler,
crm::inbound::axum_router::set_company_name::handler,
diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rs
index 4edd080e35..dd9038d39d 100644
--- a/services/document_storage_service/src/server.rs
+++ b/services/document_storage_service/src/server.rs
@@ -1446,6 +1446,21 @@ pub async fn run() -> anyhow::Result<()> {
),
macro_event_broker.clone(),
));
+ let pipeline_service = Arc::new(crm::domain::pipelines::PipelineServiceImpl::new(
+ crm::outbound::pipelines::PgPipelineRepo::new(
+ db.clone(),
+ databases::outbound::pg_cell_store::PgCellStore::new(
+ db.clone(),
+ properties::outbound::properties_pg_repo::PropertiesPgRepo::new(db.clone()),
+ ),
+ ),
+ databases_service.clone(),
+ entity_access_service.clone(),
+ crm::outbound::stage_definitions::PropertiesStageDefinitionStore::new(
+ properties_service.clone(),
+ ),
+ ));
+
let forms_service = Arc::new(forms::wiring::build_service(
db.clone(),
databases_service.clone(),
@@ -2059,6 +2074,11 @@ pub async fn run() -> anyhow::Result<()> {
call_internal_state,
cal_webhook_state,
entity_access_management_service,
+ pipeline_state: crm::inbound::pipelines::PipelineRouterState {
+ service: pipeline_service,
+ access: entity_access_service.clone(),
+ authorization: authorization_state.clone(),
+ },
crm_state: crm::inbound::axum_router::CrmRouterState {
service: Arc::new(crm_service),
stage_service: Arc::new(crm::domain::stages::CrmStageServiceImpl::new(
diff --git a/services/document_storage_service/src/service/entity_mutation.rs b/services/document_storage_service/src/service/entity_mutation.rs
index 52684213bd..1f0a173cfa 100644
--- a/services/document_storage_service/src/service/entity_mutation.rs
+++ b/services/document_storage_service/src/service/entity_mutation.rs
@@ -433,6 +433,7 @@ where
| EntityType::StaticFile
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::CalendarEvent
| EntityType::Reminder
| EntityType::Skill
@@ -482,6 +483,7 @@ where
| EntityType::StaticFile
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::CalendarEvent
| EntityType::Reminder
| EntityType::Skill
@@ -537,6 +539,7 @@ where
| EntityType::StaticFile
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::CalendarEvent
| EntityType::Reminder
| EntityType::Skill
@@ -597,6 +600,7 @@ where
| EntityType::StaticFile
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::CalendarEvent
| EntityType::Reminder
| EntityType::Skill
@@ -632,6 +636,7 @@ where
| EntityType::StaticFile
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::CalendarEvent
| EntityType::Reminder
| EntityType::Skill
@@ -687,6 +692,7 @@ where
| EntityType::StaticFile
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::CalendarEvent
| EntityType::Reminder
| EntityType::Skill
@@ -750,6 +756,7 @@ where
| EntityType::StaticFile
| EntityType::CrmCompany
| EntityType::CrmContact
+ | EntityType::CrmPipeline
| EntityType::CalendarEvent
| EntityType::Reminder
| EntityType::Skill
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 99b398ca81..f480e69045 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -3597,6 +3597,10 @@ type GraphqlEntityReferencePropertyValue {
Canonical entity types accepted by cross-entity APIs.
"""
enum GraphqlEntityType {
+ """
+ CRM pipeline entity.
+ """
+ CRM_PIPELINE
"""
Document entity.
"""
diff --git a/tooling/seed_cli/README.md b/tooling/seed_cli/README.md
index 8cd65b61f7..bd7debaf57 100644
--- a/tooling/seed_cli/README.md
+++ b/tooling/seed_cli/README.md
@@ -11,6 +11,30 @@ be run through the `just seed` base command.
## Scenarios
+### CRM sample data in an existing local team
+
+Enable CRM for your local team in Settings → CRM, then run from the repository root:
+
+```bash
+nix develop --command bun tooling/seed_cli/seed-crm.ts \
+ --origin https://localhost:23209 --email [email protected]
+```
+
+Use your instance's HTTPS proxy port and local account email. The seed adds eight
+companies, twelve contacts, and three populated pipelines: team-shared **Demo Sales**
+and **Demo Contacts**, plus private **Demo Design Partners**. Rows include stages,
+assigned and unassigned owners, revenue, and a custom Notes column. Companies also
+get legacy CRM Stage, Owner, and Revenue values for testing the overview and board.
+Existing team stages are reused; the default set spans Lead through Churned.
+
+This uses the running app's APIs and local passwordless authentication. It does
+not reset the database. Reruns reuse companies by domain, contacts by email,
+pipelines by name and record type, and rows by their company/contact reference;
+existing values and sharing choices are preserved. Fixture data is in
+[`seed/crm.json`](seed/crm.json).
+
+### Permission scenarios
+
A scenario file describes a complete world — users, teams, channels, and
entities (documents, tasks, projects, chats, calls, emails, messages) with the
access edges between them — so varied permission patterns are testable
diff --git a/tooling/seed_cli/seed-crm.ts b/tooling/seed_cli/seed-crm.ts
new file mode 100644
index 0000000000..ea4fba738c
--- /dev/null
+++ b/tooling/seed_cli/seed-crm.ts
@@ -0,0 +1,391 @@
+import { randomUUID } from 'node:crypto';
+import { hostname } from 'node:os';
+import { parseArgs } from 'node:util';
+import type {
+ CellWrite,
+ DatabaseOp,
+} from '../../apps/web/src/lib/core/database-sql/generated/types';
+import { buildGraphqlEntitySoupInput } from '../../apps/web/src/lib/queries/soup/graphql/entity-input';
+import type { TeamWithMembers } from '../../apps/web/src/lib/service-clients/service-auth/generated/schemas/teamWithMembers';
+import type { AccessiblePipeline } from '../../apps/web/src/lib/service-clients/service-storage/generated/schemas/accessiblePipeline';
+import type { CrmCompanyResponse } from '../../apps/web/src/lib/service-clients/service-storage/generated/schemas/crmCompanyResponse';
+import type { CrmContactResponse } from '../../apps/web/src/lib/service-clients/service-storage/generated/schemas/crmContactResponse';
+import type { PropertyDefinitionWithOptions } from '../../apps/web/src/lib/service-clients/service-storage/generated/schemas/propertyDefinitionWithOptions';
+import type { StorageRows } from '../../apps/web/src/lib/service-clients/service-storage/generated/schemas/storageRows';
+import type { TableDetail } from '../../apps/web/src/lib/service-clients/service-storage/generated/schemas/tableDetail';
+import type {
+ GraphqlEntityFilterAst,
+ SoupInput,
+} from '../../apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql';
+import fixture from './seed/crm.json';
+
+// Only local passwordless auth returns a code. Never point this seed at hosted data.
+const { values } = parseArgs({
+ options: {
+ origin: { type: 'string' },
+ email: { type: 'string' },
+ help: { type: 'boolean' },
+ },
+});
+if (values.help || !values.origin || !values.email) {
+ console.log(
+ 'Usage: bun tooling/seed_cli/seed-crm.ts --origin https://localhost:<proxy-port> --email <local-account-email>'
+ );
+ process.exit(values.help ? 0 : 1);
+}
+const origin = new URL(values.origin);
+if (
+ !['localhost', '127.0.0.1', '[::1]', hostname()].includes(origin.hostname)
+) {
+ throw new Error('CRM seeding requires a local stack hostname.');
+}
+const email = values.email.toLowerCase();
+let accessToken: string | undefined;
+const created = { companies: 0, contacts: 0, pipelines: 0, rows: 0 };
+
+async function send<T>(
+ method: string,
+ path: string,
+ data?: unknown
+): Promise<T> {
+ const response = await fetch(new URL(path, origin), {
+ method,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
+ },
+ body: data === undefined ? undefined : JSON.stringify(data),
+ tls: { rejectUnauthorized: false },
+ signal: AbortSignal.timeout(60_000),
+ });
+ if (!response.ok)
+ throw new Error(`${method} ${path}: HTTP ${response.status}`);
+ const body = await response.text();
+ return JSON.parse(body || 'null');
+}
+
+// Use the app's exclusion filters so reads cannot accidentally mix other entities in.
+const base = buildGraphqlEntitySoupInput(
+ 'DATABASE_ROW',
+ '00000000-0000-0000-0000-000000000000'
+)?.initial?.filters;
+async function readSoup<T>(
+ filters: GraphqlEntityFilterAst,
+ selection: string
+): Promise<T[]> {
+ const items: T[] = [];
+ let input: SoupInput = {
+ initial: {
+ filters: { ...base, ...filters },
+ limit: 500,
+ sortMethod: 'CREATED_AT',
+ },
+ };
+ const seen = new Set<string>();
+ for (;;) {
+ type SoupResult = {
+ data?: { user: { soup: { items: T[]; nextCursor?: string | null } } };
+ errors?: { message: string }[];
+ };
+ const result: SoupResult = await send<SoupResult>(
+ 'POST',
+ '/dss/items/soup/graphql',
+ {
+ query: `query SeedCrm($input: SoupInput!) { user { soup(input: $input) { items { ${selection} } nextCursor } } }`,
+ variables: { input },
+ }
+ );
+ if (result.errors?.length || !result.data)
+ throw new Error(`CRM seed read failed: ${JSON.stringify(result.errors)}`);
+ items.push(...result.data.user.soup.items);
+ const cursor: string | null | undefined = result.data.user.soup.nextCursor;
+ if (!cursor) return items;
+ if (seen.has(cursor))
+ throw new Error('CRM seed pagination did not advance.');
+ seen.add(cursor);
+ input = { continuation: { cursor } };
+ }
+}
+
+type Company = { id: string; domains: string[] };
+type SeedRecord = {
+ id: string;
+ key: string;
+ stage: string;
+ revenue: number;
+ notes: string;
+ unassigned?: boolean;
+};
+async function applyOps(pipelineId: string, ops: DatabaseOp[]) {
+ if (ops.length)
+ await send('POST', `/dss/crm/pipelines/${pipelineId}/ops`, { ops });
+}
+
+try {
+ const login = await send<{ code?: string }>(
+ 'POST',
+ '/auth/login/passwordless',
+ { email, redirect_uri: `${origin.origin}/app/companies` }
+ );
+ if (!login.code)
+ throw new Error(
+ 'Expected local passwordless auth. No seed data was written.'
+ );
+ const tokens = await send<{ access_token: string }>(
+ 'GET',
+ `/auth/oauth/passwordless/${encodeURIComponent(login.code)}?email=${encodeURIComponent(email)}&disable_redirect=true`
+ );
+ accessToken = tokens.access_token;
+ const team = await send<TeamWithMembers>('GET', '/auth/team');
+ if (!team?.team?.crm_enabled)
+ throw new Error(
+ 'Enable CRM for this local account’s team in Settings → CRM, then rerun.'
+ );
+ const owner = `macro|${email}`;
+ const companies = await readSoup<Company>(
+ { crmCompanyFilter: { literal: { hidden: false } } },
+ '... on GraphqlSoupCrmCompany { id domains }'
+ );
+ const definitions = await send<PropertyDefinitionWithOptions[]>(
+ 'GET',
+ '/dss/properties/definitions?scope=team&include_options=true'
+ );
+ const customStages = definitions.find(
+ (entry) =>
+ entry.definition.display_name === 'Deal Stage' &&
+ entry.definition.data_type === 'SELECT_STRING'
+ );
+ const stageDefinition = customStages?.property_options.length
+ ? customStages
+ : (
+ await send<PropertyDefinitionWithOptions[]>(
+ 'GET',
+ '/dss/properties/definitions?scope=all&include_options=true'
+ )
+ ).find(
+ (entry) =>
+ entry.definition.id === '00000001-0000-0000-0000-000000000010'
+ );
+ if (!stageDefinition)
+ throw new Error('CRM Stage property is missing from this local database.');
+ const stages = stageDefinition.property_options.map((option) => ({
+ id: option.id,
+ label: option.value.value,
+ }));
+ const companyRecords: SeedRecord[] = [];
+ const contactRecords: SeedRecord[] = [];
+
+ for (const [index, sample] of fixture.companies.entries()) {
+ const domain = `${sample.key}.crm-seed.example.com`;
+ let company = companies.find((item) => item.domains.includes(domain));
+ const stage =
+ stages.find((item) => item.label === sample.stage) ??
+ stages[index % stages.length];
+ if (!stage || typeof stage.label !== 'string')
+ throw new Error('This team needs at least one text stage.');
+ const record = {
+ key: sample.key,
+ stage: stage.label,
+ revenue: sample.revenue,
+ notes: sample.notes,
+ unassigned: sample.unassigned,
+ };
+ if (!company) {
+ const added = await send<CrmCompanyResponse>(
+ 'POST',
+ '/dss/crm/companies',
+ { name: sample.name, domain }
+ );
+ company = { id: added.id, domains: [domain] };
+ created.companies++;
+ companies.push(company);
+ // Initialize legacy CRM fields only on new sample companies; reruns preserve edits.
+ const propertyPath = `/dss/properties/entities/COMPANY/${company.id}`;
+ await send('PUT', `${propertyPath}/${stageDefinition.definition.id}`, {
+ value: { type: 'select_option', option_id: stage.id },
+ });
+ await send(
+ 'PUT',
+ `${propertyPath}/00000001-0000-0000-0000-000000000012`,
+ { value: { type: 'number', value: sample.revenue } }
+ );
+ if (!sample.unassigned)
+ await send(
+ 'PUT',
+ `${propertyPath}/00000001-0000-0000-0000-000000000011`,
+ {
+ value: {
+ type: 'entity_reference',
+ reference: { entity_type: 'USER', entity_id: owner },
+ },
+ }
+ );
+ }
+ companyRecords.push({ ...record, id: company.id });
+ const contacts = await send<CrmContactResponse[]>(
+ 'GET',
+ `/dss/crm/companies/${company.id}/contacts`
+ );
+ for (const name of sample.contacts) {
+ const contactEmail = `${name.toLowerCase().replaceAll(' ', '.')}@${domain}`;
+ let contact = contacts.find((item) => item.email === contactEmail);
+ if (!contact) {
+ contact = await send<CrmContactResponse>(
+ 'POST',
+ `/dss/crm/companies/${company.id}/contacts`,
+ { name, email: contactEmail }
+ );
+ created.contacts++;
+ }
+ contactRecords.push({ ...record, id: contact.id });
+ }
+ }
+
+ const pipelines = await send<AccessiblePipeline[]>(
+ 'GET',
+ '/dss/crm/pipelines'
+ );
+ for (const sample of fixture.pipelines) {
+ let pipeline = pipelines.find(
+ (item) =>
+ item.name === sample.name && item.recordType === sample.recordType
+ );
+ if (!pipeline) {
+ pipeline = await send<AccessiblePipeline>('POST', '/dss/crm/pipelines', {
+ name: sample.name,
+ recordType: sample.recordType,
+ sharing: sample.sharing,
+ });
+ created.pipelines++;
+ pipelines.push(pipeline);
+ }
+ const table = await send<TableDetail>(
+ 'GET',
+ `/dss/crm/pipelines/${pipeline.id}/table`
+ );
+ const column = (name: string) =>
+ table.columns.find(
+ (item) => item.definition.definition.display_name === name
+ )?.column.id;
+ const primary = table.columns.find(
+ (item) => item.column.id === pipeline.primaryColumnId
+ );
+ if (!primary) throw new Error(`Missing primary column for ${sample.name}`);
+ const existing = new Set<string>();
+ let after: string | undefined;
+ do {
+ const page = await send<StorageRows>(
+ 'GET',
+ `/dss/crm/pipelines/${pipeline.id}/rows${after ? `?after=${after}` : ''}`
+ );
+ for (const row of page.rows) {
+ const value = row.cells[pipeline.primaryColumnId];
+ if (value?.type === 'EntityReference')
+ for (const ref of value.value) existing.add(ref.entity_id);
+ }
+ after = page.next ?? undefined;
+ } while (after);
+ const records = (
+ sample.recordType === 'company' ? companyRecords : contactRecords
+ ).filter(
+ (record) =>
+ (!sample.companies || sample.companies.includes(record.key)) &&
+ !existing.has(record.id)
+ );
+ // Preserve all existing pipeline values and custom columns on repeat runs.
+ if (!records.length) continue;
+ const stageColumn = column('Stage');
+ const ownerColumn = column('Owner');
+ const revenueColumn = column('Revenue');
+ const notesColumn = column('Notes') ?? randomUUID();
+ const ops: DatabaseOp[] = column('Notes')
+ ? []
+ : [
+ {
+ kind: 'column',
+ table: pipeline.tableId,
+ column: notesColumn,
+ change: {
+ kind: 'create',
+ definition: {
+ source: 'new',
+ name: 'Notes',
+ type: { type: 'text' },
+ },
+ },
+ },
+ ];
+ ops.push({
+ kind: 'rows',
+ table: pipeline.tableId,
+ change: {
+ kind: 'insert',
+ rows: records.map((record): CellWrite[] => [
+ {
+ column: pipeline.primaryColumnId,
+ value: {
+ type: 'entities',
+ value: [
+ {
+ entityType:
+ sample.recordType === 'company' ? 'COMPANY' : 'CONTACT',
+ entityId: record.id,
+ },
+ ],
+ },
+ },
+ ...(stageColumn
+ ? [
+ {
+ column: stageColumn,
+ value: {
+ type: 'options' as const,
+ value: [{ label: record.stage }],
+ },
+ },
+ ]
+ : []),
+ ...(ownerColumn && !record.unassigned
+ ? [
+ {
+ column: ownerColumn,
+ value: {
+ type: 'entities' as const,
+ value: [{ entityType: 'USER' as const, entityId: owner }],
+ },
+ },
+ ]
+ : []),
+ ...(revenueColumn
+ ? [
+ {
+ column: revenueColumn,
+ value: { type: 'number' as const, value: record.revenue },
+ },
+ ]
+ : []),
+ { column: notesColumn, value: { type: 'text', value: record.notes } },
+ ]),
+ },
+ });
+ await applyOps(pipeline.id, ops);
+ created.rows += records.length;
+ }
+ console.log(
+ JSON.stringify(
+ {
+ team: team.team.name,
+ created,
+ companies: companyRecords.length,
+ contacts: contactRecords.length,
+ stages: stages.map((stage) => stage.label),
+ pipelines: fixture.pipelines.map((pipeline) => pipeline.name),
+ url: `${origin.origin}/app/companies`,
+ },
+ null,
+ 2
+ )
+ );
+} finally {
+ accessToken = undefined;
+}
diff --git a/tooling/seed_cli/seed/crm.json b/tooling/seed_cli/seed/crm.json
new file mode 100644
index 0000000000..b3262f6c0b
--- /dev/null
+++ b/tooling/seed_cli/seed/crm.json
@@ -0,0 +1,79 @@
+{
+ "companies": [
+ {
+ "key": "atlas",
+ "name": "Atlas Labs",
+ "stage": "Lead",
+ "revenue": 12000,
+ "notes": "Inbound interest; schedule discovery.",
+ "contacts": ["Maya Chen", "Alex Rivera"]
+ },
+ {
+ "key": "cedar",
+ "name": "Cedar Health",
+ "stage": "Qualified",
+ "revenue": 36000,
+ "notes": "Operations team evaluating a 40-seat rollout.",
+ "contacts": ["Jordan Patel", "Sam Brooks"]
+ },
+ {
+ "key": "northstar",
+ "name": "Northstar Analytics",
+ "stage": "Demo",
+ "revenue": 24000,
+ "notes": "Demo requested with the data and sales teams.",
+ "contacts": ["Morgan Lee", "Taylor Kim"]
+ },
+ {
+ "key": "orbit",
+ "name": "Orbit Design",
+ "stage": "Trial",
+ "revenue": 18000,
+ "notes": "Two-week pilot; review adoption next week.",
+ "contacts": ["Casey Nguyen", "Riley Park"]
+ },
+ {
+ "key": "summit",
+ "name": "Summit Logistics",
+ "stage": "Negotiation",
+ "revenue": 72000,
+ "notes": "Procurement reviewing annual terms.",
+ "contacts": ["Jamie Wilson"]
+ },
+ {
+ "key": "harbor",
+ "name": "Harbor Finance",
+ "stage": "Customer",
+ "revenue": 96000,
+ "notes": "Annual customer; expansion opportunity next quarter.",
+ "contacts": ["Avery Thompson"]
+ },
+ {
+ "key": "juniper",
+ "name": "Juniper Commerce",
+ "stage": "Churned",
+ "revenue": 9000,
+ "notes": "Paused after reorganization; revisit in six months.",
+ "contacts": ["Drew Martinez"]
+ },
+ {
+ "key": "maple",
+ "name": "Maple Robotics",
+ "stage": "Lead",
+ "revenue": 4500,
+ "notes": "Unassigned lead from a founder introduction.",
+ "unassigned": true,
+ "contacts": ["Quinn Davis"]
+ }
+ ],
+ "pipelines": [
+ { "name": "Demo Sales", "recordType": "company", "sharing": "team" },
+ { "name": "Demo Contacts", "recordType": "contact", "sharing": "team" },
+ {
+ "name": "Demo Design Partners",
+ "recordType": "company",
+ "sharing": "private",
+ "companies": ["atlas", "cedar", "orbit"]
+ }
+ ]
+}
diff --git a/tooling/xtask/crates/xtask_local/Cargo.toml b/tooling/xtask/crates/xtask_local/Cargo.toml
index 451a9beed9..78e48184ad 100644
--- a/tooling/xtask/crates/xtask_local/Cargo.toml
+++ b/tooling/xtask/crates/xtask_local/Cargo.toml
@@ -51,6 +51,9 @@ libc = "0.2"
macro_env_var = { path = "../../../../crates/macro_env_var" }
xtask_paths = { path = "../xtask_paths" }
+[dev-dependencies]
+jsonwebtoken = { workspace = true }
+
[features]
# Local Kafka topic provisioning (`run-local` / `kafka-provision`). Off by
# default so a plain build avoids compiling bundled librdkafka; the just recipes
diff --git a/tooling/xtask/crates/xtask_local/src/local/identity.rs b/tooling/xtask/crates/xtask_local/src/local/identity.rs
index ca9457b400..1db6b04034 100644
--- a/tooling/xtask/crates/xtask_local/src/local/identity.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/identity.rs
@@ -19,6 +19,14 @@ pub const JWT_SIGNING_KEY_ID: &str = "d7d09513-a3f5-401c-9685-34ab6c552453";
/// The HS256 secret. `macro_auth` reads this as `JWT_SECRET_KEY`.
pub const JWT_SECRET: &str = "super-secret-jwt-signing-key-for-local-development-only";
+/// Public fixture key for local Macro API tokens, including CRM settings calls.
+pub const MACRO_API_TOKEN_PUBLIC_KEY: &str =
+ include_str!("identity/macro-api-token.local.public.pem");
+
+/// Local-only fixture signing key. Never use this identity in a deployed environment.
+pub const MACRO_API_TOKEN_PRIVATE_KEY: &str =
+ include_str!("identity/macro-api-token.local.private.pem");
+
/// The populate-JWT lambda id (the unlicensed local variant).
pub const POPULATE_JWT_LAMBDA_ID: &str = "a7f3e8d2-4b91-4c5a-9e6f-1a2b3c4d5e6f";
diff --git a/tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.private.pem b/tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.private.pem
new file mode 100644
index 0000000000..2cf1cac05f
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.private.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCeFPBYUf44tMo/
+lVgFgX8vs+qMNaAUZbW6cZ2mFjDE2njljglEEZ5wpxOzAkseAi14DAuI7ip3OUv1
+Jk+yRLrn/pbt1spvQnRnsBep8OJJwmz4k56U8YRCuzBA/4pzPBOBgEjnI7JHe++E
+y0XqkQdN53D7A0l1433coWSxnLlj0njl7az3NeLjm0XAxOsvd1n2c1YrEq5EpbtM
+3OP4YU1Xw4EuFM+uctBc66BV7Z6jhjE+aAEPGx+jYznCQlw28DBvYSh9Pd5q5VrK
+JNOgBMD3jukfYoFCiS4yzlgEgPbSP4OGpoYVFMuBtLyAp/GmLxQQai8F9ySt5kct
+gS5i6wOxAgMBAAECggEAAi9z6ySnCQ2mxh5Aa0MRCQ3JrkqHfgCx9HPhpAwmfHIw
+vaurAR/lOtV0dkMP2shY7JHuDuSL/b3zCN6Qt3wvwUlJuNwBTGx0w4IxsY288xwW
++ZDA3npAQ9PmpN9jgJhSBLZLS7a4njheZU2SF94NZcxPSYkQGOseMFCi3bm27mRS
+5pn60cTfRhoNyULGfFGM8r1v4sEjrqYD/lfznWx3oEfD92bZJ+C3lSMBKN9Ea+3F
+2UwQa9FdhjLCONOGv1QieWD5NI1D2hgjgKtStypVuteikXYzvvZS9a0Z2BGyb8E7
+dE0/1XyvMJuSh/IpA2mNqy+sXjKpG85O5kxwID9DiQKBgQDa01GoJqeYRwKt91dH
+Be2wp/sr9OT43EwDFSETMynvjxJ5BUHlZzU2OpPH8zwauxMVtfU/VPukg5Kh1nre
+erl52lxygxjDQiEeRw7qESbR83mangOes46eBYMTZ2OYCOld6jL2fG0Adnfr83AW
+gdNT1+c7tqNv6B0ZyJvbVVXIMwKBgQC47+NjQswo/o1SeHUPOeqBGc3i88UJq69v
+x9rorpaTQl1S/aT7l4YXETk+tRScb3VuTbNCm6qvzcrSz5gkNFXZwdGvVG51Mc+n
+F3qthGXf/Xsx8HtdbQ07+UkkouVHxXlobVj2PYZCfAvkd4xaakX4hh58GwuRCcPk
+Um8YFjtwiwKBgAU7bkVl/zXd5MuCEX0qQB+sNI49gcgNhGfCdpL98y++LQPlw0iX
+6ibMycHLKBG/jVpEioOkJYwudTAXb8KoDo1CUlmOluX8S8xsiIfCNzpn5u1yf8Wo
+p21R1mt9Wl1FQUc0lVldakHLk1x56qEvI31quSWtXUUMuL1oFYnuBWoPAoGAYGuq
+GWGFQkZddkcZeSPQERlcD9zauU0K/fOsPa5xETwDnjZiY04/+hzfxMLyiRFPn3/h
+W3P/zQM1oS3c+9tRe2QjKA+UO4QJ6OtD6d3io6LsLUBdgXtO8BrruK85bW8W+oww
+Wsn/CwDTzn1J7wYDjyyWDkynfioiOROFmoBU4zsCgYEAs7N1D6uhskhtAi7xuJra
+1ogURJKh6sXFVhiyfT25mVK+S4kIffAiI2iAtpMyCDtDaVB2w07mQEjjLQhTrG9R
+gQXYOk6QaEqtfI+h+7jd7/kC+ZqWUT1OeglCJuKy3SlTNg5m7ZijE3cE+DxDHy9t
+15N1AIiNEOsbkGqIeR06/xk=
+-----END PRIVATE KEY-----
diff --git a/tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.public.pem b/tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.public.pem
new file mode 100644
index 0000000000..8c41903fe6
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/identity/macro-api-token.local.public.pem
@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnhTwWFH+OLTKP5VYBYF/
+L7PqjDWgFGW1unGdphYwxNp45Y4JRBGecKcTswJLHgIteAwLiO4qdzlL9SZPskS6
+5/6W7dbKb0J0Z7AXqfDiScJs+JOelPGEQrswQP+KczwTgYBI5yOyR3vvhMtF6pEH
+Tedw+wNJdeN93KFksZy5Y9J45e2s9zXi45tFwMTrL3dZ9nNWKxKuRKW7TNzj+GFN
+V8OBLhTPrnLQXOugVe2eo4YxPmgBDxsfo2M5wkJcNvAwb2EofT3eauVayiTToATA
+947pH2KBQokuMs5YBID20j+DhqaGFRTLgbS8gKfxpi8UEGovBfckreZHLYEuYusD
+sQIDAQAB
+-----END PUBLIC KEY-----
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index 4a42eabf95..228f7840e6 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -644,10 +644,10 @@ impl FusionAuthEnv {
/// Values the services' `macro_config` loaders require but that only exist in
/// Doppler's `lcl_personal` config. Without these a `--no-doppler` stack's
/// containers crash at startup ("missing required value") before any of the
-/// integration the value backs is ever exercised. Each entry is a deterministic
-/// local stub: good enough to boot, never a real secret, and only meaningful
-/// for the specific integration it names (which won't work locally anyway —
-/// that's what `--env-file` / `run_dev` are for).
+/// integration the value backs is ever exercised. Entries are deterministic
+/// local fixtures or third-party placeholders, never deployed secrets. Local
+/// authentication fixtures must support real requests; third-party integrations
+/// need `--env-file` / `run_dev` for working credentials.
///
/// Unlike the rest of [`LocalEnv`], these are a FALLBACK layer: the resolver
/// applies them below Doppler (see `env_layer::resolve`), so a developer with
@@ -738,18 +738,17 @@ impl BootStubEnv {
"15000".into(),
);
env.insert("AI_USAGE_OVERAGE_MARKUP_PERCENT".into(), "25".into());
- // macro_auth's `JwtValidationArgs` (used by every service that mounts
- // the auth middleware) reads these at boot. The keys are only parsed
- // when a Macro API token is actually validated — normal local auth
- // uses FusionAuth JWTs — so dummies are fine.
+ // Browser clients exchange FusionAuth sessions for Macro API tokens
+ // for actions such as enabling CRM. Both issuance and validation need
+ // the same usable local key pair, even without Doppler.
env.insert("MACRO_API_TOKEN_ISSUER".into(), "local".into());
env.insert(
"MACRO_API_TOKEN_PUBLIC_KEY".into(),
- "local-macro-api-token-public-key".into(),
+ identity::MACRO_API_TOKEN_PUBLIC_KEY.into(),
);
env.insert(
"MACRO_API_TOKEN_PRIVATE_SECRET_KEY".into(),
- "local-macro-api-token-private-key".into(),
+ identity::MACRO_API_TOKEN_PRIVATE_KEY.into(),
);
env.insert("MACRO_API_TOKEN_EXPIRY_SECONDS".into(), "3600".into());
// email_service's GCP pubsub queue (gmail watch notifications) and
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
index 451f7e4654..c14fde2d9a 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
@@ -12,6 +12,36 @@ fn local_env() -> BTreeMap<String, String> {
env
}
+#[test]
+fn local_macro_api_tokens_can_be_signed_and_verified() {
+ use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ let env = local_env();
+ let claims = serde_json::json!({
+ "iss": env["MACRO_API_TOKEN_ISSUER"],
+ "exp": SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + 60,
+ "macro_user_id": "macro|[email protected]",
+ });
+ let mut header = Header::new(Algorithm::RS256);
+ header.kid = Some("macro".into());
+ let token = jsonwebtoken::encode(
+ &header,
+ &claims,
+ &EncodingKey::from_rsa_pem(env["MACRO_API_TOKEN_PRIVATE_SECRET_KEY"].as_bytes()).unwrap(),
+ )
+ .unwrap();
+ let mut validation = Validation::new(Algorithm::RS256);
+ validation.set_issuer(&[&env["MACRO_API_TOKEN_ISSUER"]]);
+ let decoded = jsonwebtoken::decode::<serde_json::Value>(
+ &token,
+ &DecodingKey::from_rsa_pem(env["MACRO_API_TOKEN_PUBLIC_KEY"].as_bytes()).unwrap(),
+ &validation,
+ )
+ .unwrap();
+ assert_eq!(decoded.claims, claims);
+}
+
/// Every key a local service relies on must be present — this is the test that
/// replaces "someone remembers to update defaults.env".
#[test]