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 role-gated deal stage endpoints (#6242)

Panat Taranat6ee04c442d95
diff --git a/.sqlx/query-5dfd371c2fd5f4355fefbbb5e105c55e35ef9da6b0bbc04f67f8e1ef73675d52.json b/.sqlx/query-5dfd371c2fd5f4355fefbbb5e105c55e35ef9da6b0bbc04f67f8e1ef73675d52.json
new file mode 100644
index 0000000000..1fbbcf1858
--- /dev/null
+++ b/.sqlx/query-5dfd371c2fd5f4355fefbbb5e105c55e35ef9da6b0bbc04f67f8e1ef73675d52.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE property_options\n SET string_value = chr(31) || id::text, number_value = NULL, updated_at = NOW()\n WHERE property_definition_id = $1 AND id = ANY($2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5dfd371c2fd5f4355fefbbb5e105c55e35ef9da6b0bbc04f67f8e1ef73675d52"
+}
diff --git a/.sqlx/query-657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f.json b/.sqlx/query-657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f.json
new file mode 100644
index 0000000000..8390945791
--- /dev/null
+++ b/.sqlx/query-657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET\n values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE NOT (to_jsonb($2::text[]) @> elem)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE property_definition_id = $1\n AND values -> 'value' ?| $2::text[]\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "657e0c6418ff6bc4ada878194f855cd596d4b9a03aa07e03d924f815ad5ae95f"
+}
diff --git a/.sqlx/query-6ba1b1fa24a8af68ac9a09748284c761164c83262d5b73764fa28b236e55f667.json b/.sqlx/query-6ba1b1fa24a8af68ac9a09748284c761164c83262d5b73764fa28b236e55f667.json
new file mode 100644
index 0000000000..04ab8a5197
--- /dev/null
+++ b/.sqlx/query-6ba1b1fa24a8af68ac9a09748284c761164c83262d5b73764fa28b236e55f667.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO property_options (\n id, property_definition_id, display_order, number_value, string_value\n )\n SELECT insert.id, $1, insert.display_order, insert.number_value, insert.string_value\n FROM UNNEST($2::uuid[], $3::int4[], $4::float8[], $5::text[])\n AS insert(id, display_order, number_value, string_value)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray",
+ "Int4Array",
+ "Float8Array",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "6ba1b1fa24a8af68ac9a09748284c761164c83262d5b73764fa28b236e55f667"
+}
diff --git a/.sqlx/query-773314bffad8bdc4351c29edfd296ad5d7c8e62882c588c4d0684b5e0f44ece7.json b/.sqlx/query-773314bffad8bdc4351c29edfd296ad5d7c8e62882c588c4d0684b5e0f44ece7.json
new file mode 100644
index 0000000000..ef08de5600
--- /dev/null
+++ b/.sqlx/query-773314bffad8bdc4351c29edfd296ad5d7c8e62882c588c4d0684b5e0f44ece7.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n FROM property_options\n WHERE property_definition_id = $1\n ORDER BY display_order, number_value, LOWER(string_value)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "display_order",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 3,
+ "name": "number_value",
+ "type_info": "Float8"
+ },
+ {
+ "ordinal": 4,
+ "name": "string_value",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "color",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "773314bffad8bdc4351c29edfd296ad5d7c8e62882c588c4d0684b5e0f44ece7"
+}
diff --git a/.sqlx/query-a026a932f7aae1b8038497a1f5c863b09dfda03fe4dbe2be7b01859e78b1544f.json b/.sqlx/query-a026a932f7aae1b8038497a1f5c863b09dfda03fe4dbe2be7b01859e78b1544f.json
new file mode 100644
index 0000000000..7254b27e7e
--- /dev/null
+++ b/.sqlx/query-a026a932f7aae1b8038497a1f5c863b09dfda03fe4dbe2be7b01859e78b1544f.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM property_options WHERE property_definition_id = $1 AND id = ANY($2)",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "a026a932f7aae1b8038497a1f5c863b09dfda03fe4dbe2be7b01859e78b1544f"
+}
diff --git a/.sqlx/query-f38e6319f78abcbdd707dd0d810cdb3abf5f85e9d68b7ae2e777ea140b224868.json b/.sqlx/query-f38e6319f78abcbdd707dd0d810cdb3abf5f85e9d68b7ae2e777ea140b224868.json
new file mode 100644
index 0000000000..6f2d9c94da
--- /dev/null
+++ b/.sqlx/query-f38e6319f78abcbdd707dd0d810cdb3abf5f85e9d68b7ae2e777ea140b224868.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE property_options AS option\n SET\n number_value = rewrite.number_value,\n string_value = rewrite.string_value,\n display_order = rewrite.display_order,\n updated_at = NOW()\n FROM UNNEST($2::uuid[], $3::float8[], $4::text[], $5::int4[])\n AS rewrite(id, number_value, string_value, display_order)\n WHERE option.property_definition_id = $1 AND option.id = rewrite.id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "UuidArray",
+ "Float8Array",
+ "TextArray",
+ "Int4Array"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f38e6319f78abcbdd707dd0d810cdb3abf5f85e9d68b7ae2e777ea140b224868"
+}
diff --git a/apps/web/src/features/property/constants.ts b/apps/web/src/features/property/constants.ts
index f4f8a8a290..8aed8fa0cd 100644
--- a/apps/web/src/features/property/constants.ts
+++ b/apps/web/src/features/property/constants.ts
@@ -12,7 +12,7 @@ export const NUMBER_DECIMAL_PLACES = 4;
* (unique per team). Managed exclusively from CRM settings, so generic
* property pickers must not offer it.
*/
-export const CRM_TEAM_STAGE_DEFINITION_NAME = 'Stage';
+export const CRM_TEAM_STAGE_DEFINITION_NAME = 'Deal Stage';
/**
* System property definition IDs (from backend seed migration).
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageInput.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageInput.ts
new file mode 100644
index 0000000000..814e1b75c0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageInput.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CrmStageInputId } from './crmStageInputId';
+
+/**
+ * One stage in a `PUT /crm/stages` body.
+ */
+export interface CrmStageInput {
+ /** Existing stage to keep; omit to add one. */
+ id?: CrmStageInputId;
+ /** Label after the update; non-blank and unique within the set. */
+ label: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageInputId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageInputId.ts
new file mode 100644
index 0000000000..73c27ab7cb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageInputId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Existing stage to keep; omit to add one.
+ */
+export type CrmStageInputId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageResponse.ts
new file mode 100644
index 0000000000..d8c5efe37f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStageResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * One stage of the team's custom pipeline.
+ */
+export interface CrmStageResponse {
+ /** Property option id companies carry as their stage value. */
+ id: string;
+ /** Label. */
+ label: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStagesResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStagesResponse.ts
new file mode 100644
index 0000000000..2fc3d5f538
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmStagesResponse.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CrmStageResponse } from './crmStageResponse';
+
+/**
+ * The team's custom stage set.
+ */
+export interface CrmStagesResponse {
+ /** Team-scoped stage definition id. */
+ definition_id: string;
+ /** Stages in pipeline order. */
+ stages: CrmStageResponse[];
+}
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 a8635610d0..d58ac5b692 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
@@ -444,6 +444,10 @@ export * from './crmContactResponse';
export * from './crmContactResponseName';
export * from './crmDomainResponse';
export * from './crmPermissionRole';
+export * from './crmStageInput';
+export * from './crmStageInputId';
+export * from './crmStageResponse';
+export * from './crmStagesResponse';
export * from './crmTeamSettingsResponse';
export * from './crmTeamSettingsResponseClosedStageIds';
export * from './crmTeamSettingsResponseDefaultTeamViewId';
@@ -994,6 +998,7 @@ export * from './remindersListNextCursor';
export * from './removeParticipantsRequest';
export * from './reorderFavoritesRequest';
export * from './reorderPinRequest';
+export * from './replaceCrmStagesRequest';
export * from './requestedHarnessScope';
export * from './ringStatus';
export * from './ringStatusResponse';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/replaceCrmStagesRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/replaceCrmStagesRequest.ts
new file mode 100644
index 0000000000..8a0c970603
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/replaceCrmStagesRequest.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 { CrmStageInput } from './crmStageInput';
+
+/**
+ * Request body for `PUT /crm/stages`: the whole stage set in order.
+ */
+export interface ReplaceCrmStagesRequest {
+ /** Stages first to last. */
+ stages: CrmStageInput[];
+}
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 c3dff4a7a2..c1a02363e0 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
@@ -5100,6 +5100,53 @@ export const putCrmTeamSettingsResponse = zod
"The team's CRM configuration (everything on `team_crm_settings`\nexcept the `crm_enabled` killswitch, which is managed via\n`PATCH \/team\/crm` on the auth service)."
);
+/**
+ * @summary Replace the team's deal stages; requires `edit_stages_role` (403 otherwise).
+ */
+export const putCrmTeamStagesBody = zod
+ .object({
+ stages: zod
+ .array(
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .nullish()
+ .describe('Existing stage to keep; omit to add one.'),
+ label: zod
+ .string()
+ .describe(
+ 'Label after the update; non-blank and unique within the set.'
+ ),
+ })
+ .describe('One stage in a `PUT \/crm\/stages` body.')
+ )
+ .describe('Stages first to last.'),
+ })
+ .describe(
+ 'Request body for `PUT \/crm\/stages`: the whole stage set in order.'
+ );
+
+export const putCrmTeamStagesResponse = zod
+ .object({
+ definition_id: zod.uuid().describe('Team-scoped stage definition id.'),
+ stages: zod
+ .array(
+ zod
+ .object({
+ id: zod
+ .uuid()
+ .describe(
+ 'Property option id companies carry as their stage value.'
+ ),
+ label: zod.string().describe('Label.'),
+ })
+ .describe("One stage of the team's custom pipeline.")
+ )
+ .describe('Stages in pipeline order.'),
+ })
+ .describe("The team's custom stage set.");
+
/**
* @summary Gets the users documents to populate their recent document list
*/
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 a6c74d3edc..8281164e6d 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -5942,6 +5942,115 @@
}
}
},
+ "/crm/stages": {
+ "put": {
+ "tags": ["crm::inbound::axum_router::stages"],
+ "summary": "Replace the team's deal stages; requires `edit_stages_role` (403 otherwise).",
+ "operationId": "put_crm_team_stages",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReplaceCrmStagesRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CrmStagesResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["crm::inbound::axum_router::stages"],
+ "summary": "Reset the team's deal stages to the defaults; gated like `PUT /crm/stages`.",
+ "operationId": "reset_crm_team_stages",
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/documents": {
"get": {
"tags": ["document"],
@@ -17955,6 +18064,57 @@
"description": "Minimum team role required for a CRM governance capability. Members\ncan edit visible CRM records (e.g. company properties), but the\ngovernance capabilities these settings gate stay restricted to\nadmin (default) vs owner. Maps to the `team_role` Postgres enum;\n`member` is deliberately not representable.",
"enum": ["admin", "owner"]
},
+ "CrmStageInput": {
+ "type": "object",
+ "description": "One stage in a `PUT /crm/stages` body.",
+ "required": ["label"],
+ "properties": {
+ "id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Existing stage to keep; omit to add one."
+ },
+ "label": {
+ "type": "string",
+ "description": "Label after the update; non-blank and unique within the set."
+ }
+ }
+ },
+ "CrmStageResponse": {
+ "type": "object",
+ "description": "One stage of the team's custom pipeline.",
+ "required": ["id", "label"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Property option id companies carry as their stage value."
+ },
+ "label": {
+ "type": "string",
+ "description": "Label."
+ }
+ }
+ },
+ "CrmStagesResponse": {
+ "type": "object",
+ "description": "The team's custom stage set.",
+ "required": ["definition_id", "stages"],
+ "properties": {
+ "definition_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Team-scoped stage definition id."
+ },
+ "stages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CrmStageResponse"
+ },
+ "description": "Stages in pipeline order."
+ }
+ }
+ },
"CrmTeamSettingsResponse": {
"type": "object",
"description": "The team's CRM configuration (everything on `team_crm_settings`\nexcept the `crm_enabled` killswitch, which is managed via\n`PATCH /team/crm` on the auth service).",
@@ -23887,6 +24047,20 @@
}
}
},
+ "ReplaceCrmStagesRequest": {
+ "type": "object",
+ "description": "Request body for `PUT /crm/stages`: the whole stage set in order.",
+ "required": ["stages"],
+ "properties": {
+ "stages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CrmStageInput"
+ },
+ "description": "Stages first to last."
+ }
+ }
+ },
"RequestedHarnessScope": {
"type": "string",
"description": "The ownership scope a daemon's config asks for.\n\nAdvisory, not binding: the approving user confirms it in the dialog, which\narrives preselected to this. Approval is what actually sets ownership.",
diff --git a/crates/crm/Cargo.toml b/crates/crm/Cargo.toml
index b110875b3f..d7521031d0 100644
--- a/crates/crm/Cargo.toml
+++ b/crates/crm/Cargo.toml
@@ -29,7 +29,15 @@ axum = [
]
default = ["ai_tools", "inbound", "outbound", "ports"]
inbound = ["axum", "ports"]
-outbound = ["dep:reqwest", "dep:sqlx", "dep:unfurl", "ports"]
+outbound = [
+ "dep:macro_user_id",
+ "dep:models_properties",
+ "dep:properties",
+ "dep:reqwest",
+ "dep:sqlx",
+ "dep:unfurl",
+ "ports",
+]
ports = []
# Read-only CRM search (name/domain). Pulls only sqlx + ports — no
# reqwest/unfurl/axum — so search consumers stay lightweight.
@@ -73,6 +81,10 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
macro_user_id = { path = "../macro_user_id" }
+properties = { path = "../properties", default-features = false, features = [
+ "outbound",
+ "ports",
+] }
rootcause = { workspace = true }
tokio = { workspace = true, features = ["macros"] }
tower = { workspace = true }
diff --git a/crates/crm/src/domain.rs b/crates/crm/src/domain.rs
index c6958a93ff..01839c2894 100644
--- a/crates/crm/src/domain.rs
+++ b/crates/crm/src/domain.rs
@@ -18,6 +18,9 @@ pub mod company_metadata_resolver;
/// The CRM service trait and implementation
#[cfg(feature = "ports")]
pub mod service;
+/// Team deal stages: the role-gated write path over the team's stage definition
+#[cfg(feature = "ports")]
+pub mod stages;
/// Capability-token receipt wrappers gating per-entity CRM service calls
#[cfg(feature = "ports")]
diff --git a/crates/crm/src/domain/auth.rs b/crates/crm/src/domain/auth.rs
index 64e6ccd7b5..4a4c7c4442 100644
--- a/crates/crm/src/domain/auth.rs
+++ b/crates/crm/src/domain/auth.rs
@@ -23,7 +23,10 @@ use entity_access::domain::models::{
};
use uuid::Uuid;
-use crate::domain::{comment::CrmCommentEntityType, model::CrmError};
+use crate::domain::{
+ comment::CrmCommentEntityType,
+ model::{CrmError, CrmPermissionRole},
+};
#[cfg(test)]
mod test;
@@ -244,9 +247,16 @@ impl<T: RequiredPermission> CrmTeamReceipt<T> {
/// service to gate admin-only mutations that share an endpoint with
/// member-level ones (e.g. the governance fields of team settings).
pub(crate) fn has_admin_role(&self) -> bool {
- self.receipt
- .entity_permission()
- .allows_team_role(entity_access::domain::models::TeamRole::Admin)
+ self.satisfies_permission_role(CrmPermissionRole::Admin)
+ }
+
+ /// Whether the caller's team role meets a configurable CRM threshold.
+ pub(crate) fn satisfies_permission_role(&self, role: CrmPermissionRole) -> bool {
+ let required = match role {
+ CrmPermissionRole::Admin => TeamRole::Admin,
+ CrmPermissionRole::Owner => TeamRole::Owner,
+ };
+ self.receipt.entity_permission().allows_team_role(required)
}
/// Test-only: mints an `Owner` receipt with no access check.
diff --git a/crates/crm/src/domain/model.rs b/crates/crm/src/domain/model.rs
index 8f7bb2bc93..6e3e8de358 100644
--- a/crates/crm/src/domain/model.rs
+++ b/crates/crm/src/domain/model.rs
@@ -388,6 +388,9 @@ pub enum CrmError {
/// is below admin/owner.
#[error("changing crm permission or stage settings requires admin/owner team role")]
SettingsAdminRequired,
+ /// Caller's team role is below the team's `edit_stages_role`.
+ #[error("editing deal stages requires the {} team role", .0.as_db_str())]
+ StageEditRoleRequired(CrmPermissionRole),
/// Tried to mutate a CRM company in a way that contradicts its
/// `hidden = true` state — currently raised when attempting to
/// re-enable `email_sync` on a hidden company.
diff --git a/crates/crm/src/domain/stages.rs b/crates/crm/src/domain/stages.rs
new file mode 100644
index 0000000000..7f75e147ac
--- /dev/null
+++ b/crates/crm/src/domain/stages.rs
@@ -0,0 +1,396 @@
+//! Team deal stages: the role-gated write path over the team's stage definition.
+
+use std::collections::{HashMap, HashSet};
+
+use entity_access::domain::models::MemberTeamRole;
+use uuid::Uuid;
+
+use crate::domain::{
+ auth::CrmTeamReceipt,
+ model::{CrmError, CrmTeamSettings, CrmTeamSettingsPatch},
+};
+
+#[cfg(test)]
+mod test;
+
+/// Name of the team-scoped stage definition; `Stage` is reserved by a trigger.
+pub const CRM_TEAM_STAGE_DEFINITION_NAME: &str = "Deal Stage";
+
+/// Maximum stages in one pipeline.
+pub const MAX_STAGES: usize = 50;
+
+/// Maximum stage label length.
+pub const MAX_STAGE_LABEL_CHARS: usize = 100;
+
+/// One stage of a team's custom pipeline.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TeamStage {
+ /// Property option id, stored on companies as their stage value.
+ pub id: Uuid,
+ /// Display label.
+ pub label: String,
+ /// Pipeline position.
+ pub display_order: i32,
+}
+
+/// A team's custom stage set.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TeamStageSet {
+ /// Team-scoped stage definition id.
+ pub definition_id: Uuid,
+ /// Stages in pipeline order.
+ pub stages: Vec<TeamStage>,
+}
+
+/// One requested stage: an existing id to keep, or `None` to add.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct StageInput {
+ /// Existing stage id, or `None` for a new stage.
+ pub id: Option<Uuid>,
+ /// Label after the update.
+ pub label: String,
+}
+
+/// A stage kept through a replace, with its label and position afterwards.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct StageRewrite {
+ /// The stage to keep.
+ pub id: Uuid,
+ /// Label after the replace.
+ pub label: String,
+ /// Position after the replace.
+ pub display_order: i32,
+}
+
+/// A stage added by a replace.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct StageInsert {
+ /// Label of the new stage.
+ pub label: String,
+ /// Position of the new stage.
+ pub display_order: i32,
+}
+
+/// A whole-set change to a team's stages, applied atomically.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct StageReplacePlan {
+ /// Stages to remove.
+ pub delete: Vec<Uuid>,
+ /// Stages to keep, renamed or moved.
+ pub rewrite: Vec<StageRewrite>,
+ /// Stages to add.
+ pub insert: Vec<StageInsert>,
+}
+
+/// Outbound port over the caller's team stage definition.
+pub trait StageDefinitionStore: Send + Sync + 'static {
+ /// The team's custom stage set, `None` on the system defaults.
+ fn get_team_stage_set(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ ) -> impl Future<Output = Result<Option<TeamStageSet>, CrmError>> + Send;
+
+ /// Create the definition with one option per label, in order, atomically.
+ fn create_team_stage_set(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ labels: &[String],
+ ) -> impl Future<Output = Result<TeamStageSet, CrmError>> + Send;
+
+ /// Apply a plan to an existing definition in one transaction.
+ fn replace_stages(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ definition_id: Uuid,
+ plan: StageReplacePlan,
+ ) -> impl Future<Output = Result<TeamStageSet, CrmError>> + Send;
+
+ /// Delete the definition and its options.
+ fn delete_team_stage_set(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ definition_id: Uuid,
+ ) -> impl Future<Output = Result<(), CrmError>> + Send;
+}
+
+/// The team's CRM settings, as the stage service needs them.
+pub trait TeamSettingsStore: Send + Sync + 'static {
+ /// The team's CRM settings, defaults when no row exists.
+ fn read_team_settings(
+ &self,
+ team_id: &Uuid,
+ ) -> impl Future<Output = Result<CrmTeamSettings, CrmError>> + Send;
+
+ /// Field-wise partial update of the team's CRM settings.
+ fn patch_team_settings(
+ &self,
+ team_id: &Uuid,
+ patch: &CrmTeamSettingsPatch,
+ ) -> impl Future<Output = Result<CrmTeamSettings, CrmError>> + Send;
+}
+
+/// Team stage mutations, gated on the team's `edit_stages_role`.
+pub trait CrmStageService: Send + Sync + 'static {
+ /// Replace the team's stage set; created on first use, diffed afterwards.
+ fn replace_stages(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ stages: Vec<StageInput>,
+ ) -> impl Future<Output = Result<TeamStageSet, CrmError>> + Send;
+
+ /// Delete the custom stage set; no-op on the defaults.
+ fn reset_stages(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ ) -> impl Future<Output = Result<(), CrmError>> + Send;
+}
+
+/// [`CrmStageService`] over team settings and a [`StageDefinitionStore`].
+#[derive(Clone, Debug)]
+pub struct CrmStageServiceImpl<TS, SD> {
+ team_settings: TS,
+ stage_definitions: SD,
+}
+
+impl<TS, SD> CrmStageServiceImpl<TS, SD>
+where
+ TS: TeamSettingsStore,
+ SD: StageDefinitionStore,
+{
+ /// Create the service.
+ pub fn new(team_settings: TS, stage_definitions: SD) -> Self {
+ Self {
+ team_settings,
+ stage_definitions,
+ }
+ }
+
+ async fn require_edit_stages_role(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ ) -> Result<CrmTeamSettings, CrmError> {
+ let settings = self
+ .team_settings
+ .read_team_settings(&access.team_id())
+ .await?;
+ if access.satisfies_permission_role(settings.edit_stages_role) {
+ Ok(settings)
+ } else {
+ Err(CrmError::StageEditRoleRequired(settings.edit_stages_role))
+ }
+ }
+
+ async fn prune_closed_stage_ids(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ settings: &CrmTeamSettings,
+ live: &[Uuid],
+ ) -> Result<(), CrmError> {
+ let Some(closed) = &settings.closed_stage_ids else {
+ return Ok(());
+ };
+ if closed.iter().all(|id| live.contains(id)) {
+ return Ok(());
+ }
+ let kept: Vec<Uuid> = closed
+ .iter()
+ .copied()
+ .filter(|id| live.contains(id))
+ .collect();
+ self.write_closed_stage_ids(access, Some(kept)).await
+ }
+
+ async fn clear_closed_stage_ids(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ settings: &CrmTeamSettings,
+ ) -> Result<(), CrmError> {
+ if settings.closed_stage_ids.is_none() {
+ return Ok(());
+ }
+ self.write_closed_stage_ids(access, None).await
+ }
+
+ async fn write_closed_stage_ids(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ closed: Option<Vec<Uuid>>,
+ ) -> Result<(), CrmError> {
+ let patch = CrmTeamSettingsPatch {
+ closed_stage_ids: Some(closed),
+ ..Default::default()
+ };
+ self.team_settings
+ .patch_team_settings(&access.team_id(), &patch)
+ .await?;
+ Ok(())
+ }
+}
+
+fn validate_stage_inputs(stages: Vec<StageInput>) -> Result<Vec<StageInput>, CrmError> {
+ if stages.is_empty() {
+ return Err(CrmError::InvalidRequest(
+ "at least one stage is required".into(),
+ ));
+ }
+ if stages.len() > MAX_STAGES {
+ return Err(CrmError::InvalidRequest(format!(
+ "a pipeline can have at most {MAX_STAGES} stages"
+ )));
+ }
+
+ let mut seen_labels = HashSet::with_capacity(stages.len());
+ let mut seen_ids = HashSet::with_capacity(stages.len());
+ let mut normalized = Vec::with_capacity(stages.len());
+ for stage in stages {
+ let label = stage.label.trim().to_string();
+ if label.is_empty() {
+ return Err(CrmError::InvalidRequest(
+ "stage labels must not be blank".into(),
+ ));
+ }
+ if label.chars().count() > MAX_STAGE_LABEL_CHARS {
+ return Err(CrmError::InvalidRequest(format!(
+ "stage labels must be at most {MAX_STAGE_LABEL_CHARS} characters"
+ )));
+ }
+ if !seen_labels.insert(label.to_lowercase()) {
+ return Err(CrmError::InvalidRequest(format!(
+ "duplicate stage label: {label}"
+ )));
+ }
+ if let Some(id) = stage.id
+ && !seen_ids.insert(id)
+ {
+ return Err(CrmError::InvalidRequest(format!(
+ "stage {id} appears more than once"
+ )));
+ }
+ normalized.push(StageInput {
+ id: stage.id,
+ label,
+ });
+ }
+ Ok(normalized)
+}
+
+impl<TS, SD> CrmStageService for CrmStageServiceImpl<TS, SD>
+where
+ TS: TeamSettingsStore,
+ SD: StageDefinitionStore,
+{
+ #[tracing::instrument(skip(self, access, stages), err)]
+ async fn replace_stages(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ stages: Vec<StageInput>,
+ ) -> Result<TeamStageSet, CrmError> {
+ let settings = self.require_edit_stages_role(access).await?;
+ let requested = validate_stage_inputs(stages)?;
+
+ let Some(current) = self.stage_definitions.get_team_stage_set(access).await? else {
+ if let Some(stage) = requested.iter().find(|stage| stage.id.is_some()) {
+ return Err(CrmError::InvalidRequest(format!(
+ "stage {} does not exist: the team has no custom stages yet",
+ stage.id.unwrap_or_default()
+ )));
+ }
+ let labels: Vec<String> = requested.into_iter().map(|stage| stage.label).collect();
+ let set = self
+ .stage_definitions
+ .create_team_stage_set(access, &labels)
+ .await?;
+ self.clear_closed_stage_ids(access, &settings).await?;
+ return Ok(set);
+ };
+
+ let existing: HashMap<Uuid, &TeamStage> = current
+ .stages
+ .iter()
+ .map(|stage| (stage.id, stage))
+ .collect();
+ if let Some(unknown) = requested
+ .iter()
+ .filter_map(|stage| stage.id)
+ .find(|id| !existing.contains_key(id))
+ {
+ return Err(CrmError::InvalidRequest(format!(
+ "stage {unknown} does not belong to the team's pipeline"
+ )));
+ }
+
+ let kept: HashSet<Uuid> = requested.iter().filter_map(|stage| stage.id).collect();
+ let mut plan = StageReplacePlan {
+ delete: current
+ .stages
+ .iter()
+ .map(|stage| stage.id)
+ .filter(|id| !kept.contains(id))
+ .collect(),
+ ..Default::default()
+ };
+ for (index, stage) in requested.into_iter().enumerate() {
+ let display_order = i32::try_from(index)
+ .map_err(|_| CrmError::InvalidRequest("too many stages".into()))?;
+ match stage.id {
+ Some(id) => {
+ let unchanged = existing.get(&id).is_some_and(|current| {
+ current.label == stage.label && current.display_order == display_order
+ });
+ if !unchanged {
+ plan.rewrite.push(StageRewrite {
+ id,
+ label: stage.label,
+ display_order,
+ });
+ }
+ }
+ None => plan.insert.push(StageInsert {
+ label: stage.label,
+ display_order,
+ }),
+ }
+ }
+
+ let set = if plan == StageReplacePlan::default() {
+ current
+ } else {
+ self.stage_definitions
+ .replace_stages(access, current.definition_id, plan)
+ .await?
+ };
+ let live: Vec<Uuid> = set.stages.iter().map(|stage| stage.id).collect();
+ self.prune_closed_stage_ids(access, &settings, &live)
+ .await?;
+ Ok(set)
+ }
+
+ #[tracing::instrument(skip(self, access), err)]
+ async fn reset_stages(&self, access: &CrmTeamReceipt<MemberTeamRole>) -> Result<(), CrmError> {
+ let settings = self.require_edit_stages_role(access).await?;
+ if let Some(current) = self.stage_definitions.get_team_stage_set(access).await? {
+ self.stage_definitions
+ .delete_team_stage_set(access, current.definition_id)
+ .await?;
+ }
+ self.clear_closed_stage_ids(access, &settings).await
+ }
+}
+
+/// [`CrmStageService`] that panics on every call.
+#[derive(Clone, Debug)]
+pub struct NoOpCrmStageService;
+
+impl CrmStageService for NoOpCrmStageService {
+ async fn replace_stages(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ _stages: Vec<StageInput>,
+ ) -> Result<TeamStageSet, CrmError> {
+ unimplemented!("NoOpCrmStageService.replace_stages")
+ }
+
+ async fn reset_stages(&self, _access: &CrmTeamReceipt<MemberTeamRole>) -> Result<(), CrmError> {
+ unimplemented!("NoOpCrmStageService.reset_stages")
+ }
+}
diff --git a/crates/crm/src/domain/stages/test.rs b/crates/crm/src/domain/stages/test.rs
new file mode 100644
index 0000000000..267276877b
--- /dev/null
+++ b/crates/crm/src/domain/stages/test.rs
@@ -0,0 +1,567 @@
+use std::sync::{Arc, Mutex};
+
+use entity_access::domain::models::{
+ Entity, EntityAccessReceipt, EntityPermission, EntityType, TeamRole,
+};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+
+use super::*;
+use crate::domain::model::CrmPermissionRole;
+
+#[derive(Clone, Default)]
+struct StubSettings {
+ settings: Arc<Mutex<CrmTeamSettings>>,
+ patches: Arc<Mutex<Vec<CrmTeamSettingsPatch>>>,
+}
+
+impl StubSettings {
+ fn requiring(role: CrmPermissionRole) -> Self {
+ let stub = Self::default();
+ stub.settings.lock().unwrap().edit_stages_role = role;
+ stub
+ }
+
+ fn with_closed(self, ids: Vec<Uuid>) -> Self {
+ self.settings.lock().unwrap().closed_stage_ids = Some(ids);
+ self
+ }
+
+ fn patches(&self) -> Vec<CrmTeamSettingsPatch> {
+ self.patches.lock().unwrap().clone()
+ }
+}
+
+impl TeamSettingsStore for StubSettings {
+ async fn read_team_settings(&self, _team_id: &Uuid) -> Result<CrmTeamSettings, CrmError> {
+ Ok(self.settings.lock().unwrap().clone())
+ }
+
+ async fn patch_team_settings(
+ &self,
+ _team_id: &Uuid,
+ patch: &CrmTeamSettingsPatch,
+ ) -> Result<CrmTeamSettings, CrmError> {
+ self.patches.lock().unwrap().push(patch.clone());
+ let mut settings = self.settings.lock().unwrap();
+ if let Some(closed) = &patch.closed_stage_ids {
+ settings.closed_stage_ids = closed.clone();
+ }
+ Ok(settings.clone())
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Write {
+ Create(Vec<String>),
+ Replace(StageReplacePlan),
+ DeleteSet,
+}
+
+#[derive(Clone, Default)]
+struct MemoryStore {
+ set: Arc<Mutex<Option<TeamStageSet>>>,
+ writes: Arc<Mutex<Vec<Write>>>,
+}
+
+impl MemoryStore {
+ fn customized(labels: &[&str]) -> Self {
+ let store = Self::default();
+ *store.set.lock().unwrap() = Some(TeamStageSet {
+ definition_id: Uuid::now_v7(),
+ stages: labels
+ .iter()
+ .enumerate()
+ .map(|(index, label)| TeamStage {
+ id: Uuid::now_v7(),
+ label: (*label).to_string(),
+ display_order: index as i32,
+ })
+ .collect(),
+ });
+ store
+ }
+
+ fn stage_ids(&self) -> Vec<Uuid> {
+ self.set
+ .lock()
+ .unwrap()
+ .as_ref()
+ .map(|set| set.stages.iter().map(|stage| stage.id).collect())
+ .unwrap_or_default()
+ }
+
+ fn writes(&self) -> Vec<Write> {
+ self.writes.lock().unwrap().clone()
+ }
+
+ fn record(&self, write: Write) {
+ self.writes.lock().unwrap().push(write);
+ }
+}
+
+impl StageDefinitionStore for MemoryStore {
+ async fn get_team_stage_set(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ ) -> Result<Option<TeamStageSet>, CrmError> {
+ Ok(self.set.lock().unwrap().clone().map(|mut set| {
+ set.stages.sort_by_key(|stage| stage.display_order);
+ set
+ }))
+ }
+
+ async fn create_team_stage_set(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ labels: &[String],
+ ) -> Result<TeamStageSet, CrmError> {
+ self.record(Write::Create(labels.to_vec()));
+ let set = TeamStageSet {
+ definition_id: Uuid::now_v7(),
+ stages: labels
+ .iter()
+ .enumerate()
+ .map(|(index, label)| TeamStage {
+ id: Uuid::now_v7(),
+ label: label.clone(),
+ display_order: index as i32,
+ })
+ .collect(),
+ };
+ *self.set.lock().unwrap() = Some(set.clone());
+ Ok(set)
+ }
+
+ async fn replace_stages(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ definition_id: Uuid,
+ plan: StageReplacePlan,
+ ) -> Result<TeamStageSet, CrmError> {
+ self.record(Write::Replace(plan.clone()));
+ let mut guard = self.set.lock().unwrap();
+ let set = guard.as_mut().expect("replace on missing set");
+ set.stages.retain(|stage| !plan.delete.contains(&stage.id));
+ for rewrite in &plan.rewrite {
+ let stage = set
+ .stages
+ .iter_mut()
+ .find(|stage| stage.id == rewrite.id)
+ .expect("rewrite of missing stage");
+ stage.label = rewrite.label.clone();
+ stage.display_order = rewrite.display_order;
+ }
+ for insert in &plan.insert {
+ set.stages.push(TeamStage {
+ id: Uuid::now_v7(),
+ label: insert.label.clone(),
+ display_order: insert.display_order,
+ });
+ }
+ set.stages.sort_by_key(|stage| stage.display_order);
+ assert_eq!(set.definition_id, definition_id);
+ Ok(set.clone())
+ }
+
+ async fn delete_team_stage_set(
+ &self,
+ _access: &CrmTeamReceipt<MemberTeamRole>,
+ _definition_id: Uuid,
+ ) -> Result<(), CrmError> {
+ self.record(Write::DeleteSet);
+ *self.set.lock().unwrap() = None;
+ Ok(())
+ }
+}
+
+fn service(
+ required: CrmPermissionRole,
+ store: MemoryStore,
+) -> CrmStageServiceImpl<StubSettings, MemoryStore> {
+ CrmStageServiceImpl::new(StubSettings::requiring(required), store)
+}
+
+fn receipt_with_role(role: TeamRole) -> CrmTeamReceipt<MemberTeamRole> {
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ CrmTeamReceipt::from_team_receipt(
+ EntityAccessReceipt::<MemberTeamRole>::try_new_authenticated_user(
+ user,
+ Entity {
+ entity_id: Uuid::now_v7().to_string(),
+ entity_type: EntityType::Team,
+ },
+ EntityPermission::TeamRole { role },
+ )
+ .unwrap(),
+ )
+ .unwrap()
+}
+
+fn new_stage(label: &str) -> StageInput {
+ StageInput {
+ id: None,
+ label: label.to_string(),
+ }
+}
+
+fn keep(id: Uuid, label: &str) -> StageInput {
+ StageInput {
+ id: Some(id),
+ label: label.to_string(),
+ }
+}
+
+fn labels(set: &TeamStageSet) -> Vec<&str> {
+ set.stages
+ .iter()
+ .map(|stage| stage.label.as_str())
+ .collect()
+}
+
+#[tokio::test]
+async fn member_cannot_edit_stages_when_admin_required() {
+ let store = MemoryStore::default();
+ let err = service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Member),
+ vec![new_stage("Lead")],
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ err,
+ CrmError::StageEditRoleRequired(CrmPermissionRole::Admin)
+ ));
+ assert!(store.writes().is_empty());
+}
+
+#[tokio::test]
+async fn admin_cannot_edit_stages_when_owner_required() {
+ let store = MemoryStore::default();
+ let err = service(CrmPermissionRole::Owner, store.clone())
+ .replace_stages(&receipt_with_role(TeamRole::Admin), vec![new_stage("Lead")])
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ err,
+ CrmError::StageEditRoleRequired(CrmPermissionRole::Owner)
+ ));
+ assert!(store.writes().is_empty());
+}
+
+#[tokio::test]
+async fn owner_satisfies_every_threshold() {
+ for required in [CrmPermissionRole::Admin, CrmPermissionRole::Owner] {
+ let store = MemoryStore::default();
+ service(required, store)
+ .replace_stages(&receipt_with_role(TeamRole::Owner), vec![new_stage("Lead")])
+ .await
+ .unwrap();
+ }
+}
+
+#[tokio::test]
+async fn reset_is_gated_the_same_way() {
+ let store = MemoryStore::customized(&["Lead"]);
+ let err = service(CrmPermissionRole::Admin, store.clone())
+ .reset_stages(&receipt_with_role(TeamRole::Member))
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::StageEditRoleRequired(_)));
+ assert!(store.writes().is_empty());
+}
+
+#[tokio::test]
+async fn uncustomized_team_gets_a_definition_seeded_in_order() {
+ let store = MemoryStore::default();
+ let set = service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![
+ new_stage(" Lead "),
+ new_stage("Demo"),
+ new_stage("Customer"),
+ ],
+ )
+ .await
+ .unwrap();
+ assert_eq!(labels(&set), ["Lead", "Demo", "Customer"]);
+ assert_eq!(
+ store.writes(),
+ [Write::Create(vec![
+ "Lead".into(),
+ "Demo".into(),
+ "Customer".into()
+ ])]
+ );
+}
+
+#[tokio::test]
+async fn uncustomized_team_rejects_stage_ids() {
+ let store = MemoryStore::default();
+ let err = service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![keep(Uuid::now_v7(), "Lead")],
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)));
+ assert!(store.writes().is_empty());
+}
+
+#[tokio::test]
+async fn customized_team_is_diffed_not_recreated() {
+ let store = MemoryStore::customized(&["Lead", "Demo", "Customer", "Churned"]);
+ let [lead, demo, customer, churned] = store.stage_ids()[..] else {
+ panic!("expected four seeded stages");
+ };
+
+ let set = service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![
+ keep(lead, "Lead"),
+ keep(customer, "Customer"),
+ keep(demo, "Demo call"),
+ new_stage("Renewal"),
+ ],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(labels(&set), ["Lead", "Customer", "Demo call", "Renewal"]);
+ assert_eq!(
+ store.writes(),
+ [Write::Replace(StageReplacePlan {
+ delete: vec![churned],
+ rewrite: vec![
+ StageRewrite {
+ id: customer,
+ label: "Customer".into(),
+ display_order: 1,
+ },
+ StageRewrite {
+ id: demo,
+ label: "Demo call".into(),
+ display_order: 2,
+ },
+ ],
+ insert: vec![StageInsert {
+ label: "Renewal".into(),
+ display_order: 3,
+ }],
+ })]
+ );
+}
+
+#[tokio::test]
+async fn swapping_two_labels_is_one_plan() {
+ let store = MemoryStore::customized(&["Lead", "Demo"]);
+ let [lead, demo] = store.stage_ids()[..] else {
+ panic!("expected two seeded stages");
+ };
+ let set = service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![keep(lead, "Demo"), keep(demo, "Lead")],
+ )
+ .await
+ .unwrap();
+ assert_eq!(labels(&set), ["Demo", "Lead"]);
+ assert_eq!(set.stages[0].id, lead);
+ assert_eq!(store.writes().len(), 1);
+}
+
+#[tokio::test]
+async fn deleting_a_closed_stage_prunes_the_closed_set() {
+ let store = MemoryStore::customized(&["Lead", "Won", "Lost"]);
+ let [lead, won, lost] = store.stage_ids()[..] else {
+ panic!("expected three seeded stages");
+ };
+ let settings = StubSettings::requiring(CrmPermissionRole::Admin).with_closed(vec![won, lost]);
+ CrmStageServiceImpl::new(settings.clone(), store)
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![keep(lead, "Lead"), keep(won, "Won")],
+ )
+ .await
+ .unwrap();
+ let patches = settings.patches();
+ assert_eq!(patches.len(), 1);
+ assert_eq!(patches[0].closed_stage_ids, Some(Some(vec![won])));
+}
+
+#[tokio::test]
+async fn an_identical_put_still_prunes_stale_closed_ids() {
+ let store = MemoryStore::customized(&["Lead", "Won"]);
+ let [lead, won] = store.stage_ids()[..] else {
+ panic!("expected two seeded stages");
+ };
+ let settings =
+ StubSettings::requiring(CrmPermissionRole::Admin).with_closed(vec![won, Uuid::now_v7()]);
+ CrmStageServiceImpl::new(settings.clone(), store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![keep(lead, "Lead"), keep(won, "Won")],
+ )
+ .await
+ .unwrap();
+ assert!(store.writes().is_empty());
+ assert_eq!(
+ settings.patches()[0].closed_stage_ids,
+ Some(Some(vec![won]))
+ );
+}
+
+#[tokio::test]
+async fn deleting_the_last_closed_stage_keeps_an_explicit_empty_set() {
+ let store = MemoryStore::customized(&["Lead", "Won"]);
+ let [lead, won] = store.stage_ids()[..] else {
+ panic!("expected two seeded stages");
+ };
+ let settings = StubSettings::requiring(CrmPermissionRole::Admin).with_closed(vec![won]);
+ CrmStageServiceImpl::new(settings.clone(), store)
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![keep(lead, "Lead")],
+ )
+ .await
+ .unwrap();
+ assert_eq!(settings.patches()[0].closed_stage_ids, Some(Some(vec![])));
+}
+
+#[tokio::test]
+async fn customizing_clears_closed_ids_that_pointed_at_the_defaults() {
+ let store = MemoryStore::default();
+ let settings =
+ StubSettings::requiring(CrmPermissionRole::Admin).with_closed(vec![Uuid::now_v7()]);
+ CrmStageServiceImpl::new(settings.clone(), store)
+ .replace_stages(&receipt_with_role(TeamRole::Admin), vec![new_stage("Lead")])
+ .await
+ .unwrap();
+ assert_eq!(settings.patches()[0].closed_stage_ids, Some(None));
+}
+
+#[tokio::test]
+async fn reset_on_defaults_still_clears_a_stale_closed_set() {
+ let store = MemoryStore::default();
+ let settings =
+ StubSettings::requiring(CrmPermissionRole::Admin).with_closed(vec![Uuid::now_v7()]);
+ CrmStageServiceImpl::new(settings.clone(), store)
+ .reset_stages(&receipt_with_role(TeamRole::Admin))
+ .await
+ .unwrap();
+ assert_eq!(settings.patches()[0].closed_stage_ids, Some(None));
+}
+
+#[tokio::test]
+async fn deleting_an_unclosed_stage_leaves_settings_alone() {
+ let store = MemoryStore::customized(&["Lead", "Won"]);
+ let [lead, won] = store.stage_ids()[..] else {
+ panic!("expected two seeded stages");
+ };
+ let settings = StubSettings::requiring(CrmPermissionRole::Admin).with_closed(vec![won]);
+ CrmStageServiceImpl::new(settings.clone(), store)
+ .replace_stages(&receipt_with_role(TeamRole::Admin), vec![keep(won, "Won")])
+ .await
+ .unwrap();
+ let _ = lead;
+ assert!(settings.patches().is_empty());
+}
+
+#[tokio::test]
+async fn reset_clears_the_closed_set() {
+ let store = MemoryStore::customized(&["Lead", "Won"]);
+ let [_, won] = store.stage_ids()[..] else {
+ panic!("expected two seeded stages");
+ };
+ let settings = StubSettings::requiring(CrmPermissionRole::Admin).with_closed(vec![won]);
+ CrmStageServiceImpl::new(settings.clone(), store)
+ .reset_stages(&receipt_with_role(TeamRole::Admin))
+ .await
+ .unwrap();
+ assert_eq!(settings.patches()[0].closed_stage_ids, Some(None));
+}
+
+#[tokio::test]
+async fn unchanged_stages_are_not_rewritten() {
+ let store = MemoryStore::customized(&["Lead", "Demo"]);
+ let [lead, demo] = store.stage_ids()[..] else {
+ panic!("expected two seeded stages");
+ };
+ service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![keep(lead, "Lead"), keep(demo, "Demo")],
+ )
+ .await
+ .unwrap();
+ assert!(store.writes().is_empty());
+}
+
+#[tokio::test]
+async fn foreign_stage_id_is_rejected_before_any_write() {
+ let store = MemoryStore::customized(&["Lead"]);
+ let [lead] = store.stage_ids()[..] else {
+ panic!("expected one seeded stage");
+ };
+ let err = service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(
+ &receipt_with_role(TeamRole::Admin),
+ vec![keep(lead, "Lead"), keep(Uuid::now_v7(), "Stranger")],
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)));
+ assert!(store.writes().is_empty());
+}
+
+#[tokio::test]
+async fn invalid_sets_are_rejected() {
+ let too_many: Vec<StageInput> = (0..=MAX_STAGES)
+ .map(|index| new_stage(&format!("Stage {index}")))
+ .collect();
+ let too_long = "x".repeat(MAX_STAGE_LABEL_CHARS + 1);
+ let repeated = Uuid::now_v7();
+ let cases: Vec<Vec<StageInput>> = vec![
+ vec![],
+ vec![new_stage(" ")],
+ vec![new_stage("Lead"), new_stage("lead")],
+ vec![new_stage(&too_long)],
+ vec![keep(repeated, "A"), keep(repeated, "B")],
+ too_many,
+ ];
+ for stages in cases {
+ let store = MemoryStore::default();
+ let err = service(CrmPermissionRole::Admin, store.clone())
+ .replace_stages(&receipt_with_role(TeamRole::Owner), stages)
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "{err:?}");
+ assert!(store.writes().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn reset_deletes_the_definition() {
+ let store = MemoryStore::customized(&["Lead"]);
+ service(CrmPermissionRole::Admin, store.clone())
+ .reset_stages(&receipt_with_role(TeamRole::Admin))
+ .await
+ .unwrap();
+ assert_eq!(store.writes(), [Write::DeleteSet]);
+ assert!(store.stage_ids().is_empty());
+}
+
+#[tokio::test]
+async fn reset_on_defaults_is_a_no_op() {
+ let store = MemoryStore::default();
+ service(CrmPermissionRole::Admin, store.clone())
+ .reset_stages(&receipt_with_role(TeamRole::Admin))
+ .await
+ .unwrap();
+ assert!(store.writes().is_empty());
+}
diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rs
index a88a61bec1..ec34c52d8c 100644
--- a/crates/crm/src/inbound/axum_extractors/test.rs
+++ b/crates/crm/src/inbound/axum_extractors/test.rs
@@ -535,12 +535,17 @@ fn test_router(
macro_authorization::NoBotAuthorizer,
macro_authorization::NoUserApiKeyAuthorizer,
);
- let state: CrmRouterState<FakeCrmService, FakeEntityAccessService, TestAuthorizationService> =
- CrmRouterState {
- service: Arc::new(crm_service.clone()),
- entity_access_service: Arc::new(entity_access.clone()),
- authorization_state: MacroAuthorizationState::new(Arc::new(authorization_service)),
- };
+ let state: CrmRouterState<
+ FakeCrmService,
+ (),
+ FakeEntityAccessService,
+ TestAuthorizationService,
+ > = CrmRouterState {
+ service: Arc::new(crm_service.clone()),
+ stage_service: Arc::new(()),
+ entity_access_service: Arc::new(entity_access.clone()),
+ authorization_state: MacroAuthorizationState::new(Arc::new(authorization_service)),
+ };
let router = Router::new()
.route("/companies/{company_id}", get(company_handler))
.route("/company-without-id/{other_id}", get(company_handler))
diff --git a/crates/crm/src/inbound/axum_router.rs b/crates/crm/src/inbound/axum_router.rs
index a3fe6147f7..fb1be54185 100644
--- a/crates/crm/src/inbound/axum_router.rs
+++ b/crates/crm/src/inbound/axum_router.rs
@@ -44,6 +44,9 @@ pub mod comments;
/// team saved views).
pub mod team_settings;
+/// The team's deal stage set, gated on `edit_stages_role`.
+pub mod stages;
+
use std::sync::Arc;
use axum::{
@@ -57,27 +60,29 @@ use entity_access::domain::ports::EntityAccessService;
use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
use model_error_response::ErrorResponse;
-use crate::domain::{model::CrmError, service::CrmService};
+use crate::domain::{model::CrmError, service::CrmService, stages::CrmStageService};
/// Router state for the CRM endpoints, including service-backed authorization
/// for direct user credentials and internal service access.
-pub struct CrmRouterState<C, Eas, Auth> {
+pub struct CrmRouterState<C, St, Eas, Auth> {
/// CRM service.
pub service: Arc<C>,
+ /// Team deal stage service.
+ pub stage_service: Arc<St>,
/// Entity access service used by the team-scoped extractors.
pub entity_access_service: Arc<Eas>,
/// State used to authorize direct users and internal service callers.
pub authorization_state: MacroAuthorizationState<Auth>,
}
-impl<C, Eas, Auth> FromRef<CrmRouterState<C, Eas, Auth>> for Arc<Eas> {
- fn from_ref(state: &CrmRouterState<C, Eas, Auth>) -> Self {
+impl<C, St, Eas, Auth> FromRef<CrmRouterState<C, St, Eas, Auth>> for Arc<Eas> {
+ fn from_ref(state: &CrmRouterState<C, St, Eas, Auth>) -> Self {
state.entity_access_service.clone()
}
}
-impl<C, Eas, Auth> FromRef<CrmRouterState<C, Eas, Auth>> for MacroAuthorizationState<Auth> {
- fn from_ref(state: &CrmRouterState<C, Eas, Auth>) -> Self {
+impl<C, St, Eas, Auth> FromRef<CrmRouterState<C, St, Eas, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &CrmRouterState<C, St, Eas, Auth>) -> Self {
state.authorization_state.clone()
}
}
@@ -97,17 +102,18 @@ impl<C> Clone for CrmServiceRef<C> {
}
}
-impl<C, Eas, Auth> FromRef<CrmRouterState<C, Eas, Auth>> for CrmServiceRef<C> {
- fn from_ref(state: &CrmRouterState<C, Eas, Auth>) -> Self {
+impl<C, St, Eas, Auth> FromRef<CrmRouterState<C, St, Eas, Auth>> for CrmServiceRef<C> {
+ fn from_ref(state: &CrmRouterState<C, St, Eas, Auth>) -> Self {
CrmServiceRef(state.service.clone())
}
}
-// Manual Clone so C, Eas, and Auth don't need Clone.
-impl<C, Eas, Auth> Clone for CrmRouterState<C, Eas, Auth> {
+// Manual Clone so C, St, Eas, and Auth don't need Clone.
+impl<C, St, Eas, Auth> Clone for CrmRouterState<C, St, Eas, Auth> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
+ stage_service: self.stage_service.clone(),
entity_access_service: self.entity_access_service.clone(),
authorization_state: self.authorization_state.clone(),
}
@@ -115,66 +121,75 @@ impl<C, Eas, Auth> Clone for CrmRouterState<C, Eas, Auth> {
}
/// Build the CRM router with all endpoints.
-pub fn crm_router<C, Eas, Auth, S>(state: CrmRouterState<C, Eas, Auth>) -> Router<S>
+pub fn crm_router<C, St, Eas, Auth, S>(state: CrmRouterState<C, St, Eas, Auth>) -> Router<S>
where
C: CrmService,
+ St: CrmStageService,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
S: Send + Sync + 'static,
{
Router::new()
- .route("/companies", post(create_company::handler::<C, Eas, Auth>))
+ .route(
+ "/companies",
+ post(create_company::handler::<C, St, Eas, Auth>),
+ )
.route(
"/companies/{company_id}/email-sync",
- put(set_email_sync::handler::<C, Eas, Auth>),
+ put(set_email_sync::handler::<C, St, Eas, Auth>),
)
.route(
"/companies/{company_id}/hidden",
- put(set_company_hidden::handler::<C, Eas, Auth>),
+ put(set_company_hidden::handler::<C, St, Eas, Auth>),
)
.route(
"/companies/{company_id}/name",
- put(set_company_name::handler::<C, Eas, Auth>),
+ put(set_company_name::handler::<C, St, Eas, Auth>),
)
.route(
"/companies/{company_id}",
- get(get_company::handler::<C, Eas, Auth>),
+ get(get_company::handler::<C, St, Eas, Auth>),
)
.route(
"/companies/{company_id}/contacts",
- get(list_company_contacts::handler::<C, Eas, Auth>)
- .post(create_contact::handler::<C, Eas, Auth>),
+ get(list_company_contacts::handler::<C, St, Eas, Auth>)
+ .post(create_contact::handler::<C, St, Eas, Auth>),
)
.route(
"/contacts/by-email",
- get(get_contact_by_email::handler::<C, Eas, Auth>),
+ get(get_contact_by_email::handler::<C, St, Eas, Auth>),
)
.route(
"/contacts/{contact_id}",
- get(get_contact::handler::<C, Eas, Auth>),
+ get(get_contact::handler::<C, St, Eas, Auth>),
)
.route(
"/contacts/{contact_id}/hidden",
- put(set_contact_hidden::handler::<C, Eas, Auth>),
+ put(set_contact_hidden::handler::<C, St, Eas, Auth>),
)
.route(
"/contacts/{contact_id}/name",
- put(set_contact_name::handler::<C, Eas, Auth>),
+ put(set_contact_name::handler::<C, St, Eas, Auth>),
)
.route(
"/comments/{entity_type}/{entity_id}",
- get(comments::list_handler::<C, Eas, Auth>)
- .post(comments::create_handler::<C, Eas, Auth>),
+ get(comments::list_handler::<C, St, Eas, Auth>)
+ .post(comments::create_handler::<C, St, Eas, Auth>),
)
.route(
"/comment/{comment_id}",
- patch(comments::edit_handler::<C, Eas, Auth>)
- .delete(comments::delete_handler::<C, Eas, Auth>),
+ patch(comments::edit_handler::<C, St, Eas, Auth>)
+ .delete(comments::delete_handler::<C, St, Eas, Auth>),
)
.route(
"/settings",
- get(team_settings::get_handler::<C, Eas, Auth>)
- .put(team_settings::update_handler::<C, Eas, Auth>),
+ get(team_settings::get_handler::<C, St, Eas, Auth>)
+ .put(team_settings::update_handler::<C, St, Eas, Auth>),
+ )
+ .route(
+ "/stages",
+ put(stages::replace_handler::<C, St, Eas, Auth>)
+ .delete(stages::reset_handler::<C, St, Eas, Auth>),
)
.with_state(state)
}
@@ -232,6 +247,16 @@ impl IntoResponse for CrmError {
.into(),
}),
),
+ CrmError::StageEditRoleRequired(role) => (
+ StatusCode::FORBIDDEN,
+ Json(ErrorResponse {
+ message: format!(
+ "editing deal stages requires the {} team role",
+ role.as_db_str()
+ )
+ .into(),
+ }),
+ ),
CrmError::CompanyHidden => (
StatusCode::CONFLICT,
Json(ErrorResponse {
diff --git a/crates/crm/src/inbound/axum_router/comments.rs b/crates/crm/src/inbound/axum_router/comments.rs
index c3e48fa7d2..8e87b0ce14 100644
--- a/crates/crm/src/inbound/axum_router/comments.rs
+++ b/crates/crm/src/inbound/axum_router/comments.rs
@@ -86,11 +86,12 @@ pub struct EditCrmCommentRequest {
#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
pub async fn list_handler<
C: CrmService,
+ St,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
>(
access: EntityPermissionExtractor<Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
) -> Result<Json<Vec<CrmCommentThread>>, CrmError> {
let (team_id, team_role) = owning_team_for_entity(&state, &access).await?;
@@ -124,11 +125,12 @@ pub async fn list_handler<
#[tracing::instrument(skip_all, err, fields(entity_id = %entity_id))]
pub async fn create_handler<
C: CrmService,
+ St,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
>(
access: EntityPermissionExtractor<Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path((_entity_type, entity_id)): Path<(CrmCommentEntityType, Uuid)>,
Json(req): Json<CreateCrmCommentRequest>,
) -> Result<Json<CrmCommentThread>, CrmError> {
@@ -182,11 +184,12 @@ pub async fn create_handler<
#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
pub async fn edit_handler<
C: CrmService,
+ St,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
>(
access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(comment_id): Path<Uuid>,
Json(req): Json<EditCrmCommentRequest>,
) -> Result<Json<CrmComment>, CrmError> {
@@ -225,11 +228,12 @@ pub async fn edit_handler<
#[tracing::instrument(skip_all, err, fields(comment_id = %comment_id))]
pub async fn delete_handler<
C: CrmService,
+ St,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
>(
access: CrmCommentAccessLevelExtractor<ViewAccessLevel, C, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(comment_id): Path<Uuid>,
) -> Result<Json<DeleteCrmCommentResult>, CrmError> {
let result = state
@@ -248,10 +252,11 @@ pub async fn delete_handler<
/// than a real authorization miss.
async fn owning_team_for_entity<
C: CrmService,
+ St,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
>(
- state: &CrmRouterState<C, Eas, Auth>,
+ state: &CrmRouterState<C, St, Eas, Auth>,
access: &EntityPermissionExtractor<Eas, Auth>,
) -> Result<(Uuid, TeamRole), CrmError> {
let user_id = access
diff --git a/crates/crm/src/inbound/axum_router/create_company.rs b/crates/crm/src/inbound/axum_router/create_company.rs
index 5e0d2a724f..7d1e8b1ff8 100644
--- a/crates/crm/src/inbound/axum_router/create_company.rs
+++ b/crates/crm/src/inbound/axum_router/create_company.rs
@@ -44,9 +44,14 @@ pub struct CreateCrmCompanyRequest {
),
)]
#[tracing::instrument(skip_all, err)]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Json(req): Json<CreateCrmCompanyRequest>,
) -> Result<Json<CrmCompanyResponse>, CrmError> {
let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
diff --git a/crates/crm/src/inbound/axum_router/create_contact.rs b/crates/crm/src/inbound/axum_router/create_contact.rs
index b87b2a600f..dc68196f4f 100644
--- a/crates/crm/src/inbound/axum_router/create_contact.rs
+++ b/crates/crm/src/inbound/axum_router/create_contact.rs
@@ -52,9 +52,14 @@ pub struct CreateCrmContactRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(company_id): Path<Uuid>,
Json(req): Json<CreateCrmContactRequest>,
) -> Result<Json<CrmContactResponse>, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/get_company.rs b/crates/crm/src/inbound/axum_router/get_company.rs
index e03b637753..d0059bee20 100644
--- a/crates/crm/src/inbound/axum_router/get_company.rs
+++ b/crates/crm/src/inbound/axum_router/get_company.rs
@@ -126,9 +126,14 @@ impl From<CrmCompanyWithContacts> for CrmCompanyResponse {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(company_id): Path<Uuid>,
) -> Result<Json<CrmCompanyResponse>, CrmError> {
let record = state
diff --git a/crates/crm/src/inbound/axum_router/get_contact.rs b/crates/crm/src/inbound/axum_router/get_contact.rs
index 6a77ebd06c..c997612c91 100644
--- a/crates/crm/src/inbound/axum_router/get_contact.rs
+++ b/crates/crm/src/inbound/axum_router/get_contact.rs
@@ -34,9 +34,14 @@ use super::{CrmRouterState, list_company_contacts::CrmContactResponse};
),
)]
#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmContactAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(contact_id): Path<Uuid>,
) -> Result<Json<CrmContactResponse>, CrmError> {
let contact = state
diff --git a/crates/crm/src/inbound/axum_router/get_contact_by_email.rs b/crates/crm/src/inbound/axum_router/get_contact_by_email.rs
index bc466e42d4..973d22aecf 100644
--- a/crates/crm/src/inbound/axum_router/get_contact_by_email.rs
+++ b/crates/crm/src/inbound/axum_router/get_contact_by_email.rs
@@ -47,9 +47,14 @@ pub struct GetContactByEmailResponse {
),
)]
#[tracing::instrument(skip_all, err, fields(email = %params.email))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Query(params): Query<GetContactByEmailParams>,
) -> Result<Json<GetContactByEmailResponse>, CrmError> {
let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
diff --git a/crates/crm/src/inbound/axum_router/list_company_contacts.rs b/crates/crm/src/inbound/axum_router/list_company_contacts.rs
index af8b48eaa7..00a3b2decd 100644
--- a/crates/crm/src/inbound/axum_router/list_company_contacts.rs
+++ b/crates/crm/src/inbound/axum_router/list_company_contacts.rs
@@ -83,9 +83,14 @@ impl From<CrmContact> for CrmContactResponse {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(company_id): Path<Uuid>,
) -> Result<Json<Vec<CrmContactResponse>>, CrmError> {
let contacts = state
diff --git a/crates/crm/src/inbound/axum_router/set_company_hidden.rs b/crates/crm/src/inbound/axum_router/set_company_hidden.rs
index a63c9a1886..65a75cc4f5 100644
--- a/crates/crm/src/inbound/axum_router/set_company_hidden.rs
+++ b/crates/crm/src/inbound/axum_router/set_company_hidden.rs
@@ -52,9 +52,14 @@ pub struct SetCompanyHiddenRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id, hidden = req.hidden))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(company_id): Path<Uuid>,
Json(req): Json<SetCompanyHiddenRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/set_company_name.rs b/crates/crm/src/inbound/axum_router/set_company_name.rs
index d67fbfd408..51467ce33d 100644
--- a/crates/crm/src/inbound/axum_router/set_company_name.rs
+++ b/crates/crm/src/inbound/axum_router/set_company_name.rs
@@ -49,9 +49,14 @@ pub struct SetCompanyNameRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmCompanyAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(company_id): Path<Uuid>,
Json(req): Json<SetCompanyNameRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/set_contact_hidden.rs b/crates/crm/src/inbound/axum_router/set_contact_hidden.rs
index 545bb076de..1aa55e2815 100644
--- a/crates/crm/src/inbound/axum_router/set_contact_hidden.rs
+++ b/crates/crm/src/inbound/axum_router/set_contact_hidden.rs
@@ -44,9 +44,14 @@ pub struct SetContactHiddenRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id, hidden = req.hidden))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmContactAccessLevelExtractor<EditAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(contact_id): Path<Uuid>,
Json(req): Json<SetContactHiddenRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/set_contact_name.rs b/crates/crm/src/inbound/axum_router/set_contact_name.rs
index db8a8d5bb8..9f05efe6d6 100644
--- a/crates/crm/src/inbound/axum_router/set_contact_name.rs
+++ b/crates/crm/src/inbound/axum_router/set_contact_name.rs
@@ -48,9 +48,14 @@ pub struct SetContactNameRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(contact_id = %contact_id))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmContactAccessLevelExtractor<ViewAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(contact_id): Path<Uuid>,
Json(req): Json<SetContactNameRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/set_email_sync.rs b/crates/crm/src/inbound/axum_router/set_email_sync.rs
index 24cbc90c01..522d19aa60 100644
--- a/crates/crm/src/inbound/axum_router/set_email_sync.rs
+++ b/crates/crm/src/inbound/axum_router/set_email_sync.rs
@@ -49,9 +49,14 @@ pub struct SetEmailSyncRequest {
),
)]
#[tracing::instrument(skip_all, err, fields(company_id = %company_id, email_sync = req.email_sync))]
-pub async fn handler<C: CrmService, Eas: EntityAccessService, Auth: MacroAuthorizationService>(
+pub async fn handler<
+ C: CrmService,
+ St,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
access: CrmCompanyAccessLevelExtractor<EditAccessLevel, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Path(company_id): Path<Uuid>,
Json(req): Json<SetEmailSyncRequest>,
) -> Result<StatusCode, CrmError> {
diff --git a/crates/crm/src/inbound/axum_router/stages.rs b/crates/crm/src/inbound/axum_router/stages.rs
new file mode 100644
index 0000000000..f51bc3467e
--- /dev/null
+++ b/crates/crm/src/inbound/axum_router/stages.rs
@@ -0,0 +1,134 @@
+use axum::{Json, extract::State, http::StatusCode};
+use entity_access::{
+ domain::{models::MemberTeamRole, ports::EntityAccessService},
+ inbound::axum_extractors::MacroUserTeamExtractorV2,
+};
+use macro_authorization::MacroAuthorizationService;
+use model_error_response::ErrorResponse;
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+use crate::domain::{
+ auth::CrmTeamReceipt,
+ model::CrmError,
+ stages::{CrmStageService, StageInput, TeamStageSet},
+};
+
+use super::CrmRouterState;
+
+/// One stage in a `PUT /crm/stages` body.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct CrmStageInput {
+ /// Existing stage to keep; omit to add one.
+ #[serde(default)]
+ pub id: Option<Uuid>,
+ /// Label after the update; non-blank and unique within the set.
+ pub label: String,
+}
+
+/// Request body for `PUT /crm/stages`: the whole stage set in order.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct ReplaceCrmStagesRequest {
+ /// Stages first to last.
+ pub stages: Vec<CrmStageInput>,
+}
+
+/// One stage of the team's custom pipeline.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct CrmStageResponse {
+ /// Property option id companies carry as their stage value.
+ pub id: Uuid,
+ /// Label.
+ pub label: String,
+}
+
+/// The team's custom stage set.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct CrmStagesResponse {
+ /// Team-scoped stage definition id.
+ pub definition_id: Uuid,
+ /// Stages in pipeline order.
+ pub stages: Vec<CrmStageResponse>,
+}
+
+impl From<TeamStageSet> for CrmStagesResponse {
+ fn from(set: TeamStageSet) -> Self {
+ Self {
+ definition_id: set.definition_id,
+ stages: set
+ .stages
+ .into_iter()
+ .map(|stage| CrmStageResponse {
+ id: stage.id,
+ label: stage.label,
+ })
+ .collect(),
+ }
+ }
+}
+
+/// Replace the team's deal stages; requires `edit_stages_role` (403 otherwise).
+#[utoipa::path(
+ put,
+ path = "/crm/stages",
+ operation_id = "put_crm_team_stages",
+ request_body = ReplaceCrmStagesRequest,
+ responses(
+ (status = 200, body = CrmStagesResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn replace_handler<
+ C,
+ St: CrmStageService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
+ Json(req): Json<ReplaceCrmStagesRequest>,
+) -> Result<Json<CrmStagesResponse>, CrmError> {
+ let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
+ let stages = req
+ .stages
+ .into_iter()
+ .map(|stage| StageInput {
+ id: stage.id,
+ label: stage.label,
+ })
+ .collect();
+ let set = state.stage_service.replace_stages(&receipt, stages).await?;
+ Ok(Json(set.into()))
+}
+
+/// Reset the team's deal stages to the defaults; gated like `PUT /crm/stages`.
+#[utoipa::path(
+ delete,
+ path = "/crm/stages",
+ operation_id = "reset_crm_team_stages",
+ responses(
+ (status = 204),
+ (status = 401, body = ErrorResponse),
+ (status = 403, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ ),
+)]
+#[tracing::instrument(skip_all, err)]
+pub async fn reset_handler<
+ C,
+ St: CrmStageService,
+ Eas: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
+) -> Result<StatusCode, CrmError> {
+ let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
+ state.stage_service.reset_stages(&receipt).await?;
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/crates/crm/src/inbound/axum_router/team_settings.rs b/crates/crm/src/inbound/axum_router/team_settings.rs
index b169ba7cc0..1a85a6369d 100644
--- a/crates/crm/src/inbound/axum_router/team_settings.rs
+++ b/crates/crm/src/inbound/axum_router/team_settings.rs
@@ -111,11 +111,12 @@ impl From<UpdateCrmTeamSettingsRequest> for CrmTeamSettingsPatch {
#[tracing::instrument(skip_all, err)]
pub async fn get_handler<
C: CrmService,
+ St,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
>(
access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
) -> Result<Json<CrmTeamSettingsResponse>, CrmError> {
let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
let settings = state.service.get_team_settings(&receipt).await?;
@@ -144,11 +145,12 @@ pub async fn get_handler<
#[tracing::instrument(skip_all, err)]
pub async fn update_handler<
C: CrmService,
+ St,
Eas: EntityAccessService,
Auth: MacroAuthorizationService,
>(
access: MacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,
- State(state): State<CrmRouterState<C, Eas, Auth>>,
+ State(state): State<CrmRouterState<C, St, Eas, Auth>>,
Json(req): Json<UpdateCrmTeamSettingsRequest>,
) -> Result<Json<CrmTeamSettingsResponse>, CrmError> {
let receipt = CrmTeamReceipt::from_team_receipt(access.entity_access_receipt)?;
diff --git a/crates/crm/src/inbound/toolset.rs b/crates/crm/src/inbound/toolset.rs
index ae0408c382..fc6838a5be 100644
--- a/crates/crm/src/inbound/toolset.rs
+++ b/crates/crm/src/inbound/toolset.rs
@@ -29,7 +29,10 @@ use serde::Serialize;
use system_properties::{StageOption, SystemPropertyKey};
use uuid::Uuid;
-use crate::domain::{auth::CrmTeamReceipt, model::CrmError, service::CrmService};
+use crate::domain::{
+ auth::CrmTeamReceipt, model::CrmError, service::CrmService,
+ stages::CRM_TEAM_STAGE_DEFINITION_NAME,
+};
pub use get_company::{GetCompany, GetCompanyResponse};
pub use list_companies::{ListCompanies, ListCompaniesResponse};
@@ -191,7 +194,7 @@ where
let mut team_stage_definition_ids = Vec::new();
for def in defs {
let is_stage_definition = def.definition.id == SystemPropertyKey::STAGE_UUID
- || (def.definition.display_name.eq_ignore_ascii_case("stage")
+ || (def.definition.display_name == CRM_TEAM_STAGE_DEFINITION_NAME
&& matches!(
def.definition.data_type,
DataType::SelectString | DataType::SelectNumber
@@ -262,7 +265,7 @@ pub(crate) fn extract_company_crm_props(
let is_system_stage = definition_id == SystemPropertyKey::STAGE_UUID;
let is_team_stage = !is_system_stage
&& (stages.team_stage_definition_ids.contains(&definition_id)
- || prop.definition.display_name.eq_ignore_ascii_case("stage"));
+ || prop.definition.display_name == CRM_TEAM_STAGE_DEFINITION_NAME);
let slot = if is_system_stage {
&mut system_stage
} else if is_team_stage {
@@ -386,6 +389,10 @@ pub(crate) fn crm_error(err: CrmError) -> ToolCallError {
"CRM contact not found for the caller's team".to_string()
}
CrmError::InvalidRequest(msg) => msg.clone(),
+ CrmError::StageEditRoleRequired(role) => format!(
+ "editing deal stages requires the {} team role",
+ role.as_db_str()
+ ),
_ => "CRM request failed".to_string(),
};
diff --git a/crates/crm/src/outbound.rs b/crates/crm/src/outbound.rs
index 83bef2a03a..9d37243c43 100644
--- a/crates/crm/src/outbound.rs
+++ b/crates/crm/src/outbound.rs
@@ -10,6 +10,9 @@ pub mod no_op_resolver;
/// Postgres implementation of the CRM search repository
#[cfg(feature = "search")]
pub mod search_repo;
+/// Properties-service implementation of the team stage definition store
+#[cfg(feature = "outbound")]
+pub mod stage_definitions;
/// Unfurl-backed implementation of the company metadata resolver
#[cfg(feature = "outbound")]
pub mod unfurl_resolver;
diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rs
index e7250bd17a..0bcfd3f1d7 100644
--- a/crates/crm/src/outbound/companies_repo.rs
+++ b/crates/crm/src/outbound/companies_repo.rs
@@ -1,7 +1,7 @@
//! Implementation of [`CompaniesRepository`] backed by MacroDB.
#[cfg(test)]
-mod test;
+pub(crate) mod test;
use crate::domain::{
comment::{
@@ -13,6 +13,7 @@ use crate::domain::{
CrmDomain, CrmDomainStatus, CrmError, CrmPermissionRole, CrmScopePrecheck, CrmTeamSettings,
CrmTeamSettingsPatch, DepopulateContactOutcome, DomainMetadata,
},
+ stages::TeamSettingsStore,
};
use chrono::{DateTime, Utc};
use serde_json::Value;
@@ -2492,3 +2493,17 @@ async fn fetch_comments_for_threads(
})
.collect())
}
+
+impl TeamSettingsStore for CompaniesRepositoryImpl {
+ async fn read_team_settings(&self, team_id: &Uuid) -> Result<CrmTeamSettings, CrmError> {
+ self.get_team_settings(team_id).await
+ }
+
+ async fn patch_team_settings(
+ &self,
+ team_id: &Uuid,
+ patch: &CrmTeamSettingsPatch,
+ ) -> Result<CrmTeamSettings, CrmError> {
+ self.update_team_settings(team_id, patch).await
+ }
+}
diff --git a/crates/crm/src/outbound/companies_repo/test.rs b/crates/crm/src/outbound/companies_repo/test.rs
index 8e51462f24..24a5a7e44a 100644
--- a/crates/crm/src/outbound/companies_repo/test.rs
+++ b/crates/crm/src/outbound/companies_repo/test.rs
@@ -4,7 +4,7 @@
//! closely-related cluster of methods, e.g. all CRM comment operations
//! in [`comments`]).
-mod helpers;
+pub(crate) mod helpers;
mod comments;
mod create_company;
diff --git a/crates/crm/src/outbound/companies_repo/test/helpers.rs b/crates/crm/src/outbound/companies_repo/test/helpers.rs
index f1e613bbdb..a4f9158941 100644
--- a/crates/crm/src/outbound/companies_repo/test/helpers.rs
+++ b/crates/crm/src/outbound/companies_repo/test/helpers.rs
@@ -1,7 +1,7 @@
use sqlx::PgPool;
use uuid::Uuid;
-pub(super) async fn seed_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> sqlx::Result<()> {
+pub(crate) async fn seed_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> sqlx::Result<()> {
let macro_user_id = Uuid::now_v7();
sqlx::query(
diff --git a/crates/crm/src/outbound/stage_definitions.rs b/crates/crm/src/outbound/stage_definitions.rs
new file mode 100644
index 0000000000..3501f52dfb
--- /dev/null
+++ b/crates/crm/src/outbound/stage_definitions.rs
@@ -0,0 +1,231 @@
+//! [`StageDefinitionStore`] over the properties domain service.
+
+use std::sync::Arc;
+
+use entity_access::domain::models::MemberTeamRole;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_properties::api::{
+ CreatePropertyDefinitionRequest, CreatePropertyScope, PropertyDataType, SelectStringOption,
+};
+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;
+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};
+use models_properties::{DataType, PropertyOwner};
+use properties::domain::model::{
+ PropertyOptionInsert, PropertyOptionReplacePlan, PropertyOptionRewrite,
+};
+use properties::{PropertiesErr, PropertiesService};
+use uuid::Uuid;
+
+use crate::domain::{
+ auth::CrmTeamReceipt,
+ model::CrmError,
+ stages::{
+ CRM_TEAM_STAGE_DEFINITION_NAME, StageDefinitionStore, StageReplacePlan, TeamStage,
+ TeamStageSet,
+ },
+};
+
+#[cfg(test)]
+mod test;
+
+/// Properties-backed [`StageDefinitionStore`].
+#[derive(Debug)]
+pub struct PropertiesStageDefinitionStore<P> {
+ properties: Arc<P>,
+}
+
+impl<P> Clone for PropertiesStageDefinitionStore<P> {
+ fn clone(&self) -> Self {
+ Self {
+ properties: self.properties.clone(),
+ }
+ }
+}
+
+impl<P: PropertiesService> PropertiesStageDefinitionStore<P> {
+ /// Wrap a properties service.
+ pub fn new(properties: Arc<P>) -> Self {
+ Self { properties }
+ }
+}
+
+fn is_team_stage_definition(definition: &PropertyDefinitionWithOptions) -> bool {
+ let definition = &definition.definition;
+ definition.display_name == CRM_TEAM_STAGE_DEFINITION_NAME
+ && definition.data_type == DataType::SelectString
+ && !definition.is_multi_select
+ && !definition.is_system
+ && matches!(definition.owner, PropertyOwner::Team { .. })
+}
+
+fn stage_from_option(option: &PropertyOption) -> Option<TeamStage> {
+ let PropertyOptionValue::String(label) = &option.value else {
+ return None;
+ };
+ Some(TeamStage {
+ id: option.id,
+ label: label.clone(),
+ display_order: option.display_order,
+ })
+}
+
+fn stage_set_from_definition(definition: PropertyDefinitionWithOptions) -> TeamStageSet {
+ let mut stages: Vec<TeamStage> = definition
+ .property_options
+ .iter()
+ .filter_map(stage_from_option)
+ .collect();
+ stages.sort_by_key(|stage| stage.display_order);
+ TeamStageSet {
+ definition_id: definition.definition.id,
+ stages,
+ }
+}
+
+fn acting_user(
+ access: &CrmTeamReceipt<MemberTeamRole>,
+) -> Result<&MacroUserIdStr<'static>, CrmError> {
+ access.receipt().acting_user_id().ok_or_else(|| {
+ CrmError::InvalidRequest("editing deal stages requires an authenticated user".into())
+ })
+}
+
+fn is_unique_violation(err: &anyhow::Error) -> bool {
+ err.chain().any(|cause| {
+ matches!(
+ cause.downcast_ref::<sqlx::Error>(),
+ Some(sqlx::Error::Database(db_err)) if db_err.is_unique_violation()
+ )
+ })
+}
+
+fn stage_store_error(err: PropertiesErr) -> CrmError {
+ match err {
+ PropertiesErr::DuplicateOptionValue => {
+ CrmError::InvalidRequest("a stage with that label already exists".into())
+ }
+ PropertiesErr::Repo(err) if is_unique_violation(&err) => {
+ CrmError::InvalidRequest("a stage with that label already exists".into())
+ }
+ PropertiesErr::Validation(message) => CrmError::InvalidRequest(message),
+ PropertiesErr::NotFound | PropertiesErr::OptionNotFound => {
+ CrmError::InvalidRequest("stage not found for the team".into())
+ }
+ other => CrmError::StorageLayerError(other.into()),
+ }
+}
+
+impl<P: PropertiesService> StageDefinitionStore for PropertiesStageDefinitionStore<P> {
+ #[tracing::instrument(skip_all, err)]
+ async fn get_team_stage_set(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ ) -> Result<Option<TeamStageSet>, CrmError> {
+ let definitions = self
+ .properties
+ .list_property_definitions_with_options(Some(access.receipt()), None, false, None)
+ .await
+ .map_err(stage_store_error)?;
+ Ok(definitions
+ .into_iter()
+ .find(is_team_stage_definition)
+ .map(stage_set_from_definition))
+ }
+
+ #[tracing::instrument(skip_all, err)]
+ async fn create_team_stage_set(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ labels: &[String],
+ ) -> Result<TeamStageSet, CrmError> {
+ let user = acting_user(access)?;
+ let request = CreatePropertyDefinitionRequest {
+ scope: CreatePropertyScope::Team,
+ display_name: CRM_TEAM_STAGE_DEFINITION_NAME.to_string(),
+ data_type: PropertyDataType::SelectString {
+ multi: false,
+ options: labels
+ .iter()
+ .enumerate()
+ .map(|(index, label)| SelectStringOption {
+ display_order: index as i32,
+ value: label.clone(),
+ })
+ .collect(),
+ },
+ };
+ let definition = self
+ .properties
+ .create_property_definition(user, Some(access.receipt()), &request)
+ .await
+ .map_err(stage_store_error)?;
+ let options = self
+ .properties
+ .get_property_options(definition.id, user, Some(access.receipt()))
+ .await
+ .map_err(stage_store_error)?;
+ let mut stages: Vec<TeamStage> = options.iter().filter_map(stage_from_option).collect();
+ stages.sort_by_key(|stage| stage.display_order);
+ Ok(TeamStageSet {
+ definition_id: definition.id,
+ stages,
+ })
+ }
+
+ #[tracing::instrument(skip_all, err)]
+ async fn replace_stages(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ definition_id: Uuid,
+ plan: StageReplacePlan,
+ ) -> Result<TeamStageSet, CrmError> {
+ let plan = PropertyOptionReplacePlan {
+ delete: plan.delete,
+ rewrite: plan
+ .rewrite
+ .into_iter()
+ .map(|stage| PropertyOptionRewrite {
+ option_id: stage.id,
+ value: PropertyOptionValue::String(stage.label),
+ display_order: stage.display_order,
+ })
+ .collect(),
+ insert: plan
+ .insert
+ .into_iter()
+ .map(|stage| PropertyOptionInsert {
+ value: PropertyOptionValue::String(stage.label),
+ display_order: stage.display_order,
+ })
+ .collect(),
+ };
+ let options = self
+ .properties
+ .replace_property_options(
+ acting_user(access)?,
+ Some(access.receipt()),
+ definition_id,
+ plan,
+ )
+ .await
+ .map_err(stage_store_error)?;
+ let mut stages: Vec<TeamStage> = options.iter().filter_map(stage_from_option).collect();
+ stages.sort_by_key(|stage| stage.display_order);
+ Ok(TeamStageSet {
+ definition_id,
+ stages,
+ })
+ }
+
+ #[tracing::instrument(skip_all, err)]
+ async fn delete_team_stage_set(
+ &self,
+ access: &CrmTeamReceipt<MemberTeamRole>,
+ definition_id: Uuid,
+ ) -> Result<(), CrmError> {
+ self.properties
+ .delete_property_definition(definition_id, acting_user(access)?, Some(access.receipt()))
+ .await
+ .map_err(stage_store_error)
+ }
+}
diff --git a/crates/crm/src/outbound/stage_definitions/test.rs b/crates/crm/src/outbound/stage_definitions/test.rs
new file mode 100644
index 0000000000..8f2f7bef56
--- /dev/null
+++ b/crates/crm/src/outbound/stage_definitions/test.rs
@@ -0,0 +1,340 @@
+use std::sync::Arc;
+
+use entity_access::domain::models::EntityType as AccessEntityType;
+use entity_access::domain::models::{
+ Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole, TeamRole,
+};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use properties::domain::model::TaskAssignedNotification;
+use properties::domain::model::{EditReceipt, ViewReceipt};
+use properties::{NotificationService, PermissionService, PropertiesPgRepo, PropertiesServiceImpl};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::*;
+use crate::domain::stages::{StageInsert, StageRewrite};
+use crate::outbound::companies_repo::test::helpers::seed_team;
+
+struct NoPermissions;
+
+impl PermissionService for NoPermissions {
+ type Err = anyhow::Error;
+
+ async fn mint_view_receipt<'a>(
+ &self,
+ _user_id: Option<&'a MacroUserIdStr<'a>>,
+ _entity_id: &str,
+ _entity_type: AccessEntityType,
+ ) -> Result<ViewReceipt, Self::Err> {
+ unimplemented!("stage definitions never mint view receipts")
+ }
+
+ async fn mint_edit_receipt<'a>(
+ &self,
+ _user_id: &MacroUserIdStr<'a>,
+ _entity_id: &str,
+ _entity_type: AccessEntityType,
+ ) -> Result<EditReceipt, Self::Err> {
+ unimplemented!("stage definitions never mint edit receipts")
+ }
+
+ async fn grant_permissions_to_task<'a>(
+ &self,
+ _user_ids: &[MacroUserIdStr<'a>],
+ _task_id: &str,
+ ) -> Result<(), Self::Err> {
+ unimplemented!("stage definitions never grant task permissions")
+ }
+}
+
+struct NoNotifications;
+
+impl NotificationService for NoNotifications {
+ type Err = anyhow::Error;
+
+ async fn send_task_assigned<'a>(
+ &self,
+ _notification: TaskAssignedNotification<'a>,
+ ) -> Result<(), Self::Err> {
+ unimplemented!("stage definitions never notify")
+ }
+}
+
+type Store = PropertiesStageDefinitionStore<
+ PropertiesServiceImpl<PropertiesPgRepo, NoPermissions, NoNotifications>,
+>;
+
+fn store(pool: &PgPool) -> Store {
+ PropertiesStageDefinitionStore::new(Arc::new(PropertiesServiceImpl::new(
+ PropertiesPgRepo::new(pool.clone()),
+ None::<NoPermissions>,
+ None::<NoNotifications>,
+ )))
+}
+
+async fn team_receipt(pool: &PgPool, email: &str) -> CrmTeamReceipt<MemberTeamRole> {
+ let team_id = Uuid::now_v7();
+ seed_team(pool, team_id, email).await.expect("seed team");
+ let user = MacroUserIdStr::parse_from_str(email).unwrap().into_owned();
+ CrmTeamReceipt::from_team_receipt(
+ EntityAccessReceipt::<MemberTeamRole>::try_new_authenticated_user(
+ user,
+ Entity {
+ entity_id: team_id.to_string(),
+ entity_type: EntityType::Team,
+ },
+ EntityPermission::TeamRole {
+ role: TeamRole::Admin,
+ },
+ )
+ .unwrap(),
+ )
+ .unwrap()
+}
+
+fn labels(set: &TeamStageSet) -> Vec<&str> {
+ set.stages
+ .iter()
+ .map(|stage| stage.label.as_str())
+ .collect()
+}
+
+fn owned(labels: &[&str]) -> Vec<String> {
+ labels.iter().map(|label| (*label).to_string()).collect()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_without_definition_has_no_stage_set(pool: PgPool) {
+ let access = team_receipt(&pool, "macro|[email protected]").await;
+ assert_eq!(
+ store(&pool).get_team_stage_set(&access).await.unwrap(),
+ None
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_seeds_options_in_order_and_reads_back(pool: PgPool) {
+ let access = team_receipt(&pool, "macro|[email protected]").await;
+ let store = store(&pool);
+
+ let created = store
+ .create_team_stage_set(&access, &owned(&["Lead", "Demo", "Customer"]))
+ .await
+ .unwrap();
+ assert_eq!(labels(&created), ["Lead", "Demo", "Customer"]);
+ assert_eq!(
+ created
+ .stages
+ .iter()
+ .map(|stage| stage.display_order)
+ .collect::<Vec<_>>(),
+ [0, 1, 2]
+ );
+
+ let read = store.get_team_stage_set(&access).await.unwrap();
+ assert_eq!(read, Some(created));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn replace_applies_delete_rewrite_and_insert_together(pool: PgPool) {
+ let access = team_receipt(&pool, "macro|[email protected]").await;
+ let store = store(&pool);
+ let set = store
+ .create_team_stage_set(&access, &owned(&["Lead", "Demo", "Churned"]))
+ .await
+ .unwrap();
+ let [lead, demo, churned] = [set.stages[0].id, set.stages[1].id, set.stages[2].id];
+
+ let replaced = store
+ .replace_stages(
+ &access,
+ set.definition_id,
+ StageReplacePlan {
+ delete: vec![churned],
+ rewrite: vec![
+ StageRewrite {
+ id: demo,
+ label: "Demo call".into(),
+ display_order: 0,
+ },
+ StageRewrite {
+ id: lead,
+ label: "Lead".into(),
+ display_order: 1,
+ },
+ ],
+ insert: vec![StageInsert {
+ label: "Renewal".into(),
+ display_order: 2,
+ }],
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(labels(&replaced), ["Demo call", "Lead", "Renewal"]);
+ assert_eq!(replaced.stages[0].id, demo);
+ assert_eq!(replaced.stages[1].id, lead);
+ assert_eq!(
+ store.get_team_stage_set(&access).await.unwrap(),
+ Some(replaced)
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn two_stages_can_trade_labels(pool: PgPool) {
+ let access = team_receipt(&pool, "macro|[email protected]").await;
+ let store = store(&pool);
+ let set = store
+ .create_team_stage_set(&access, &owned(&["Lead", "Demo"]))
+ .await
+ .unwrap();
+ let [lead, demo] = [set.stages[0].id, set.stages[1].id];
+ let replaced = store
+ .replace_stages(
+ &access,
+ set.definition_id,
+ StageReplacePlan {
+ rewrite: vec![
+ StageRewrite {
+ id: lead,
+ label: "Demo".into(),
+ display_order: 0,
+ },
+ StageRewrite {
+ id: demo,
+ label: "Lead".into(),
+ display_order: 1,
+ },
+ ],
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(labels(&replaced), ["Demo", "Lead"]);
+ assert_eq!(replaced.stages[0].id, lead);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn duplicate_label_rolls_back_the_whole_plan(pool: PgPool) {
+ let access = team_receipt(&pool, "macro|[email protected]").await;
+ let store = store(&pool);
+ let set = store
+ .create_team_stage_set(&access, &owned(&["Lead", "Demo"]))
+ .await
+ .unwrap();
+ let err = store
+ .replace_stages(
+ &access,
+ set.definition_id,
+ StageReplacePlan {
+ delete: vec![set.stages[1].id],
+ insert: vec![StageInsert {
+ label: "Lead".into(),
+ display_order: 1,
+ }],
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "{err:?}");
+ assert_eq!(
+ labels(&store.get_team_stage_set(&access).await.unwrap().unwrap()),
+ ["Lead", "Demo"]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn duplicate_label_is_a_client_error(pool: PgPool) {
+ let access = team_receipt(&pool, "macro|[email protected]").await;
+ let store = store(&pool);
+ let set = store
+ .create_team_stage_set(&access, &owned(&["Lead"]))
+ .await
+ .unwrap();
+ let err = store
+ .replace_stages(
+ &access,
+ set.definition_id,
+ StageReplacePlan {
+ insert: vec![StageInsert {
+ label: "Lead".into(),
+ display_order: 1,
+ }],
+ ..Default::default()
+ },
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "{err:?}");
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn delete_set_returns_team_to_defaults(pool: PgPool) {
+ let access = team_receipt(&pool, "macro|[email protected]").await;
+ let store = store(&pool);
+ let set = store
+ .create_team_stage_set(&access, &owned(&["Lead"]))
+ .await
+ .unwrap();
+ store
+ .delete_team_stage_set(&access, set.definition_id)
+ .await
+ .unwrap();
+ assert_eq!(store.get_team_stage_set(&access).await.unwrap(), None);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn another_team_cannot_see_or_touch_the_set(pool: PgPool) {
+ let owner = team_receipt(&pool, "macro|[email protected]").await;
+ let stranger = team_receipt(&pool, "macro|[email protected]").await;
+ let store = store(&pool);
+ let set = store
+ .create_team_stage_set(&owner, &owned(&["Lead"]))
+ .await
+ .unwrap();
+
+ assert_eq!(store.get_team_stage_set(&stranger).await.unwrap(), None);
+ assert!(
+ store
+ .replace_stages(
+ &stranger,
+ set.definition_id,
+ StageReplacePlan {
+ insert: vec![StageInsert {
+ label: "Intruder".into(),
+ display_order: 1,
+ }],
+ ..Default::default()
+ },
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ store
+ .delete_team_stage_set(&stranger, set.definition_id)
+ .await
+ .is_err()
+ );
+ assert_eq!(
+ labels(&store.get_team_stage_set(&owner).await.unwrap().unwrap()),
+ ["Lead"]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn internal_receipt_cannot_write(pool: PgPool) {
+ let team_id = Uuid::now_v7();
+ seed_team(&pool, team_id, "macro|[email protected]")
+ .await
+ .unwrap();
+ let access = CrmTeamReceipt::<MemberTeamRole>::dangerously_internal(team_id);
+ let err = store(&pool)
+ .create_team_stage_set(&access, &owned(&["Lead"]))
+ .await
+ .unwrap_err();
+ assert!(matches!(err, CrmError::InvalidRequest(_)), "{err:?}");
+}
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index e074bbbdbb..8a757947fb 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -313,6 +313,48 @@ pub enum EntityOptionUpdateOutcome {
},
}
+/// One option to rewrite in place during a replace.
+#[derive(Debug, Clone, PartialEq)]
+pub struct PropertyOptionRewrite {
+ /// The option to rewrite; keeps its id.
+ pub option_id: Uuid,
+ /// Value after the replace.
+ pub value: PropertyOptionValue,
+ /// Display order after the replace.
+ pub display_order: i32,
+}
+
+/// One option to create during a replace.
+#[derive(Debug, Clone, PartialEq)]
+pub struct PropertyOptionInsert {
+ /// Value of the new option.
+ pub value: PropertyOptionValue,
+ /// Display order of the new option.
+ pub display_order: i32,
+}
+
+/// A whole-set change to a definition's options, applied in one transaction.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct PropertyOptionReplacePlan {
+ /// Options to delete, stripping their ids from entity values.
+ pub delete: Vec<Uuid>,
+ /// Options to rewrite in place.
+ pub rewrite: Vec<PropertyOptionRewrite>,
+ /// Options to create.
+ pub insert: Vec<PropertyOptionInsert>,
+}
+
+/// Outcome of a whole-set option replace.
+#[derive(Debug, Clone)]
+pub enum PropertyOptionReplaceOutcome {
+ /// Every change applied; carries the definition's options afterwards.
+ Replaced(Vec<PropertyOption>),
+ /// An option to delete or rewrite does not belong to the definition.
+ OptionNotFound,
+ /// Two options would share a value; nothing was applied.
+ DuplicateValue,
+}
+
/// Outcome of an in-place property option update.
#[derive(Debug, Clone)]
pub enum UpdatePropertyOptionOutcome {
diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rs
index db9e9cf68b..a1b8252f40 100644
--- a/crates/properties/src/domain/ports.rs
+++ b/crates/properties/src/domain/ports.rs
@@ -23,8 +23,9 @@ use uuid::Uuid;
use super::model::{
EditReceipt, EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
EntityPropertyOptionSelection, EntityPropertyOptionUpdate, GetOrCreateTagDefinitionResult,
- PropertyDefinitionOwner, TagPromotionOutcome, TagRemapOutcome, TaskAssignedNotification,
- UpdatePropertyOptionOutcome, ViewReceipt,
+ PropertyDefinitionOwner, PropertyOptionReplaceOutcome, PropertyOptionReplacePlan,
+ TagPromotionOutcome, TagRemapOutcome, TaskAssignedNotification, UpdatePropertyOptionOutcome,
+ ViewReceipt,
};
/// Repository trait for property operations.
@@ -131,6 +132,15 @@ pub trait PropertiesRepo: Send + Sync + 'static {
display_order: i32,
) -> impl Future<Output = Result<UpdatePropertyOptionOutcome, Self::Err>> + Send;
+ /// Apply a whole-set option change in one transaction: deletes (stripping
+ /// ids from entity values), in-place rewrites, then inserts. Rewrites go
+ /// through temporary values so a set of options can trade values.
+ fn replace_property_options(
+ &self,
+ property_definition_id: Uuid,
+ plan: &PropertyOptionReplacePlan,
+ ) -> impl Future<Output = Result<PropertyOptionReplaceOutcome, Self::Err>> + Send;
+
/// Delete a property option and strip its id from every entity value that
/// references it, atomically. Returns `true` if the option was deleted,
/// `false` if it didn't exist.
diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rs
index 6123ae17c3..c8f8466218 100644
--- a/crates/properties/src/domain/service.rs
+++ b/crates/properties/src/domain/service.rs
@@ -28,7 +28,8 @@ use uuid::Uuid;
use super::error::PropertiesErr;
use super::model::{
EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyOptionSelection,
- EntityPropertyOptionUpdate, PropertyTargetKey, TagScope, TagSet, ViewReceipt,
+ EntityPropertyOptionUpdate, PropertyOptionReplacePlan, PropertyTargetKey, TagScope, TagSet,
+ ViewReceipt,
};
/// The caller's team-membership proof, used to scope definition/option/tag
@@ -227,6 +228,19 @@ pub trait PropertiesService: Send + Sync + 'static {
request: &UpdatePropertyOptionRequest,
) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;
+ /// Apply a whole-set option change on a `SelectString` property owned by
+ /// the caller, in one transaction. Fails with
+ /// [`PropertiesErr::OptionNotFound`] when a deleted or rewritten option is
+ /// not on the definition and [`PropertiesErr::DuplicateOptionValue`] when
+ /// two options would share a value; neither partially applies.
+ fn replace_property_options(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ property_definition_id: Uuid,
+ plan: PropertyOptionReplacePlan,
+ ) -> impl Future<Output = Result<Vec<PropertyOption>, PropertiesErr>> + Send;
+
/// Delete a property option on a property owned by the caller, stripping
/// its id from every entity value that references it.
fn delete_property_option(
diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rs
index 3cfb1496e5..dcc1bc9965 100644
--- a/crates/properties/src/domain/service_impl.rs
+++ b/crates/properties/src/domain/service_impl.rs
@@ -41,8 +41,9 @@ use super::metadata;
use super::model::{
EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyOptionSelection,
EntityPropertyOptionUpdate, PropertyAccessReceiptExt, PropertyDefinitionOwner,
- PropertyTargetKey, ResolvedPropertySubject, TagPromotionOutcome, TagRemapOutcome, TagScope,
- TagSet, UpdatePropertyOptionOutcome, ViewReceipt,
+ PropertyOptionReplaceOutcome, PropertyOptionReplacePlan, PropertyTargetKey,
+ ResolvedPropertySubject, TagPromotionOutcome, TagRemapOutcome, TagScope, TagSet,
+ UpdatePropertyOptionOutcome, ViewReceipt,
};
use super::ports::{NotificationService, PermissionService, PropertiesRepo};
use super::service::{PropertiesService, TeamReceipt, team_id_from_receipt};
@@ -1345,6 +1346,79 @@ where
}
}
+ #[tracing::instrument(skip(self, team, plan), err)]
+ async fn replace_property_options(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ property_definition_id: Uuid,
+ plan: PropertyOptionReplacePlan,
+ ) -> Result<Vec<PropertyOption>, PropertiesErr> {
+ let definition = self
+ .owned_modifiable_definition(
+ property_definition_id,
+ user_id,
+ team_id_from_receipt(team),
+ )
+ .await?;
+ if definition.data_type != DataType::SelectString {
+ return Err(PropertiesErr::Validation(
+ "option replacement is only supported for string select properties".to_string(),
+ ));
+ }
+ let values = plan
+ .rewrite
+ .iter()
+ .map(|rewrite| &rewrite.value)
+ .chain(plan.insert.iter().map(|insert| &insert.value));
+ for value in values {
+ match value {
+ PropertyOptionValue::String(text) if !text.trim().is_empty() => {}
+ _ => {
+ return Err(PropertiesErr::Validation(
+ "option values must be non-empty strings".to_string(),
+ ));
+ }
+ }
+ }
+
+ let before = self
+ .repository
+ .get_property_options(property_definition_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ let after = match self
+ .repository
+ .replace_property_options(property_definition_id, &plan)
+ .await
+ .map_err(anyhow::Error::from)?
+ {
+ PropertyOptionReplaceOutcome::Replaced(options) => options,
+ PropertyOptionReplaceOutcome::OptionNotFound => {
+ return Err(PropertiesErr::OptionNotFound);
+ }
+ PropertyOptionReplaceOutcome::DuplicateValue => {
+ return Err(PropertiesErr::DuplicateOptionValue);
+ }
+ };
+
+ for option in before.iter().filter(|o| plan.delete.contains(&o.id)) {
+ self.publish_property_event(Self::property_option_deleted_event(option, user_id));
+ }
+ for option in &after {
+ let event = if plan.rewrite.iter().any(|r| r.option_id == option.id) {
+ Self::property_option_updated_event(option, user_id)
+ } else if before.iter().any(|o| o.id == option.id) {
+ continue;
+ } else {
+ Self::property_option_created_event(option, user_id)
+ };
+ self.publish_property_event(event);
+ }
+ Ok(after)
+ }
+
#[tracing::instrument(skip(self, team), err)]
async fn delete_property_option(
&self,
diff --git a/crates/properties/src/outbound/options_test.rs b/crates/properties/src/outbound/options_test.rs
index 2630d7a71d..4007540adb 100644
--- a/crates/properties/src/outbound/options_test.rs
+++ b/crates/properties/src/outbound/options_test.rs
@@ -1,7 +1,10 @@
//! Integration tests for property option and tag operations on PropertiesPgRepo.
use super::properties_pg_repo::PropertiesPgRepo;
-use crate::domain::model::{PropertyDefinitionOwner, UpdatePropertyOptionOutcome};
+use crate::domain::model::{
+ PropertyDefinitionOwner, PropertyOptionInsert, PropertyOptionReplaceOutcome,
+ PropertyOptionReplacePlan, PropertyOptionRewrite, UpdatePropertyOptionOutcome,
+};
use crate::domain::ports::PropertiesRepo;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use models_properties::service::property_option::PropertyOptionValue;
@@ -437,3 +440,233 @@ async fn get_or_create_tag_definition_coexists_with_same_named_property(
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+)]
+async fn replace_property_options_applies_the_plan_in_one_pass(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let low = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();
+ let medium = PRIORITY_OPTION_MEDIUM.parse::<Uuid>().unwrap();
+ let high = PRIORITY_OPTION_HIGH.parse::<Uuid>().unwrap();
+ let urgent = PRIORITY_OPTION_URGENT.parse::<Uuid>().unwrap();
+
+ repo.upsert_entity_property(
+ "doc_replace",
+ EntityType::Document,
+ property_id,
+ Some(PropertyValue::SelectOption(vec![low, urgent])),
+ )
+ .await?;
+
+ let outcome = repo
+ .replace_property_options(
+ property_id,
+ &PropertyOptionReplacePlan {
+ delete: vec![urgent],
+ rewrite: vec![
+ PropertyOptionRewrite {
+ option_id: low,
+ value: PropertyOptionValue::String("High".to_string()),
+ display_order: 0,
+ },
+ PropertyOptionRewrite {
+ option_id: high,
+ value: PropertyOptionValue::String("Low".to_string()),
+ display_order: 2,
+ },
+ ],
+ insert: vec![PropertyOptionInsert {
+ value: PropertyOptionValue::String("Blocked".to_string()),
+ display_order: 3,
+ }],
+ },
+ )
+ .await?;
+
+ let PropertyOptionReplaceOutcome::Replaced(options) = outcome else {
+ panic!("expected Replaced, got {outcome:?}");
+ };
+ let labels: Vec<(Uuid, String)> = options
+ .iter()
+ .map(|o| {
+ let PropertyOptionValue::String(s) = &o.value else {
+ panic!("string option")
+ };
+ (o.id, s.clone())
+ })
+ .collect();
+ assert_eq!(labels[0], (low, "High".to_string()));
+ assert_eq!(labels[1], (medium, "Medium".to_string()));
+ assert_eq!(labels[2], (high, "Low".to_string()));
+ assert_eq!(labels[3].1, "Blocked");
+ assert_eq!(options.len(), 4);
+
+ let raw: serde_json::Value = sqlx::query_scalar!(
+ r#"
+ SELECT values as "values!: serde_json::Value"
+ FROM entity_properties
+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
+ "#,
+ "doc_replace",
+ EntityType::Document as EntityType,
+ property_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ let stored: PropertyValue = serde_json::from_value(raw)?;
+ assert_eq!(stored, PropertyValue::SelectOption(vec![low]));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+)]
+async fn replace_property_options_strips_every_deleted_id(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let low = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();
+ let medium = PRIORITY_OPTION_MEDIUM.parse::<Uuid>().unwrap();
+ let urgent = PRIORITY_OPTION_URGENT.parse::<Uuid>().unwrap();
+
+ repo.upsert_entity_property(
+ "doc_multi_delete",
+ EntityType::Document,
+ property_id,
+ Some(PropertyValue::SelectOption(vec![low, medium, urgent])),
+ )
+ .await?;
+
+ let outcome = repo
+ .replace_property_options(
+ property_id,
+ &PropertyOptionReplacePlan {
+ delete: vec![medium, urgent],
+ ..Default::default()
+ },
+ )
+ .await?;
+
+ let PropertyOptionReplaceOutcome::Replaced(options) = outcome else {
+ panic!("expected Replaced, got {outcome:?}");
+ };
+ assert_eq!(options.len(), 2);
+ assert!(options.iter().all(|o| o.id != medium && o.id != urgent));
+
+ let raw: serde_json::Value = sqlx::query_scalar!(
+ r#"
+ SELECT values as "values!: serde_json::Value"
+ FROM entity_properties
+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
+ "#,
+ "doc_multi_delete",
+ EntityType::Document as EntityType,
+ property_id
+ )
+ .fetch_one(&pool)
+ .await?;
+ let stored: PropertyValue = serde_json::from_value(raw)?;
+ assert_eq!(stored, PropertyValue::SelectOption(vec![low]));
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+)]
+async fn replace_property_options_rejects_duplicates_within_the_batch(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let before = repo.get_property_options(property_id).await?.len();
+
+ let outcome = repo
+ .replace_property_options(
+ property_id,
+ &PropertyOptionReplacePlan {
+ insert: vec![
+ PropertyOptionInsert {
+ value: PropertyOptionValue::String("Blocked".to_string()),
+ display_order: 4,
+ },
+ PropertyOptionInsert {
+ value: PropertyOptionValue::String("Blocked".to_string()),
+ display_order: 5,
+ },
+ ],
+ ..Default::default()
+ },
+ )
+ .await?;
+
+ assert!(matches!(
+ outcome,
+ PropertyOptionReplaceOutcome::DuplicateValue
+ ));
+ assert_eq!(repo.get_property_options(property_id).await?.len(), before);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+)]
+async fn replace_property_options_rolls_back_on_duplicate(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool);
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let urgent = PRIORITY_OPTION_URGENT.parse::<Uuid>().unwrap();
+
+ let outcome = repo
+ .replace_property_options(
+ property_id,
+ &PropertyOptionReplacePlan {
+ delete: vec![urgent],
+ insert: vec![PropertyOptionInsert {
+ value: PropertyOptionValue::String("Low".to_string()),
+ display_order: 4,
+ }],
+ ..Default::default()
+ },
+ )
+ .await?;
+ assert!(matches!(
+ outcome,
+ PropertyOptionReplaceOutcome::DuplicateValue
+ ));
+ assert_eq!(repo.get_property_options(property_id).await?.len(), 4);
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+)]
+async fn replace_property_options_rejects_foreign_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool);
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let outcome = repo
+ .replace_property_options(
+ property_id,
+ &PropertyOptionReplacePlan {
+ delete: vec![Uuid::now_v7()],
+ ..Default::default()
+ },
+ )
+ .await?;
+ assert!(matches!(
+ outcome,
+ PropertyOptionReplaceOutcome::OptionNotFound
+ ));
+ assert_eq!(repo.get_property_options(property_id).await?.len(), 4);
+ Ok(())
+}
diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rs
index 0db28af78c..84078deb09 100644
--- a/crates/properties/src/outbound/properties_pg_repo.rs
+++ b/crates/properties/src/outbound/properties_pg_repo.rs
@@ -16,8 +16,8 @@ use super::{
};
use crate::domain::model::{
EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
- GetOrCreateTagDefinitionResult, PropertyDefinitionOwner, TagPromotionOutcome, TagRemapOutcome,
- UpdatePropertyOptionOutcome,
+ GetOrCreateTagDefinitionResult, PropertyDefinitionOwner, PropertyOptionReplaceOutcome,
+ PropertyOptionReplacePlan, TagPromotionOutcome, TagRemapOutcome, UpdatePropertyOptionOutcome,
};
use crate::domain::ports::PropertiesRepo;
use models_properties::DataType;
@@ -205,6 +205,16 @@ impl PropertiesRepo for PropertiesPgRepo {
.await
}
+ #[tracing::instrument(skip(self, plan), err)]
+ async fn replace_property_options(
+ &self,
+ property_definition_id: Uuid,
+ plan: &PropertyOptionReplacePlan,
+ ) -> Result<PropertyOptionReplaceOutcome, Self::Err> {
+ property_option_queries::replace_property_options(&self.pool, property_definition_id, plan)
+ .await
+ }
+
#[tracing::instrument(skip(self), err)]
async fn delete_property_option(
&self,
diff --git a/crates/properties/src/outbound/property_option_queries.rs b/crates/properties/src/outbound/property_option_queries.rs
index ef7c5555dc..ba3a29a2ff 100644
--- a/crates/properties/src/outbound/property_option_queries.rs
+++ b/crates/properties/src/outbound/property_option_queries.rs
@@ -7,7 +7,9 @@ use models_properties::service::property_option::{PropertyOption, PropertyOption
use sqlx::{Pool, Postgres};
use uuid::Uuid;
-use crate::domain::model::UpdatePropertyOptionOutcome;
+use crate::domain::model::{
+ PropertyOptionReplaceOutcome, PropertyOptionReplacePlan, UpdatePropertyOptionOutcome,
+};
/// Gets a single property option by ID.
#[tracing::instrument(skip(pool))]
@@ -226,7 +228,20 @@ pub async fn delete_property_option(
property_option_id: Uuid,
) -> anyhow::Result<bool> {
let mut tx = pool.begin().await?;
+ let deleted =
+ delete_options_in_tx(&mut tx, property_definition_id, &[property_option_id]).await?;
+ tx.commit().await?;
+ Ok(deleted == 1)
+}
+/// Deletes the given options in one statement each for the value cleanup and
+/// the delete. Returns how many options were deleted.
+async fn delete_options_in_tx(
+ tx: &mut sqlx::Transaction<'_, Postgres>,
+ property_definition_id: Uuid,
+ option_ids: &[Uuid],
+) -> anyhow::Result<u64> {
+ let option_id_strings: Vec<String> = option_ids.iter().map(Uuid::to_string).collect();
sqlx::query!(
r#"
UPDATE entity_properties
@@ -238,29 +253,158 @@ pub async fn delete_property_option(
(
SELECT jsonb_agg(elem)
FROM jsonb_array_elements(values -> 'value') AS elem
- WHERE elem <> to_jsonb($2::text)
+ WHERE NOT (to_jsonb($2::text[]) @> elem)
),
'[]'::jsonb
)
),
updated_at = NOW()
WHERE property_definition_id = $1
- AND values @> jsonb_build_object('value', jsonb_build_array($2::text))
+ AND values -> 'value' ?| $2::text[]
"#,
property_definition_id,
- property_option_id.to_string(),
+ &option_id_strings,
)
- .execute(&mut *tx)
+ .execute(&mut **tx)
.await?;
let result = sqlx::query!(
- "DELETE FROM property_options WHERE id = $1",
- property_option_id
+ "DELETE FROM property_options WHERE property_definition_id = $1 AND id = ANY($2)",
+ property_definition_id,
+ option_ids
)
- .execute(&mut *tx)
+ .execute(&mut **tx)
.await?;
+ Ok(result.rows_affected())
+}
+
+/// Applies a [`PropertyOptionReplacePlan`] in one transaction, one statement
+/// per phase. Rewrites are staged through a placeholder value first so
+/// options can trade values under the per-definition uniqueness index.
+#[tracing::instrument(skip(pool, plan), err)]
+pub async fn replace_property_options(
+ pool: &Pool<Postgres>,
+ property_definition_id: Uuid,
+ plan: &PropertyOptionReplacePlan,
+) -> anyhow::Result<PropertyOptionReplaceOutcome> {
+ let mut tx = pool.begin().await?;
+
+ if !plan.delete.is_empty() {
+ let deleted = delete_options_in_tx(&mut tx, property_definition_id, &plan.delete).await?;
+ if deleted != plan.delete.len() as u64 {
+ return Ok(PropertyOptionReplaceOutcome::OptionNotFound);
+ }
+ }
+
+ if !plan.rewrite.is_empty() {
+ let rewrite_ids: Vec<Uuid> = plan.rewrite.iter().map(|r| r.option_id).collect();
+ let staged = sqlx::query!(
+ r#"
+ UPDATE property_options
+ SET string_value = chr(31) || id::text, number_value = NULL, updated_at = NOW()
+ WHERE property_definition_id = $1 AND id = ANY($2)
+ "#,
+ property_definition_id,
+ &rewrite_ids
+ )
+ .execute(&mut *tx)
+ .await?;
+ if staged.rows_affected() != rewrite_ids.len() as u64 {
+ return Ok(PropertyOptionReplaceOutcome::OptionNotFound);
+ }
+
+ let (number_values, string_values): (Vec<Option<f64>>, Vec<Option<String>>) =
+ plan.rewrite.iter().map(|r| r.value.to_db_values()).unzip();
+ let display_orders: Vec<i32> = plan.rewrite.iter().map(|r| r.display_order).collect();
+ let result = sqlx::query!(
+ r#"
+ UPDATE property_options AS option
+ SET
+ number_value = rewrite.number_value,
+ string_value = rewrite.string_value,
+ display_order = rewrite.display_order,
+ updated_at = NOW()
+ FROM UNNEST($2::uuid[], $3::float8[], $4::text[], $5::int4[])
+ AS rewrite(id, number_value, string_value, display_order)
+ WHERE option.property_definition_id = $1 AND option.id = rewrite.id
+ "#,
+ property_definition_id,
+ &rewrite_ids,
+ &number_values as _,
+ &string_values as _,
+ &display_orders
+ )
+ .execute(&mut *tx)
+ .await;
+ match result {
+ Ok(_) => {}
+ Err(sqlx::Error::Database(db_err)) if db_err.is_unique_violation() => {
+ return Ok(PropertyOptionReplaceOutcome::DuplicateValue);
+ }
+ Err(e) => return Err(e.into()),
+ }
+ }
+
+ if !plan.insert.is_empty() {
+ let ids: Vec<Uuid> = plan
+ .insert
+ .iter()
+ .map(|_| macro_uuid::generate_uuid_v7())
+ .collect();
+ let (number_values, string_values): (Vec<Option<f64>>, Vec<Option<String>>) =
+ plan.insert.iter().map(|i| i.value.to_db_values()).unzip();
+ let display_orders: Vec<i32> = plan.insert.iter().map(|i| i.display_order).collect();
+ let result = sqlx::query!(
+ r#"
+ INSERT INTO property_options (
+ id, property_definition_id, display_order, number_value, string_value
+ )
+ SELECT insert.id, $1, insert.display_order, insert.number_value, insert.string_value
+ FROM UNNEST($2::uuid[], $3::int4[], $4::float8[], $5::text[])
+ AS insert(id, display_order, number_value, string_value)
+ "#,
+ property_definition_id,
+ &ids,
+ &display_orders,
+ &number_values as _,
+ &string_values as _
+ )
+ .execute(&mut *tx)
+ .await;
+ match result {
+ Ok(_) => {}
+ Err(sqlx::Error::Database(db_err)) if db_err.is_unique_violation() => {
+ return Ok(PropertyOptionReplaceOutcome::DuplicateValue);
+ }
+ Err(e) => return Err(e.into()),
+ }
+ }
+
+ let rows = sqlx::query_as!(
+ db::PropertyOption,
+ r#"
+ SELECT
+ id,
+ property_definition_id,
+ display_order,
+ number_value,
+ string_value,
+ color,
+ created_at,
+ updated_at
+ FROM property_options
+ WHERE property_definition_id = $1
+ ORDER BY display_order, number_value, LOWER(string_value)
+ "#,
+ property_definition_id
+ )
+ .fetch_all(&mut *tx)
+ .await?;
tx.commit().await?;
- Ok(result.rows_affected() > 0)
+ rows.into_iter()
+ .map(|row| row.try_into().map_err(anyhow::Error::from))
+ .collect::<anyhow::Result<Vec<_>>>()
+ .map(PropertyOptionReplaceOutcome::Replaced)
}
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index 264f4739fa..fd4487b3e8 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, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, AgentMcpServer, AgentMcpServers, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, 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, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, 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, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, 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, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, 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, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, 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, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, 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, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, 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, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, 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, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, RequestedHarnessScope, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, 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, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, 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, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentChannelScope, AgentMcpServer, AgentMcpServers, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, 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, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, 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, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, 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, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityPermission, EntityPermissionResponse, 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, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, 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, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, 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, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, 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, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, 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, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, 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, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, 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, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, 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 965209ebc8..00c37607c3 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, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, 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, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, 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, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, 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, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, 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, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, 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, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, 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> & {
/**
@@ -1038,6 +1038,27 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Reset the team's deal stages to the defaults; gated like `PUT /crm/stages`.
+ */
+ public resetCrmTeamStages<ThrowOnError extends boolean = false>(options?: Options<ResetCrmTeamStagesData, ThrowOnError>): RequestResult<ResetCrmTeamStagesResponses, ResetCrmTeamStagesErrors, ThrowOnError> {
+ return (options?.client ?? this.client).delete<ResetCrmTeamStagesResponses, ResetCrmTeamStagesErrors, ThrowOnError>({ url: '/crm/stages', ...options });
+ }
+
+ /**
+ * Replace the team's deal stages; requires `edit_stages_role` (403 otherwise).
+ */
+ public putCrmTeamStages<ThrowOnError extends boolean = false>(options: Options<PutCrmTeamStagesData, ThrowOnError>): RequestResult<PutCrmTeamStagesResponses, PutCrmTeamStagesErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<PutCrmTeamStagesResponses, PutCrmTeamStagesErrors, ThrowOnError>({
+ url: '/crm/stages',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
/**
* Gets the users documents to populate their recent document list
*/
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 3d2ec2e0b9..60159c0f7f 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -3868,6 +3868,48 @@ export type CrmDomainResponse = {
*/
export type CrmPermissionRole = 'admin' | 'owner';
+/**
+ * One stage in a `PUT /crm/stages` body.
+ */
+export type CrmStageInput = {
+ /**
+ * Existing stage to keep; omit to add one.
+ */
+ id?: string | null;
+ /**
+ * Label after the update; non-blank and unique within the set.
+ */
+ label: string;
+};
+
+/**
+ * One stage of the team's custom pipeline.
+ */
+export type CrmStageResponse = {
+ /**
+ * Property option id companies carry as their stage value.
+ */
+ id: string;
+ /**
+ * Label.
+ */
+ label: string;
+};
+
+/**
+ * The team's custom stage set.
+ */
+export type CrmStagesResponse = {
+ /**
+ * Team-scoped stage definition id.
+ */
+ definition_id: string;
+ /**
+ * Stages in pipeline order.
+ */
+ stages: Array<CrmStageResponse>;
+};
+
/**
* The team's CRM configuration (everything on `team_crm_settings`
* except the `crm_enabled` killswitch, which is managed via
@@ -7112,6 +7154,16 @@ export type ReorderPinRequest = {
pinnedItemType: string;
};
+/**
+ * Request body for `PUT /crm/stages`: the whole stage set in order.
+ */
+export type ReplaceCrmStagesRequest = {
+ /**
+ * Stages first to last.
+ */
+ stages: Array<CrmStageInput>;
+};
+
/**
* The ownership scope a daemon's config asks for.
*
@@ -11570,6 +11622,49 @@ export type PutCrmTeamSettingsResponses = {
export type PutCrmTeamSettingsResponse = PutCrmTeamSettingsResponses[keyof PutCrmTeamSettingsResponses];
+export type ResetCrmTeamStagesData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/crm/stages';
+};
+
+export type ResetCrmTeamStagesErrors = {
+ 401: ErrorResponse;
+ 403: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type ResetCrmTeamStagesError = ResetCrmTeamStagesErrors[keyof ResetCrmTeamStagesErrors];
+
+export type ResetCrmTeamStagesResponses = {
+ 204: void;
+};
+
+export type ResetCrmTeamStagesResponse = ResetCrmTeamStagesResponses[keyof ResetCrmTeamStagesResponses];
+
+export type PutCrmTeamStagesData = {
+ body: ReplaceCrmStagesRequest;
+ path?: never;
+ query?: never;
+ url: '/crm/stages';
+};
+
+export type PutCrmTeamStagesErrors = {
+ 400: ErrorResponse;
+ 401: ErrorResponse;
+ 403: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type PutCrmTeamStagesError = PutCrmTeamStagesErrors[keyof PutCrmTeamStagesErrors];
+
+export type PutCrmTeamStagesResponses = {
+ 200: CrmStagesResponse;
+};
+
+export type PutCrmTeamStagesResponse = PutCrmTeamStagesResponses[keyof PutCrmTeamStagesResponses];
+
export type GetUserDocumentsHandlerData = {
body?: never;
path?: never;
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index a6c74d3edc..8281164e6d 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -5942,6 +5942,115 @@
}
}
},
+ "/crm/stages": {
+ "put": {
+ "tags": ["crm::inbound::axum_router::stages"],
+ "summary": "Replace the team's deal stages; requires `edit_stages_role` (403 otherwise).",
+ "operationId": "put_crm_team_stages",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ReplaceCrmStagesRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CrmStagesResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["crm::inbound::axum_router::stages"],
+ "summary": "Reset the team's deal stages to the defaults; gated like `PUT /crm/stages`.",
+ "operationId": "reset_crm_team_stages",
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/documents": {
"get": {
"tags": ["document"],
@@ -17955,6 +18064,57 @@
"description": "Minimum team role required for a CRM governance capability. Members\ncan edit visible CRM records (e.g. company properties), but the\ngovernance capabilities these settings gate stay restricted to\nadmin (default) vs owner. Maps to the `team_role` Postgres enum;\n`member` is deliberately not representable.",
"enum": ["admin", "owner"]
},
+ "CrmStageInput": {
+ "type": "object",
+ "description": "One stage in a `PUT /crm/stages` body.",
+ "required": ["label"],
+ "properties": {
+ "id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Existing stage to keep; omit to add one."
+ },
+ "label": {
+ "type": "string",
+ "description": "Label after the update; non-blank and unique within the set."
+ }
+ }
+ },
+ "CrmStageResponse": {
+ "type": "object",
+ "description": "One stage of the team's custom pipeline.",
+ "required": ["id", "label"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Property option id companies carry as their stage value."
+ },
+ "label": {
+ "type": "string",
+ "description": "Label."
+ }
+ }
+ },
+ "CrmStagesResponse": {
+ "type": "object",
+ "description": "The team's custom stage set.",
+ "required": ["definition_id", "stages"],
+ "properties": {
+ "definition_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Team-scoped stage definition id."
+ },
+ "stages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CrmStageResponse"
+ },
+ "description": "Stages in pipeline order."
+ }
+ }
+ },
"CrmTeamSettingsResponse": {
"type": "object",
"description": "The team's CRM configuration (everything on `team_crm_settings`\nexcept the `crm_enabled` killswitch, which is managed via\n`PATCH /team/crm` on the auth service).",
@@ -23887,6 +24047,20 @@
}
}
},
+ "ReplaceCrmStagesRequest": {
+ "type": "object",
+ "description": "Request body for `PUT /crm/stages`: the whole stage set in order.",
+ "required": ["stages"],
+ "properties": {
+ "stages": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CrmStageInput"
+ },
+ "description": "Stages first to last."
+ }
+ }
+ },
"RequestedHarnessScope": {
"type": "string",
"description": "The ownership scope a daemon's config asks for.\n\nAdvisory, not binding: the approving user confirms it in the dialog, which\narrives preselected to this. Approval is what actually sets ownership.",
diff --git a/packages/sdk/src/entities/crm/namespace.ts b/packages/sdk/src/entities/crm/namespace.ts
index bd40fa4afc..a2cdc7170f 100644
--- a/packages/sdk/src/entities/crm/namespace.ts
+++ b/packages/sdk/src/entities/crm/namespace.ts
@@ -1,6 +1,8 @@
import type {
CreateCrmCompanyRequest,
+ CrmStagesResponse,
CrmTeamSettingsResponse,
+ ReplaceCrmStagesRequest,
UpdateCrmTeamSettingsRequest,
} from '../../../generated/storage/types.gen';
import { unwrap } from '../../utils';
@@ -53,6 +55,16 @@ export class CrmNamespace {
);
}
+ /** Replace the caller's current team's deal stages, in pipeline order. */
+ async setStages(stages: ReplaceCrmStagesRequest): Promise<CrmStagesResponse> {
+ return unwrap(await this.client.storage.putCrmTeamStages({ body: stages }));
+ }
+
+ /** Reset the caller's current team's deal stages to the defaults. */
+ async resetStages(): Promise<void> {
+ unwrap(await this.client.storage.resetCrmTeamStages());
+ }
+
/** Search CRM companies by name/domain, most relevant first, auto-paginated. */
searchCompanies(query: string): AsyncGenerator<Company> {
return Company.search(this.client, query);
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 4db188d127..861efe078d 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -148,8 +148,14 @@ pub(crate) type DssEmailService = EmailServiceImpl<
>;
/// CRM router state.
+pub(crate) type DssCrmStageService = crm::domain::stages::CrmStageServiceImpl<
+ crm::outbound::companies_repo::CompaniesRepositoryImpl,
+ crm::outbound::stage_definitions::PropertiesStageDefinitionStore<PropertiesService>,
+>;
+
pub(crate) type DssCrmState = crm::inbound::axum_router::CrmRouterState<
DssCrmService,
+ DssCrmStageService,
EntityAccessService,
AuthorizationService,
>;
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index d776c1afd3..e292b64a7b 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -384,6 +384,8 @@ use utoipa::OpenApi;
crm::inbound::axum_router::comments::delete_handler,
crm::inbound::axum_router::team_settings::get_handler,
crm::inbound::axum_router::team_settings::update_handler,
+ crm::inbound::axum_router::stages::replace_handler,
+ crm::inbound::axum_router::stages::reset_handler,
),
components(
schemas(
@@ -725,6 +727,10 @@ use utoipa::OpenApi;
crm::inbound::axum_router::create_contact::CreateCrmContactRequest,
crm::inbound::axum_router::comments::CreateCrmCommentRequest,
crm::inbound::axum_router::comments::EditCrmCommentRequest,
+ crm::inbound::axum_router::stages::ReplaceCrmStagesRequest,
+ crm::inbound::axum_router::stages::CrmStageInput,
+ crm::inbound::axum_router::stages::CrmStagesResponse,
+ crm::inbound::axum_router::stages::CrmStageResponse,
crm::domain::comment::CrmCommentEntityType,
crm::domain::comment::CrmThread,
crm::domain::comment::CrmComment,
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index e387a5d7fb..35184084d7 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -1434,6 +1434,12 @@ async fn run() -> anyhow::Result<()> {
entity_access_management_service,
crm_state: crm::inbound::axum_router::CrmRouterState {
service: Arc::new(crm_service),
+ stage_service: Arc::new(crm::domain::stages::CrmStageServiceImpl::new(
+ crm::outbound::companies_repo::CompaniesRepositoryImpl::new(db.clone()),
+ crm::outbound::stage_definitions::PropertiesStageDefinitionStore::new(
+ properties_service.clone(),
+ ),
+ )),
entity_access_service: entity_access_service.clone(),
authorization_state: authorization_state.clone(),
},