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(dss): Specify created_at timestamp when creating document (#88)

Evan Hutnik63b44ea75d08
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
index 521cee220f..04e924fb7b 100644
--- 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
@@ -1,9 +1,7 @@
-use crate::{
- api::context::ApiContext,
- model::response::documents::{DocumentResponse, DocumentResponseMetadata},
-};
+use crate::api::context::ApiContext;
use axum::{http::StatusCode, response::Response};
use macro_db_client::history::upsert_user_history;
+use model::document::response::{DocumentResponse, DocumentResponseMetadata};
use model::{document::FileTypeExt, sync_service::SyncServiceVersionID};
use model::{
document::{
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.rs
index d82ec37ad7..48012fff96 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,27 +4,21 @@ 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::{
- context::ApiContext,
- documents::{
- create_document::create_document_v2,
- utils::{self},
- },
- },
- model::{
- request::documents::create::CreateDocumentRequest,
- response::documents::create::CreateDocumentResponseData,
+use crate::api::{
+ context::ApiContext,
+ documents::{
+ create_document::create_document_v2,
+ utils::{self},
},
};
+use model::document::FileTypeExt;
+use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};
use model::{
- document::{FileType, FileTypeExt},
- response::{GenericErrorResponse, GenericResponse, TypedSuccessResponse},
+ document::FileType,
+ response::{GenericErrorResponse, GenericResponse},
user::UserContext,
};
-pub type CreateDocumentResponse = TypedSuccessResponse<CreateDocumentResponseData>;
-
/// Handles creating a document
#[utoipa::path(
tag = "document",
@@ -85,10 +79,10 @@ pub(in crate::api) async fn create_document_handler(
&req.sha,
&document_name,
&user_context.user_id,
- user_context.organization_id,
file_type,
req.job_id.as_deref(),
req.project_id.as_deref(),
+ 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.rs
index ea9088d503..638b2d6573 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
@@ -1,7 +1,8 @@
use crate::api::context::ApiContext;
-use crate::model::response::documents::create::CreateDocumentResponseData;
-use crate::model::response::documents::{DocumentResponse, DocumentResponseMetadata};
use axum::http::StatusCode;
+use chrono::{DateTime, Utc};
+use model::document::response::CreateDocumentResponseData;
+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};
@@ -18,10 +19,10 @@ pub async fn create_document(
sha: &str,
document_name: &str,
owner: &str,
- organization_id: Option<i32>,
file_type: Option<FileType>,
job_id: Option<&str>,
project_id: Option<&str>,
+ created_at: Option<&DateTime<Utc>>,
) -> Result<CreateDocumentResponseData, (StatusCode, String, Option<String>)> {
tracing::trace!("creating document v2");
@@ -54,7 +55,8 @@ pub async fn create_document(
project_id,
project_name: None,
share_permission: &share_permission,
- skip_history: false,
+ skip_history: created_at.is_some(), // don't add to history if it's a backfill
+ created_at,
},
)
.await
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save.rs b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save.rs
index 9b66234281..c401650839 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save.rs
@@ -4,8 +4,8 @@ use macro_redis_cluster_client::Redis;
use sqlx::{Pool, Postgres};
use tracing::instrument;
-use crate::model::response::documents::DocumentResponseMetadata;
use crate::{model::request::documents::save::SaveDocumentRequest, service};
+use model::document::response::DocumentResponseMetadata;
use model::document::{DocumentBasic, DocumentMetadata, FileType};
/// Saves a document to the database and updates all other necessary items with the new document
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs
index d8ecc4c3bd..190c8c4026 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/save_document/save_document_handler.rs
@@ -4,10 +4,7 @@ use crate::{
api::{context::ApiContext, documents::utils},
model::{
request::documents::save::SaveDocumentRequest,
- response::documents::{
- DocumentResponseMetadata,
- save::{SaveDocumentResponse, SaveDocumentResponseData},
- },
+ response::documents::save::{SaveDocumentResponse, SaveDocumentResponseData},
},
};
use axum::{
@@ -19,6 +16,7 @@ use axum::{
use macro_middleware::cloud_storage::ensure_access::{
document::DocumentAccessExtractor, project::ProjectBodyAccessLevelExtractor,
};
+use model::document::response::DocumentResponseMetadata;
use model::{
document::{DocumentBasic, FileType, FileTypeExt, build_cloud_storage_bucket_document_key},
response::{ErrorResponse, GenericErrorResponse, GenericResponse},
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
index 61c430890b..d3a3023e76 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/simple_save.rs
@@ -2,10 +2,7 @@ use std::str::FromStr;
use crate::{
api::{context::ApiContext, documents::utils},
- model::response::documents::{
- DocumentResponseMetadata,
- save::{SaveDocumentResponse, SaveDocumentResponseData},
- },
+ model::response::documents::save::{SaveDocumentResponse, SaveDocumentResponseData},
};
use anyhow::Context;
use axum::{
@@ -15,6 +12,7 @@ use axum::{
response::IntoResponse,
};
use macro_middleware::cloud_storage::ensure_access::document::DocumentAccessExtractor;
+use model::document::response::DocumentResponseMetadata;
use model::{
document::{DocumentBasic, FileType, FileTypeExt, build_cloud_storage_bucket_document_key},
response::{GenericErrorResponse, GenericResponse},
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 505c861b8b..54f2e992e1 100644
--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs
@@ -44,7 +44,6 @@ use crate::{
annotations,
documents::{
self,
- create_document::CreateDocumentResponse,
export_document::ExportDocumentResponse,
permissions_token::{
create_permission_token::DocumentPermissionsTokenResponse,
@@ -66,7 +65,6 @@ use crate::{
request::{
documents::{
copy::{CopyDocumentQueryParams, CopyDocumentRequest},
- create::CreateDocumentRequest,
edit::EditDocumentRequestV2,
preview::GetBatchPreviewRequest,
save::{PreSaveDocumentRequest, SaveDocumentRequest},
@@ -78,11 +76,7 @@ use crate::{
response::{
activity::{GetActivitiesResponse, UserActivitiesResponse},
documents::{
- DocumentResponseMetadata,
- create::{
- CreateBulkDocumentResponse, CreateBulkDocumentResponseData,
- CreateDocumentResponseData,
- },
+ create::{CreateBulkDocumentResponse, CreateBulkDocumentResponseData},
get::{
GetDocumentKeyResponse, GetDocumentKeyResponseData,
GetDocumentPermissionsResponseDataV2, GetDocumentProcessingResult,
@@ -116,6 +110,10 @@ use models_soup::item::SoupItem;
use models_soup::item::SoupItemType;
use models_soup::project::SoupProject;
+use model::document::response::{
+ CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData,
+ DocumentResponseMetadata,
+};
use utoipa::OpenApi;
#[derive(OpenApi)]
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index a71796e86c..2939f56900 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -33,7 +33,7 @@ mod service;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let env = Environment::new_or_prod();
- MacroEntrypoint::new(env).init();
+ MacroEntrypoint::default().init();
let aws_config = aws_config::defaults(aws_config::BehaviorVersion::latest())
.region("us-east-1")
diff --git a/rust/cloud-storage/document_storage_service/src/model/request/documents/create.rs b/rust/cloud-storage/document_storage_service/src/model/request/documents/create.rs
index 681f517c7c..4f23ac3b60 100644
--- a/rust/cloud-storage/document_storage_service/src/model/request/documents/create.rs
+++ b/rust/cloud-storage/document_storage_service/src/model/request/documents/create.rs
@@ -1,31 +1,5 @@
use utoipa::ToSchema;
-#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct CreateDocumentRequest {
- /// The id of the document in the database
- pub id: Option<String>,
- /// The sha of the document.
- pub sha: String,
- /// The name of the document without extension.
- pub document_name: String,
- /// Optional file type of the document.
- pub file_type: Option<String>,
- /// The content type of the document (currently only used for logging matches against file type).
- pub mime_type: Option<String>,
- /// The document family id if the document is being branched.
- pub document_family_id: Option<i64>,
- /// The document id if the document is being branched.
- pub branched_from_id: Option<String>,
- /// The version id if the document is being branched.
- pub branched_from_version_id: Option<i64>,
- /// Optional job id to be used to track an upload job for the newly created document.
- /// Will need to have a corresponding job initiated for the file beforehand.
- pub job_id: Option<String>,
- //// Optional project id to be used to what project the document belongs to.
- pub project_id: Option<String>,
-}
-
#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateBlankDocxRequest {
diff --git a/rust/cloud-storage/document_storage_service/src/model/response/documents/create.rs b/rust/cloud-storage/document_storage_service/src/model/response/documents/create.rs
index a5aa99feb4..77805a10b9 100644
--- a/rust/cloud-storage/document_storage_service/src/model/response/documents/create.rs
+++ b/rust/cloud-storage/document_storage_service/src/model/response/documents/create.rs
@@ -2,19 +2,6 @@ use utoipa::ToSchema;
use model::{document::DocumentMetadata, response::PresignedUrl};
-use super::DocumentResponse;
-
-#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct CreateDocumentResponseData {
- #[serde(flatten)]
- pub document_response: DocumentResponse,
- /// Content type of the document converted from file type
- pub content_type: String,
- /// The file type of the document
- pub file_type: Option<String>,
-}
-
#[derive(serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateBulkDocumentResponse {
/// Indicates if an error occurred
diff --git a/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rs b/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rs
index c2a00eab09..64a12f5947 100644
--- a/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rs
+++ b/rust/cloud-storage/document_storage_service/src/model/response/documents/mod.rs
@@ -1,115 +1,5 @@
-use std::str::FromStr;
-
-use chrono::serde::ts_seconds_option;
-use model::document::{BomPart, DocumentMetadata, FileType};
-use tracing::instrument;
-use utoipa::ToSchema;
-
pub mod create;
pub mod get;
pub mod preview;
pub mod save;
pub mod user_document_view_location;
-
-#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct DocumentResponse {
- pub document_metadata: DocumentResponseMetadata,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub presigned_url: Option<String>,
-}
-
-#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct DocumentResponseMetadata {
- /// The document id
- pub document_id: String,
- /// The version of the document
- /// This could be the document_instance_id or document_bom_id depending on
- /// the file type
- pub document_version_id: i64,
- /// The owner of the document
- pub owner: String,
- /// The name of the document
- pub document_name: String,
- /// The file type of the document
- #[serde(skip_serializing_if = "Option::is_none")]
- pub file_type: Option<String>,
- /// If the document is a PDF, this is the SHA of the pdf
- /// If the document is a DOCX, this will not be present
- #[serde(skip_serializing_if = "Option::is_none")]
- pub sha: Option<String>,
- /// The id of the document this document branched from
- #[serde(skip_serializing_if = "Option::is_none")]
- pub branched_from_id: Option<String>,
- /// The id of the version this document branched from
- /// This could be either DocumentInstance or DocumentBom id depending on
- /// the file type
- #[serde(skip_serializing_if = "Option::is_none")]
- pub branched_from_version_id: Option<i64>,
- /// The id of the document family this document belongs to
- #[serde(skip_serializing_if = "Option::is_none")]
- pub document_family_id: Option<i64>,
- /// If the document is a DOCX document, the document_bom will be present
- #[serde(skip_serializing_if = "Option::is_none")]
- pub document_bom: Option<Vec<BomPart>>,
- /// The modification data for the document instance.
- /// This is only used for PDF documents.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub modification_data: Option<serde_json::Value>,
- /// The time the document was created
- #[serde(with = "ts_seconds_option")]
- #[schema(value_type = i64, nullable=false)]
- pub created_at: Option<chrono::DateTime<chrono::Utc>>,
- /// The time the document instance / document BOM was updated
- #[serde(with = "ts_seconds_option")]
- #[schema(value_type = i64, nullable=false)]
- pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
-}
-
-impl DocumentResponseMetadata {
- /// Initialize document response from document metadata
- fn initialize_from_document_metadata(document_metadata: &DocumentMetadata) -> Self {
- DocumentResponseMetadata {
- document_id: document_metadata.document_id.clone(),
- document_version_id: document_metadata.document_version_id,
- owner: document_metadata.owner.clone(),
- document_name: document_metadata.document_name.clone(),
- file_type: document_metadata.file_type.clone(),
- sha: document_metadata.sha.clone(),
- document_bom: None,
- modification_data: document_metadata.modification_data.clone(),
- branched_from_id: document_metadata.branched_from_id.clone(),
- branched_from_version_id: document_metadata.branched_from_version_id,
- document_family_id: document_metadata.document_family_id,
- created_at: document_metadata.created_at,
- updated_at: document_metadata.updated_at,
- }
- }
-
- #[instrument]
- pub fn from_document_metadata(document_metadata: &DocumentMetadata) -> anyhow::Result<Self> {
- // Initialize document response
- let mut document_response_metadata =
- DocumentResponseMetadata::initialize_from_document_metadata(document_metadata);
- // Ensure we have a valid file type
- if let Some(FileType::Docx) = document_metadata
- .file_type
- .as_deref()
- .and_then(|file_type| FileType::from_str(file_type).ok())
- && let Some(document_bom) = &document_metadata.document_bom
- {
- let document_bom: Vec<BomPart> = match serde_json::from_value(document_bom.clone()) {
- Ok(document_bom) => document_bom,
- Err(e) => {
- return Err(anyhow::anyhow!(format!(
- "document bom could not be serialized {e}",
- )));
- }
- };
- document_response_metadata.document_bom = Some(document_bom);
- };
-
- Ok(document_response_metadata)
- }
-}
diff --git a/rust/cloud-storage/document_storage_service/src/model/response/documents/save.rs b/rust/cloud-storage/document_storage_service/src/model/response/documents/save.rs
index f5633bac44..3938a68621 100644
--- a/rust/cloud-storage/document_storage_service/src/model/response/documents/save.rs
+++ b/rust/cloud-storage/document_storage_service/src/model/response/documents/save.rs
@@ -2,7 +2,7 @@ use utoipa::ToSchema;
use model::response::PresignedUrl;
-use super::DocumentResponseMetadata;
+use model::document::response::DocumentResponseMetadata;
#[derive(serde::Serialize, serde::Deserialize, ToSchema)]
pub struct SaveDocumentResponse {
diff --git a/rust/cloud-storage/document_storage_service_client/src/document.rs b/rust/cloud-storage/document_storage_service_client/src/document.rs
index dcdc3b98ec..786d298b63 100644
--- a/rust/cloud-storage/document_storage_service_client/src/document.rs
+++ b/rust/cloud-storage/document_storage_service_client/src/document.rs
@@ -3,6 +3,7 @@ use crate::constants::MACRO_INTERNAL_USER_ID_HEADER_KEY;
use super::DocumentStorageServiceClient;
use anyhow::Result;
use model::document::list::ListDocumentsWithAccessResponse;
+use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};
use model::document::{
DocumentBasic,
response::{GetDocumentResponse, LocationResponseData, LocationResponseV3},
@@ -356,4 +357,34 @@ impl DocumentStorageServiceClient {
let response_data = res.json::<ListDocumentsWithAccessResponse>().await?;
Ok(response_data)
}
+
+ /// Create a document
+ #[tracing::instrument(skip(self, jwt_token))]
+ pub async fn create_document(
+ &self,
+ req: CreateDocumentRequest,
+ jwt_token: &str,
+ ) -> Result<CreateDocumentResponse> {
+ let res = self
+ .external_request(reqwest::Method::POST, "/documents", jwt_token)
+ .json(&req)
+ .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-8ae771e6c2d2eeb5ced576ca71d374a1e726d95f64004e1a15081957123e6a04.json b/rust/cloud-storage/macro_db_client/.sqlx/query-064772b7d3d47e82f044f6efd03f52f8cc0083e99d30810753539a5df539d94d.json
similarity index 58%
rename from rust/cloud-storage/macro_db_client/.sqlx/query-8ae771e6c2d2eeb5ced576ca71d374a1e726d95f64004e1a15081957123e6a04.json
rename to rust/cloud-storage/macro_db_client/.sqlx/query-064772b7d3d47e82f044f6efd03f52f8cc0083e99d30810753539a5df539d94d.json
index ade7355a2f..0f25e57f4c 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-8ae771e6c2d2eeb5ced576ca71d374a1e726d95f64004e1a15081957123e6a04.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-064772b7d3d47e82f044f6efd03f52f8cc0083e99d30810753539a5df539d94d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO \"Document\" (owner, name, \"fileType\", \"projectId\") \n VALUES ($1, $2, $3, $4)\n RETURNING id;\n ",
+ "query": "\n INSERT INTO \"Document\" (owner, name, \"fileType\", \"projectId\", \"createdAt\", \"updatedAt\") \n VALUES ($1, $2, $3, $4, $5, $5)\n RETURNING id;\n ",
"describe": {
"columns": [
{
@@ -14,12 +14,13 @@
"Text",
"Text",
"Text",
- "Text"
+ "Text",
+ "Timestamp"
]
},
"nullable": [
false
]
},
- "hash": "8ae771e6c2d2eeb5ced576ca71d374a1e726d95f64004e1a15081957123e6a04"
+ "hash": "064772b7d3d47e82f044f6efd03f52f8cc0083e99d30810753539a5df539d94d"
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-392727e767cc408c76567cbae50c611596d66b678fd42c42dc44982d07bfa457.json b/rust/cloud-storage/macro_db_client/.sqlx/query-7c4cd009982b182b18927dc5671aad059a55440c2de73c818ef28d6cf08acf80.json
similarity index 53%
rename from rust/cloud-storage/macro_db_client/.sqlx/query-392727e767cc408c76567cbae50c611596d66b678fd42c42dc44982d07bfa457.json
rename to rust/cloud-storage/macro_db_client/.sqlx/query-7c4cd009982b182b18927dc5671aad059a55440c2de73c818ef28d6cf08acf80.json
index dc0ac88590..d51bf18635 100644
--- a/rust/cloud-storage/macro_db_client/.sqlx/query-392727e767cc408c76567cbae50c611596d66b678fd42c42dc44982d07bfa457.json
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-7c4cd009982b182b18927dc5671aad059a55440c2de73c818ef28d6cf08acf80.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO \"Document\" (id, owner, name, \"fileType\", \"projectId\")\n VALUES ($1, $2, $3, $4, $5)\n ",
+ "query": "\n INSERT INTO \"Document\" (id, owner, name, \"fileType\", \"projectId\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6, $6)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -9,10 +9,11 @@
"Text",
"Text",
"Text",
- "Text"
+ "Text",
+ "Timestamp"
]
},
"nullable": []
},
- "hash": "392727e767cc408c76567cbae50c611596d66b678fd42c42dc44982d07bfa457"
+ "hash": "7c4cd009982b182b18927dc5671aad059a55440c2de73c818ef28d6cf08acf80"
}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-8ea09698a4333b2b2d97f16423008a172b5a030ede2b8528a103397a6dc4a42e.json b/rust/cloud-storage/macro_db_client/.sqlx/query-8ea09698a4333b2b2d97f16423008a172b5a030ede2b8528a103397a6dc4a42e.json
new file mode 100644
index 0000000000..e33956234c
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-8ea09698a4333b2b2d97f16423008a172b5a030ede2b8528a103397a6dc4a42e.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentBom\" (\"documentId\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $2)\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",
+ "Timestamp"
+ ]
+ },
+ "nullable": [
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "8ea09698a4333b2b2d97f16423008a172b5a030ede2b8528a103397a6dc4a42e"
+}
diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-cd0fcad5f9177a5b57fa20cdf5996f4ea4bd008a19afc916a1147fca76b6d5b4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-cd0fcad5f9177a5b57fa20cdf5996f4ea4bd008a19afc916a1147fca76b6d5b4.json
new file mode 100644
index 0000000000..488a2cccd5
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-cd0fcad5f9177a5b57fa20cdf5996f4ea4bd008a19afc916a1147fca76b6d5b4.json
@@ -0,0 +1,42 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"DocumentInstance\" (\"documentId\", \"sha\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $3)\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",
+ "Timestamp"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "cd0fcad5f9177a5b57fa20cdf5996f4ea4bd008a19afc916a1147fca76b6d5b4"
+}
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.rs
index 8db83ba03e..4203bb5b74 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
@@ -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. defaults to now if not included
+ pub created_at: Option<&'a chrono::DateTime<chrono::Utc>>,
}
/// Creates a new document
@@ -52,7 +54,6 @@ pub async fn create_document_txn(
args: CreateDocumentArgs<'_>,
) -> anyhow::Result<DocumentMetadata> {
tracing::trace!("creating document");
-
let CreateDocumentArgs {
id,
sha,
@@ -63,8 +64,13 @@ pub async fn create_document_txn(
project_name: provided_project_name,
share_permission,
skip_history,
+ created_at: _, // overwritten below
} = args;
+ // default to now if created_at argument not included
+ let now = chrono::Utc::now();
+ let created_at = args.created_at.unwrap_or(&now);
+
// Fetches project name for provided project_id if name is not provided
let fetched_project_name: Option<String> = match (provided_project_name, project_id) {
(None, Some(proj_id)) => {
@@ -97,13 +103,21 @@ pub async fn create_document_txn(
document_name,
file_type,
project_id,
+ created_at,
)
.await?;
id.to_string()
} else {
- insert_document_no_id(transaction, user_id, document_name, file_type, project_id)
- .await?
- .id
+ insert_document_no_id(
+ transaction,
+ user_id,
+ document_name,
+ file_type,
+ project_id,
+ created_at,
+ )
+ .await?
+ .id
};
// Docx documents have their versions associated with a DocumentBom
@@ -112,11 +126,12 @@ pub async fn create_document_txn(
Some(FileType::Docx) => {
let document_bom = sqlx::query!(
r#"
- INSERT INTO "DocumentBom" ("documentId")
- VALUES ($1)
+ INSERT INTO "DocumentBom" ("documentId", "createdAt", "updatedAt")
+ VALUES ($1, $2, $2)
RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
"#,
- &document_id,
+ &document_id,
+ created_at.naive_utc(),
)
.fetch_one(transaction.as_mut())
.await?;
@@ -132,12 +147,13 @@ pub async fn create_document_txn(
sqlx::query_as!(
VersionIDWithTimeStamps,
r#"
- INSERT INTO "DocumentInstance" ("documentId", "sha")
- VALUES ($1, $2)
+ INSERT INTO "DocumentInstance" ("documentId", "sha", "createdAt", "updatedAt")
+ VALUES ($1, $2, $3, $3)
RETURNING id, sha, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;
"#,
- &document_id,
- sha,
+ &document_id,
+ sha,
+ created_at.naive_utc()
)
.fetch_one(transaction.as_mut())
.await?
@@ -188,18 +204,20 @@ async fn insert_document_no_id(
document_name: &str,
file_type: Option<FileType>,
project_id: Option<&str>,
+ created_at: &chrono::DateTime<chrono::Utc>,
) -> anyhow::Result<ID> {
sqlx::query_as!(
ID,
r#"
- INSERT INTO "Document" (owner, name, "fileType", "projectId")
- VALUES ($1, $2, $3, $4)
+ INSERT INTO "Document" (owner, name, "fileType", "projectId", "createdAt", "updatedAt")
+ VALUES ($1, $2, $3, $4, $5, $5)
RETURNING id;
"#,
user_id,
document_name,
file_type.map(|file_type| file_type.as_str().to_string()),
project_id,
+ created_at.naive_utc()
)
.fetch_one(&mut **transaction)
.await
@@ -217,17 +235,19 @@ async fn insert_document_with_id(
document_name: &str,
file_type: Option<FileType>,
project_id: Option<&str>,
+ created_at: &chrono::DateTime<chrono::Utc>,
) -> anyhow::Result<()> {
let result = sqlx::query!(
r#"
- INSERT INTO "Document" (id, owner, name, "fileType", "projectId")
- VALUES ($1, $2, $3, $4, $5)
+ INSERT INTO "Document" (id, owner, name, "fileType", "projectId", "createdAt", "updatedAt")
+ VALUES ($1, $2, $3, $4, $5, $6, $6)
"#,
id,
user_id,
document_name,
file_type.map(|file_type| file_type.as_str().to_string()),
project_id,
+ created_at.naive_utc()
)
.execute(&mut **transaction)
.await;
@@ -256,6 +276,7 @@ async fn insert_document_with_id(
#[cfg(test)]
mod tests {
use super::*;
+ use chrono::{TimeZone, Utc};
use sqlx::{Pool, Postgres};
#[sqlx::test(fixtures(path = "../../../fixtures", scripts("basic_user_with_documents")))]
@@ -269,6 +290,7 @@ mod tests {
.execute(&pool)
.await?;
+ let ts = chrono::Utc.with_ymd_and_hms(1998, 1, 16, 0, 0, 0).unwrap();
// document exists
let document_metadata = create_document(
&pool,
@@ -282,6 +304,7 @@ mod tests {
project_name: None,
share_permission: &SharePermissionV2::default(),
skip_history: false,
+ created_at: Some(&ts),
},
)
.await?;
@@ -291,6 +314,7 @@ mod tests {
assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
assert_eq!(document_metadata.project_id.as_deref(), Some("project-one"));
assert_eq!(document_metadata.project_name.as_deref(), Some("name"));
+ assert_eq!(document_metadata.created_at, Some(ts));
// document exists
let document_metadata = create_document(
@@ -305,6 +329,7 @@ mod tests {
project_name: None,
share_permission: &SharePermissionV2::default(),
skip_history: false,
+ created_at: None,
},
)
.await?;
@@ -327,6 +352,7 @@ mod tests {
.execute(&pool)
.await?;
+ let ts = chrono::Utc.with_ymd_and_hms(1998, 1, 16, 0, 0, 0).unwrap();
// document exists
let document_metadata = create_document(
&pool,
@@ -340,6 +366,7 @@ mod tests {
project_name: None,
share_permission: &SharePermissionV2::default(),
skip_history: false,
+ created_at: Some(&ts),
},
)
.await?;
@@ -352,6 +379,7 @@ mod tests {
assert_eq!(document_metadata.owner, "macro|[email protected]".to_string());
assert_eq!(document_metadata.project_id.as_deref(), Some("project-one"));
assert_eq!(document_metadata.project_name.as_deref(), Some("name"));
+ assert_eq!(document_metadata.created_at, Some(ts));
// document exists
let document_metadata = create_document(
@@ -366,6 +394,7 @@ mod tests {
project_name: None,
share_permission: &SharePermissionV2::default(),
skip_history: false,
+ created_at: None,
},
)
.await?;
@@ -394,6 +423,7 @@ mod tests {
project_name: None,
share_permission: &SharePermissionV2::default(),
skip_history: false,
+ created_at: None,
},
)
.await;
@@ -414,6 +444,8 @@ mod tests {
// First, create a document with the test ID
let mut transaction = pool.begin().await?;
+ let ts = chrono::Utc.with_ymd_and_hms(1998, 1, 16, 0, 0, 0).unwrap();
+
// Insert the first document
insert_document_with_id(
&mut transaction,
@@ -422,6 +454,7 @@ mod tests {
"First Document",
Some(FileType::Pdf),
None,
+ &ts,
)
.await?;
@@ -437,6 +470,7 @@ mod tests {
"Second Document with Same ID",
Some(FileType::Pdf),
None,
+ &ts,
)
.await;
diff --git a/rust/cloud-storage/macro_db_client/src/instructions/create.rs b/rust/cloud-storage/macro_db_client/src/instructions/create.rs
index 976019288e..caad017f2b 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,
+ created_at: None,
},
)
.await?;
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.rs
index 432c0dbb84..8639eec77a 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,
+ created_at: None,
},
)
.await?;
diff --git a/rust/cloud-storage/model/src/document/response/mod.rs b/rust/cloud-storage/model/src/document/response/mod.rs
index fe4e97bc10..433e823df5 100644
--- a/rust/cloud-storage/model/src/document/response/mod.rs
+++ b/rust/cloud-storage/model/src/document/response/mod.rs
@@ -1,9 +1,14 @@
mod location;
+
pub use location::*;
+use std::str::FromStr;
+use crate::document::{BomPart, FileType};
+use crate::response::TypedSuccessResponse;
use crate::{document::DocumentMetadata, response::PresignedUrl};
use chrono::serde::ts_seconds_option;
use models_permissions::share_permission::access_level::AccessLevel;
+use tracing::instrument;
use utoipa::ToSchema;
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
@@ -66,3 +71,147 @@ pub enum LocationResponseData {
/// The presigned urls of the docx bom parts if it is a docx
PresignedUrls(Vec<PresignedUrl>),
}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentResponse {
+ pub document_metadata: DocumentResponseMetadata,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub presigned_url: Option<String>,
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct DocumentResponseMetadata {
+ /// The document id
+ pub document_id: String,
+ /// The version of the document
+ /// This could be the document_instance_id or document_bom_id depending on
+ /// the file type
+ pub document_version_id: i64,
+ /// The owner of the document
+ pub owner: String,
+ /// The name of the document
+ pub document_name: String,
+ /// The file type of the document
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub file_type: Option<String>,
+ /// If the document is a PDF, this is the SHA of the pdf
+ /// If the document is a DOCX, this will not be present
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sha: Option<String>,
+ /// The id of the document this document branched from
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub branched_from_id: Option<String>,
+ /// The id of the version this document branched from
+ /// This could be either DocumentInstance or DocumentBom id depending on
+ /// the file type
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub branched_from_version_id: Option<i64>,
+ /// The id of the document family this document belongs to
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub document_family_id: Option<i64>,
+ /// If the document is a DOCX document, the document_bom will be present
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub document_bom: Option<Vec<BomPart>>,
+ /// The modification data for the document instance.
+ /// This is only used for PDF documents.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub modification_data: Option<serde_json::Value>,
+ /// The time the document was created
+ #[serde(with = "ts_seconds_option")]
+ #[schema(value_type = i64, nullable=false)]
+ pub created_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// The time the document instance / document BOM was updated
+ #[serde(with = "ts_seconds_option")]
+ #[schema(value_type = i64, nullable=false)]
+ pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+impl DocumentResponseMetadata {
+ /// Initialize document response from document metadata
+ fn initialize_from_document_metadata(document_metadata: &DocumentMetadata) -> Self {
+ DocumentResponseMetadata {
+ document_id: document_metadata.document_id.clone(),
+ document_version_id: document_metadata.document_version_id,
+ owner: document_metadata.owner.clone(),
+ document_name: document_metadata.document_name.clone(),
+ file_type: document_metadata.file_type.clone(),
+ sha: document_metadata.sha.clone(),
+ document_bom: None,
+ modification_data: document_metadata.modification_data.clone(),
+ branched_from_id: document_metadata.branched_from_id.clone(),
+ branched_from_version_id: document_metadata.branched_from_version_id,
+ document_family_id: document_metadata.document_family_id,
+ created_at: document_metadata.created_at,
+ updated_at: document_metadata.updated_at,
+ }
+ }
+
+ #[instrument]
+ pub fn from_document_metadata(document_metadata: &DocumentMetadata) -> anyhow::Result<Self> {
+ // Initialize document response
+ let mut document_response_metadata =
+ DocumentResponseMetadata::initialize_from_document_metadata(document_metadata);
+ // Ensure we have a valid file type
+ if let Some(FileType::Docx) = document_metadata
+ .file_type
+ .as_deref()
+ .and_then(|file_type| FileType::from_str(file_type).ok())
+ && let Some(document_bom) = &document_metadata.document_bom
+ {
+ let document_bom: Vec<BomPart> = match serde_json::from_value(document_bom.clone()) {
+ Ok(document_bom) => document_bom,
+ Err(e) => {
+ return Err(anyhow::anyhow!(format!(
+ "document bom could not be serialized {e}",
+ )));
+ }
+ };
+ document_response_metadata.document_bom = Some(document_bom);
+ };
+
+ Ok(document_response_metadata)
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateDocumentResponseData {
+ #[serde(flatten)]
+ pub document_response: DocumentResponse,
+ /// Content type of the document converted from file type
+ pub content_type: String,
+ /// The file type of the document
+ pub file_type: Option<String>,
+}
+
+pub type CreateDocumentResponse = TypedSuccessResponse<CreateDocumentResponseData>;
+
+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateDocumentRequest {
+ /// The id of the document in the database
+ pub id: Option<String>,
+ /// The sha of the document.
+ pub sha: String,
+ /// The name of the document without extension.
+ pub document_name: String,
+ /// Optional file type of the document.
+ pub file_type: Option<String>,
+ /// The content type of the document (currently only used for logging matches against file type).
+ pub mime_type: Option<String>,
+ /// The document family id if the document is being branched.
+ pub document_family_id: Option<i64>,
+ /// The document id if the document is being branched.
+ pub branched_from_id: Option<String>,
+ /// The version id if the document is being branched.
+ pub branched_from_version_id: Option<i64>,
+ /// Optional job id to be used to track an upload job for the newly created document.
+ /// Will need to have a corresponding job initiated for the file beforehand.
+ pub job_id: Option<String>,
+ //// Optional project id to be used to what project the document belongs to.
+ pub project_id: Option<String>,
+ /// Optional time to set the document's created_at to. Set when backfilling email attachments.
+ pub created_at: Option<chrono::DateTime<chrono::Utc>>,
+}