Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(dss): Add document email linking to create document (#106)
Evan Hutnik52f8d7eed8e1
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rsindex 48012fff96..1bf331e077 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_handler.rs@@ -4,6 +4,7 @@ use axum::{Extension, extract::State, http::StatusCode, response::IntoResponse};use macro_middleware::cloud_storage::ensure_access::project::ProjectBodyAccessLevelExtractor;use models_permissions::share_permission::access_level::EditAccessLevel;+use crate::api::middleware::internal_access::InternalUser;use crate::api::{context::ApiContext,documents::{@@ -21,8 +22,8 @@ use model::{/// Handles creating a document#[utoipa::path(- tag = "document",post,+ tag = "document",path = "/documents",request_body = CreateDocumentRequest,responses(@@ -37,11 +38,20 @@ use model::{#[axum::debug_handler(state = ApiContext)]pub(in crate::api) async fn create_document_handler(State(state): State<ApiContext>,+ internal_user: Option<Extension<InternalUser>>,user_context: Extension<UserContext>,project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateDocumentRequest>,) -> impl IntoResponse {let req = project.into_inner();+ // email linking is internal only+ if req.email_attachment_id.is_some() && internal_user.is_none() {+ return GenericResponse::builder()+ .message("can't link email in external request")+ .is_error(true)+ .send(StatusCode::UNAUTHORIZED);+ }+let user_provided_file_type: Option<FileType> = req.file_type.as_deref()@@ -75,14 +85,17 @@ pub(in crate::api) async fn create_document_handler(let create_document_response_data = create_document_v2::create_document(&state,- req.id.as_deref(),- &req.sha,- &document_name,- &user_context.user_id,- file_type,- req.job_id.as_deref(),- req.project_id.as_deref(),- req.created_at.as_ref(),+ create_document_v2::CreateDocumentParams {+ id: req.id.as_deref(),+ sha: &req.sha,+ document_name: &document_name,+ owner: &user_context.user_id,+ file_type,+ job_id: req.job_id.as_deref(),+ project_id: req.project_id.as_deref(),+ email_attachment_id: req.email_attachment_id,+ created_at: req.created_at.as_ref(),+ },).await;diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rsindex 638b2d6573..0d82367ae4 100644--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs@@ -6,24 +6,41 @@ use model::document::response::{DocumentResponse, DocumentResponseMetadata};use model::document::{ContentType, FileType, build_cloud_storage_bucket_document_key};use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::{IS_PUBLIC_DEFAULT, SharePermissionV2};+use uuid::Uuid;++/// Parameters for creating a document+pub struct CreateDocumentParams<'a> {+ pub id: Option<&'a str>,+ pub sha: &'a str,+ pub document_name: &'a str,+ pub owner: &'a str,+ pub file_type: Option<FileType>,+ pub job_id: Option<&'a str>,+ pub project_id: Option<&'a str>,+ pub email_attachment_id: Option<Uuid>,+ pub created_at: Option<&'a DateTime<Utc>>,+}/// Creates a document in the database/// Creates a presigned post url to upload the document to the required bucket/// In the event of an error, returns status code, error message and optional document id./// **note** If document id is present, cleanup is necessary.-#[tracing::instrument(skip(ctx, owner), fields(user_id=?owner))]-#[expect(clippy::too_many_arguments, reason = "too annoying to fix")]+#[tracing::instrument(skip(ctx, params), fields(user_id=?params.owner))]pub async fn create_document(ctx: &ApiContext,- id: Option<&str>,- sha: &str,- document_name: &str,- owner: &str,- file_type: Option<FileType>,- job_id: Option<&str>,- project_id: Option<&str>,- created_at: Option<&DateTime<Utc>>,+ params: CreateDocumentParams<'_>,) -> Result<CreateDocumentResponseData, (StatusCode, String, Option<String>)> {+ let CreateDocumentParams {+ id,+ sha,+ document_name,+ owner,+ file_type,+ job_id,+ project_id,+ email_attachment_id,+ created_at,+ } = params;tracing::trace!("creating document v2");let share_permission = if let Some(file_type) = file_type {@@ -55,7 +72,8 @@ pub async fn create_document(project_id,project_name: None,share_permission: &share_permission,- skip_history: created_at.is_some(), // don't add to history if it's a backfill+ skip_history: false,+ email_attachment_id,created_at,},)diff --git a/rust/cloud-storage/document_storage_service_client/src/document.rs b/rust/cloud-storage/document_storage_service_client/src/document.rsindex 786d298b63..72f1b82822 100644--- a/rust/cloud-storage/document_storage_service_client/src/document.rs+++ b/rust/cloud-storage/document_storage_service_client/src/document.rs@@ -360,7 +360,7 @@ impl DocumentStorageServiceClient {/// Create a document#[tracing::instrument(skip(self, jwt_token))]- pub async fn create_document(+ pub async fn create_document_external(&self,req: CreateDocumentRequest,jwt_token: &str,@@ -387,4 +387,38 @@ impl DocumentStorageServiceClient {let response_data = res.json::<CreateDocumentResponse>().await?;Ok(response_data)}++ /// Create a document+ #[tracing::instrument(skip(self))]+ pub async fn create_document_internal(+ &self,+ req: CreateDocumentRequest,+ user_id: &str,+ ) -> Result<CreateDocumentResponse> {+ let url = format!("{}/internal/documents", self.url);++ let res = self+ .client+ .post(&url)+ .json(&req)+ .header(MACRO_INTERNAL_USER_ID_HEADER_KEY, user_id)+ .send()+ .await?;++ let status_code = res.status();++ if !status_code.is_success() {+ let body = res.text().await.unwrap_or("no body".to_string());+ tracing::error!(+ body=%body,+ status=%status_code,+ document_name=%req.document_name,+ "external API error when creating document"+ );+ anyhow::bail!("HTTP {}: {}", status_code, body);+ }++ let response_data = res.json::<CreateDocumentResponse>().await?;+ Ok(response_data)+ }}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1e14d3e8348556865af942ec6e3d883668d0b8073143094ed67d34285f9cc92b.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1e14d3e8348556865af942ec6e3d883668d0b8073143094ed67d34285f9cc92b.jsonnew file mode 100644index 0000000000..e5287b48b3--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1e14d3e8348556865af942ec6e3d883668d0b8073143094ed67d34285f9cc92b.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"UserHistory\" (\"userId\", \"itemId\", \"itemType\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $4)\n ON CONFLICT (\"userId\", \"itemId\", \"itemType\") DO UPDATE\n SET \"updatedAt\" = $4;\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Timestamp"+ ]+ },+ "nullable": []+ },+ "hash": "1e14d3e8348556865af942ec6e3d883668d0b8073143094ed67d34285f9cc92b"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87.json b/rust/cloud-storage/macro_db_client/.sqlx/query-238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87.jsonnew file mode 100644index 0000000000..af89902a82--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"document_email\" (document_id, email_attachment_id)\n VALUES ($1, $2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "238fe2bbda3f3455e9fbbda9519b661393cfffe033edd3eb7f0eeb49dcc64a87"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-53d362deffc3fd04e6c80c24bfa856a5ccc917877036e5c7b3ab899f0812edf0.json b/rust/cloud-storage/macro_db_client/.sqlx/query-71b975abc8c63ea8116cd8944e99d46e5747660807a30564921bc371ddd1338d.jsonsimilarity index 55%rename from rust/cloud-storage/macro_db_client/.sqlx/query-53d362deffc3fd04e6c80c24bfa856a5ccc917877036e5c7b3ab899f0812edf0.jsonrename to rust/cloud-storage/macro_db_client/.sqlx/query-71b975abc8c63ea8116cd8944e99d46e5747660807a30564921bc371ddd1338d.jsonindex 2dc253f389..2dc1809409 100644--- a/rust/cloud-storage/macro_db_client/.sqlx/query-53d362deffc3fd04e6c80c24bfa856a5ccc917877036e5c7b3ab899f0812edf0.json+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-71b975abc8c63ea8116cd8944e99d46e5747660807a30564921bc371ddd1338d.json@@ -1,15 +1,16 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO \"ItemLastAccessed\" (\"item_id\", \"item_type\", \"last_accessed\")\n VALUES ($1, $2, NOW())\n ON CONFLICT (\"item_id\", \"item_type\") DO UPDATE\n SET \"last_accessed\" = NOW();\n ",+ "query": "\n INSERT INTO \"ItemLastAccessed\" (\"item_id\", \"item_type\", \"last_accessed\")\n VALUES ($1, $2, $3)\n ON CONFLICT (\"item_id\", \"item_type\") DO UPDATE\n SET \"last_accessed\" = $3;\n ","describe": {"columns": [],"parameters": {"Left": ["Text",- "Text"+ "Text",+ "Timestamp"]},"nullable": []},- "hash": "53d362deffc3fd04e6c80c24bfa856a5ccc917877036e5c7b3ab899f0812edf0"+ "hash": "71b975abc8c63ea8116cd8944e99d46e5747660807a30564921bc371ddd1338d"}diff --git a/rust/cloud-storage/macro_db_client/migrations/20251112211315_document_email.sql b/rust/cloud-storage/macro_db_client/migrations/20251112211315_document_email.sqlnew file mode 100644index 0000000000..b742657879--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20251112211315_document_email.sql@@ -0,0 +1,11 @@+-- table for linking email attachment documents and their emails+CREATE TABLE "document_email"+(+ document_id TEXT NOT NULL REFERENCES "Document" (id) ON DELETE CASCADE,+ email_attachment_id uuid NOT NULL REFERENCES email_attachments (id) ON DELETE CASCADE,+ PRIMARY KEY (document_id, email_attachment_id)+);++-- composite index already exists for querying on document_id due to primary key.+-- need separate index to query by email_attachment_id efficiently.+CREATE INDEX idx_document_email_attachment_id ON "document_email" (email_attachment_id);diff --git a/rust/cloud-storage/macro_db_client/src/document/document_email.rs b/rust/cloud-storage/macro_db_client/src/document/document_email.rsnew file mode 100644index 0000000000..a1394ba91b--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/document/document_email.rs@@ -0,0 +1,25 @@+use uuid::Uuid;++/// create record in document_email table, linking the document (an email attachment) and email message+pub async fn create_document_email_record(+ transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ document_id: &str,+ email_attachment_id: Uuid,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO "document_email" (document_id, email_attachment_id)+ VALUES ($1, $2)+ "#,+ document_id,+ email_attachment_id,+ )+ .execute(&mut **transaction)+ .await+ .map_err(|err| {+ tracing::error!(error=?err, "unable to create document email record");+ anyhow::anyhow!("unable to create document email record: {}", err)+ })?;++ Ok(())+}diff --git a/rust/cloud-storage/macro_db_client/src/document/mod.rs b/rust/cloud-storage/macro_db_client/src/document/mod.rsindex 437258ca88..3517356b40 100644--- a/rust/cloud-storage/macro_db_client/src/document/mod.rs+++ b/rust/cloud-storage/macro_db_client/src/document/mod.rs@@ -22,6 +22,7 @@ pub use list_documents_with_access::*;pub use save_document::*;pub mod build_pdf_modification_data;pub mod create_blank_docx;+mod document_email;pub mod document_shas;pub mod get_all_documents;pub mod get_document_history;diff --git a/rust/cloud-storage/macro_db_client/src/document/v2/create.rs b/rust/cloud-storage/macro_db_client/src/document/v2/create.rsindex 4203bb5b74..4e8d5070d3 100644--- a/rust/cloud-storage/macro_db_client/src/document/v2/create.rs+++ b/rust/cloud-storage/macro_db_client/src/document/v2/create.rs@@ -1,5 +1,4 @@-use crate::history::upsert_item_last_accessed;-use crate::history::upsert_user_history;+use crate::history::{upsert_item_last_accessed_timestamp, upsert_user_history_timestamp};use crate::share_permission::create::create_document_permission;use model::document::DocumentMetadata;use model::document::FileType;@@ -11,6 +10,7 @@ use sqlx::Pool;use sqlx::Postgres;use sqlx::Transaction;use tracing::instrument;+use uuid::Uuid;/// struct for creating a document#[derive(Debug)]@@ -24,6 +24,8 @@ pub struct CreateDocumentArgs<'a> {pub project_name: Option<&'a str>,pub share_permission: &'a SharePermissionV2,pub skip_history: bool,+ /// Optional value. If set, creates entry in document_email+ pub email_attachment_id: Option<Uuid>,/// Optional value. defaults to now if not includedpub created_at: Option<&'a chrono::DateTime<chrono::Utc>>,}@@ -65,6 +67,7 @@ pub async fn create_document_txn(share_permission,skip_history,created_at: _, // overwritten below+ email_attachment_id,} = args;// default to now if created_at argument not included@@ -165,8 +168,10 @@ pub async fn create_document_txn(// Add item to user history for creatorif !skip_history {- upsert_user_history(transaction, user_id, &document_id, "document").await?;- upsert_item_last_accessed(transaction, &document_id, "document").await?;+ upsert_user_history_timestamp(transaction, user_id, &document_id, "document", created_at)+ .await?;+ upsert_item_last_accessed_timestamp(transaction, &document_id, "document", created_at)+ .await?;}crate::item_access::insert::insert_user_item_access(@@ -179,6 +184,15 @@ pub async fn create_document_txn().await?;+ if email_attachment_id.is_some() {+ crate::document::document_email::create_document_email_record(+ transaction,+ &document_id,+ email_attachment_id.unwrap(),+ )+ .await?;+ }+Ok(DocumentMetadata::new_document(&document_id,document_version.id,@@ -304,6 +318,7 @@ mod tests {project_name: None,share_permission: &SharePermissionV2::default(),skip_history: false,+ email_attachment_id: None,created_at: Some(&ts),},)@@ -329,6 +344,7 @@ mod tests {project_name: None,share_permission: &SharePermissionV2::default(),skip_history: false,+ email_attachment_id: None,created_at: None,},)@@ -366,6 +382,7 @@ mod tests {project_name: None,share_permission: &SharePermissionV2::default(),skip_history: false,+ email_attachment_id: None,created_at: Some(&ts),},)@@ -394,6 +411,7 @@ mod tests {project_name: None,share_permission: &SharePermissionV2::default(),skip_history: false,+ email_attachment_id: None,created_at: None,},)@@ -423,6 +441,7 @@ mod tests {project_name: None,share_permission: &SharePermissionV2::default(),skip_history: false,+ email_attachment_id: None,created_at: None,},)diff --git a/rust/cloud-storage/macro_db_client/src/history/upsert_history.rs b/rust/cloud-storage/macro_db_client/src/history/upsert_history.rsindex c6e1abd8d2..afd0752fed 100644--- a/rust/cloud-storage/macro_db_client/src/history/upsert_history.rs+++ b/rust/cloud-storage/macro_db_client/src/history/upsert_history.rs@@ -7,16 +7,28 @@ pub async fn upsert_item_last_accessed(transaction: &mut Transaction<'_, Postgres>,item_id: &str,item_type: &str,+) -> anyhow::Result<()> {+ upsert_item_last_accessed_timestamp(transaction, item_id, item_type, &Utc::now()).await+}++/// Upserts an item into the ItemLastAccessed table with the specified timestamp+#[tracing::instrument(skip(transaction))]+pub async fn upsert_item_last_accessed_timestamp(+ transaction: &mut Transaction<'_, Postgres>,+ item_id: &str,+ item_type: &str,+ timestamp: &DateTime<Utc>,) -> anyhow::Result<()> {sqlx::query!(r#"INSERT INTO "ItemLastAccessed" ("item_id", "item_type", "last_accessed")- VALUES ($1, $2, NOW())+ VALUES ($1, $2, $3)ON CONFLICT ("item_id", "item_type") DO UPDATE- SET "last_accessed" = NOW();+ SET "last_accessed" = $3;"#,item_id,item_type,+ timestamp.naive_utc()).execute(transaction.as_mut()).await?;@@ -31,17 +43,30 @@ pub async fn upsert_user_history(user_id: &str,item_id: &str,item_type: &str,+) -> anyhow::Result<()> {+ upsert_user_history_timestamp(transaction, user_id, item_id, item_type, &Utc::now()).await+}++/// Upserts an item into the user's history with the specified timestamp+#[tracing::instrument(skip(transaction))]+pub async fn upsert_user_history_timestamp(+ transaction: &mut Transaction<'_, Postgres>,+ user_id: &str,+ item_id: &str,+ item_type: &str,+ timestamp: &DateTime<Utc>,) -> anyhow::Result<()> {sqlx::query!(r#"INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")- VALUES ($1, $2, $3, NOW(), NOW())+ VALUES ($1, $2, $3, $4, $4)ON CONFLICT ("userId", "itemId", "itemType") DO UPDATE- SET "updatedAt" = NOW();+ SET "updatedAt" = $4;"#,user_id,item_id,item_type,+ timestamp.naive_utc()).execute(transaction.as_mut()).await?;diff --git a/rust/cloud-storage/macro_db_client/src/instructions/create.rs b/rust/cloud-storage/macro_db_client/src/instructions/create.rsindex caad017f2b..091d16b5ae 100644--- a/rust/cloud-storage/macro_db_client/src/instructions/create.rs+++ b/rust/cloud-storage/macro_db_client/src/instructions/create.rs@@ -32,6 +32,7 @@ pub async fn create_instructions_document(project_name: None,share_permission: &SharePermissionV2::user_only(),skip_history: false,+ email_attachment_id: None,created_at: None,},)diff --git a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rsindex 8639eec77a..c451c8f0d6 100644--- a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs+++ b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs@@ -119,6 +119,7 @@ async fn traverse_with_ids(project_name: Some(project_name),share_permission,skip_history: true,+ email_attachment_id: None,created_at: None,},)diff --git a/rust/cloud-storage/model/src/document/response/mod.rs b/rust/cloud-storage/model/src/document/response/mod.rsindex 433e823df5..e53b4a29a9 100644--- a/rust/cloud-storage/model/src/document/response/mod.rs+++ b/rust/cloud-storage/model/src/document/response/mod.rs@@ -10,6 +10,7 @@ use chrono::serde::ts_seconds_option;use models_permissions::share_permission::access_level::AccessLevel;use tracing::instrument;use utoipa::ToSchema;+use uuid::Uuid;#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]#[serde(rename_all = "camelCase")]@@ -212,6 +213,9 @@ pub struct CreateDocumentRequest {pub job_id: Option<String>,//// Optional project id to be used to what project the document belongs to.pub project_id: Option<String>,+ /// Internal only field that links the document created to the specified email attachment by+ /// creating a row in the document_email table.+ pub email_attachment_id: Option<Uuid>,/// Optional time to set the document's created_at to. Set when backfilling email attachments.pub created_at: Option<chrono::DateTime<chrono::Utc>>,}