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(documents): move copy_document to documents hex crate (#2512)

Will Hutchinson6063edd29675
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentHandlerParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentParams.ts
similarity index 86%
rename from js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentHandlerParams.ts
rename to js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentParams.ts
index 4b0320a838..3f0c9bf9b7 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentHandlerParams.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentParams.ts
@@ -5,7 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
-export type CopyDocumentHandlerParams = {
+export type CopyDocumentParams = {
/**
* The version id of the document to copy. Defaults to copying the latest version of the document.
*/
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParams.ts
index 049ea978f1..52d5fdb489 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParams.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParams.ts
@@ -6,7 +6,10 @@
*/
import type { CopyDocumentQueryParamsVersionId } from './copyDocumentQueryParamsVersionId';
+/**
+ * Query parameters for the copy document endpoint.
+ */
export interface CopyDocumentQueryParams {
- /** The version id of the document to copy. Defaults to copying the latest version of the document. */
+ /** The DB version id of the document to copy. Defaults to latest. */
version_id?: CopyDocumentQueryParamsVersionId;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParamsVersionId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParamsVersionId.ts
index 7d53bdd25b..f9de4e8204 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParamsVersionId.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentQueryParamsVersionId.ts
@@ -6,6 +6,6 @@
*/
/**
- * The version id of the document to copy. Defaults to copying the latest version of the document.
+ * The DB version id of the document to copy. Defaults to latest.
*/
export type CopyDocumentQueryParamsVersionId = number | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentRequest.ts
index 4bdd06c053..4800ea1857 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentRequest.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentRequest.ts
@@ -6,8 +6,11 @@
*/
import type { CopyDocumentRequestVersionId } from './copyDocumentRequestVersionId';
+/**
+ * Request body for copying a document.
+ */
export interface CopyDocumentRequest {
- /** The name of the document without extension. */
+ /** The name of the new document (without extension). */
documentName: string;
versionId?: CopyDocumentRequestVersionId;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentResponse.ts
new file mode 100644
index 0000000000..f7b38aaadd
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/copyDocumentResponse.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentResponse } from './documentResponse';
+
+/**
+ * Response wrapper for the copy document endpoint.
+ */
+export interface CopyDocumentResponse {
+ /** The copied document data. */
+ data: DocumentResponse;
+ /** Indicates if an error occurred. */
+ error: boolean;
+}
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.ts
index 9f29183a6b..3f1432ebe4 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
@@ -112,11 +112,12 @@ export * from './commentOrder';
export * from './commentSender';
export * from './commentThread';
export * from './commentUpdatedAt';
-export * from './copyDocumentHandlerParams';
+export * from './copyDocumentParams';
export * from './copyDocumentQueryParams';
export * from './copyDocumentQueryParamsVersionId';
export * from './copyDocumentRequest';
export * from './copyDocumentRequestVersionId';
+export * from './copyDocumentResponse';
export * from './createBulkDocumentResponse';
export * from './createBulkDocumentResponseData';
export * from './createBulkDocumentResponseDataDocumentMetadata';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index fff935a57f..014684f0dd 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -2660,17 +2660,15 @@ export const editDocumentResponse = zod
.describe('Edit document response.');
/**
- * @summary Handles copying a given document. This is the similar to
-create_document_handler where you provide the branched_from_id,
-branched_from_version_id and document_family_id in the request body. Except
-this will not require you to re-upload the document when it's made saving
-time and resources.
+ * Copies an existing document, creating a new document with the same content.
+Does not require re-uploading the document file.
+ * @summary Handler for `POST /documents/{document_id}/copy`.
*/
-export const copyDocumentHandlerParams = zod.object({
+export const copyDocumentParams = zod.object({
document_id: zod.string().describe('Document ID'),
});
-export const copyDocumentHandlerQueryParams = zod.object({
+export const copyDocumentQueryParams = zod.object({
version_id: zod
.number()
.optional()
@@ -2679,124 +2677,111 @@ export const copyDocumentHandlerQueryParams = zod.object({
),
});
-export const copyDocumentHandlerBody = zod.object({
- documentName: zod
- .string()
- .describe('The name of the document without extension.'),
- versionId: zod
- .union([
- zod.null(),
- zod.object({
- counter: zod.number(),
- peer: zod.string(),
- }),
- ])
- .optional(),
-});
+export const copyDocumentBody = zod
+ .object({
+ documentName: zod
+ .string()
+ .describe('The name of the new document (without extension).'),
+ versionId: zod
+ .union([
+ zod.null(),
+ zod.object({
+ counter: zod.number(),
+ peer: zod.string(),
+ }),
+ ])
+ .optional(),
+ })
+ .describe('Request body for copying a document.');
-export const copyDocumentHandlerResponse = zod.object({
- data: zod.object({
- documentMetadata: zod.object({
- branchedFromId: zod
- .string()
- .nullish()
- .describe('The id of the document this document branched from'),
- branchedFromVersionId: zod
- .number()
- .nullish()
- .describe(
- 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
- ),
- createdAt: zod
- .string()
- .datetime({})
- .nullish()
- .describe('The time the document was created'),
- deletedAt: zod
- .string()
- .datetime({})
- .nullish()
- .describe('The time the document was deleted'),
- documentBom: zod
- .array(
- zod.object({
- id: zod.string().describe('The uuid of the bom part'),
- path: zod
- .string()
- .describe('The file path of the bom part content'),
- sha: zod
- .string()
+export const copyDocumentResponse = zod
+ .object({
+ data: zod.object({
+ documentMetadata: zod.object({
+ branchedFromId: zod
+ .string()
+ .nullish()
+ .describe('The id of the document this document branched from'),
+ branchedFromVersionId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the version this document branched from\nThis could be either DocumentInstance or DocumentBom id depending on\nthe file type'
+ ),
+ createdAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe('The time the document was created'),
+ documentBom: zod
+ .array(
+ zod.object({
+ id: zod.string().describe('The uuid of the bom part'),
+ path: zod
+ .string()
+ .describe('The file path of the bom part content'),
+ sha: zod
+ .string()
+ .describe(
+ 'The sha of the bom part content\nThere is an index on sha for more performant queries based on it.'
+ ),
+ })
+ )
+ .nullish()
+ .describe(
+ 'If the document is a DOCX document, the document_bom will be present'
+ ),
+ documentFamilyId: zod
+ .number()
+ .nullish()
+ .describe('The id of the document family this document belongs to'),
+ documentId: zod.string().describe('The document id'),
+ documentName: zod.string().describe('The name of the document'),
+ documentVersionId: zod
+ .number()
+ .describe(
+ 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
+ ),
+ fileType: zod
+ .string()
+ .nullish()
+ .describe('The file type of the document'),
+ modificationData: zod
+ .any()
+ .optional()
+ .describe(
+ 'The modification data for the document instance.\nThis is only used for PDF documents.'
+ ),
+ owner: zod.string().describe('The owner of the document'),
+ sha: zod
+ .string()
+ .nullish()
+ .describe(
+ 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
+ ),
+ subType: zod
+ .union([
+ zod.null(),
+ zod
+ .enum(['task'])
.describe(
- 'The sha of the bom part content\nThere is an index on sha for more performant queries based on it.'
+ 'The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'
),
- })
- )
- .nullish()
- .describe(
- 'If the document is a DOCX document and unzipped, the document_bom will be present'
- ),
- documentFamilyId: zod
- .number()
- .nullish()
- .describe('The id of the document family this document belongs to'),
- documentId: zod.string().describe('The document id'),
- documentName: zod.string().describe('The name of the document'),
- documentVersionId: zod
- .number()
- .describe(
- 'The version of the document\nThis could be the document_instance_id or document_bom_id depending on\nthe file type'
- ),
- fileType: zod
- .string()
- .nullish()
- .describe('The file type of the document (file extension)'),
- modificationData: zod
- .any()
- .optional()
- .describe(
- 'The modification data for the document instance.\nThis is only used for PDF documents.'
- ),
- owner: zod.string().describe('The owner of the document'),
- projectId: zod
- .string()
- .nullish()
- .describe('The id of the project that this document belongs to'),
- projectName: zod
- .string()
- .nullish()
- .describe('The name of the project that this document belongs to'),
- sha: zod
- .string()
- .nullish()
- .describe(
- 'If the document is a PDF, this is the SHA of the pdf\nIf the document is a DOCX, this will not be present'
- ),
- subType: zod
- .union([
- zod.null(),
- zod
- .enum(['task'])
- .describe(
- 'The document sub type enum represents all values of document sub types.\nThese values should match the `document_sub_type_value` table in macrodb.'
- ),
- ])
- .optional(),
- updatedAt: zod
- .string()
- .datetime({})
- .nullish()
- .describe('The time the document instance / document BOM was updated'),
+ ])
+ .optional(),
+ updatedAt: zod
+ .string()
+ .datetime({})
+ .nullish()
+ .describe(
+ 'The time the document instance / document BOM was updated'
+ ),
+ }),
+ presignedUrl: zod.string().nullish(),
}),
- userAccessLevel: zod
- .enum(['view', 'comment', 'edit', 'owner'])
- .describe('Ordered from least to most access top -> bottom'),
- viewLocation: zod
- .string()
- .nullish()
- .describe('The users view location if there is one'),
- }),
- error: zod.boolean().describe('Indicates if an error occurred'),
-});
+ error: zod.boolean().describe('Indicates if an error occurred.'),
+ })
+ .describe('Response wrapper for the copy document endpoint.');
/**
* @summary Generates a presigned url to download the raw content of the document
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index e0e459eb53..8d59645c81 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -2054,8 +2054,9 @@
"/documents/{document_id}/copy": {
"post": {
"tags": ["document"],
- "summary": "Handles copying a given document. This is the similar to\ncreate_document_handler where you provide the branched_from_id,\nbranched_from_version_id and document_family_id in the request body. Except\nthis will not require you to re-upload the document when it's made saving\ntime and resources.",
- "operationId": "copy_document_handler",
+ "summary": "Handler for `POST /documents/{document_id}/copy`.",
+ "description": "Copies an existing document, creating a new document with the same content.\nDoes not require re-uploading the document file.",
+ "operationId": "copy_document",
"parameters": [
{
"name": "document_id",
@@ -2093,7 +2094,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GetDocumentResponse"
+ "$ref": "#/components/schemas/CopyDocumentResponse"
}
}
}
@@ -2103,7 +2104,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -2113,17 +2114,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
- }
- }
- }
- },
- "403": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -2133,7 +2124,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -2143,7 +2134,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/GenericErrorResponse"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
@@ -6166,21 +6157,23 @@
},
"CopyDocumentQueryParams": {
"type": "object",
+ "description": "Query parameters for the copy document endpoint.",
"properties": {
"version_id": {
"type": ["integer", "null"],
"format": "int64",
- "description": "The version id of the document to copy. Defaults to copying the latest version of the document."
+ "description": "The DB version id of the document to copy. Defaults to latest."
}
}
},
"CopyDocumentRequest": {
"type": "object",
+ "description": "Request body for copying a document.",
"required": ["documentName"],
"properties": {
"documentName": {
"type": "string",
- "description": "The name of the document without extension."
+ "description": "The name of the new document (without extension)."
},
"versionId": {
"oneOf": [
@@ -6188,12 +6181,28 @@
"type": "null"
},
{
- "$ref": "#/components/schemas/SyncServiceVersionID"
+ "$ref": "#/components/schemas/SyncServiceVersionID",
+ "description": "Optional sync service version ID for MD documents."
}
]
}
}
},
+ "CopyDocumentResponse": {
+ "type": "object",
+ "description": "Response wrapper for the copy document endpoint.",
+ "required": ["error", "data"],
+ "properties": {
+ "data": {
+ "$ref": "#/components/schemas/DocumentResponse",
+ "description": "The copied document data."
+ },
+ "error": {
+ "type": "boolean",
+ "description": "Indicates if an error occurred."
+ }
+ }
+ },
"CreateBulkDocumentResponse": {
"type": "object",
"required": ["error", "data"],
diff --git a/js/app/packages/service-clients/service-storage/service.ts b/js/app/packages/service-clients/service-storage/service.ts
index 66a8c5f2d6..fde8822271 100644
--- a/js/app/packages/service-clients/service-storage/service.ts
+++ b/js/app/packages/service-clients/service-storage/service.ts
@@ -420,15 +420,14 @@ export const StorageService = new Svc('Document++ Storage Service API')
throws: withFetchErrors('INVALID_RESPONSE'),
})
.fn('copyDocument', {
- description: schemas.copyDocumentHandlerResponse.description!,
+ description: schemas.copyDocumentResponse.description!,
args: {
- documentId: schemas.copyDocumentHandlerParams.shape.document_id,
- ...schemas.copyDocumentHandlerQueryParams.shape,
- ...schemas.copyDocumentHandlerBody.shape,
+ documentId: schemas.copyDocumentParams.shape.document_id,
+ ...schemas.copyDocumentQueryParams.shape,
+ ...schemas.copyDocumentBody.shape,
},
result:
- schemas.copyDocumentHandlerResponse.shape.data.shape.documentMetadata
- .shape,
+ schemas.copyDocumentResponse.shape.data.shape.documentMetadata.shape,
modifies: true,
throws: withFetchErrors(),
})
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 058e374b66..8fe24292bb 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -66,6 +66,13 @@ impl TaskPropertiesPort for NoOpTaskProperties {
) -> anyhow::Result<()> {
Ok(())
}
+ async fn copy_task_properties(
+ &self,
+ _from_task_id: &str,
+ _to_task_id: &str,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
}
/// No-op connection service
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index f1c5fa5a60..a2f0719e28 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -135,6 +135,19 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {
.await
.map_err(Into::into)
}
+
+ async fn copy_task_properties(
+ &self,
+ from_task_id: &str,
+ to_task_id: &str,
+ ) -> anyhow::Result<()> {
+ use system_properties::SystemPropertiesService as _;
+
+ self.system_properties
+ .copy_task_properties(from_task_id, to_task_id)
+ .await
+ .map_err(Into::into)
+ }
}
pub(crate) type DocumentService = DocumentServiceImpl<
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_cleanup.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_cleanup.rs
deleted file mode 100644
index 0ac35dd4f6..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_cleanup.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use crate::service::s3::S3;
-use sqlx::{Pool, Postgres};
-use std::sync::Arc;
-
-/// spawns a thread to cleanup the copy document resources in the background
-#[tracing::instrument(skip(db))]
-pub(in crate::api::documents::copy_document) async fn copy_document_cleanup(
- db: &Pool<Postgres>,
- s3_client: &Arc<S3>,
- user_id: String,
- document_id: String,
-) {
- // Delete from db
- let _ = macro_db_client::document::delete_document(db, &document_id)
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to delete document"));
-
- let _ = s3_client
- .delete_document(&user_id, document_id.as_str())
- .await
- .inspect_err(|e| tracing::error!(error=?e, "failed to delete document from s3"));
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
deleted file mode 100644
index 0ea40698e0..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
+++ /dev/null
@@ -1,309 +0,0 @@
-use crate::api::context::ApiContext;
-use axum::{http::StatusCode, response::Response};
-use document_sub_type::DocumentSubType;
-use macro_db_client::history::upsert_user_history;
-use macro_user_id::cowlike::CowLike;
-use macro_user_id::user_id::MacroUserIdStr;
-use model::document::response::{DocumentResponse, DocumentResponseMetadata};
-use model::{document::FileTypeExt, sync_service::SyncServiceVersionID};
-use model::{
- document::{BomPart, DocumentMetadata, FileType},
- response::GenericResponse,
-};
-use models_permissions::share_permission::SharePermissionV2;
-use s3_key::{build_cloud_storage_bucket_document_key, build_docx_to_pdf_converted_document_key};
-use system_properties::SystemPropertiesService;
-
-#[tracing::instrument(skip(ctx))]
-pub async fn copy_document<'a>(
- ctx: &'a ApiContext,
- user_id: MacroUserIdStr<'static>,
- original_document_metadata: &'a DocumentMetadata,
- updated_document_name: &'a str,
- file_type: Option<&'a FileType>,
- version_id: Option<SyncServiceVersionID>,
-) -> Result<Response, (Option<String>, anyhow::Error, &'a str)> {
- tracing::info!("copy document");
- let share_permission = SharePermissionV2::new_document_share_permission(file_type.copied());
- // Create new document in db using document metadata
- let updated_document_metadata = match macro_db_client::document::v2::copy::copy_document(
- &ctx.db,
- original_document_metadata,
- user_id.clone(),
- updated_document_name,
- file_type,
- &share_permission,
- )
- .await
- {
- Ok(document_metadata) => document_metadata,
- Err(e) => {
- tracing::error!(error=?e, "unable to copy document");
- return Err((None, e, "unable to copy document"));
- }
- };
-
- match file_type {
- Some(FileType::Docx) => {
- let document_bom: Vec<BomPart> =
- serde_json::from_value(updated_document_metadata.document_bom.clone().unwrap())
- .map_err(|e| {
- tracing::error!(error=?e, "unable to deserialize document bom");
- (
- Some(updated_document_metadata.document_id.clone()),
- anyhow::anyhow!(e),
- "unable to deserialize document bom",
- )
- })?;
-
- let shas: Vec<String> = document_bom.into_iter().map(|b| b.sha).collect();
-
- // update sha ref count
- if let Err(e) = ctx.redis_client.increment_counts(shas).await {
- tracing::error!("unable to increment sha ref count: {e}");
- return Err((
- Some(updated_document_metadata.document_id),
- e,
- "unable to increment sha ref count",
- ));
- }
-
- // Since we now store a pdf version of docx files (when the conversion is successful)
- // we need to also copy this over into the new dss file
- let url_encoded_owner = urlencoding::encode(original_document_metadata.owner.as_ref());
- // Get the source document key
- let source_key = build_docx_to_pdf_converted_document_key(
- &url_encoded_owner,
- &original_document_metadata.document_id,
- );
-
- let dest_key = build_docx_to_pdf_converted_document_key(
- user_id.as_ref(),
- &updated_document_metadata.document_id,
- );
-
- if let Err(e) = ctx.s3_client.copy_document(&source_key, &dest_key).await {
- tracing::error!(error=?e, "unable to copy converted docx document");
- return Err((
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to copy converted docx document",
- ));
- }
- }
- // handle live collab
- Some(FileType::Md) => {
- tracing::debug!("md file type, copying through sync service");
-
- // send copy document request to sync service
- if let Err(e) = ctx
- .sync_service_client
- .copy_document(
- &original_document_metadata.document_id, // document we are copying from
- &updated_document_metadata.document_id, // document we are copying to
- version_id,
- )
- .await
- {
- tracing::error!(error=?e, "unable to copy document through sync service");
- return Err((
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to copy document through sync service",
- ));
- }
-
- // TODO: REMOVE_LIVE_COLLAB
- let document_version_id = macro_db_client::document::get_latest_document_version_id(
- &ctx.db,
- &original_document_metadata.document_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get document version id");
- (
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to get document version id",
- )
- })?
- .0;
-
- let dest_key = build_cloud_storage_bucket_document_key(
- user_id.as_ref(),
- &updated_document_metadata.document_id,
- updated_document_metadata.document_version_id,
- );
-
- let source_key = build_cloud_storage_bucket_document_key(
- original_document_metadata.owner.as_ref(),
- &original_document_metadata.document_id,
- document_version_id,
- );
-
- let _ = ctx
- .s3_client
- .copy_document(&source_key, &dest_key)
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "unable to copy live collab document");
- });
- // END: REMOVE_LIVE_COLLAB
- }
- _ => {
- if file_type == Some(&FileType::Pdf) {
- tracing::trace!("pdf file type, copying extra file information");
- macro_db_client::document::copy_document::copy_pdf_parts::copy_pdf_parts(
- ctx.db.clone(),
- &updated_document_metadata.document_id,
- &original_document_metadata.document_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to copy pdf parts");
- (
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to copy pdf parts",
- )
- })?;
- }
-
- let document_version_id = if file_type.is_none_or(|f| f.is_static()) {
- macro_db_client::document::get_document_version_id(
- &ctx.db,
- &original_document_metadata.document_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get document version id");
- (
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to get document version id",
- )
- })?
- .0
- } else {
- macro_db_client::document::get_latest_document_version_id(
- &ctx.db,
- &original_document_metadata.document_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get document version id");
- (
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to get document version id",
- )
- })?
- .0
- };
-
- let dest_key = build_cloud_storage_bucket_document_key(
- user_id.as_ref(),
- &updated_document_metadata.document_id,
- updated_document_metadata.document_version_id,
- );
-
- let source_key = build_cloud_storage_bucket_document_key(
- original_document_metadata.owner.as_ref(),
- &original_document_metadata.document_id,
- document_version_id,
- );
-
- // handle non live collab
- ctx.s3_client
- .copy_document(&source_key, &dest_key)
- .await
- .map_err(|err| {
- tracing::error!(error=?err, "unable to copy document");
- (
- Some(updated_document_metadata.document_id.clone()),
- err,
- "unable to copy document",
- )
- })?;
- }
- };
-
- let document_response_metadata = match DocumentResponseMetadata::from_document_metadata(
- &updated_document_metadata,
- ) {
- Ok(document_response_metadata) => document_response_metadata,
- Err(e) => {
- tracing::error!(error=?e, "unable to convert document metadata. this should never happen");
- return Err((
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to copy document metadata. this should never happen",
- ));
- }
- };
-
- let mut transaction = match ctx.db.begin().await {
- Ok(transaction) => transaction,
- Err(e) => {
- tracing::error!(error=?e, "unable to begin transaction");
-
- return Err((
- Some(updated_document_metadata.document_id.clone()),
- e.into(),
- "unable to copy document",
- ));
- }
- };
- if let Err(e) = upsert_user_history(
- &mut transaction,
- user_id.copied(),
- &updated_document_metadata.document_id,
- "document",
- )
- .await
- {
- tracing::error!(error=?e, "unable to insert document into history");
- return Err((
- Some(updated_document_metadata.document_id.clone()),
- e,
- "unable to create document",
- ));
- }
-
- if let Err(e) = transaction.commit().await {
- tracing::error!(error=?e, "unable to commit transaction");
- return Err((
- Some(updated_document_metadata.document_id.clone()),
- e.into(),
- "unable to copy document",
- ));
- }
-
- // Copy task properties if the original document is a task
- if original_document_metadata.sub_type == Some(DocumentSubType::Task)
- && let Err(e) = ctx
- .system_properties_service
- .copy_task_properties(
- &original_document_metadata.document_id,
- &updated_document_metadata.document_id,
- )
- .await
- {
- tracing::error!(error=?e, document_id=?updated_document_metadata.document_id, "failed to copy task properties");
- return Err((
- Some(updated_document_metadata.document_id.clone()),
- e.into(),
- "failed to copy task properties",
- ));
- }
-
- let response_data = DocumentResponse {
- document_metadata: document_response_metadata,
- // Only used in create/update
- presigned_url: None,
- };
-
- Ok(GenericResponse::builder()
- .data(&response_data)
- .send(StatusCode::OK))
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs
deleted file mode 100644
index 3a850a92de..0000000000
--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/mod.rs
+++ /dev/null
@@ -1,177 +0,0 @@
-mod copy_document_cleanup;
-mod copy_document_v2;
-
-use std::str::FromStr;
-
-use crate::api::context::EntityAccessService;
-use crate::{
- api::context::ApiContext,
- model::request::documents::copy::{CopyDocumentQueryParams, CopyDocumentRequest},
-};
-use axum::{
- Extension,
- extract::{Json, Path, Query, State},
- http::StatusCode,
- response::IntoResponse,
-};
-use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
-use model::{
- document::{
- DocumentBasic, DocumentMetadata, FileType, FileTypeExt, response::GetDocumentResponse,
- },
- response::{ErrorResponse, GenericErrorResponse, GenericResponse},
- user::axum_extractor::MacroUserExtractor,
-};
-
-use models_permissions::share_permission::access_level::ViewAccessLevel;
-use serde::Deserialize;
-
-#[derive(Deserialize)]
-pub struct Params {
- pub document_id: String,
-}
-
-/// Handles copying a given document. This is the similar to
-/// create_document_handler where you provide the branched_from_id,
-/// branched_from_version_id and document_family_id in the request body. Except
-/// this will not require you to re-upload the document when it's made saving
-/// time and resources.
-#[utoipa::path(
- tag = "document",
- post,
- path = "/documents/{document_id}/copy",
- params(
- ("document_id" = String, Path, description = "Document ID"),
- ("version_id" = Option<i64>, Query, description = "The version id of the document to copy. Defaults to copying the latest version of the document.")
- ),
- responses(
- (status = 200, body=GetDocumentResponse),
- (status = 400, body=GenericErrorResponse),
- (status = 401, body=GenericErrorResponse),
- (status = 403, body=GenericErrorResponse),
- (status = 404, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(state, user_context, document_context, req, _access), fields(user_id=%user_context.macro_user_id, document_version_id=?params.version_id))]
-pub(in crate::api) async fn copy_document_handler(
- _access: DocumentAccessExtractor<ViewAccessLevel, EntityAccessService>,
- State(state): State<ApiContext>,
- user_context: MacroUserExtractor,
- document_context: Extension<DocumentBasic>,
- Path(Params { document_id }): Path<Params>,
- Query(params): Query<CopyDocumentQueryParams>,
- Json(mut req): Json<CopyDocumentRequest>,
-) -> Result<impl IntoResponse, impl IntoResponse> {
- if document_context.deleted_at.is_some() {
- return Err((
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "cannot copy deleted document".into(),
- }),
- )
- .into_response());
- }
-
- // Overrides the document name cleaned document name (removing file extension)
- // if it was accidentally included
- req.document_name =
- FileType::clean_document_name(&req.document_name).unwrap_or(req.document_name);
-
- let mut document_metadata: DocumentMetadata = if let Some(version_id) = params.version_id {
- match macro_db_client::document::get_document_version(
- &state.db,
- document_id.as_str(),
- version_id,
- )
- .await
- {
- Ok(document_metadata) => document_metadata,
- Err(e) => {
- tracing::error!(error=?e, "unable to get document metadata");
- return Err(GenericResponse::builder()
- .message("unable to get document metadata")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR));
- }
- }
- } else {
- match macro_db_client::document::get_document(&state.db, document_id.as_str()).await {
- Ok(document_metadata) => document_metadata,
- Err(e) => {
- tracing::error!(error=?e, "unable to get document metadata");
- return Err(GenericResponse::builder()
- .message("unable to get document metadata")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR));
- }
- }
- };
-
- if let Some(project_id) = &document_metadata.project_id {
- // Depending on if you are the project owner, we should copy the project id
- let project = macro_db_client::projects::get_project::get_basic_project::get_basic_project(
- &state.db, project_id,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get project");
- GenericResponse::builder()
- .message("unable to get project")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR)
- })?;
-
- if !project.user_id.eq(&user_context.macro_user_id) {
- // Do not copy the project id of the document
- document_metadata.project_id = None;
- document_metadata.project_name = None;
- }
- }
-
- let file_type: Option<FileType> = document_context
- .file_type
- .as_deref()
- .and_then(|f| FileType::from_str(f).ok());
-
- // If the docx doesn't have a document bom associated with it, we cannot copy it
- if file_type == Some(FileType::Docx) && document_metadata.document_bom.is_none() {
- tracing::error!("document bom is missing");
- return Err(GenericResponse::builder()
- .message("document bom is missing")
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR));
- }
-
- match copy_document_v2::copy_document(
- &state,
- user_context.macro_user_id.clone(),
- &document_metadata,
- &req.document_name,
- file_type.as_ref(),
- req.version_id,
- )
- .await
- {
- Ok(response) => Ok(response),
- Err((document, e, msg)) => {
- tracing::error!(error=?e, msg, "unable to copy document");
- // TODO: cleanup if document exists
- if let Some(document_id) = document {
- tracing::trace!("document exists, cleaning up");
- copy_document_cleanup::copy_document_cleanup(
- &state.db,
- &state.s3_client,
- user_context.macro_user_id.to_string(),
- document_id,
- )
- .await;
- }
-
- Err(GenericResponse::builder()
- .message(msg)
- .is_error(true)
- .send(StatusCode::INTERNAL_SERVER_ERROR))
- }
- }
-}
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
index 00a3f24f6a..1672ca0459 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/mod.rs
@@ -5,8 +5,7 @@ use axum::{
};
use tower::ServiceBuilder;
-// needs to be public in api crate for swagger
-pub(in crate::api) mod copy_document;
+// NOTE: copy_document is now served by the documents hex crate router
pub(in crate::api) mod delete_document;
pub(in crate::api) mod export_document;
pub(in crate::api) mod get_batch_preview;
@@ -92,24 +91,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
get(get_document_key::get_document_key_handler)
.layer(ensure_document_exists_middleware.clone()),
)
- .route(
- "/{document_id}/copy",
- post(copy_document::copy_document_handler).layer(
- ServiceBuilder::new()
- .layer(axum::middleware::from_fn(
- macro_middleware::auth::ensure_user_exists::handler,
- ))
- .layer(ensure_document_exists_middleware.clone())
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- macro_middleware::user_permissions::attach_user_permissions::handler,
- ))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- macro_middleware::user_permissions::validate_user_quota::document_handler,
- )),
- ),
- )
+ // NOTE: /{document_id}/copy is now served by the documents hex crate router
// NOTE: GET /{document_id} is now served by the documents hex crate router
.route(
"/{document_id}/views",
diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
index 0ee4a0c8c5..1d7ab3de49 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -31,7 +31,6 @@ use crate::{
model::{
request::{
documents::{
- copy::{CopyDocumentQueryParams, CopyDocumentRequest},
preview::GetBatchPreviewRequest,
save::{PreSaveDocumentRequest, SaveDocumentRequest},
user_document_view_location::UpsertUserDocumentViewLocationRequest,
@@ -141,7 +140,7 @@ use utoipa::OpenApi;
documents_hex::inbound::axum_router::get_document_handler,
documents::get_document_version::handler,
documents_hex::inbound::axum_router::create_document_handler,
- documents::copy_document::copy_document_handler,
+ documents_hex::inbound::axum_router::copy_document_handler,
documents::save_document::save_document_handler,
documents::pre_save::presave_document_handler,
documents_hex::inbound::axum_router::edit_document_handler,
@@ -267,8 +266,9 @@ use utoipa::OpenApi;
CreateBulkDocumentResponse, // Create document bulk
GetDocumentListResult,
GetDocumentSearchResponse, // Search document
- CopyDocumentRequest,
- CopyDocumentQueryParams, // Copy document
+ documents_hex::domain::models::CopyDocumentRequest,
+ documents_hex::domain::models::CopyDocumentQueryParams,
+ documents_hex::domain::models::CopyDocumentResponse, // Copy document
documents_hex::domain::models::EditDocumentServiceArgs,
documents_hex::inbound::axum_router::EditDocumentResponse, // Edit document
UserDocumentsResponse,
diff --git a/rust/cloud-storage/document_storage_service/src/model/request/documents/copy.rs b/rust/cloud-storage/document_storage_service/src/model/request/documents/copy.rs
deleted file mode 100644
index b046a89eff..0000000000
--- a/rust/cloud-storage/document_storage_service/src/model/request/documents/copy.rs
+++ /dev/null
@@ -1,16 +0,0 @@
-use model::sync_service::SyncServiceVersionID;
-use utoipa::ToSchema;
-
-#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct CopyDocumentRequest {
- /// The name of the document without extension.
- pub document_name: String,
- pub version_id: Option<SyncServiceVersionID>,
-}
-
-#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, ToSchema)]
-pub struct CopyDocumentQueryParams {
- /// The version id of the document to copy. Defaults to copying the latest version of the document.
- pub version_id: Option<i64>,
-}
diff --git a/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rs
index 68450bcc65..7adefbb1da 100644
--- a/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/model/request/documents/mod.rs
@@ -1,4 +1,3 @@
-pub mod copy;
pub mod get_user_documents;
pub mod location;
pub mod preview;
diff --git a/rust/cloud-storage/documents/.sqlx/query-038bbad2a1388db2e9d3da5f107ecc5418ff770838a4acfbd28bec8b78e16874.json b/rust/cloud-storage/documents/.sqlx/query-038bbad2a1388db2e9d3da5f107ecc5418ff770838a4acfbd28bec8b78e16874.json
new file mode 100644
index 0000000000..4ca8943e4a
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-038bbad2a1388db2e9d3da5f107ecc5418ff770838a4acfbd28bec8b78e16874.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentInstance\" (\"documentId\", \"sha\")\n VALUES ($1, $2)\n RETURNING id, sha, \"createdAt\"::timestamptz as created_at, \"updatedAt\"::timestamptz as updated_at;\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "sha",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "038bbad2a1388db2e9d3da5f107ecc5418ff770838a4acfbd28bec8b78e16874"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json b/rust/cloud-storage/documents/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json
deleted file mode 100644
index 83caec4173..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $2\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "03a323aefdba22727c6789b28d90d7200e795a4591812dab4c4e7718c5512055"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-0a4d1f2c9890cc537fde22835fc5298215a79e06fd983ac9a13f52836719e8fc.json b/rust/cloud-storage/documents/.sqlx/query-0a4d1f2c9890cc537fde22835fc5298215a79e06fd983ac9a13f52836719e8fc.json
new file mode 100644
index 0000000000..9efa7fb5d4
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-0a4d1f2c9890cc537fde22835fc5298215a79e06fd983ac9a13f52836719e8fc.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentText\" (\"documentId\", \"content\", \"tokenCount\")\n SELECT $1, content, \"tokenCount\" FROM \"DocumentText\"\n WHERE \"documentId\" = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0a4d1f2c9890cc537fde22835fc5298215a79e06fd983ac9a13f52836719e8fc"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-2b56d4020e5e9882bf82e2909868eda21c8f93ee647274cbd0f7f8b8cfad02bf.json b/rust/cloud-storage/documents/.sqlx/query-2b56d4020e5e9882bf82e2909868eda21c8f93ee647274cbd0f7f8b8cfad02bf.json
new file mode 100644
index 0000000000..158ddfee1e
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-2b56d4020e5e9882bf82e2909868eda21c8f93ee647274cbd0f7f8b8cfad02bf.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentInstanceModificationData\" (\"documentInstanceId\", \"modificationData\")\n VALUES ($1, $2);\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Int8",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "2b56d4020e5e9882bf82e2909868eda21c8f93ee647274cbd0f7f8b8cfad02bf"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-3463e587c615fd82082c41897c917aef97239bcdd408c928caffed0d69c21613.json b/rust/cloud-storage/documents/.sqlx/query-3463e587c615fd82082c41897c917aef97239bcdd408c928caffed0d69c21613.json
new file mode 100644
index 0000000000..68c21db99b
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-3463e587c615fd82082c41897c917aef97239bcdd408c928caffed0d69c21613.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentProcessResult\" (\"documentId\", \"content\", \"jobType\")\n SELECT $1, content, 'pdf_preprocess' FROM \"DocumentProcessResult\"\n WHERE \"documentId\" = $2 and \"jobType\" = 'pdf_preprocess'\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "3463e587c615fd82082c41897c917aef97239bcdd408c928caffed0d69c21613"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json b/rust/cloud-storage/documents/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
deleted file mode 100644
index 44d3a67e72..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT EXISTS (\n SELECT 1\n FROM public.email_threads t\n JOIN public.email_links l ON l.id = t.link_id\n WHERE t.id = $1::uuid\n AND l.macro_id = $2\n ) AS \"exists!\"\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "exists!",
- "type_info": "Bool"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "37b5168f739c490a3373c65eab35f247a34af0a8e659cbad61cb99e3094e5a60"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json b/rust/cloud-storage/documents/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
deleted file mode 100644
index 60bfee0647..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "3a7be99469ed150e0506efa786b672198a6d3419c6bd5548418520cd3e6a8e95"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json b/rust/cloud-storage/documents/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
deleted file mode 100644
index 58618b2697..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n -- CTE to recursively find all parent projects, starting from the given project.\n WITH RECURSIVE project_hierarchy AS (\n -- Base case: Start with the project ID provided.\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n -- Recursive case: Find the parent of the project from the previous step.\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n -- The subquery now gathers all levels as plain text.\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n -- The hierarchy CTE includes the starting project, so this is all we need.\n SELECT project_id FROM project_hierarchy\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n -- We only need to check ProjectPermission for the items in the hierarchy.\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\"\n WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4afa79ca95bdbcebe9d3de7ebb204636419e6cf89e650a8716c40ab2e588aa5b"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json b/rust/cloud-storage/documents/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
deleted file mode 100644
index 524cc25ec7..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $2 AND item_id IN (\n SELECT $1 -- The chat itself\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "4c695b011d49ba7d5fce4b309875ed952dc386ac760444d7883c5a76718f15be"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json b/rust/cloud-storage/documents/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
deleted file mode 100644
index 03a8dbf6bb..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Chat\" c\n JOIN \"Project\" p ON c.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE c.id = $1 AND c.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "54e3755d63a676a7fa70da77321e618032f0130c73eb6b0ae985f07c5c6c448b"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json b/rust/cloud-storage/documents/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
deleted file mode 100644
index 655495fb29..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT c.id\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "UuidArray"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "7617f808df94ffe77c8195a911ee6b230a21fe9935e099d1310d244248ca253a"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json b/rust/cloud-storage/documents/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
deleted file mode 100644
index 2bde15938f..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT id as project_id\n FROM \"Project\"\n WHERE id = $1 AND \"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "79d3bc72e6f424765706f7deea426379ae49cbd70dd122daedd95343618b9ac6"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154.json b/rust/cloud-storage/documents/.sqlx/query-7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154.json
new file mode 100644
index 0000000000..b30cb13f0f
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154.json
@@ -0,0 +1,128 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n d.id as \"document_id\",\n d.owner as \"owner\",\n d.name as \"document_name\",\n COALESCE(di.id, db.id) as \"document_version_id!\",\n d.\"branchedFromId\" as \"branched_from_id\",\n d.\"branchedFromVersionId\" as \"branched_from_version_id\",\n d.\"documentFamilyId\" as \"document_family_id\",\n d.\"createdAt\"::timestamptz as \"created_at\",\n d.\"updatedAt\"::timestamptz as \"updated_at\",\n d.\"fileType\" as \"file_type\",\n db.bom_parts as \"document_bom?\",\n di.modification_data as \"modification_data?\",\n d.\"projectId\" as \"project_id\",\n p.name as \"project_name?\",\n di.sha as \"sha?\",\n dt.sub_type as \"sub_type?: DocumentSubType\",\n d.\"deletedAt\"::timestamptz as \"deleted_at\"\n FROM\n \"Document\" d\n LEFT JOIN document_sub_type dt ON dt.document_id = d.id\n LEFT JOIN LATERAL (\n SELECT\n i.id,\n i.sha,\n i.\"createdAt\",\n (\n SELECT\n imod.\"modificationData\"\n FROM\n \"DocumentInstanceModificationData\" imod\n WHERE\n imod.\"documentInstanceId\" = i.id\n ) as modification_data,\n i.\"updatedAt\"\n FROM\n \"DocumentInstance\" i\n WHERE\n i.\"documentId\" = d.id\n AND\n i.id = $2\n ) di ON true\n LEFT JOIN LATERAL (\n SELECT\n b.id,\n (\n SELECT\n json_agg(\n json_build_object(\n 'id', bp.id,\n 'sha', bp.sha,\n 'path', bp.path\n )\n )\n FROM\n \"BomPart\" bp\n WHERE\n bp.\"documentBomId\" = b.id\n ) as bom_parts\n FROM\n \"DocumentBom\" b\n WHERE\n b.\"documentId\" = d.id\n AND\n b.id = $2\n ) db ON d.\"fileType\" = 'docx'\n LEFT JOIN LATERAL (\n SELECT\n p.name\n FROM \"Project\" p\n WHERE p.id = d.\"projectId\"\n ) p ON d.\"projectId\" IS NOT NULL\n WHERE\n d.id = $1\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "document_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "document_version_id!",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 4,
+ "name": "branched_from_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "branched_from_version_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 6,
+ "name": "document_family_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 7,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 8,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "file_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "document_bom?",
+ "type_info": "Json"
+ },
+ {
+ "ordinal": 11,
+ "name": "modification_data?",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 12,
+ "name": "project_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 13,
+ "name": "project_name?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 14,
+ "name": "sha?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 15,
+ "name": "sub_type?: DocumentSubType",
+ "type_info": {
+ "Custom": {
+ "name": "document_sub_type_value",
+ "kind": {
+ "Enum": [
+ "task"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 16,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ null,
+ true,
+ true,
+ true,
+ null,
+ null,
+ true,
+ null,
+ null,
+ true,
+ false,
+ false,
+ false,
+ null
+ ]
+ },
+ "hash": "7fc9da48b6c62ab0db6327e300eb80eafcff34b2d5d13621a688883acc3db154"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3.json b/rust/cloud-storage/documents/.sqlx/query-96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3.json
new file mode 100644
index 0000000000..44fbc49ef1
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3.json
@@ -0,0 +1,24 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO document_sub_type (document_id, sub_type)\n VALUES ($1, $2)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "document_sub_type_value",
+ "kind": {
+ "Enum": [
+ "task"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "96a2c0a064e56b4fd812c2768403fc086f4518149772d661222d54592df920d3"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json b/rust/cloud-storage/documents/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
deleted file mode 100644
index e42c9f2009..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM \"Document\" d\n JOIN \"Project\" p ON d.\"projectId\" = p.id AND p.\"deletedAt\" IS NULL\n WHERE d.id = $1 AND d.\"deletedAt\" IS NULL\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT DISTINCT user_id FROM \"UserItemAccess\"\n WHERE item_id IN (\n SELECT $1\n UNION\n SELECT project_id FROM project_hierarchy\n )\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "96d853b887f2e6d7aac6b15ddd2b71a8d8900d2ef30047da7ca1a5940503b6d0"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-a9adc96aff5f25177495a9258a185d8cf8a255b6805fecec787953461a09d78b.json b/rust/cloud-storage/documents/.sqlx/query-a9adc96aff5f25177495a9258a185d8cf8a255b6805fecec787953461a09d78b.json
new file mode 100644
index 0000000000..7376c5ab40
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-a9adc96aff5f25177495a9258a185d8cf8a255b6805fecec787953461a09d78b.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"Document\" (owner, name, \"fileType\", \"documentFamilyId\", \"branchedFromId\", \"branchedFromVersionId\", \"projectId\")\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id, \"createdAt\"::timestamptz as created_at, \"updatedAt\"::timestamptz as updated_at;\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Int8",
+ "Text",
+ "Int8",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "a9adc96aff5f25177495a9258a185d8cf8a255b6805fecec787953461a09d78b"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-bd6ed4253d2bff9f78562aa09f2cbb794195e1e69ffcbf722c0a2e523f196c2f.json b/rust/cloud-storage/documents/.sqlx/query-bd6ed4253d2bff9f78562aa09f2cbb794195e1e69ffcbf722c0a2e523f196c2f.json
new file mode 100644
index 0000000000..c6c0800423
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-bd6ed4253d2bff9f78562aa09f2cbb794195e1e69ffcbf722c0a2e523f196c2f.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT \"userId\" as user_id FROM \"Project\" WHERE id = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "bd6ed4253d2bff9f78562aa09f2cbb794195e1e69ffcbf722c0a2e523f196c2f"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-c12febd2112dc6065735c6e44d735684cd0163b2f71460d838be8eb16a25b7b6.json b/rust/cloud-storage/documents/.sqlx/query-c12febd2112dc6065735c6e44d735684cd0163b2f71460d838be8eb16a25b7b6.json
new file mode 100644
index 0000000000..4670c2e5dd
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-c12febd2112dc6065735c6e44d735684cd0163b2f71460d838be8eb16a25b7b6.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentBom\" (\"documentId\")\n VALUES ($1)\n RETURNING id, \"createdAt\"::timestamptz as created_at, \"updatedAt\"::timestamptz as updated_at;\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 1,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "c12febd2112dc6065735c6e44d735684cd0163b2f71460d838be8eb16a25b7b6"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json b/rust/cloud-storage/documents/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json
deleted file mode 100644
index 6ef8856744..0000000000
--- a/rust/cloud-storage/documents/.sqlx/query-d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH RECURSIVE project_hierarchy AS (\n SELECT p.id as project_id\n FROM email_threads t\n JOIN \"Project\" p ON t.project_id = p.id AND p.\"deletedAt\" IS NULL\n WHERE t.id = $1\n UNION ALL\n SELECT parent.id as project_id\n FROM project_hierarchy ph\n JOIN \"Project\" parent ON parent.id = (\n SELECT \"parentId\" FROM \"Project\" WHERE id = ph.project_id AND \"parentId\" IS NOT NULL AND \"deletedAt\" IS NULL\n )\n )\n SELECT access_level FROM (\n -- Source 1: Cast the AccessLevel enum to text.\n SELECT access_level::text FROM \"UserItemAccess\"\n WHERE user_id = $3 AND item_id IN (\n SELECT $2 -- The thread ID as text\n UNION\n SELECT project_id FROM project_hierarchy -- All parent projects\n )\n UNION ALL\n -- Source 2: Select the publicAccessLevel (which is already text).\n SELECT \"publicAccessLevel\" as access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true AND \"publicAccessLevel\" IS NOT NULL AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $2\n UNION\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" IN (SELECT project_id FROM project_hierarchy)\n )\n ) as all_levels\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "access_level",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text"
- ]
- },
- "nullable": [
- null
- ]
- },
- "hash": "d536db3ccfb32aee9a48227e2b15d2404023ea24b62c159466c95899d76e29ed"
-}
diff --git a/rust/cloud-storage/documents/.sqlx/query-debae3edf7b8f02aefffa4464ad9a4c474f1e7d5c0071bdb1261df0c1d8b2373.json b/rust/cloud-storage/documents/.sqlx/query-debae3edf7b8f02aefffa4464ad9a4c474f1e7d5c0071bdb1261df0c1d8b2373.json
new file mode 100644
index 0000000000..be486fcbde
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-debae3edf7b8f02aefffa4464ad9a4c474f1e7d5c0071bdb1261df0c1d8b2373.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \"modificationData\" as modification_data\n FROM \"DocumentInstanceModificationData\"\n WHERE \"documentInstanceId\" = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "modification_data",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "debae3edf7b8f02aefffa4464ad9a4c474f1e7d5c0071bdb1261df0c1d8b2373"
+}
diff --git a/rust/cloud-storage/documents/examples/documents_toolset.rs b/rust/cloud-storage/documents/examples/documents_toolset.rs
index fe26d8373c..1ba24de8e2 100644
--- a/rust/cloud-storage/documents/examples/documents_toolset.rs
+++ b/rust/cloud-storage/documents/examples/documents_toolset.rs
@@ -80,6 +80,14 @@ impl TaskPropertiesPort for NoOpTaskProperties {
) -> anyhow::Result<()> {
Ok(())
}
+
+ async fn copy_task_properties(
+ &self,
+ _from_task_id: &str,
+ _to_task_id: &str,
+ ) -> anyhow::Result<()> {
+ Ok(())
+ }
}
/// The prompt to use in the example.
diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rs
index fb3baa2489..551a82afc7 100644
--- a/rust/cloud-storage/documents/src/domain/models.rs
+++ b/rust/cloud-storage/documents/src/domain/models.rs
@@ -1,7 +1,8 @@
//! Domain models for the documents crate.
use macro_user_id::user_id::MacroUserIdStr;
-use model::document::FileType;
+use model::document::{DocumentMetadata, FileType};
+use model::sync_service::SyncServiceVersionID;
use models_properties::api::requests::SetPropertyValue;
/// SHA256 hash of an empty string — used for empty markdown documents (tasks).
@@ -30,6 +31,48 @@ pub enum DocumentError {
Internal(#[from] anyhow::Error),
}
+/// Response wrapper for the copy document endpoint.
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CopyDocumentResponse {
+ /// Indicates if an error occurred.
+ pub error: bool,
+ /// The copied document data.
+ pub data: model::document::response::DocumentResponse,
+}
+
+/// Arguments for copying a document in the repository.
+pub struct CopyDocumentRepoArgs {
+ /// The original document metadata to copy from.
+ pub original_document: DocumentMetadata,
+ /// The new owner/copier user ID.
+ pub user_id: MacroUserIdStr<'static>,
+ /// The name for the new document.
+ pub document_name: String,
+ /// The file type of the document.
+ pub file_type: Option<FileType>,
+}
+
+/// Request body for copying a document.
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct CopyDocumentRequest {
+ /// The name of the new document (without extension).
+ pub document_name: String,
+ /// Optional sync service version ID for MD documents.
+ pub version_id: Option<SyncServiceVersionID>,
+}
+
+/// Query parameters for the copy document endpoint.
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
+pub struct CopyDocumentQueryParams {
+ /// The DB version id of the document to copy. Defaults to latest.
+ pub version_id: Option<i64>,
+}
+
/// Arguments for creating a document in the repository.
pub struct CreateDocumentRepoArgs {
/// Optional user-provided document ID.
diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rs
index 20ff68f327..fea1060033 100644
--- a/rust/cloud-storage/documents/src/domain/ports.rs
+++ b/rust/cloud-storage/documents/src/domain/ports.rs
@@ -13,9 +13,11 @@ use model::document::response::{
};
use model::document::{ContentType, DocumentBasic, DocumentMetadata};
+use model::sync_service::SyncServiceVersionID;
+
use super::models::{
- CreateDocumentRepoArgs, CreateTaskRequest, CreateTaskResponse, DocumentError,
- EditDocumentRepoArgs, EditDocumentServiceArgs, LocationQueryParams,
+ CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest, CreateTaskResponse,
+ DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs, LocationQueryParams,
};
/// Repository for accessing document data from the database.
@@ -127,6 +129,35 @@ pub trait DocumentRepo: Send + Sync + 'static {
user_id: &str,
document_id: &str,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Get document metadata at a specific version ID.
+ fn get_document_metadata_at_version(
+ &self,
+ document_id: &str,
+ version_id: i64,
+ ) -> impl Future<Output = Result<DocumentMetadata, Self::Err>> + Send;
+
+ /// Get the owner of a project by project ID.
+ fn get_project_owner(
+ &self,
+ project_id: &str,
+ ) -> impl Future<Output = Result<MacroUserIdStr<'static>, Self::Err>> + Send;
+
+ /// Copy a document's DB records in a single transaction.
+ ///
+ /// Creates: Document row, version (DocumentBom or DocumentInstance),
+ /// SharePermission, DocumentPermission, UserItemAccess, and user history.
+ fn copy_document(
+ &self,
+ args: CopyDocumentRepoArgs,
+ ) -> impl Future<Output = Result<DocumentMetadata, Self::Err>> + Send;
+
+ /// Copy PDF-specific data (DocumentText, DocumentProcessResult) for a copied document.
+ fn copy_pdf_parts(
+ &self,
+ new_document_id: &str,
+ original_document_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
/// Port for generating S3 presigned upload URLs.
@@ -146,6 +177,13 @@ pub trait PresignedUploadUrlPort: Send + Sync + 'static {
sha: &str,
content_type: ContentType,
) -> impl Future<Output = anyhow::Result<String>> + Send;
+
+ /// Copy a document object from source key to destination key within the storage bucket.
+ fn copy_object(
+ &self,
+ source_key: &str,
+ destination_key: &str,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
}
/// Port for attaching task system properties.
@@ -171,6 +209,13 @@ pub trait TaskPropertiesPort: Send + Sync + 'static {
property_definition_id: uuid::Uuid,
value: Option<models_properties::api::requests::SetPropertyValue>,
) -> impl Future<Output = anyhow::Result<()>> + Send;
+
+ /// Copy all task property values from one task to another.
+ fn copy_task_properties(
+ &self,
+ from_task_id: &str,
+ to_task_id: &str,
+ ) -> impl Future<Output = anyhow::Result<()>> + Send;
}
/// Service interface for document operations.
@@ -243,6 +288,17 @@ pub trait DocumentService: Send + Sync + 'static {
status: &str,
) -> impl Future<Output = Result<(), DocumentError>> + Send;
+ /// Copy an existing document, creating a new document with the same content.
+ fn copy_document(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ document_context: DocumentBasic,
+ user_id: MacroUserIdStr<'static>,
+ document_name: String,
+ query_version_id: Option<i64>,
+ sync_version_id: Option<SyncServiceVersionID>,
+ ) -> impl Future<Output = Result<model::document::response::DocumentResponse, DocumentError>> + Send;
+
/// Create a task document and optionally set property values on it.
fn create_task(
&self,
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index d83fc4ba40..4ea8d26248 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -30,9 +30,9 @@ use s3_key::{
use tracing;
use super::models::{
- CloudFrontConfig, CreateDocumentRepoArgs, CreateTaskRequest, CreateTaskResponse, DocumentError,
- EMPTY_SHA256, EditDocumentRepoArgs, EditDocumentServiceArgs, FileTypeUpdate,
- LocationQueryParams,
+ CloudFrontConfig, CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest,
+ CreateTaskResponse, DocumentError, EMPTY_SHA256, EditDocumentRepoArgs, EditDocumentServiceArgs,
+ FileTypeUpdate, LocationQueryParams,
};
use super::ports::{DocumentRepo, DocumentService, PresignedUploadUrlPort, TaskPropertiesPort};
@@ -691,6 +691,219 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
Ok(())
}
+ #[tracing::instrument(err, skip(self, document_context, document_name))]
+ async fn copy_document(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ document_context: DocumentBasic,
+ user_id: MacroUserIdStr<'static>,
+ document_name: String,
+ query_version_id: Option<i64>,
+ sync_version_id: Option<model::sync_service::SyncServiceVersionID>,
+ ) -> Result<DocumentResponse, DocumentError> {
+ use model::document::response::DocumentResponseMetadata;
+
+ if document_name.graphemes(true).count() > 100 {
+ return Err(DocumentError::BadRequest("name too long".to_string()));
+ }
+
+ if document_context.deleted_at.is_some() {
+ return Err(DocumentError::BadRequest(
+ "cannot copy deleted document".to_string(),
+ ));
+ }
+
+ let document_id = &entity_access_receipt.entity().entity_id;
+
+ // Get full document metadata (at specific version or latest)
+ let mut original_metadata = if let Some(version_id) = query_version_id {
+ self.repo
+ .get_document_metadata_at_version(document_id, version_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ } else {
+ self.repo
+ .get_document_metadata(document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ };
+
+ // Check project ownership - only copy project_id if the user owns the project
+ if let Some(project_id) = &original_metadata.project_id {
+ match self.repo.get_project_owner(project_id).await {
+ Ok(project_owner) => {
+ if project_owner.as_ref() != user_id.as_ref() {
+ original_metadata.project_id = None;
+ original_metadata.project_name = None;
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "unable to get project owner");
+ return Err(DocumentError::Internal(e.into()));
+ }
+ }
+ }
+
+ let file_type: Option<FileType> = document_context
+ .file_type
+ .as_deref()
+ .and_then(|f| FileType::from_str(f).ok());
+
+ // Validate DOCX has BOM
+ if file_type == Some(FileType::Docx) && original_metadata.document_bom.is_none() {
+ return Err(DocumentError::Internal(anyhow!("document bom is missing")));
+ }
+
+ // Clean the document name
+ let document_name = FileType::clean_document_name(&document_name).unwrap_or(document_name);
+
+ // Create the copy in the database
+ let new_metadata = self
+ .repo
+ .copy_document(CopyDocumentRepoArgs {
+ original_document: original_metadata.clone(),
+ user_id: user_id.clone(),
+ document_name,
+ file_type,
+ })
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?;
+
+ let new_document_id = new_metadata.document_id.clone();
+
+ // File-type-specific S3 operations
+ let copy_result = match file_type {
+ Some(FileType::Docx) => {
+ // Copy the converted PDF version
+ let url_encoded_owner = urlencoding::encode(original_metadata.owner.as_ref());
+ let source_key = build_docx_to_pdf_converted_document_key(
+ &url_encoded_owner,
+ &original_metadata.document_id,
+ );
+ let dest_key =
+ build_docx_to_pdf_converted_document_key(user_id.as_ref(), &new_document_id);
+ self.upload_url_service
+ .copy_object(&source_key, &dest_key)
+ .await
+ }
+ Some(FileType::Md) => {
+ // Copy via sync service
+ if let Err(e) = self
+ .sync_service_client
+ .copy_document(
+ &original_metadata.document_id,
+ &new_document_id,
+ sync_version_id,
+ )
+ .await
+ {
+ tracing::error!(error=?e, "unable to copy document through sync service");
+ self.cleanup_document(&new_document_id).await;
+ return Err(DocumentError::Internal(e));
+ }
+
+ // Also copy S3 file
+ let source_version_id = self
+ .repo
+ .get_latest_document_version_id(&original_metadata.document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ .0;
+
+ let source_key = build_cloud_storage_bucket_document_key(
+ original_metadata.owner.as_ref(),
+ &original_metadata.document_id,
+ source_version_id,
+ );
+ let dest_key = build_cloud_storage_bucket_document_key(
+ user_id.as_ref(),
+ &new_document_id,
+ new_metadata.document_version_id,
+ );
+ // Best effort S3 copy for live collab
+ let _ = self
+ .upload_url_service
+ .copy_object(&source_key, &dest_key)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "unable to copy live collab document");
+ });
+ Ok(())
+ }
+ _ => {
+ // Copy PDF parts if applicable
+ if file_type == Some(FileType::Pdf)
+ && let Err(e) = self
+ .repo
+ .copy_pdf_parts(&new_document_id, &original_metadata.document_id)
+ .await
+ {
+ tracing::error!(error=?e, "unable to copy pdf parts");
+ self.cleanup_document(&new_document_id).await;
+ return Err(DocumentError::Internal(e.into()));
+ }
+
+ // Get source version id
+ let source_version_id = if file_type.is_none_or(|f| f.is_static()) {
+ self.repo
+ .get_document_version_id(&original_metadata.document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ .0
+ } else {
+ self.repo
+ .get_latest_document_version_id(&original_metadata.document_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?
+ .0
+ };
+
+ let source_key = build_cloud_storage_bucket_document_key(
+ original_metadata.owner.as_ref(),
+ &original_metadata.document_id,
+ source_version_id,
+ );
+ let dest_key = build_cloud_storage_bucket_document_key(
+ user_id.as_ref(),
+ &new_document_id,
+ new_metadata.document_version_id,
+ );
+ self.upload_url_service
+ .copy_object(&source_key, &dest_key)
+ .await
+ }
+ };
+
+ if let Err(e) = copy_result {
+ tracing::error!(error=?e, "unable to copy document files");
+ self.cleanup_document(&new_document_id).await;
+ return Err(DocumentError::Internal(e));
+ }
+
+ // Copy task properties if the original document is a task
+ if original_metadata.sub_type == Some(document_sub_type::DocumentSubType::Task)
+ && let Err(e) = self
+ .task_properties_service
+ .copy_task_properties(&original_metadata.document_id, &new_document_id)
+ .await
+ {
+ tracing::error!(error=?e, document_id=?new_document_id, "failed to copy task properties");
+ self.cleanup_document(&new_document_id).await;
+ return Err(DocumentError::Internal(e));
+ }
+
+ let document_response_metadata =
+ DocumentResponseMetadata::from_document_metadata(&new_metadata).map_err(|e| {
+ tracing::error!(error=?e, "unable to convert document metadata");
+ DocumentError::Internal(anyhow!("unable to convert document metadata"))
+ })?;
+
+ Ok(DocumentResponse {
+ document_metadata: document_response_metadata,
+ presigned_url: None,
+ })
+ }
+
#[tracing::instrument(skip(self))]
async fn update_task_status(
&self,
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
index f759d99555..af4ebeeab5 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -10,6 +10,7 @@
#[cfg(test)]
mod tests;
+mod copy_document;
mod create_document;
mod create_task;
mod delete_document;
@@ -37,6 +38,7 @@ use crate::domain::models::DocumentError;
use crate::domain::ports::DocumentService;
// Re-export handlers and utoipa path types for external use (swagger, internal routes)
+pub use copy_document::*;
pub use create_document::*;
pub use create_task::*;
pub use delete_document::*;
@@ -127,6 +129,10 @@ where
"/{document_id}/short_id",
axum::routing::get(get_short_id_handler::<T, Svc>),
)
+ .route(
+ "/{document_id}/copy",
+ axum::routing::post(copy_document_handler::<T, Svc>),
+ )
.layer(middleware::from_fn_with_state(
state.clone(),
ensure_document_exists,
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/copy_document.rs b/rust/cloud-storage/documents/src/inbound/axum_router/copy_document.rs
new file mode 100644
index 0000000000..e093458d1c
--- /dev/null
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/copy_document.rs
@@ -0,0 +1,71 @@
+//! Handler for `POST /documents/{document_id}/copy`.
+
+use axum::{
+ Extension, Json,
+ extract::{Path, Query, State},
+};
+use entity_access::domain::ports::EntityAccessService;
+use entity_access::inbound::axum_extractors::DocumentAccessExtractor;
+use model::document::{DocumentBasic, FileTypeExt};
+use model_user::axum_extractor::MacroUserExtractor;
+use models_permissions::share_permission::access_level::ViewAccessLevel;
+
+use super::{DocumentRouterState, Params};
+use crate::domain::models::{
+ CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, DocumentError,
+};
+use crate::domain::ports::DocumentService;
+
+/// Handler for `POST /documents/{document_id}/copy`.
+///
+/// Copies an existing document, creating a new document with the same content.
+/// Does not require re-uploading the document file.
+#[utoipa::path(
+ tag = "document",
+ post,
+ path = "/documents/{document_id}/copy",
+ operation_id = "copy_document",
+ params(
+ ("document_id" = String, Path, description = "Document ID"),
+ ("version_id" = Option<i64>, Query, description = "The version id of the document to copy. Defaults to copying the latest version of the document.")
+ ),
+ request_body = CopyDocumentRequest,
+ responses(
+ (status = 200, body = CopyDocumentResponse),
+ (status = 400, body = model_error_response::ErrorResponse),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 404, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, access, user_context, document_context, req), fields(user_id=%user_context.macro_user_id, document_version_id=?params.version_id))]
+pub async fn copy_document_handler<T: DocumentService, Svc: EntityAccessService>(
+ access: DocumentAccessExtractor<ViewAccessLevel, Svc>,
+ State(state): State<DocumentRouterState<T, Svc>>,
+ user_context: MacroUserExtractor,
+ document_context: Extension<DocumentBasic>,
+ Path(Params { document_id }): Path<Params>,
+ Query(params): Query<CopyDocumentQueryParams>,
+ Json(mut req): Json<CopyDocumentRequest>,
+) -> Result<Json<CopyDocumentResponse>, DocumentError> {
+ // Clean the document name (remove file extension if present)
+ req.document_name = model::document::FileType::clean_document_name(&req.document_name)
+ .unwrap_or(req.document_name);
+
+ let response = state
+ .service
+ .copy_document(
+ access.entity_access_receipt,
+ document_context.0,
+ user_context.macro_user_id,
+ req.document_name,
+ params.version_id,
+ req.version_id,
+ )
+ .await?;
+
+ Ok(Json(CopyDocumentResponse {
+ error: false,
+ data: response,
+ }))
+}
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
index 48e657c16b..64823beec3 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
@@ -5,6 +5,7 @@
#[cfg(test)]
mod tests;
+mod copy;
mod create;
mod edit;
mod share;
@@ -14,7 +15,7 @@ use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model::document::{DocumentBasic, DocumentMetadata};
use sqlx::PgPool;
-use crate::domain::models::{CreateDocumentRepoArgs, EditDocumentRepoArgs};
+use crate::domain::models::{CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs};
use crate::domain::ports::DocumentRepo;
/// PostgreSQL-backed document repository.
@@ -553,4 +554,200 @@ impl DocumentRepo for PgDocumentRepo {
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
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_metadata_at_version(
+ &self,
+ document_id: &str,
+ version_id: i64,
+ ) -> Result<DocumentMetadata, Self::Err> {
+ sqlx::query!(
+ r#"
+ SELECT
+ d.id as "document_id",
+ d.owner as "owner",
+ d.name as "document_name",
+ COALESCE(di.id, db.id) as "document_version_id!",
+ d."branchedFromId" as "branched_from_id",
+ d."branchedFromVersionId" as "branched_from_version_id",
+ d."documentFamilyId" as "document_family_id",
+ d."createdAt"::timestamptz as "created_at",
+ d."updatedAt"::timestamptz as "updated_at",
+ d."fileType" as "file_type",
+ db.bom_parts as "document_bom?",
+ di.modification_data as "modification_data?",
+ d."projectId" as "project_id",
+ p.name as "project_name?",
+ di.sha as "sha?",
+ dt.sub_type as "sub_type?: DocumentSubType",
+ d."deletedAt"::timestamptz as "deleted_at"
+ FROM
+ "Document" d
+ LEFT JOIN document_sub_type dt ON dt.document_id = d.id
+ LEFT JOIN LATERAL (
+ SELECT
+ i.id,
+ i.sha,
+ i."createdAt",
+ (
+ SELECT
+ imod."modificationData"
+ FROM
+ "DocumentInstanceModificationData" imod
+ WHERE
+ imod."documentInstanceId" = i.id
+ ) as modification_data,
+ i."updatedAt"
+ FROM
+ "DocumentInstance" i
+ WHERE
+ i."documentId" = d.id
+ AND
+ i.id = $2
+ ) di ON true
+ LEFT JOIN LATERAL (
+ SELECT
+ b.id,
+ (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', bp.id,
+ 'sha', bp.sha,
+ 'path', bp.path
+ )
+ )
+ FROM
+ "BomPart" bp
+ WHERE
+ bp."documentBomId" = b.id
+ ) as bom_parts
+ FROM
+ "DocumentBom" b
+ WHERE
+ b."documentId" = d.id
+ AND
+ b.id = $2
+ ) db ON d."fileType" = 'docx'
+ LEFT JOIN LATERAL (
+ SELECT
+ p.name
+ FROM "Project" p
+ WHERE p.id = d."projectId"
+ ) p ON d."projectId" IS NOT NULL
+ WHERE
+ d.id = $1
+ LIMIT 1
+ "#,
+ document_id,
+ version_id,
+ )
+ .try_map(|row| {
+ Ok(DocumentMetadata {
+ document_id: row.document_id,
+ document_version_id: row.document_version_id,
+ owner: MacroUserIdStr::parse_from_str(&row.owner)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .into_owned(),
+ document_name: row.document_name,
+ file_type: row.file_type,
+ sha: row.sha,
+ project_id: row.project_id,
+ project_name: row.project_name,
+ branched_from_id: row.branched_from_id,
+ branched_from_version_id: row.branched_from_version_id,
+ document_family_id: row.document_family_id,
+ document_bom: row.document_bom,
+ modification_data: row.modification_data,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ sub_type: row.sub_type,
+ deleted_at: row.deleted_at,
+ })
+ })
+ .fetch_one(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_project_owner(
+ &self,
+ project_id: &str,
+ ) -> Result<MacroUserIdStr<'static>, Self::Err> {
+ let row = sqlx::query!(
+ r#"SELECT "userId" as user_id FROM "Project" WHERE id = $1"#,
+ project_id,
+ )
+ .fetch_one(&self.pool)
+ .await?;
+
+ MacroUserIdStr::parse_from_str(&row.user_id)
+ .map(|u| u.into_owned())
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))
+ }
+
+ #[tracing::instrument(err, skip(self, args))]
+ async fn copy_document(
+ &self,
+ args: CopyDocumentRepoArgs,
+ ) -> Result<DocumentMetadata, Self::Err> {
+ let CopyDocumentRepoArgs {
+ original_document,
+ user_id,
+ document_name,
+ file_type,
+ } = args;
+
+ let mut transaction = self.pool.begin().await?;
+
+ let document = match file_type {
+ Some(model::document::FileType::Docx) => {
+ copy::copy_docx_document(
+ &mut transaction,
+ &original_document,
+ user_id.clone(),
+ &document_name,
+ )
+ .await
+ }
+ _ => {
+ copy::copy_non_docx_document(
+ &mut transaction,
+ &original_document,
+ user_id.clone(),
+ &document_name,
+ )
+ .await
+ }
+ }?;
+
+ let document_id = uuid::Uuid::parse_str(&document.document_id)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ // Create share permission
+ create::set_share_permission(&mut transaction, &document_id, file_type).await?;
+
+ // Insert user item access (Owner level)
+ create::insert_item_access(&mut transaction, &document_id, &user_id).await?;
+
+ // Insert user history
+ let now = chrono::Utc::now();
+ create::insert_history(&mut transaction, &document_id, &user_id, &now).await?;
+
+ transaction.commit().await?;
+
+ Ok(document)
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn copy_pdf_parts(
+ &self,
+ new_document_id: &str,
+ original_document_id: &str,
+ ) -> Result<(), Self::Err> {
+ let mut transaction = self.pool.begin().await?;
+ copy::copy_pdf_parts(&mut transaction, new_document_id, original_document_id).await?;
+ transaction.commit().await?;
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/copy.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/copy.rs
new file mode 100644
index 0000000000..074096e747
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/copy.rs
@@ -0,0 +1,292 @@
+use document_sub_type::DocumentSubType;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::{
+ BomPart, DocumentMetadata, IDWithTimeStamps, SaveBomPart, VersionIDWithTimeStamps,
+ VersionIDWithTimeStampsNoSha,
+};
+use sqlx::{Postgres, Transaction};
+
+/// Copies a given docx document (Document + DocumentBom + BomParts).
+#[tracing::instrument(skip(transaction))]
+pub async fn copy_docx_document(
+ transaction: &mut Transaction<'_, Postgres>,
+ original_document: &DocumentMetadata,
+ user_id: MacroUserIdStr<'static>,
+ new_document_name: &str,
+) -> Result<DocumentMetadata, sqlx::Error> {
+ let original_document_id = &original_document.document_id;
+ let original_document_version_id = original_document.document_version_id;
+
+ let document = sqlx::query_as!(
+ IDWithTimeStamps,
+ r#"
+ INSERT INTO "Document" (owner, name, "fileType", "documentFamilyId", "branchedFromId", "branchedFromVersionId", "projectId")
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
+ "#,
+ user_id.as_ref(),
+ new_document_name,
+ original_document.file_type,
+ original_document.document_family_id,
+ original_document_id,
+ original_document_version_id,
+ original_document.project_id,
+ )
+ .fetch_one(transaction.as_mut())
+ .await
+ .map_err(|err| {
+ tracing::error!(error=?err, "unable to copy document");
+ map_insert_document_error(err)
+ })?;
+
+ let document_bom = sqlx::query_as!(
+ VersionIDWithTimeStampsNoSha,
+ r#"
+ INSERT INTO "DocumentBom" ("documentId")
+ VALUES ($1)
+ RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
+ "#,
+ &document.id,
+ )
+ .fetch_one(transaction.as_mut())
+ .await?;
+
+ // Copy bom parts from the original document
+ let document_bom_parts: Vec<BomPart> =
+ serde_json::from_value(original_document.document_bom.as_ref().unwrap().clone())
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ let saved_bom_parts = create_bom_parts(
+ transaction,
+ document_bom.id,
+ document_bom_parts
+ .into_iter()
+ .map(|b| SaveBomPart {
+ sha: b.sha,
+ path: b.path,
+ })
+ .collect(),
+ )
+ .await?;
+
+ let saved_bom_parts =
+ serde_json::to_value(saved_bom_parts).map_err(|e| sqlx::Error::Decode(Box::new(e)))?;
+
+ Ok(DocumentMetadata {
+ document_id: document.id.clone(),
+ owner: user_id,
+ document_name: new_document_name.to_string(),
+ file_type: original_document.file_type.clone(),
+ sha: None,
+ modification_data: None,
+ branched_from_id: Some(original_document_id.to_string()),
+ branched_from_version_id: Some(original_document_version_id),
+ document_family_id: original_document.document_family_id,
+ project_id: original_document.project_id.clone(),
+ project_name: original_document.project_name.clone(),
+ document_version_id: document_bom.id,
+ document_bom: Some(saved_bom_parts),
+ created_at: document.created_at,
+ updated_at: document.updated_at,
+ sub_type: None,
+ deleted_at: None,
+ })
+}
+
+/// Copies a given non-docx document (Document + DocumentInstance + modification data + sub_type).
+#[tracing::instrument(skip(transaction))]
+pub async fn copy_non_docx_document(
+ transaction: &mut Transaction<'_, Postgres>,
+ original_document: &DocumentMetadata,
+ user_id: MacroUserIdStr<'static>,
+ new_document_name: &str,
+) -> Result<DocumentMetadata, sqlx::Error> {
+ let original_document_id = &original_document.document_id;
+ let original_document_version_id = original_document.document_version_id;
+
+ let sha = original_document.sha.as_deref().ok_or_else(|| {
+ tracing::error!("unable to copy document, sha is missing");
+ sqlx::Error::Protocol("unable to copy document, sha is missing".to_string())
+ })?;
+
+ let document = sqlx::query_as!(
+ IDWithTimeStamps,
+ r#"
+ INSERT INTO "Document" (owner, name, "fileType", "documentFamilyId", "branchedFromId", "branchedFromVersionId", "projectId")
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
+ "#,
+ user_id.as_ref(),
+ new_document_name,
+ original_document.file_type,
+ original_document.document_family_id,
+ original_document_id,
+ original_document_version_id,
+ original_document.project_id,
+ )
+ .fetch_one(transaction.as_mut())
+ .await
+ .map_err(|err| {
+ tracing::error!(error=?err, "unable to copy document");
+ map_insert_document_error(err)
+ })?;
+
+ let document_instance = sqlx::query_as!(
+ VersionIDWithTimeStamps,
+ r#"
+ INSERT INTO "DocumentInstance" ("documentId", "sha")
+ VALUES ($1, $2)
+ RETURNING id, sha, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
+ "#,
+ &document.id,
+ sha,
+ )
+ .fetch_one(transaction.as_mut())
+ .await?;
+
+ // Copy modification data if present
+ let original_document_modification = sqlx::query!(
+ r#"
+ SELECT "modificationData" as modification_data
+ FROM "DocumentInstanceModificationData"
+ WHERE "documentInstanceId" = $1
+ "#,
+ original_document_version_id
+ )
+ .fetch_optional(transaction.as_mut())
+ .await?;
+
+ let original_modification_data = if let Some(modification) = original_document_modification {
+ sqlx::query!(
+ r#"
+ INSERT INTO "DocumentInstanceModificationData" ("documentInstanceId", "modificationData")
+ VALUES ($1, $2);
+ "#,
+ document_instance.id,
+ modification.modification_data
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ Some(modification.modification_data)
+ } else {
+ None
+ };
+
+ // Copy sub_type if the original is a task
+ if original_document.sub_type == Some(DocumentSubType::Task) {
+ sqlx::query!(
+ r#"
+ INSERT INTO document_sub_type (document_id, sub_type)
+ VALUES ($1, $2)
+ "#,
+ document.id,
+ DocumentSubType::Task as _,
+ )
+ .execute(transaction.as_mut())
+ .await?;
+ }
+
+ Ok(DocumentMetadata {
+ document_id: document.id.clone(),
+ owner: user_id,
+ document_name: new_document_name.to_string(),
+ file_type: original_document.file_type.clone(),
+ sha: Some(document_instance.sha),
+ branched_from_id: Some(original_document_id.to_string()),
+ branched_from_version_id: Some(original_document_version_id),
+ document_family_id: original_document.document_family_id,
+ document_version_id: document_instance.id,
+ document_bom: None,
+ project_id: original_document.project_id.clone(),
+ project_name: original_document.project_name.clone(),
+ modification_data: original_modification_data,
+ created_at: document.created_at,
+ updated_at: document.updated_at,
+ sub_type: original_document.sub_type,
+ deleted_at: None,
+ })
+}
+
+/// Copies PDF-specific parts (DocumentText and DocumentProcessResult).
+#[tracing::instrument(skip(transaction))]
+pub async fn copy_pdf_parts(
+ transaction: &mut Transaction<'_, Postgres>,
+ new_document_id: &str,
+ original_document_id: &str,
+) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ r#"
+ INSERT INTO "DocumentText" ("documentId", "content", "tokenCount")
+ SELECT $1, content, "tokenCount" FROM "DocumentText"
+ WHERE "documentId" = $2
+ "#,
+ new_document_id,
+ original_document_id
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ sqlx::query!(
+ r#"
+ INSERT INTO "DocumentProcessResult" ("documentId", "content", "jobType")
+ SELECT $1, content, 'pdf_preprocess' FROM "DocumentProcessResult"
+ WHERE "documentId" = $2 and "jobType" = 'pdf_preprocess'
+ "#,
+ new_document_id,
+ original_document_id
+ )
+ .execute(transaction.as_mut())
+ .await?;
+
+ Ok(())
+}
+
+/// Creates bom parts for a document bom.
+async fn create_bom_parts(
+ transaction: &mut Transaction<'_, Postgres>,
+ document_bom_id: i64,
+ bom_parts: Vec<SaveBomPart>,
+) -> Result<Vec<BomPart>, sqlx::Error> {
+ if bom_parts.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let mut query =
+ "INSERT INTO \"BomPart\" (\"documentBomId\", \"sha\", \"path\") VALUES ".to_string();
+ let mut set_parts: Vec<String> = Vec::new();
+ let mut parameters: Vec<String> = Vec::new();
+
+ for bom_part in &bom_parts {
+ let param_number = parameters.len() + 2;
+ set_parts.push(format!("($1, ${}, ${})", param_number, param_number + 1));
+ parameters.push(bom_part.sha.clone());
+ parameters.push(bom_part.path.clone());
+ }
+
+ query += &set_parts.join(", ");
+ query += ";";
+
+ let mut query = sqlx::query_as::<_, BomPart>(&query);
+ query = query.bind(document_bom_id);
+
+ for param in parameters {
+ query = query.bind(param);
+ }
+
+ let saved_bom_parts: Vec<BomPart> = query
+ .fetch_all(transaction.as_mut())
+ .await
+ .map_err(|e| sqlx::Error::Protocol(format!("failed to create bom parts: {e}")))?;
+
+ Ok(saved_bom_parts)
+}
+
+fn map_insert_document_error(err: sqlx::Error) -> sqlx::Error {
+ let no_user_found = "error returned from database: insert or update on table \"Document\" violates foreign key constraint \"Document_owner_fkey\"";
+ let err_string = err.to_string();
+ if err_string.contains(no_user_found) {
+ return sqlx::Error::Protocol("no user found".to_string());
+ }
+ sqlx::Error::Protocol("unable to copy document".to_string())
+}
diff --git a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
index d37b9beaac..fa811f3b77 100644
--- a/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
+++ b/rust/cloud-storage/documents/src/outbound/s3_upload_url.rs
@@ -65,6 +65,23 @@ impl PresignedUploadUrlPort for S3UploadUrlAdapter {
)
.await
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn copy_object(&self, source_key: &str, destination_key: &str) -> anyhow::Result<()> {
+ if macro_aws_config::is_local_aws() {
+ return Ok(());
+ }
+
+ self.client
+ .copy_object()
+ .bucket(&self.document_storage_bucket)
+ .copy_source(format!("{}/{}", self.document_storage_bucket, source_key))
+ .key(destination_key)
+ .send()
+ .await?;
+
+ Ok(())
+ }
}
async fn put_presigned_url(
diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rs
index ff4bfac920..4f06edd890 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -182,6 +182,18 @@ impl DocumentService for StubDocumentService {
Ok(())
}
+ async fn copy_document(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ _document_context: DocumentBasic,
+ _user_id: MacroUserIdStr<'static>,
+ _document_name: String,
+ _query_version_id: Option<i64>,
+ _sync_version_id: Option<model::sync_service::SyncServiceVersionID>,
+ ) -> Result<model::document::response::DocumentResponse, DocumentError> {
+ unimplemented!()
+ }
+
async fn create_task(
&self,
_user_id: MacroUserIdStr<'static>,