Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(teams): team task id (#3421)
Will Hutchinsone91db3defa56
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.tsindex cf10cc1b39..1299bddc7e 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts@@ -1615,6 +1615,8 @@ export const ReadMetadataResponse = z.object({projectName: z.union([z.string(), z.null()]).optional(),sha: z.union([z.string(), z.null()]).optional(),subType: z.union([z.literal('task'), z.null()]).optional(),+ teamId: z.union([z.string(), z.null()]).optional(),+ teamTaskId: z.union([z.number().int(), z.null()]).optional(),updatedAt: z.union([z.string().datetime({ offset: true }), z.null()]).optional(),diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 87042ddbcd..7be56e1e89 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -2120,6 +2120,14 @@ export interface ReadDocumentMetadata {* The sub type of the document if present.*/subType?: DocumentSubType | null;+ /**+ * The team this task number is scoped to, for task documents.+ */+ teamId?: string | null;+ /**+ * The task number assigned within the team, for task documents.+ */+ teamTaskId?: number | null;/*** The time the document instance / document BOM was updated*/diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentRequest.tsindex dd1835121a..6e4822413c 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentRequest.ts@@ -14,6 +14,7 @@ import type { CreateDocumentRequestId } from './createDocumentRequestId';import type { CreateDocumentRequestJobId } from './createDocumentRequestJobId';import type { CreateDocumentRequestMimeType } from './createDocumentRequestMimeType';import type { CreateDocumentRequestProjectId } from './createDocumentRequestProjectId';+import type { CreateDocumentRequestTeamId } from './createDocumentRequestTeamId';export interface CreateDocumentRequest {/** The document id if the document is being branched. */@@ -47,4 +48,7 @@ Will need to have a corresponding job initiated for the file beforehand. */sha: string;/** Whether to add a viewed_at record for this document upon creation. */skipHistory?: boolean;+ /** Team to assign the task number within when creating a task document. If omitted,+the service may infer it only when the creator belongs to exactly one team. */+ teamId?: CreateDocumentRequestTeamId;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentRequestTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentRequestTeamId.tsnew file mode 100644index 0000000000..e244fe85f7--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createDocumentRequestTeamId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Team to assign the task number within when creating a task document. If omitted,+the service may infer it only when the creator belongs to exactly one team.+ */+export type CreateDocumentRequestTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.tsindex c058204b67..e3d43f17e7 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200.ts@@ -4,6 +4,8 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { CreateTaskHandler200TeamId } from './createTaskHandler200TeamId';+import type { CreateTaskHandler200TeamTaskId } from './createTaskHandler200TeamTaskId';/*** Response for creating a task.@@ -11,4 +13,8 @@export type CreateTaskHandler200 = {/** The document ID of the created task. */documentId: string;+ /** The team this task number is scoped to. */+ teamId?: CreateTaskHandler200TeamId;+ /** The task number assigned within the team. */+ teamTaskId?: CreateTaskHandler200TeamTaskId;};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200TeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200TeamId.tsnew file mode 100644index 0000000000..bb1776e006--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200TeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The team this task number is scoped to.+ */+export type CreateTaskHandler200TeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200TeamTaskId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200TeamTaskId.tsnew file mode 100644index 0000000000..74f478e2e6--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskHandler200TeamTaskId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The task number assigned within the team.+ */+export type CreateTaskHandler200TeamTaskId = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.tsindex f5fa0b7fcc..3a877d2cd3 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequest.ts@@ -7,6 +7,7 @@import type { CreateTaskRequestMarkdown } from './createTaskRequestMarkdown';import type { CreateTaskRequestProjectId } from './createTaskRequestProjectId';import type { CreateTaskRequestPropertyValues } from './createTaskRequestPropertyValues';+import type { CreateTaskRequestTeamId } from './createTaskRequestTeamId';/*** Request body for creating a task.@@ -23,4 +24,7 @@ Defaults to true */shareWithTeam?: boolean;/** The name of the task. */taskName: string;+ /** Team to assign the task number within. If omitted, it is inferred only+when the creator belongs to exactly one team. */+ teamId?: CreateTaskRequestTeamId;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestTeamId.tsnew file mode 100644index 0000000000..fb21d371a8--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskRequestTeamId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Team to assign the task number within. If omitted, it is inferred only+when the creator belongs to exactly one team.+ */+export type CreateTaskRequestTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.tsindex 9178597dea..2d767d8e81 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponse.ts@@ -4,6 +4,8 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { CreateTaskResponseTeamId } from './createTaskResponseTeamId';+import type { CreateTaskResponseTeamTaskId } from './createTaskResponseTeamTaskId';/*** Response for creating a task.@@ -11,4 +13,8 @@export interface CreateTaskResponse {/** The document ID of the created task. */documentId: string;+ /** The team this task number is scoped to. */+ teamId?: CreateTaskResponseTeamId;+ /** The task number assigned within the team. */+ teamTaskId?: CreateTaskResponseTeamTaskId;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponseTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponseTeamId.tsnew file mode 100644index 0000000000..6c4e215a3a--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponseTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The team this task number is scoped to.+ */+export type CreateTaskResponseTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponseTeamTaskId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponseTeamTaskId.tsnew file mode 100644index 0000000000..5a8e6329f2--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/createTaskResponseTeamTaskId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The task number assigned within the team.+ */+export type CreateTaskResponseTeamTaskId = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOf.tsindex adcff6c834..b3e426aa17 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOf.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOf.ts@@ -5,8 +5,14 @@* OpenAPI spec version: 0.1.0*/import type { DocumentContent } from './documentContent';+import type { DocumentMetadataWithContentAllOfTeamId } from './documentMetadataWithContentAllOfTeamId';+import type { DocumentMetadataWithContentAllOfTeamTaskId } from './documentMetadataWithContentAllOfTeamTaskId';export type DocumentMetadataWithContentAllOf = {/** Content lifecycle and location metadata. */content: DocumentContent;+ /** The team this task number is scoped to, for task documents. */+ teamId?: DocumentMetadataWithContentAllOfTeamId;+ /** The task number assigned within the team, for task documents. */+ teamTaskId?: DocumentMetadataWithContentAllOfTeamTaskId;};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOfTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOfTeamId.tsnew file mode 100644index 0000000000..1a82b252d0--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOfTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The team this task number is scoped to, for task documents.+ */+export type DocumentMetadataWithContentAllOfTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOfTeamTaskId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOfTeamTaskId.tsnew file mode 100644index 0000000000..0d6ba24933--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentMetadataWithContentAllOfTeamTaskId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The task number assigned within the team, for task documents.+ */+export type DocumentMetadataWithContentAllOfTeamTaskId = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOf.tsindex a061dd5d28..6b2625c90a 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOf.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOf.ts@@ -5,8 +5,14 @@* OpenAPI spec version: 0.1.0*/import type { DocumentContent } from './documentContent';+import type { DocumentResponseMetadataWithContentAllOfTeamId } from './documentResponseMetadataWithContentAllOfTeamId';+import type { DocumentResponseMetadataWithContentAllOfTeamTaskId } from './documentResponseMetadataWithContentAllOfTeamTaskId';export type DocumentResponseMetadataWithContentAllOf = {/** Content lifecycle and location metadata. */content: DocumentContent;+ /** The team this task number is scoped to, for task documents. */+ teamId?: DocumentResponseMetadataWithContentAllOfTeamId;+ /** The task number assigned within the team, for task documents. */+ teamTaskId?: DocumentResponseMetadataWithContentAllOfTeamTaskId;};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOfTeamId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOfTeamId.tsnew file mode 100644index 0000000000..3d62456c2c--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOfTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The team this task number is scoped to, for task documents.+ */+export type DocumentResponseMetadataWithContentAllOfTeamId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOfTeamTaskId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOfTeamTaskId.tsnew file mode 100644index 0000000000..92d6daf15a--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/documentResponseMetadataWithContentAllOfTeamTaskId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The task number assigned within the team, for task documents.+ */+export type DocumentResponseMetadataWithContentAllOfTeamTaskId = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 85f676d411..2b3250782f 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -182,6 +182,7 @@ export * from './createDocumentRequestId';export * from './createDocumentRequestJobId';export * from './createDocumentRequestMimeType';export * from './createDocumentRequestProjectId';+export * from './createDocumentRequestTeamId';export * from './createDocumentResponseData';export * from './createDocumentResponseDataAllOf';export * from './createDocumentResponseDataAllOfFileType';@@ -195,11 +196,16 @@ export * from './createProjectRequest';export * from './createProjectRequestProjectParentId';export * from './createProjectResponse';export * from './createTaskHandler200';+export * from './createTaskHandler200TeamId';+export * from './createTaskHandler200TeamTaskId';export * from './createTaskRequest';export * from './createTaskRequestMarkdown';export * from './createTaskRequestProjectId';export * from './createTaskRequestPropertyValues';+export * from './createTaskRequestTeamId';export * from './createTaskResponse';+export * from './createTaskResponseTeamId';+export * from './createTaskResponseTeamTaskId';export * from './createUnthreadedAnchorRequest';export * from './createUnthreadedAnchorRequestOneOf';export * from './createUnthreadedAnchorRequestOneOfAllOf';@@ -262,6 +268,8 @@ export * from './documentMetadataSubType';export * from './documentMetadataUpdatedAt';export * from './documentMetadataWithContent';export * from './documentMetadataWithContentAllOf';+export * from './documentMetadataWithContentAllOfTeamId';+export * from './documentMetadataWithContentAllOfTeamTaskId';export * from './documentPermissionsToken';export * from './documentPermissionsTokenRequest';export * from './documentPermissionsTokenResponse';@@ -296,6 +304,8 @@ export * from './documentResponseMetadataSubType';export * from './documentResponseMetadataUpdatedAt';export * from './documentResponseMetadataWithContent';export * from './documentResponseMetadataWithContentAllOf';+export * from './documentResponseMetadataWithContentAllOfTeamId';+export * from './documentResponseMetadataWithContentAllOfTeamTaskId';export * from './documentResponsePresignedUrl';export * from './documentStorageServiceApiVersion';export * from './documentSubType';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 95e580f837..e37d5f8db5 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -2006,6 +2006,12 @@ export const createDocumentBody = zod.object({.describe('Whether to add a viewed_at record for this document upon creation.'),+ teamId: zod+ .uuid()+ .nullish()+ .describe(+ 'Team to assign the task number within when creating a task document. If omitted,\nthe service may infer it only when the creator belongs to exactly one team.'+ ),});export const createDocumentResponse = zod.object({@@ -2117,6 +2123,18 @@ export const createDocumentResponse = zod.object({),}).describe('API-visible content lifecycle and location metadata.'),+ teamId: zod+ .uuid()+ .nullish()+ .describe(+ 'The team this task number is scoped to, for task documents.'+ ),+ teamTaskId: zod+ .number()+ .nullish()+ .describe(+ 'The task number assigned within the team, for task documents.'+ ),})).describe(@@ -2336,12 +2354,26 @@ export const createTaskHandlerBody = zod'Whether to share the task with your team or not\nDefaults to true'),taskName: zod.string().describe('The name of the task.'),+ teamId: zod+ .uuid()+ .nullish()+ .describe(+ 'Team to assign the task number within. If omitted, it is inferred only\nwhen the creator belongs to exactly one team.'+ ),}).describe('Request body for creating a task.');export const createTaskHandlerResponse = zod.object({documentId: zod.string().describe('The document ID of the created task.'),+ teamId: zod+ .uuid()+ .nullish()+ .describe('The team this task number is scoped to.'),+ teamTaskId: zod+ .number()+ .nullish()+ .describe('The task number assigned within the team.'),}).describe('Response for creating a task.');@@ -3503,6 +3535,18 @@ export const copyDocumentResponse = zod.describe('API-visible content lifecycle and location metadata.'),+ teamId: zod+ .uuid()+ .nullish()+ .describe(+ 'The team this task number is scoped to, for task documents.'+ ),+ teamTaskId: zod+ .number()+ .nullish()+ .describe(+ 'The task number assigned within the team, for task documents.'+ ),})).describe(diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 986764f72e..276b847705 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -2105,6 +2105,16 @@"documentId": {"type": "string","description": "The document ID of the created task."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The team this task number is scoped to."+ },+ "teamTaskId": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "The task number assigned within the team."}}}@@ -7592,6 +7602,11 @@"skipHistory": {"type": "boolean","description": "Whether to add a viewed_at record for this document upon creation."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team to assign the task number within when creating a task document. If omitted,\nthe service may infer it only when the creator belongs to exactly one team."}}},@@ -7717,6 +7732,11 @@"taskName": {"type": "string","description": "The name of the task."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team to assign the task number within. If omitted, it is inferred only\nwhen the creator belongs to exactly one team."}}},@@ -7728,6 +7748,16 @@"documentId": {"type": "string","description": "The document ID of the created task."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The team this task number is scoped to."+ },+ "teamTaskId": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "The task number assigned within the team."}}},@@ -8200,6 +8230,16 @@"content": {"$ref": "#/components/schemas/DocumentContent","description": "Content lifecycle and location metadata."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The team this task number is scoped to, for task documents."+ },+ "teamTaskId": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "The task number assigned within the team, for task documents."}}}@@ -8475,6 +8515,16 @@"content": {"$ref": "#/components/schemas/DocumentContent","description": "Content lifecycle and location metadata."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The team this task number is scoped to, for task documents."+ },+ "teamTaskId": {+ "type": ["integer", "null"],+ "format": "int32",+ "description": "The task number assigned within the team, for task documents."}}}diff --git a/rust/cloud-storage/.sqlx/query-b7e2765c4c0999ea37d38e4a7f41e3986bdcced6e86a9c9869e38ff3e6d91c2d.json b/rust/cloud-storage/.sqlx/query-b7e2765c4c0999ea37d38e4a7f41e3986bdcced6e86a9c9869e38ff3e6d91c2d.jsonnew file mode 100644index 0000000000..8f79a3db1f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-b7e2765c4c0999ea37d38e4a7f41e3986bdcced6e86a9c9869e38ff3e6d91c2d.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT team_id, task_num\n FROM team_task\n WHERE document_id = $1\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "task_num",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "b7e2765c4c0999ea37d38e4a7f41e3986bdcced6e86a9c9869e38ff3e6d91c2d"+}diff --git a/rust/cloud-storage/.sqlx/query-b8176bd2c038b0cfb2b74f3c7b6a51a2d068b5253bcd3a9d16b43527ae4e8f1a.json b/rust/cloud-storage/.sqlx/query-b8176bd2c038b0cfb2b74f3c7b6a51a2d068b5253bcd3a9d16b43527ae4e8f1a.jsonnew file mode 100644index 0000000000..255d60be8b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-b8176bd2c038b0cfb2b74f3c7b6a51a2d068b5253bcd3a9d16b43527ae4e8f1a.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH allocated AS (\n INSERT INTO team_task_counter (team_id, last_task_num)\n VALUES ($1, 1)\n ON CONFLICT (team_id) DO UPDATE\n SET last_task_num = team_task_counter.last_task_num + 1,\n updated_at = NOW()\n RETURNING last_task_num AS task_num\n )\n INSERT INTO team_task (team_id, document_id, task_num)\n SELECT $1, $2, task_num\n FROM allocated\n RETURNING task_num AS \"task_num!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_num!",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b8176bd2c038b0cfb2b74f3c7b6a51a2d068b5253bcd3a9d16b43527ae4e8f1a"+}diff --git a/rust/cloud-storage/.sqlx/query-c77469ffc5cc502c63d2ecb76a8578d085a7aec81551a38aa0c14b8e20491e3e.json b/rust/cloud-storage/.sqlx/query-c77469ffc5cc502c63d2ecb76a8578d085a7aec81551a38aa0c14b8e20491e3e.jsonnew file mode 100644index 0000000000..1ebd795f6e--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c77469ffc5cc502c63d2ecb76a8578d085a7aec81551a38aa0c14b8e20491e3e.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT team_id\n FROM team_user\n WHERE user_id = $1\n ORDER BY team_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "team_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "c77469ffc5cc502c63d2ecb76a8578d085a7aec81551a38aa0c14b8e20491e3e"+}diff --git a/rust/cloud-storage/documents/src/domain/create/mod.rs b/rust/cloud-storage/documents/src/domain/create/mod.rsindex 3e5ffff183..9834d3a43d 100644--- a/rust/cloud-storage/documents/src/domain/create/mod.rs+++ b/rust/cloud-storage/documents/src/domain/create/mod.rs@@ -64,6 +64,7 @@ impl NewDocumentMetadata {user_id,file_type: kind.file_type,project_id: self.project_id,+ team_id: kind.team_id,email_attachment_id: self.email_attachment_id,created_at: self.created_at,is_task: kind.subtype.is_task(),@@ -119,6 +120,7 @@ struct RepoDocumentKind {file_type: Option<FileType>,sha: String,subtype: RepoDocumentSubtype,+ team_id: Option<uuid::Uuid>,}enum RepoDocumentSubtype {@@ -143,6 +145,9 @@ pub enum MarkdownSubtype {property_values: Option<Vec<PropertyInput>>,/// Whether to share the task with the user's team.share_with_team: bool,+ /// Team to assign the task number within. If omitted, it is inferred only+ /// when the creator belongs to exactly one team.+ team_id: Option<uuid::Uuid>,},}@@ -153,6 +158,7 @@ impl MarkdownSubtype {Self::Task {property_values: None,share_with_team: true,+ team_id: None,}} else {Self::Note@@ -491,7 +497,18 @@ whereMarkdownSubtype::Task {property_values,share_with_team,- } => Some((property_values.clone(), *share_with_team)),+ team_id,+ } => Some((property_values.clone(), *share_with_team, *team_id)),+ };++ let resolved_team_id = if let Some((_, _, requested_team_id)) = task.as_ref() {+ Some(+ self.document_service+ .resolve_task_team_id(user_id.clone(), *requested_team_id)+ .await?,+ )+ } else {+ None};let task_name = metadata.document_name.clone();@@ -506,6 +523,7 @@ where} else {RepoDocumentSubtype::Regular},+ team_id: resolved_team_id,},);@@ -522,7 +540,7 @@ where.clone();let finalize_result = async {- if let Some((property_values, share_with_team)) = task {+ if let Some((property_values, share_with_team, _)) = task {self.document_service.handle_task_properties(user_id,@@ -531,6 +549,7 @@ wheretask_name,markdown: None,project_id,+ team_id: resolved_team_id,property_values,share_with_team,},@@ -585,6 +604,7 @@ wherefile_type: Some(file_type.into_file_type()),sha: hashes.hex,subtype: RepoDocumentSubtype::Regular,+ team_id: None,},);diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rsindex 5d18a9bb59..c991114128 100644--- a/rust/cloud-storage/documents/src/domain/models.rs+++ b/rust/cloud-storage/documents/src/domain/models.rs@@ -66,6 +66,19 @@ pub struct CopyDocumentRepoArgs {pub document_name: String,/// The file type of the document.pub file_type: Option<FileType>,+ /// Team that should receive a new per-team task number when copying a task.+ pub team_id: Option<uuid::Uuid>,+}++/// Immutable per-team task metadata assigned at task creation time.+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, Copy)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TeamTaskMetadata {+ /// The team this task number is scoped to.+ pub team_id: uuid::Uuid,+ /// Monotonic task number within the team.+ pub task_num: i32,}/// Request body for copying a document.@@ -101,6 +114,8 @@ pub struct CreateDocumentRepoArgs {pub file_type: Option<FileType>,/// Project to associate the document with.pub project_id: Option<uuid::Uuid>,+ /// Team to use when assigning a per-team task number.+ pub team_id: Option<uuid::Uuid>,/// Email attachment to link (internal only).pub email_attachment_id: Option<uuid::Uuid>,/// Custom creation timestamp.@@ -229,6 +244,9 @@ pub struct CreateTaskRequest {pub markdown: Option<String>,/// Optional project ID to associate the task with.pub project_id: Option<uuid::Uuid>,+ /// Team to assign the task number within. If omitted, it is inferred only+ /// when the creator belongs to exactly one team.+ pub team_id: Option<uuid::Uuid>,/// Optional property values to set on the task.pub property_values: Option<Vec<PropertyInput>>,/// Whether to share the task with your team or not@@ -244,6 +262,12 @@ pub struct CreateTaskRequest {pub struct CreateTaskResponse {/// The document ID of the created task.pub document_id: String,+ /// The team this task number is scoped to.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team_id: Option<uuid::Uuid>,+ /// The task number assigned within the team.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team_task_id: Option<i32>,}/// A comment thread attached to a document.diff --git a/rust/cloud-storage/documents/src/domain/ports/create/mod.rs b/rust/cloud-storage/documents/src/domain/ports/create/mod.rsindex ed22c3fe29..d4464d6ab3 100644--- a/rust/cloud-storage/documents/src/domain/ports/create/mod.rs+++ b/rust/cloud-storage/documents/src/domain/ports/create/mod.rs@@ -48,6 +48,13 @@ pub trait DocumentCreationService: Send + Sync {request: &CreateTaskRequest,) -> impl Future<Output = Result<(), DocumentError>> + Send;+ /// Resolve the team to use for per-team task numbering.+ fn resolve_task_team_id(+ &self,+ user_id: MacroUserIdStr<'static>,+ requested_team_id: Option<uuid::Uuid>,+ ) -> impl Future<Output = Result<uuid::Uuid, DocumentError>> + Send;+/// Mark a created document's upload/finalization lifecycle as complete.fn mark_document_uploaded(&self,@@ -89,6 +96,16 @@ where.await}+ async fn resolve_task_team_id(+ &self,+ user_id: MacroUserIdStr<'static>,+ requested_team_id: Option<uuid::Uuid>,+ ) -> Result<uuid::Uuid, DocumentError> {+ (**self)+ .resolve_task_team_id(user_id, requested_team_id)+ .await+ }+async fn mark_document_uploaded(&self, document_id: &str) -> Result<(), DocumentError> {(**self).mark_document_uploaded(document_id).await}diff --git a/rust/cloud-storage/documents/src/domain/ports/mod.rs b/rust/cloud-storage/documents/src/domain/ports/mod.rsindex 0f68b425cb..03e577a6dc 100644--- a/rust/cloud-storage/documents/src/domain/ports/mod.rs+++ b/rust/cloud-storage/documents/src/domain/ports/mod.rs@@ -25,7 +25,7 @@ use model_entity::Entity;use super::models::{CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest, DocumentError,- EditDocumentRepoArgs, EditDocumentServiceArgs, LocationQueryParams,+ EditDocumentRepoArgs, EditDocumentServiceArgs, LocationQueryParams, TeamTaskMetadata,};/// Repository for accessing document data from the database.@@ -159,10 +159,22 @@ pub trait DocumentRepo: Send + Sync + 'static {document_id: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;- /// Share a document with all members of the user's team.- fn share_with_team(+ /// Get all team IDs the user belongs to.+ fn get_team_ids_for_user(&self,user_id: &str,+ ) -> impl Future<Output = Result<Vec<uuid::Uuid>, Self::Err>> + Send;++ /// Get per-team task metadata for a document, when it is a team task.+ fn get_team_task_metadata(+ &self,+ document_id: &str,+ ) -> impl Future<Output = Result<Option<TeamTaskMetadata>, Self::Err>> + Send;++ /// Share a document with the given team.+ fn share_with_team(+ &self,+ team_id: &uuid::Uuid,document_id: &str,) -> impl Future<Output = Result<(), Self::Err>> + Send;@@ -318,6 +330,13 @@ pub trait DocumentService: Send + Sync + 'static {job_id: Option<String>,) -> impl Future<Output = Result<CreateDocumentResponseData, DocumentError>> + Send;+ /// Resolve the team to use for per-team task numbering.+ fn resolve_task_team_id(+ &self,+ user_id: MacroUserIdStr<'static>,+ requested_team_id: Option<uuid::Uuid>,+ ) -> impl Future<Output = Result<uuid::Uuid, DocumentError>> + Send;+/// Get content lifecycle metadata for a document.fn get_document_content(&self,diff --git a/rust/cloud-storage/documents/src/domain/response.rs b/rust/cloud-storage/documents/src/domain/response.rsindex 98e49d982b..ca85105866 100644--- a/rust/cloud-storage/documents/src/domain/response.rs+++ b/rust/cloud-storage/documents/src/domain/response.rs@@ -8,6 +8,7 @@ use model::response::{PresignedUrl, TypedSuccessResponse};use models_permissions::share_permission::access_level::AccessLevel;use super::content::DocumentContent;+use super::models::TeamTaskMetadata;/// Full document metadata plus content lifecycle metadata.#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]@@ -18,6 +19,13 @@ pub struct DocumentMetadataWithContent {/// Legacy document metadata.#[serde(flatten)]pub metadata: DocumentMetadata,+ /// The team this task number is scoped to, for task documents.+ #[serde(skip_serializing_if = "Option::is_none")]+ #[cfg_attr(feature = "ai_tools", schemars(with = "Option<String>"))]+ pub team_id: Option<uuid::Uuid>,+ /// The task number assigned within the team, for task documents.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team_task_id: Option<i32>,/// Content lifecycle and location metadata.pub content: DocumentContent,}@@ -25,7 +33,21 @@ pub struct DocumentMetadataWithContent {impl DocumentMetadataWithContent {/// Attach content metadata to legacy document metadata.pub fn new(metadata: DocumentMetadata, content: DocumentContent) -> Self {- Self { metadata, content }+ Self {+ metadata,+ team_id: None,+ team_task_id: None,+ content,+ }+ }++ /// Attach per-team task metadata, when present.+ pub fn with_team_task_metadata(mut self, metadata: Option<TeamTaskMetadata>) -> Self {+ if let Some(metadata) = metadata {+ self.team_id = Some(metadata.team_id);+ self.team_task_id = Some(metadata.task_num);+ }+ self}}@@ -37,6 +59,12 @@ pub struct DocumentResponseMetadataWithContent {/// Legacy create/copy response metadata.#[serde(flatten)]pub metadata: DocumentResponseMetadata,+ /// The team this task number is scoped to, for task documents.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team_id: Option<uuid::Uuid>,+ /// The task number assigned within the team, for task documents.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub team_task_id: Option<i32>,/// Content lifecycle and location metadata.pub content: DocumentContent,}@@ -44,7 +72,21 @@ pub struct DocumentResponseMetadataWithContent {impl DocumentResponseMetadataWithContent {/// Attach content metadata to legacy response metadata.pub fn new(metadata: DocumentResponseMetadata, content: DocumentContent) -> Self {- Self { metadata, content }+ Self {+ metadata,+ team_id: None,+ team_task_id: None,+ content,+ }+ }++ /// Attach per-team task metadata, when present.+ pub fn with_team_task_metadata(mut self, metadata: Option<TeamTaskMetadata>) -> Self {+ if let Some(metadata) = metadata {+ self.team_id = Some(metadata.team_id);+ self.team_task_id = Some(metadata.task_num);+ }+ self}}diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex d214a7585e..7d607bd597 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -38,7 +38,7 @@ use super::content::{DocumentContent, DocumentContentLocation, DocumentContentStuse super::models::{CloudFrontConfig, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs,CreateTaskRequest, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,- FileTypeUpdate, LocationQueryParams,+ FileTypeUpdate, LocationQueryParams, TeamTaskMetadata,};#[cfg(feature = "document_create")]use super::ports::create::DocumentCreationService;@@ -376,6 +376,48 @@ impl<tracing::error!(error=?e, document_id=?document_id, "failed to clean up document");}}++ async fn resolve_task_team_id_for_user(+ &self,+ user_id: &MacroUserIdStr<'_>,+ requested_team_id: Option<uuid::Uuid>,+ ) -> Result<uuid::Uuid, DocumentError> {+ let team_ids = self+ .repo+ .get_team_ids_for_user(user_id.as_ref())+ .await+ .map_err(|e| DocumentError::Internal(e.into()))?;++ if let Some(requested_team_id) = requested_team_id {+ if team_ids.contains(&requested_team_id) {+ return Ok(requested_team_id);+ }++ return Err(DocumentError::BadRequest(+ "user is not a member of the requested team".to_string(),+ ));+ }++ match team_ids.as_slice() {+ [team_id] => Ok(*team_id),+ [] => Err(DocumentError::BadRequest(+ "teamId is required because the user does not belong to a team".to_string(),+ )),+ _ => Err(DocumentError::BadRequest(+ "teamId is required because the user belongs to multiple teams".to_string(),+ )),+ }+ }++ async fn team_task_metadata_for_document(+ &self,+ document_id: &str,+ ) -> Result<Option<TeamTaskMetadata>, DocumentError> {+ self.repo+ .get_team_task_metadata(document_id)+ .await+ .map_err(|e| DocumentError::Internal(e.into()))+ }}#[cfg(feature = "document_create")]@@ -405,6 +447,15 @@ impl<<Self as DocumentService>::handle_task_properties(self, user_id, document_id, request).await}+ async fn resolve_task_team_id(+ &self,+ user_id: MacroUserIdStr<'static>,+ requested_team_id: Option<uuid::Uuid>,+ ) -> Result<uuid::Uuid, DocumentError> {+ self.resolve_task_team_id_for_user(&user_id, requested_team_id)+ .await+ }+#[tracing::instrument(err, skip(self))]async fn mark_document_uploaded(&self, document_id: &str) -> Result<(), DocumentError> {self.repo@@ -484,9 +535,11 @@ impl<.as_deref().and_then(|file_type| FileType::from_str(file_type).ok());let content = self.content_for_document(&document_id, file_type).await?;+ let team_task_metadata = self.team_task_metadata_for_document(&document_id).await?;Ok(GetDocumentResponseData {- document_metadata: DocumentMetadataWithContent::new(document_metadata, content),+ document_metadata: DocumentMetadataWithContent::new(document_metadata, content)+ .with_team_task_metadata(team_task_metadata),user_access_level: *access_level,view_location,})@@ -681,17 +734,33 @@ impl<.await}+ async fn resolve_task_team_id(+ &self,+ user_id: MacroUserIdStr<'static>,+ requested_team_id: Option<uuid::Uuid>,+ ) -> Result<uuid::Uuid, DocumentError> {+ self.resolve_task_team_id_for_user(&user_id, requested_team_id)+ .await+ }+#[tracing::instrument(err, skip(self, args))]async fn create_document(&self,user_id: MacroUserIdStr<'static>,- args: CreateDocumentRepoArgs,+ mut args: CreateDocumentRepoArgs,job_id: Option<String>,) -> Result<CreateDocumentResponseData, DocumentError> {if args.document_name.graphemes(true).count() > 100 {return Err(DocumentError::BadRequest("name too long".to_string()));}+ if args.is_task {+ let team_id = self+ .resolve_task_team_id_for_user(&args.user_id, args.team_id)+ .await?;+ args.team_id = Some(team_id);+ }+let file_type = args.file_type;let project_id = args.project_id;let sha = args.sha.clone();@@ -800,12 +869,15 @@ impl<})?;}+ let team_task_metadata = self.team_task_metadata_for_document(&document_id).await?;+Ok(CreateDocumentResponseData {document_response: DocumentResponse {document_metadata: DocumentResponseMetadataWithContent::new(document_response_metadata,initial_content,- ),+ )+ .with_team_task_metadata(team_task_metadata),presigned_url: Some(presigned_url),},content_type: mime_type,@@ -1004,6 +1076,12 @@ impl<// Clean the document namelet document_name = FileType::clean_document_name(&document_name).unwrap_or(document_name);+ let copy_team_id = if original_metadata.sub_type == Some(DocumentSubType::Task) {+ Some(self.resolve_task_team_id_for_user(&user_id, None).await?)+ } else {+ None+ };+// Create the copy in the databaselet new_metadata = self.repo@@ -1012,6 +1090,7 @@ impl<user_id: user_id.clone(),document_name,file_type,+ team_id: copy_team_id,}).await.map_err(|e| DocumentError::Internal(e.into()))?;@@ -1156,11 +1235,16 @@ impl<DocumentError::Internal(anyhow!("unable to convert document metadata"))})?;+ let team_task_metadata = self+ .team_task_metadata_for_document(&new_document_id)+ .await?;+Ok(DocumentResponse {document_metadata: DocumentResponseMetadataWithContent::new(document_response_metadata,content,- ),+ )+ .with_team_task_metadata(team_task_metadata),presigned_url: None,})}@@ -1202,9 +1286,15 @@ impl<request: &CreateTaskRequest,) -> Result<(), DocumentError> {if request.share_with_team {+ let Some(team_id) = request.team_id else {+ return Err(DocumentError::BadRequest(+ "teamId is required to share a task with a team".to_string(),+ ));+ };+let _ = self.repo- .share_with_team(user_id.as_ref(), document_id)+ .share_with_team(&team_id, document_id).await.inspect_err(|e| {tracing::error!(error=?e, "failed to share task with team");diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rsindex 87e6225017..aca1d38dbf 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_document.rs@@ -78,6 +78,8 @@ pub async fn create_document_handler<T: DocumentService, Svc: EntityAccessServic);}+ let team_id = req.team_id;+let args = CreateDocumentRepoArgs {id: req.id,sha: req.sha,@@ -85,6 +87,7 @@ pub async fn create_document_handler<T: DocumentService, Svc: EntityAccessServicuser_id: user_context.macro_user_id.clone(),file_type,project_id: req.project_id,+ team_id,email_attachment_id: req.email_attachment_id,created_at: req.created_at,is_task: req.is_task,diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rsindex e217d502cb..be181de162 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs@@ -1,8 +1,11 @@//! Handler for `POST /documents/create_task`.use axum::{Json, extract::State};+use entity_access::domain::models::MemberTeamRole;use entity_access::domain::ports::EntityAccessService;-use entity_access::inbound::axum_extractors::ProjectBodyAccessLevelExtractor;+use entity_access::inbound::axum_extractors::{+ OptionalMacroUserTeamExtractor, ProjectBodyAccessLevelExtractor,+};use model_user::axum_extractor::MacroUserExtractor;use models_permissions::share_permission::access_level::EditAccessLevel;@@ -26,13 +29,14 @@ use crate::domain::ports::create::DocumentCreationService;(status = 500, body = model_error_response::ErrorResponse),))]-#[tracing::instrument(skip(state, user_context, project), fields(user_id=?user_context.macro_user_id))]+#[tracing::instrument(skip(state, user_context, optional_team, project), fields(user_id=?user_context.macro_user_id))]pub async fn create_task_handler<T: DocumentService + DocumentCreationService,Svc: EntityAccessService,>(State(state): State<DocumentRouterState<T, Svc>>,user_context: MacroUserExtractor,+ optional_team: OptionalMacroUserTeamExtractor<MemberTeamRole, Svc>,project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateTaskRequest, Svc>,) -> Result<Json<CreateTaskResponse>, DocumentError> {let req = project.into_inner();@@ -42,6 +46,14 @@ pub async fn create_task_handler<metadata = metadata.project_id(project_id);}+ let team_id = if req.share_with_team {+ optional_team+ .entity_access_receipt+ .map(|team| macro_uuid::string_to_uuid(&team.entity().entity_id).unwrap())+ } else {+ None+ };+let created = state.creator.create_markdown_text(@@ -51,13 +63,18 @@ pub async fn create_task_handler<markdown: req.markdown.unwrap_or_default(),subtype: MarkdownSubtype::Task {property_values: req.property_values,- share_with_team: req.share_with_team,+ share_with_team: req.share_with_team && team_id.is_some(), // we should only try and share if the user is in a team and they have share_with_team set+ team_id,},},).await?;+ let task_metadata = &created.response().document_response.document_metadata;+Ok(Json(CreateTaskResponse {document_id: created.document_id().to_string(),+ team_id: task_metadata.team_id,+ team_task_id: task_metadata.team_task_id,}))}diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rsindex e32c2484f3..67fb9633b4 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs@@ -22,7 +22,7 @@ use sqlx::Row;use crate::domain::content::{DocumentContent, DocumentContentState};use crate::domain::models::{Comment, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs,- Thread,+ TeamTaskMetadata, Thread,};use crate::domain::ports::DocumentRepo;@@ -400,6 +400,7 @@ impl DocumentRepo for PgDocumentRepo {user_id,file_type,project_id,+ team_id,email_attachment_id,created_at: provided_created_at,is_task,@@ -438,6 +439,10 @@ impl DocumentRepo for PgDocumentRepo {let sub_type: Option<DocumentSubType> =create::set_document_sub_type(&mut transaction, &document_id, is_task).await?;+ if is_task && let Some(team_id) = team_id.as_ref() {+ create::allocate_team_task_number(&mut transaction, team_id, &document_id).await?;+ }+// Insert document version (DocumentBom for docx, DocumentInstance for others)let document_version = create::set_document_version(&mut transaction,@@ -650,8 +655,55 @@ impl DocumentRepo for PgDocumentRepo {}#[tracing::instrument(err, skip(self))]- async fn share_with_team(&self, user_id: &str, document_id: &str) -> Result<(), Self::Err> {- share::share_with_team(&self.pool, user_id, document_id).await+ async fn get_team_ids_for_user(&self, user_id: &str) -> Result<Vec<uuid::Uuid>, Self::Err> {+ let rows = sqlx::query!(+ r#"+ SELECT team_id+ FROM team_user+ WHERE user_id = $1+ ORDER BY team_id+ "#,+ user_id,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows.into_iter().map(|row| row.team_id).collect())+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_team_task_metadata(+ &self,+ document_id: &str,+ ) -> Result<Option<TeamTaskMetadata>, Self::Err> {+ let Some(row) = sqlx::query!(+ r#"+ SELECT team_id, task_num+ FROM team_task+ WHERE document_id = $1+ LIMIT 1+ "#,+ document_id,+ )+ .fetch_optional(&self.pool)+ .await?+ else {+ return Ok(None);+ };++ Ok(Some(TeamTaskMetadata {+ team_id: row.team_id,+ task_num: row.task_num,+ }))+ }++ #[tracing::instrument(err, skip(self))]+ async fn share_with_team(+ &self,+ team_id: &uuid::Uuid,+ document_id: &str,+ ) -> Result<(), Self::Err> {+ share::share_with_team(&self.pool, team_id, document_id).await}#[tracing::instrument(err, skip(self))]@@ -833,6 +885,7 @@ impl DocumentRepo for PgDocumentRepo {user_id,document_name,file_type,+ team_id,} = args;let mut transaction = self.pool.begin().await?;@@ -861,6 +914,12 @@ impl DocumentRepo for PgDocumentRepo {let document_id = uuid::Uuid::parse_str(&document.document_id).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;+ if document.sub_type == Some(DocumentSubType::Task)+ && let Some(team_id) = team_id.as_ref()+ {+ create::allocate_team_task_number(&mut transaction, team_id, &document_id).await?;+ }+// Create share permissioncreate::set_share_permission(&mut transaction, &document_id, file_type).await?;diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rsindex 0be485477e..caac82a4eb 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/create.rs@@ -74,6 +74,37 @@ pub async fn set_document_sub_type(}}+/// Allocates the next per-team task number and records the document association.+#[tracing::instrument(skip(transaction), err)]+pub async fn allocate_team_task_number(+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ team_id: &uuid::Uuid,+ document_id: &uuid::Uuid,+) -> Result<i32, sqlx::Error> {+ let document_id = document_id.to_string();++ sqlx::query_scalar!(+ r#"+ WITH allocated AS (+ INSERT INTO team_task_counter (team_id, last_task_num)+ VALUES ($1, 1)+ ON CONFLICT (team_id) DO UPDATE+ SET last_task_num = team_task_counter.last_task_num + 1,+ updated_at = NOW()+ RETURNING last_task_num AS task_num+ )+ INSERT INTO team_task (team_id, document_id, task_num)+ SELECT $1, $2, task_num+ FROM allocated+ RETURNING task_num AS "task_num!"+ "#,+ team_id,+ document_id,+ )+ .fetch_one(transaction.as_mut())+ .await+}+pub async fn set_document_version(transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,document_id: &uuid::Uuid,diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rsindex fb44fe5aea..8169c7bb5e 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs@@ -2,30 +2,13 @@ use entity_access_db_utils::AccessLevel;use sqlx::PgPool;use uuid::Uuid;-/// Share a document with all members of the given user's team.+/// Share a document with the given team.#[tracing::instrument(err, skip(pool))]pub async fn share_with_team(pool: &PgPool,- user_id: &str,+ team_id: &Uuid,document_id: &str,) -> Result<(), sqlx::Error> {- // Find the team_id for the given user.- let team_id: Option<Uuid> = sqlx::query_scalar!(- r#"- SELECT team_id- FROM team_user- WHERE user_id = $1- LIMIT 1- "#,- user_id,- )- .fetch_optional(pool)- .await?;-- let Some(team_id) = team_id else {- return Ok(());- };-let document_uuid = macro_uuid::string_to_uuid(document_id).map_err(|e| sqlx::Error::Protocol(e.to_string()))?;diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rsindex e0e56b7cc1..46cedc63f1 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs@@ -1,16 +1,126 @@use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::cowlike::CowLike;use model_entity::EntityType;use models_permissions::share_permission::UpdateSharePermissionRequestV2;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::{UpdateChannelSharePermission, UpdateOperation,};-use sqlx::{Pool, Postgres};+use sqlx::{Pool, Postgres, Row};-use crate::domain::models::{EditDocumentRepoArgs, FileTypeUpdate};+use crate::domain::models::{+ CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs, FileTypeUpdate,+};use crate::domain::ports::DocumentRepo;use crate::outbound::pg_document_repo::PgDocumentRepo;+const TEST_TEAM_ID: uuid::Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000001");+const SECOND_TEAM_ID: uuid::Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000002");++fn user_id(user_id: &str) -> macro_user_id::user_id::MacroUserIdStr<'static> {+ macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)+ .unwrap()+ .into_owned()+}++fn create_document_args(+ user_id: &str,+ is_task: bool,+ team_id: Option<uuid::Uuid>,+) -> CreateDocumentRepoArgs {+ CreateDocumentRepoArgs {+ id: None,+ sha: "sha".to_string(),+ document_name: "task".to_string(),+ user_id: self::user_id(user_id),+ file_type: Some(model::document::FileType::Md),+ project_id: None,+ team_id,+ email_attachment_id: None,+ created_at: None,+ is_task,+ skip_history: false,+ }+}++async fn create_task_for_team(+ repo: &PgDocumentRepo,+ user_id: &str,+ team_id: uuid::Uuid,+) -> model::document::DocumentMetadata {+ repo.create_document(create_document_args(user_id, true, Some(team_id)))+ .await+ .unwrap()+}++async fn team_task_numbers(pool: &Pool<Postgres>, team_id: uuid::Uuid) -> Vec<i32> {+ sqlx::query(+ r#"+ SELECT task_num+ FROM team_task+ WHERE team_id = $1+ ORDER BY task_num+ "#,+ )+ .bind(team_id)+ .fetch_all(pool)+ .await+ .unwrap()+ .into_iter()+ .map(|row| row.try_get("task_num").unwrap())+ .collect()+}++async fn insert_second_team(pool: &Pool<Postgres>) {+ sqlx::query(+ r#"+ INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")+ VALUES ($1, 'other', '[email protected]', 'stripe_id_other')+ ON CONFLICT DO NOTHING+ "#,+ )+ .bind(uuid::uuid!("a4444444-4444-4444-4444-444444444444"))+ .execute(pool)+ .await+ .unwrap();++ sqlx::query(+ r#"+ INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId", "macro_user_id")+ VALUES ('macro|[email protected]', '[email protected]', 'stripe_id_other', 1, $1)+ ON CONFLICT DO NOTHING+ "#,+ )+ .bind(uuid::uuid!("a4444444-4444-4444-4444-444444444444"))+ .execute(pool)+ .await+ .unwrap();++ sqlx::query(+ r#"+ INSERT INTO public."team" ("id", "name", "owner_id")+ VALUES ($1, 'second-team', 'macro|[email protected]')+ ON CONFLICT DO NOTHING+ "#,+ )+ .bind(SECOND_TEAM_ID)+ .execute(pool)+ .await+ .unwrap();++ sqlx::query(+ r#"+ INSERT INTO public."team_user" ("user_id", "team_id", "team_role")+ VALUES ('macro|[email protected]', $1, 'owner')+ ON CONFLICT DO NOTHING+ "#,+ )+ .bind(SECOND_TEAM_ID)+ .execute(pool)+ .await+ .unwrap();+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data"))@@ -398,12 +508,9 @@ async fn test_edit_document_name_and_project(pool: Pool<Postgres>) {async fn test_share_with_team_creates_access_for_team_members(pool: Pool<Postgres>) {let repo = PgDocumentRepo::new(pool.clone());- repo.share_with_team(- "macro|[email protected]",- "d0000000-0000-0000-0000-000000000001",- )- .await- .unwrap();+ repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")+ .await+ .unwrap();// All 3 team members should have access rowslet doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();@@ -441,33 +548,15 @@ async fn test_share_with_team_creates_access_for_team_members(pool: Pool<Postgremigrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data")))]-async fn test_share_with_team_no_op_when_user_not_on_team(pool: Pool<Postgres>) {- let repo = PgDocumentRepo::new(pool.clone());-- // teammate1 is on a team, but let's use a user that isn't on any team- // We'll use a non-existent user id to simulate no team membership- repo.share_with_team(- "macro|[email protected]",- "d0000000-0000-0000-0000-000000000001",- )- .await- .unwrap();+async fn test_get_team_ids_for_user_returns_empty_when_user_not_on_team(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool);- // Only the pre-existing owner row should exist- let doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();- let count = sqlx::query_scalar!(- r#"- SELECT COUNT(*) as "count!"- FROM entity_access- WHERE entity_id = $1 AND entity_type = 'document'- "#,- doc_uuid,- )- .fetch_one(&pool)- .await- .unwrap();+ let team_ids = repo+ .get_team_ids_for_user("macro|[email protected]")+ .await+ .unwrap();- assert_eq!(count, 1); // just the owner row from fixtures+ assert!(team_ids.is_empty());}#[sqlx::test(@@ -478,18 +567,12 @@ async fn test_share_with_team_idempotent(pool: Pool<Postgres>) {let repo = PgDocumentRepo::new(pool.clone());// Call twice — second call should be a no-op- repo.share_with_team(- "macro|[email protected]",- "d0000000-0000-0000-0000-000000000001",- )- .await- .unwrap();- repo.share_with_team(- "macro|[email protected]",- "d0000000-0000-0000-0000-000000000001",- )- .await- .unwrap();+ repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")+ .await+ .unwrap();+ repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")+ .await+ .unwrap();let doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();let count = sqlx::query_scalar!(@@ -529,12 +612,9 @@ async fn test_share_with_team_skips_user_with_existing_direct_access(pool: Pool<.await.unwrap();- repo.share_with_team(- "macro|[email protected]",- "d0000000-0000-0000-0000-000000000001",- )- .await- .unwrap();+ repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")+ .await+ .unwrap();// teammate1 should still have just their original edit row, not a second comment rowlet rows = sqlx::query!(@@ -558,17 +638,12 @@ async fn test_share_with_team_skips_user_with_existing_direct_access(pool: Pool<migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data")))]-async fn test_share_with_team_called_by_teammate(pool: Pool<Postgres>) {+async fn test_share_with_explicit_team_id(pool: Pool<Postgres>) {let repo = PgDocumentRepo::new(pool.clone());- // A teammate (not the owner) triggers the share — should still find the- // same team and share with all members including the owner.- repo.share_with_team(- "macro|[email protected]",- "d0000000-0000-0000-0000-000000000001",- )- .await- .unwrap();+ repo.share_with_team(&TEST_TEAM_ID, "d0000000-0000-0000-0000-000000000001")+ .await+ .unwrap();let doc_uuid = macro_uuid::string_to_uuid("d0000000-0000-0000-0000-000000000001").unwrap();let rows = sqlx::query!(@@ -600,6 +675,181 @@ async fn test_share_with_team_called_by_teammate(pool: Pool<Postgres>) {assert_eq!(t1.access_level, Some("comment".to_string()));}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_create_first_task_assigns_team_task_id_one(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());++ let metadata = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;+ let task_metadata = repo+ .get_team_task_metadata(&metadata.document_id)+ .await+ .unwrap()+ .unwrap();++ assert_eq!(task_metadata.team_id, TEST_TEAM_ID);+ assert_eq!(task_metadata.task_num, 1);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_create_multiple_tasks_same_team_assigns_sequence(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());++ for _ in 0..3 {+ create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;+ }++ assert_eq!(team_task_numbers(&pool, TEST_TEAM_ID).await, vec![1, 2, 3]);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_create_tasks_different_teams_have_independent_sequences(pool: Pool<Postgres>) {+ insert_second_team(&pool).await;+ let repo = PgDocumentRepo::new(pool.clone());++ create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;+ create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;+ create_task_for_team(&repo, "macro|[email protected]", SECOND_TEAM_ID).await;++ assert_eq!(team_task_numbers(&pool, TEST_TEAM_ID).await, vec![1, 2]);+ assert_eq!(team_task_numbers(&pool, SECOND_TEAM_ID).await, vec![1]);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_concurrent_task_creates_same_team_get_unique_numbers(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ let mut handles = Vec::new();++ for _ in 0..8 {+ let repo = repo.clone();+ handles.push(tokio::spawn(async move {+ create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;+ }));+ }++ for handle in handles {+ handle.await.unwrap();+ }++ assert_eq!(+ team_task_numbers(&pool, TEST_TEAM_ID).await,+ (1..=8).collect::<Vec<_>>()+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_non_task_document_does_not_create_team_task_row(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool);++ let metadata = repo+ .create_document(create_document_args(+ "macro|[email protected]",+ false,+ Some(TEST_TEAM_ID),+ ))+ .await+ .unwrap();++ assert!(+ repo.get_team_task_metadata(&metadata.document_id)+ .await+ .unwrap()+ .is_none()+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_task_without_team_id_does_not_create_team_task_row(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool);++ let metadata = repo+ .create_document(create_document_args("macro|[email protected]", true, None))+ .await+ .unwrap();++ assert!(+ repo.get_team_task_metadata(&metadata.document_id)+ .await+ .unwrap()+ .is_none()+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_deleting_document_cascades_team_task_row(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ let metadata = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;++ repo.delete_document_by_id(&metadata.document_id)+ .await+ .unwrap();++ let count: i64 = sqlx::query(+ r#"+ SELECT COUNT(*) AS count+ FROM team_task+ WHERE document_id = $1+ "#,+ )+ .bind(&metadata.document_id)+ .fetch_one(&pool)+ .await+ .unwrap()+ .try_get("count")+ .unwrap();++ assert_eq!(count, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_copying_task_allocates_new_team_task_number(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ let original = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;++ let copied = repo+ .copy_document(CopyDocumentRepoArgs {+ original_document: original,+ user_id: user_id("macro|[email protected]"),+ document_name: "copied task".to_string(),+ file_type: Some(model::document::FileType::Md),+ team_id: Some(TEST_TEAM_ID),+ })+ .await+ .unwrap();++ let copied_task_metadata = repo+ .get_team_task_metadata(&copied.document_id)+ .await+ .unwrap()+ .unwrap();++ assert_eq!(copied_task_metadata.task_num, 2);+ assert_eq!(team_task_numbers(&pool, TEST_TEAM_ID).await, vec![1, 2]);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data"))diff --git a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rsindex 633bd8f96b..abe207c7cb 100644--- a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs+++ b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs@@ -132,6 +132,7 @@ impl AttachmentProcessor {branched_from_version_id: None,job_id: None,project_id: None,+ team_id: None,created_at: Some(attachment.internal_date_ts),email_attachment_id: Some(attachment.attachment_db_id),is_task: false,diff --git a/rust/cloud-storage/email_service/src/util/upload_attachment.rs b/rust/cloud-storage/email_service/src/util/upload_attachment.rsindex 90859bc1f0..9f1403bd73 100644--- a/rust/cloud-storage/email_service/src/util/upload_attachment.rs+++ b/rust/cloud-storage/email_service/src/util/upload_attachment.rs@@ -286,6 +286,7 @@ async fn create_dss_document_record(branched_from_version_id: None,job_id: None,project_id: None,+ team_id: None,created_at,email_attachment_id: Some(p.attachment_db_id),is_task: false,diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex 226eb8a2d3..d32a98eab7 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -176,6 +176,14 @@ impl DocumentService for StubDocumentService {) -> Result<CreateDocumentResponseData, DocumentError> {unimplemented!()}++ async fn resolve_task_team_id(+ &self,+ _user_id: MacroUserIdStr<'static>,+ requested_team_id: Option<uuid::Uuid>,+ ) -> Result<uuid::Uuid, DocumentError> {+ requested_team_id.ok_or_else(|| DocumentError::BadRequest("teamId is required".into()))+ }async fn get_document_content(&self,_document_context: &DocumentBasic,diff --git a/rust/cloud-storage/macro_db_client/migrations/20260520130000_create_team_task.sql b/rust/cloud-storage/macro_db_client/migrations/20260520130000_create_team_task.sqlnew file mode 100644index 0000000000..1cd4bdfb8e--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260520130000_create_team_task.sql@@ -0,0 +1,54 @@+CREATE TABLE team_task_counter (+ team_id UUID PRIMARY KEY REFERENCES team(id) ON DELETE CASCADE,+ last_task_num INTEGER NOT NULL DEFAULT 0,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ CONSTRAINT team_task_counter_positive CHECK (last_task_num >= 0)+);++CREATE TABLE team_task (+ team_id UUID NOT NULL REFERENCES team(id) ON DELETE CASCADE,+ document_id TEXT NOT NULL REFERENCES "Document"(id) ON DELETE CASCADE,+ task_num INTEGER NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ PRIMARY KEY (team_id, task_num),+ CONSTRAINT team_task_document_unique UNIQUE (document_id),+ CONSTRAINT team_task_num_positive CHECK (task_num > 0)+);++CREATE INDEX team_task_document_id_idx ON team_task(document_id);++-- Backfill existing task documents only when the owner's team is deterministic.+WITH deterministic_task_team AS (+ SELECT+ d.id AS document_id,+ tu.team_id,+ d."createdAt",+ COUNT(*) OVER (PARTITION BY d.id) AS team_count+ FROM "Document" d+ JOIN document_sub_type dst ON dst.document_id = d.id+ JOIN team_user tu ON tu.user_id = d.owner+ WHERE dst.sub_type = 'task'+), numbered AS (+ SELECT+ team_id,+ document_id,+ ROW_NUMBER() OVER (+ PARTITION BY team_id+ ORDER BY "createdAt", document_id+ )::int AS task_num+ FROM deterministic_task_team+ WHERE team_count = 1+)+INSERT INTO team_task (team_id, document_id, task_num)+SELECT team_id, document_id, task_num+FROM numbered+ON CONFLICT DO NOTHING;++INSERT INTO team_task_counter (team_id, last_task_num)+SELECT team_id, MAX(task_num)+FROM team_task+GROUP BY team_id+ON CONFLICT (team_id) DO UPDATE+SET last_task_num = EXCLUDED.last_task_num,+ updated_at = NOW();diff --git a/rust/cloud-storage/model/src/document/response/mod.rs b/rust/cloud-storage/model/src/document/response/mod.rsindex 2f05aa7ec8..ae20a640ee 100644--- a/rust/cloud-storage/model/src/document/response/mod.rs+++ b/rust/cloud-storage/model/src/document/response/mod.rs@@ -209,6 +209,9 @@ pub struct CreateDocumentRequest {pub job_id: Option<String>,//// Optional project id to be used to what project the document belongs to.pub project_id: Option<uuid::Uuid>,+ /// Team to assign the task number within when creating a task document. If omitted,+ /// the service may infer it only when the creator belongs to exactly one team.+ pub team_id: Option<uuid::Uuid>,/// Internal only field that links the document created to the specified email attachment by/// creating a row in the document_email table.pub email_attachment_id: Option<Uuid>,