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(document) get by team slug (#5037)

Will Hutchinsone593ef4a3b82
diff --git a/.sqlx/query-6aa131b80d6798a97932488e921d1df01b0b324180df348d01ceac3fea3f333f.json b/.sqlx/query-6aa131b80d6798a97932488e921d1df01b0b324180df348d01ceac3fea3f333f.json
new file mode 100644
index 0000000000..2f785f96ae
--- /dev/null
+++ b/.sqlx/query-6aa131b80d6798a97932488e921d1df01b0b324180df348d01ceac3fea3f333f.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT document_id\n FROM team_task\n WHERE team_id = $1 AND task_num = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "document_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "6aa131b80d6798a97932488e921d1df01b0b324180df348d01ceac3fea3f333f"
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 676f695b7d..691e510001 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -4520,6 +4520,162 @@ export const getBatchPreviewHandlerResponse = zod.object({
),
});
+/**
+ * Returns document metadata, user access level, and view location.
+ * @summary Handler for `GET /documents/slug/{slug}`.
+ */
+export const getDocumentByTeamSlugParams = zod.object({
+ slug: zod.string().describe('Team-task reference, such as ENG-42'),
+});
+
+export const getDocumentByTeamSlugResponse = zod.object({
+ data: zod
+ .object({
+ items: zod
+ .array(
+ zod.union([
+ 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.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the document was created'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the document was deleted'),
+ documentFamilyId: zod
+ .number()
+ .nullish()
+ .describe(
+ 'The id of the document family this document belongs to'
+ ),
+ 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 (e.g. pdf, docx)'),
+ id: zod.string().describe('The document id'),
+ name: zod.string().describe('The name of the document'),
+ owner: zod.string().describe('The owner of the document'),
+ projectId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The id 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
+ .union([
+ zod
+ .object({
+ is_completed: zod
+ .boolean()
+ .describe(
+ 'Whether the task is completed.\nTrue if the Status property is set to \"Completed\".'
+ ),
+ type: zod.enum(['task']),
+ })
+ .describe(
+ 'A task document with its associated properties'
+ ),
+ zod
+ .object({
+ type: zod.enum(['snippet']),
+ })
+ .describe('A snippet document — reusable markdown'),
+ ])
+ .describe(
+ 'Sub type of a document with associated properties encoded in each variant.\nThis ensures type-safety: task properties only exist when the document is a task.'
+ ),
+ ])
+ .optional(),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ 'The time the document instance \/ document BOM was updated'
+ ),
+ type: zod.enum(['document']),
+ }),
+ zod.object({
+ createdAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was created'),
+ deletedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was deleted'),
+ id: zod.string().describe('The chat uuid'),
+ isPersistent: zod.boolean(),
+ model: zod
+ .string()
+ .nullish()
+ .describe('The model used to generate the chat'),
+ name: zod.string().describe('The name of the chat'),
+ projectId: zod
+ .string()
+ .nullish()
+ .describe('The project id of the chat'),
+ tokenCount: zod.number().nullish(),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the chat was last updated'),
+ userId: zod.string().describe('Who the chat belongs to'),
+ type: zod.enum(['chat']),
+ }),
+ zod.object({
+ createdAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the project was created'),
+ deletedAt: zod.iso.datetime({}).nullish(),
+ id: zod.string().describe('The id of the project'),
+ name: zod.string().describe('The name of the project'),
+ parentId: zod
+ .string()
+ .nullish()
+ .describe('The parent project id'),
+ updatedAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe('The time the project was updated'),
+ userId: zod
+ .string()
+ .describe('The user id of who created the project'),
+ type: zod.enum(['project']),
+ }),
+ ])
+ )
+ .describe('The items returned from the call'),
+ })
+ .describe('Data to be returned'),
+ error: zod.boolean().describe('Indicates if an error occurred'),
+});
+
/**
* Returns document metadata, user access level, and view location.
* @summary Handler for `GET /documents/{document_id}`.
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 7ac4e45249..dafe5030ae 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -5506,6 +5506,77 @@
}
}
},
+ "/documents/slug/{slug}": {
+ "get": {
+ "tags": ["document"],
+ "summary": "Handler for `GET /documents/slug/{slug}`.",
+ "description": "Returns document metadata, user access level, and view location.",
+ "operationId": "get_document_by_team_slug",
+ "parameters": [
+ {
+ "name": "slug",
+ "in": "path",
+ "description": "Team-task reference, such as ENG-42",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TypedSuccessResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/documents/{document_id}": {
"get": {
"tags": ["document"],
diff --git a/crates/documents/src/domain/ports/mod.rs b/crates/documents/src/domain/ports/mod.rs
index 6d66c3883c..d5c100ed4e 100644
--- a/crates/documents/src/domain/ports/mod.rs
+++ b/crates/documents/src/domain/ports/mod.rs
@@ -10,7 +10,7 @@ pub mod markdown;
use std::future::Future;
use entity_access::domain::models::{
- EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
+ EditAccessLevel, EntityAccessReceipt, MemberTeamRole, OwnerAccessLevel, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
use model::document::{ContentType, DocumentBasic, DocumentMetadata};
@@ -174,6 +174,13 @@ pub trait DocumentRepo: Send + Sync + 'static {
document_id: &str,
) -> impl Future<Output = Result<Option<TeamTaskMetadata>, Self::Err>> + Send;
+ /// Get the document ID assigned to a task number within a team.
+ fn get_document_id_by_team_task_number(
+ &self,
+ team_id: &uuid::Uuid,
+ task_num: i32,
+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+
/// Get user/team data needed to build a branch name for this user and task.
fn get_branch_name_context(
&self,
@@ -345,6 +352,13 @@ pub trait DocumentService: Send + Sync + 'static {
document_id: &str,
) -> impl Future<Output = Result<DocumentBasic, DocumentError>> + Send;
+ /// Resolve a team task slug to its document ID.
+ fn get_document_by_team_slug(
+ &self,
+ team_receipt: EntityAccessReceipt<MemberTeamRole>,
+ slug: &str,
+ ) -> impl Future<Output = Result<String, DocumentError>> + Send;
+
/// Get a document with metadata, access level, and view location.
fn get_document(
&self,
diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rs
index d67c1af44f..c48472b200 100644
--- a/crates/documents/src/domain/service.rs
+++ b/crates/documents/src/domain/service.rs
@@ -19,7 +19,8 @@ use connection::domain::models::{InvalidationEvent, InvalidationReason};
use connection::domain::ports::ConnectionService;
use document_sub_type::DocumentSubType;
use entity_access::domain::models::{
- EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
+ EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, MemberTeamRole, OwnerAccessLevel,
+ ViewAccessLevel,
};
use foreign_entity::domain::models::{ForeignEntity, SourceId};
use foreign_entity::domain::ports::ForeignEntityService;
@@ -154,6 +155,31 @@ fn short_id_for_entity_id(entity_id: &str) -> Result<String, DocumentError> {
Ok(macro_uuid::ShortUuidConverter::default().from_uuid(&uuid))
}
+fn invalid_team_task_slug() -> DocumentError {
+ DocumentError::BadRequest("invalid team task slug".to_string())
+}
+
+fn team_task_number_from_slug(slug: &str) -> Result<i32, DocumentError> {
+ let (prefix, number) = slug.rsplit_once('-').ok_or_else(invalid_team_task_slug)?;
+
+ let has_malformed_separator = prefix.split('-').any(str::is_empty);
+ if has_malformed_separator
+ || number.is_empty()
+ || !number.bytes().all(|byte| byte.is_ascii_digit())
+ {
+ return Err(invalid_team_task_slug());
+ }
+
+ let task_num = number
+ .parse::<i32>()
+ .map_err(|_| invalid_team_task_slug())?;
+ if task_num <= 0 {
+ return Err(invalid_team_task_slug());
+ }
+
+ Ok(task_num)
+}
+
fn foreign_entity_matches_source_id(foreign_entity: &ForeignEntity, source_id: &SourceId) -> bool {
foreign_entity.stored_for_id == source_id.id
&& foreign_entity.stored_for_auth_entity == source_id.auth_entity
@@ -593,6 +619,44 @@ impl<
B: MacroEventBroker,
> DocumentService for DocumentServiceImpl<R, U, T, C, Eam, F, B>
{
+ #[tracing::instrument(err, skip(self, team_receipt))]
+ async fn get_document_by_team_slug(
+ &self,
+ team_receipt: EntityAccessReceipt<MemberTeamRole>,
+ slug: &str,
+ ) -> Result<String, DocumentError> {
+ if team_receipt.entity().entity_type != EntityType::Team {
+ return Err(DocumentError::BadRequest(
+ "access receipt must be for a team".to_string(),
+ ));
+ }
+
+ let team_id = uuid::Uuid::parse_str(&team_receipt.entity().entity_id)
+ .map_err(|_| DocumentError::BadRequest("invalid team id".to_string()))?;
+ let task_num = team_task_number_from_slug(slug)?;
+ let document_id = self
+ .repo
+ .get_document_id_by_team_task_number(&team_id, task_num)
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))?
+ .ok_or_else(|| DocumentError::NotFound(slug.to_string()))?;
+ let document = self
+ .repo
+ .get_basic_document(&document_id)
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))?;
+
+ let is_owner = matches!(
+ team_receipt.auth(),
+ EntityAccessAuth::Authenticated(user_id) if document.owner == *user_id
+ );
+ if document.deleted_at.is_some() && !is_owner {
+ return Err(DocumentError::Unauthorized);
+ }
+
+ Ok(document_id)
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_document(
&self,
diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rs
index d36331d037..cfd167332f 100644
--- a/crates/documents/src/domain/service/tests.rs
+++ b/crates/documents/src/domain/service/tests.rs
@@ -1,3 +1,4 @@
+use entity_access::domain::models::MemberTeamRole;
use foreign_entity::domain::models::{
CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,
};
@@ -83,6 +84,14 @@ fn internal_receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {
EntityAccessReceipt::dangerously_assert_internal_user(document_id, EntityType::Document)
}
+fn member_team_receipt(team_id: &str, user_id: &str) -> EntityAccessReceipt<MemberTeamRole> {
+ let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)
+ .unwrap()
+ .into_owned();
+
+ EntityAccessReceipt::dangerously_assert_authenticated_user(user_id, team_id, EntityType::Team)
+}
+
fn bot_id() -> entity_access::domain::models::BotId {
entity_access::domain::models::BotId::new_from_uuid(uuid::uuid!(
"00000000-0000-0000-0000-000000000123"
@@ -597,6 +606,223 @@ fn assert_shallow_pull_request_with_foreign_entity_id(
);
}
+#[tokio::test]
+async fn get_document_by_team_slug_resolves_valid_slug() {
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000701");
+ let mut repo = make_mock_repo();
+
+ repo.expect_get_document_id_by_team_task_number()
+ .withf(move |actual_team_id, task_num| actual_team_id == &team_id && *task_num == 42)
+ .return_once(|_, _| Box::pin(std::future::ready(Ok(Some("doc-1".to_string())))));
+ repo.expect_get_basic_document()
+ .withf(|document_id| document_id == "doc-1")
+ .return_once(|_| Box::pin(std::future::ready(Ok(task_document_context("doc-1")))));
+
+ let document_id = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(&team_id.to_string(), "macro|[email protected]"),
+ "engineering-platform-42",
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(document_id, "doc-1");
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_rejects_malformed_slugs() {
+ for slug in [
+ "",
+ "engineering",
+ "-1",
+ "engineering-",
+ "engineering--task-1",
+ "engineering-task",
+ "engineering-1.5",
+ "engineering-+1",
+ ] {
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number().times(0);
+ repo.expect_get_basic_document().times(0);
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(
+ "00000000-0000-0000-0000-000000000701",
+ ),
+ slug,
+ )
+ .await;
+
+ assert!(
+ matches!(result, Err(DocumentError::BadRequest(_))),
+ "expected {slug:?} to be rejected, got {result:?}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_rejects_non_positive_and_overflowing_numbers() {
+ for slug in ["engineering-0", "engineering--1", "engineering-2147483648"] {
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number().times(0);
+ repo.expect_get_basic_document().times(0);
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(
+ "00000000-0000-0000-0000-000000000701",
+ ),
+ slug,
+ )
+ .await;
+
+ assert!(
+ matches!(result, Err(DocumentError::BadRequest(_))),
+ "expected {slug:?} to be rejected, got {result:?}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_rejects_wrong_receipt_entity_type() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number().times(0);
+ repo.expect_get_basic_document().times(0);
+ let receipt = EntityAccessReceipt::<MemberTeamRole>::dangerously_assert_authenticated_user(
+ macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ "00000000-0000-0000-0000-000000000701",
+ EntityType::Document,
+ );
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(receipt, "engineering-1")
+ .await;
+
+ assert!(matches!(result, Err(DocumentError::BadRequest(_))));
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_rejects_malformed_team_uuid() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number().times(0);
+ repo.expect_get_basic_document().times(0);
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt("not-a-team-uuid", "macro|[email protected]"),
+ "engineering-1",
+ )
+ .await;
+
+ assert!(matches!(result, Err(DocumentError::BadRequest(_))));
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_maps_missing_lookup_to_not_found() {
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000701");
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number()
+ .withf(move |actual_team_id, task_num| actual_team_id == &team_id && *task_num == 404)
+ .return_once(|_, _| Box::pin(std::future::ready(Ok(None))));
+ repo.expect_get_basic_document().times(0);
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(&team_id.to_string(), "macro|[email protected]"),
+ "engineering-404",
+ )
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(DocumentError::NotFound(slug)) if slug == "engineering-404"
+ ));
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_maps_lookup_error_to_internal() {
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000701");
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number()
+ .return_once(|_, _| Box::pin(std::future::ready(Err(anyhow!("database unavailable")))));
+ repo.expect_get_basic_document().times(0);
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(&team_id.to_string(), "macro|[email protected]"),
+ "engineering-1",
+ )
+ .await;
+
+ assert!(matches!(result, Err(DocumentError::Internal(_))));
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_maps_document_load_error_to_internal() {
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000701");
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number()
+ .return_once(|_, _| Box::pin(std::future::ready(Ok(Some("doc-1".to_string())))));
+ repo.expect_get_basic_document()
+ .return_once(|_| Box::pin(std::future::ready(Err(anyhow!("database unavailable")))));
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(&team_id.to_string(), "macro|[email protected]"),
+ "engineering-1",
+ )
+ .await;
+
+ assert!(matches!(result, Err(DocumentError::Internal(_))));
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_allows_owner_of_deleted_document() {
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000701");
+ let mut document = task_document_context("doc-1");
+ document.deleted_at = Some(chrono::Utc::now());
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number()
+ .return_once(|_, _| Box::pin(std::future::ready(Ok(Some("doc-1".to_string())))));
+ repo.expect_get_basic_document()
+ .return_once(move |_| Box::pin(std::future::ready(Ok(document))));
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(&team_id.to_string(), "macro|[email protected]"),
+ "engineering-1",
+ )
+ .await;
+
+ assert_eq!(result.unwrap(), "doc-1");
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_rejects_non_owner_of_deleted_document() {
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000701");
+ let mut document = task_document_context("doc-1");
+ document.deleted_at = Some(chrono::Utc::now());
+ let mut repo = make_mock_repo();
+ repo.expect_get_document_id_by_team_task_number()
+ .return_once(|_, _| Box::pin(std::future::ready(Ok(Some("doc-1".to_string())))));
+ repo.expect_get_basic_document()
+ .return_once(move |_| Box::pin(std::future::ready(Ok(document))));
+
+ let result = make_test_service(repo)
+ .get_document_by_team_slug(
+ member_team_receipt(&team_id.to_string(), "macro|[email protected]"),
+ "engineering-1",
+ )
+ .await;
+
+ assert!(matches!(result, Err(DocumentError::Unauthorized)));
+}
+
#[tokio::test]
async fn bot_document_has_no_saved_user_view_location() {
let mut repo = make_mock_repo();
diff --git a/crates/documents/src/inbound/axum_router.rs b/crates/documents/src/inbound/axum_router.rs
index ee95962ea8..89b78b4e37 100644
--- a/crates/documents/src/inbound/axum_router.rs
+++ b/crates/documents/src/inbound/axum_router.rs
@@ -3,6 +3,7 @@
//! Provides routes:
//! - `POST /` — create a new document
//! - `GET /{document_id}` — get document metadata
+//! - `GET /slug/{slug}` - get document by team slug
//! - `GET /{document_id}/location_v3` — get document content location (presigned URL)
//! - `GET /{document_id}/branch_name` — get short ID + task-aware git branch name (when the document is a task)
//! - `GET /{document_id}/github_prs` — get GitHub pull requests associated with a task document
@@ -27,6 +28,7 @@ pub mod edit_document;
pub mod get_branch_name;
pub mod get_cached_snapshot_url;
pub mod get_document;
+pub mod get_document_by_team_slug;
pub mod get_github_pull_requests;
pub mod get_location;
pub mod get_short_id;
@@ -65,6 +67,7 @@ use self::{
get_branch_name::get_branch_name_handler,
get_cached_snapshot_url::get_cached_snapshot_url_handler,
get_document::get_document_handler,
+ get_document_by_team_slug::get_document_by_team_slug_handler,
get_github_pull_requests::get_github_pull_requests_handler,
get_location::get_location_v3_handler,
get_short_id::get_short_id_handler,
@@ -269,6 +272,10 @@ where
let router = Router::new()
.merge(document_id_routes)
+ .route(
+ "/slug/{slug}",
+ axum::routing::get(get_document_by_team_slug_handler::<T, Svc, Auth>),
+ )
.route(
"/",
axum::routing::post(create_document_handler::<T, Svc, Auth>),
diff --git a/crates/documents/src/inbound/axum_router/get_document_by_team_slug.rs b/crates/documents/src/inbound/axum_router/get_document_by_team_slug.rs
new file mode 100644
index 0000000000..5ee125fd11
--- /dev/null
+++ b/crates/documents/src/inbound/axum_router/get_document_by_team_slug.rs
@@ -0,0 +1,132 @@
+//! Handler for `GET /documents/slug/{slug}`.
+
+use std::marker::PhantomData;
+
+use axum::{
+ Json, RequestPartsExt,
+ extract::{FromRequestParts, Path, State},
+ http::request::Parts,
+ response::{IntoResponse, Response},
+};
+use entity_access::{
+ domain::{
+ models::{
+ EntityAccessReceipt, EntityType, MemberTeamRole, RequiredPermission, ViewAccessLevel,
+ },
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::{ExtractorError, MacroUserTeamExtractorV2},
+};
+use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService};
+use serde::Deserialize;
+
+use super::DocumentRouterState;
+use crate::domain::models::DocumentError;
+use crate::domain::ports::DocumentService;
+use crate::domain::response::GetDocumentResponse;
+
+#[derive(Deserialize)]
+struct TeamSlugParams {
+ slug: String,
+}
+
+/// Resolves a team-task slug and verifies access to its document.
+///
+/// Authentication and team membership are required before the slug is resolved.
+/// `Level` specifies the minimum document access required by the caller.
+pub struct DocumentTeamSlugAccessExtractor<Level: RequiredPermission, T, Svc, Auth> {
+ /// The access receipt for the document resolved from the team-task slug.
+ pub entity_access_receipt: EntityAccessReceipt<Level>,
+ _marker: PhantomData<(T, Svc, Auth)>,
+}
+
+impl<Level, T, Svc, Auth> FromRequestParts<DocumentRouterState<T, Svc, Auth>>
+ for DocumentTeamSlugAccessExtractor<Level, T, Svc, Auth>
+where
+ Level: RequiredPermission,
+ T: DocumentService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ type Rejection = Response;
+
+ #[tracing::instrument(err(Debug), skip(state, parts))]
+ async fn from_request_parts(
+ parts: &mut Parts,
+ state: &DocumentRouterState<T, Svc, Auth>,
+ ) -> Result<Self, Self::Rejection> {
+ let user = parts
+ .extract_with_state::<MacroAuthorizationExtractor<Auth>, _>(state)
+ .await
+ .map_err(IntoResponse::into_response)?;
+ let team = parts
+ .extract_with_state::<MacroUserTeamExtractorV2<MemberTeamRole, Svc, Auth>, _>(state)
+ .await
+ .map_err(IntoResponse::into_response)?;
+ let Path(TeamSlugParams { slug }) = parts
+ .extract::<Path<TeamSlugParams>>()
+ .await
+ .map_err(IntoResponse::into_response)?;
+
+ let document_id = state
+ .service
+ .get_document_by_team_slug(team.entity_access_receipt, &slug)
+ .await
+ .map_err(IntoResponse::into_response)?;
+ let entity_access_receipt = state
+ .access_service
+ .generate_entity_access_receipt::<Level>(
+ &user.macro_user_id,
+ user.user_context.organization_id.map(i64::from),
+ &document_id,
+ EntityType::Document,
+ )
+ .await
+ .map_err(ExtractorError::from)
+ .map_err(IntoResponse::into_response)?;
+
+ Ok(Self {
+ entity_access_receipt,
+ _marker: PhantomData,
+ })
+ }
+}
+
+/// Handler for `GET /documents/slug/{slug}`.
+///
+/// Returns document metadata, user access level, and view location.
+#[utoipa::path(
+ tag = "document",
+ get,
+ path = "/documents/slug/{slug}",
+ operation_id = "get_document_by_team_slug",
+ params(
+ ("slug" = String, Path, description = "Team-task reference, such as ENG-42")
+ ),
+ responses(
+ (status = 200, body = GetDocumentResponse),
+ (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), err)]
+pub async fn get_document_by_team_slug_handler<
+ T: DocumentService,
+ Svc: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<DocumentRouterState<T, Svc, Auth>>,
+ access: DocumentTeamSlugAccessExtractor<ViewAccessLevel, T, Svc, Auth>,
+) -> Result<Json<GetDocumentResponse>, DocumentError> {
+ let response_data = state
+ .service
+ .get_document(access.entity_access_receipt)
+ .await?;
+
+ Ok(Json(GetDocumentResponse {
+ error: false,
+ data: response_data,
+ }))
+}
diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rs
index c3534001f7..2fe174763f 100644
--- a/crates/documents/src/inbound/axum_router/tests.rs
+++ b/crates/documents/src/inbound/axum_router/tests.rs
@@ -10,7 +10,7 @@ use embedding::embedding_provider::openai::TextEmbedding3Small;
use entity_access::domain::{
models::{
AccessError, AccessLevel, BotId, CallChannelInfo, EntityAccessReceipt, EntityPermission,
- EntityType, RequiredPermission, UserTeamInfo,
+ EntityType, MemberTeamRole, RequiredPermission, TeamRole, UserTeamInfo,
},
ports::EntityAccessService,
};
@@ -22,7 +22,7 @@ use macro_authorization::{
};
use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};
use model::{
- document::{DocumentBasic, response::DocumentResponseMetadata},
+ document::{DocumentBasic, DocumentMetadata, response::DocumentResponseMetadata},
sync_service::SyncServiceVersionID,
};
use model_entity::Entity;
@@ -54,8 +54,8 @@ use crate::{
},
ports::{DocumentService, create::DocumentCreationService},
response::{
- CreateDocumentResponseData, DocumentResponse, DocumentResponseMetadataWithContent,
- GetDocumentResponseData, LocationResponseV3,
+ CreateDocumentResponseData, DocumentMetadataWithContent, DocumentResponse,
+ DocumentResponseMetadataWithContent, GetDocumentResponseData, LocationResponseV3,
},
},
outbound::{
@@ -72,6 +72,9 @@ const LEGACY_INTERNAL_KEY: &str = "legacy-internal-key";
const LEGACY_INTERNAL_USER_ID: &str = "macro|[email protected]";
const LEGACY_INTERNAL_API_KEY_HEADER: &str = "x-document-storage-service-auth-key";
const LEGACY_INTERNAL_USER_ID_HEADER: &str = "x-document-storage-service-user-id";
+const TEST_ORGANIZATION_ID: i32 = 42;
+const TEAM_ID: Uuid = Uuid::from_u128(0x82c6f359_691f_4ff3_965a_016a2970b1a2);
+const RESOLVED_DOCUMENT_ID: &str = "resolved-document";
#[derive(Clone, Debug, Eq, PartialEq)]
struct CreateDocumentCall {
@@ -85,10 +88,28 @@ struct UploadSnapshotCall {
bytes: Vec<u8>,
}
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct TeamSlugCall {
+ team_id: String,
+ user_id: String,
+ slug: String,
+}
+
+#[derive(Clone, Debug)]
+enum TeamSlugResult {
+ Success(String),
+ BadRequest(String),
+ NotFound(String),
+}
+
#[derive(Default)]
struct FakeDocumentService {
create_calls: Mutex<Vec<CreateDocumentCall>>,
upload_snapshot_calls: Mutex<Vec<UploadSnapshotCall>>,
+ internal_get_calls: Mutex<Vec<String>>,
+ team_slug_calls: Mutex<Vec<TeamSlugCall>>,
+ team_slug_result: Mutex<Option<TeamSlugResult>>,
+ get_document_calls: Mutex<Vec<String>>,
}
impl FakeDocumentService {
@@ -105,6 +126,34 @@ impl FakeDocumentService {
.expect("upload snapshot calls lock poisoned")
.clone()
}
+
+ fn set_team_slug_result(&self, result: TeamSlugResult) {
+ *self
+ .team_slug_result
+ .lock()
+ .expect("team slug result lock poisoned") = Some(result);
+ }
+
+ fn internal_get_calls(&self) -> Vec<String> {
+ self.internal_get_calls
+ .lock()
+ .expect("internal get calls lock poisoned")
+ .clone()
+ }
+
+ fn team_slug_calls(&self) -> Vec<TeamSlugCall> {
+ self.team_slug_calls
+ .lock()
+ .expect("team slug calls lock poisoned")
+ .clone()
+ }
+
+ fn get_document_calls(&self) -> Vec<String> {
+ self.get_document_calls
+ .lock()
+ .expect("get document calls lock poisoned")
+ .clone()
+ }
}
impl DocumentService for FakeDocumentService {
@@ -112,6 +161,11 @@ impl DocumentService for FakeDocumentService {
&self,
document_id: &str,
) -> Result<DocumentBasic, DocumentError> {
+ self.internal_get_calls
+ .lock()
+ .expect("internal get calls lock poisoned")
+ .push(document_id.to_string());
+
Ok(DocumentBasic {
document_id: document_id.to_string(),
document_name: "test document".to_string(),
@@ -127,11 +181,48 @@ impl DocumentService for FakeDocumentService {
})
}
+ async fn get_document_by_team_slug(
+ &self,
+ team_receipt: EntityAccessReceipt<MemberTeamRole>,
+ slug: &str,
+ ) -> Result<String, DocumentError> {
+ self.team_slug_calls
+ .lock()
+ .expect("team slug calls lock poisoned")
+ .push(TeamSlugCall {
+ team_id: team_receipt.entity().entity_id.clone(),
+ user_id: team_receipt
+ .get_authenticated_user()
+ .expect("team receipt should have an authenticated user")
+ .as_ref()
+ .to_string(),
+ slug: slug.to_string(),
+ });
+
+ match self
+ .team_slug_result
+ .lock()
+ .expect("team slug result lock poisoned")
+ .clone()
+ .expect("team slug result should be configured")
+ {
+ TeamSlugResult::Success(document_id) => Ok(document_id),
+ TeamSlugResult::BadRequest(message) => Err(DocumentError::BadRequest(message)),
+ TeamSlugResult::NotFound(message) => Err(DocumentError::NotFound(message)),
+ }
+ }
+
async fn get_document(
&self,
- _entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::ViewAccessLevel>,
+ entity_access_receipt: EntityAccessReceipt<entity_access::domain::models::ViewAccessLevel>,
) -> Result<GetDocumentResponseData, DocumentError> {
- panic!("unexpected get_document call")
+ let document_id = entity_access_receipt.entity().entity_id.clone();
+ self.get_document_calls
+ .lock()
+ .expect("get document calls lock poisoned")
+ .push(document_id.clone());
+
+ Ok(get_document_response(&document_id))
}
async fn get_document_location(
@@ -359,18 +450,118 @@ fn create_document_response(user_id: MacroUserIdStr<'static>) -> CreateDocumentR
}
}
-#[derive(Clone, Default)]
-struct FakeEntityAccessService;
+fn get_document_response(document_id: &str) -> GetDocumentResponseData {
+ GetDocumentResponseData {
+ document_metadata: DocumentMetadataWithContent::new(
+ DocumentMetadata {
+ document_id: document_id.to_string(),
+ document_version_id: 1,
+ owner: MacroUserIdStr::try_from(JWT_USER_ID.to_string())
+ .expect("test user id should be valid"),
+ document_name: "resolved document".to_string(),
+ file_type: Some("pdf".to_string()),
+ sha: Some("test-sha".to_string()),
+ project_id: None,
+ project_name: None,
+ branched_from_id: None,
+ branched_from_version_id: None,
+ document_family_id: None,
+ document_bom: None,
+ modification_data: None,
+ created_at: None,
+ updated_at: None,
+ deleted_at: None,
+ sub_type: None,
+ },
+ DocumentContent::pending(),
+ ),
+ user_access_level: AccessLevel::View,
+ view_location: None,
+ }
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct DocumentAccessCall {
+ user_id: String,
+ organization_id: Option<i64>,
+ entity_id: String,
+ entity_type: EntityType,
+}
+
+#[derive(Clone)]
+struct FakeEntityAccessService {
+ team_info: Arc<Mutex<Option<UserTeamInfo>>>,
+ deny_document_access: Arc<Mutex<bool>>,
+ document_access_calls: Arc<Mutex<Vec<DocumentAccessCall>>>,
+}
+
+impl Default for FakeEntityAccessService {
+ fn default() -> Self {
+ Self {
+ team_info: Arc::new(Mutex::new(None)),
+ deny_document_access: Arc::new(Mutex::new(false)),
+ document_access_calls: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+}
+
+impl FakeEntityAccessService {
+ fn set_team(&self, team_info: Option<UserTeamInfo>) {
+ *self.team_info.lock().expect("team info lock poisoned") = team_info;
+ }
+
+ fn deny_document_access(&self) {
+ *self
+ .deny_document_access
+ .lock()
+ .expect("document access result lock poisoned") = true;
+ }
+
+ fn document_access_calls(&self) -> Vec<DocumentAccessCall> {
+ self.document_access_calls
+ .lock()
+ .expect("document access calls lock poisoned")
+ .clone()
+ }
+}
impl EntityAccessService for FakeEntityAccessService {
async fn generate_entity_access_receipt<T: RequiredPermission>(
&self,
- _user_id: &MacroUserId<Lowercase<'_>>,
- _user_org_id: Option<i64>,
- _entity_id: &str,
- _entity_type: EntityType,
+ user_id: &MacroUserId<Lowercase<'_>>,
+ user_org_id: Option<i64>,
+ entity_id: &str,
+ entity_type: EntityType,
) -> Result<EntityAccessReceipt<T>, AccessError> {
- panic!("unexpected generate_entity_access_receipt call")
+ self.document_access_calls
+ .lock()
+ .expect("document access calls lock poisoned")
+ .push(DocumentAccessCall {
+ user_id: user_id.as_ref().to_string(),
+ organization_id: user_org_id,
+ entity_id: entity_id.to_string(),
+ entity_type,
+ });
+
+ if *self
+ .deny_document_access
+ .lock()
+ .expect("document access result lock poisoned")
+ {
+ return Err(AccessError::Unauthorized);
+ }
+
+ EntityAccessReceipt::try_new_authenticated_user(
+ MacroUserIdStr::try_from(user_id.as_ref().to_string())
+ .expect("test user id should be valid"),
+ entity_access::domain::models::Entity {
+ entity_id: entity_id.to_string(),
+ entity_type,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ )
}
async fn generate_bot_entity_access_receipt<T: RequiredPermission>(
@@ -455,7 +646,7 @@ impl EntityAccessService for FakeEntityAccessService {
&self,
_user_id: &MacroUserId<Lowercase<'_>>,
) -> Result<Option<UserTeamInfo>, AccessError> {
- panic!("unexpected get_user_team call")
+ Ok(*self.team_info.lock().expect("team info lock poisoned"))
}
}
@@ -519,7 +710,7 @@ fn user_context(user_id: &str) -> UserContext {
user_id: user_id.to_string(),
fusion_user_id: "test-fusion-user".to_string(),
permissions: None,
- organization_id: None,
+ organization_id: Some(TEST_ORGANIZATION_ID),
}
}
@@ -541,12 +732,18 @@ impl TaskDedupNotifier for FakeTaskDedupNotifier {
}
}
-fn test_router() -> (Router, Arc<FakeDocumentService>, FakeAuthorizationService) {
+fn test_router() -> (
+ Router,
+ Arc<FakeDocumentService>,
+ FakeEntityAccessService,
+ FakeAuthorizationService,
+) {
let pool = PgPoolOptions::new()
.connect_lazy("postgres://postgres:postgres@localhost/documents-router-test")
.expect("test database URL should be valid");
let document_service = Arc::new(FakeDocumentService::default());
let authorization_service = FakeAuthorizationService::default();
+ let access_service = FakeEntityAccessService::default();
let lexical_client = Arc::new(LexicalClient::new(
"unused-internal-key".to_string(),
"http://localhost/lexical".to_string(),
@@ -572,7 +769,7 @@ fn test_router() -> (Router, Arc<FakeDocumentService>, FakeAuthorizationService)
);
let state = DocumentRouterState {
service: document_service.clone(),
- access_service: Arc::new(FakeEntityAccessService),
+ access_service: Arc::new(access_service.clone()),
authorization_state: MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
pool,
task_dedup_service,
@@ -587,7 +784,12 @@ fn test_router() -> (Router, Arc<FakeDocumentService>, FakeAuthorizationService)
(),
>(state);
- (router, document_service, authorization_service)
+ (
+ router,
+ document_service,
+ access_service,
+ authorization_service,
+ )
}
fn create_request() -> Builder {
@@ -630,10 +832,137 @@ async fn send_status(router: &Router, request: Request<Body>) -> StatusCode {
router.clone().oneshot(request).await.unwrap().status()
}
+fn team_slug_request(slug: &str) -> Builder {
+ Request::get(format!("/slug/{slug}"))
+}
+
+fn team_member() -> UserTeamInfo {
+ UserTeamInfo {
+ team_id: TEAM_ID,
+ role: TeamRole::Member,
+ }
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_succeeds_without_document_id_middleware() {
+ let (router, document_service, access_service, _authorization_service) = test_router();
+ access_service.set_team(Some(team_member()));
+ document_service
+ .set_team_slug_result(TeamSlugResult::Success(RESOLVED_DOCUMENT_ID.to_string()));
+ let request = team_slug_request("ENG-42")
+ .header("authorization", format!("Bearer {JWT_TOKEN}"))
+ .body(Body::empty())
+ .expect("request should build");
+
+ assert_eq!(send_status(&router, request).await, StatusCode::OK);
+ assert_eq!(
+ document_service.team_slug_calls(),
+ [TeamSlugCall {
+ team_id: TEAM_ID.to_string(),
+ user_id: JWT_USER_ID.to_string(),
+ slug: "ENG-42".to_string(),
+ }]
+ );
+ assert_eq!(
+ access_service.document_access_calls(),
+ [DocumentAccessCall {
+ user_id: JWT_USER_ID.to_string(),
+ organization_id: Some(i64::from(TEST_ORGANIZATION_ID)),
+ entity_id: RESOLVED_DOCUMENT_ID.to_string(),
+ entity_type: EntityType::Document,
+ }]
+ );
+ assert_eq!(
+ document_service.get_document_calls(),
+ [RESOLVED_DOCUMENT_ID.to_string()]
+ );
+ assert!(document_service.internal_get_calls().is_empty());
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_requires_credentials_and_team_membership() {
+ let (router, document_service, _access_service, _authorization_service) = test_router();
+ let missing_credentials = team_slug_request("ENG-42")
+ .body(Body::empty())
+ .expect("request should build");
+
+ assert_eq!(
+ send_status(&router, missing_credentials).await,
+ StatusCode::UNAUTHORIZED
+ );
+ assert!(document_service.team_slug_calls().is_empty());
+ assert!(document_service.internal_get_calls().is_empty());
+
+ let (router, document_service, _access_service, _authorization_service) = test_router();
+ let missing_team = team_slug_request("ENG-42")
+ .header("authorization", format!("Bearer {JWT_TOKEN}"))
+ .body(Body::empty())
+ .expect("request should build");
+
+ assert_eq!(
+ send_status(&router, missing_team).await,
+ StatusCode::UNAUTHORIZED
+ );
+ assert!(document_service.team_slug_calls().is_empty());
+ assert!(document_service.internal_get_calls().is_empty());
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_preserves_document_access_denial() {
+ let (router, document_service, access_service, _authorization_service) = test_router();
+ access_service.set_team(Some(team_member()));
+ access_service.deny_document_access();
+ document_service
+ .set_team_slug_result(TeamSlugResult::Success(RESOLVED_DOCUMENT_ID.to_string()));
+ let request = team_slug_request("ENG-42")
+ .header("authorization", format!("Bearer {JWT_TOKEN}"))
+ .body(Body::empty())
+ .expect("request should build");
+
+ assert_eq!(
+ send_status(&router, request).await,
+ StatusCode::UNAUTHORIZED
+ );
+ assert!(document_service.get_document_calls().is_empty());
+ assert!(document_service.internal_get_calls().is_empty());
+}
+
+#[tokio::test]
+async fn get_document_by_team_slug_preserves_domain_error_statuses() {
+ let (router, document_service, access_service, _authorization_service) = test_router();
+ access_service.set_team(Some(team_member()));
+ document_service.set_team_slug_result(TeamSlugResult::BadRequest(
+ "invalid team-task slug".to_string(),
+ ));
+ let malformed_request = team_slug_request("invalid")
+ .header("authorization", format!("Bearer {JWT_TOKEN}"))
+ .body(Body::empty())
+ .expect("request should build");
+
+ assert_eq!(
+ send_status(&router, malformed_request).await,
+ StatusCode::BAD_REQUEST
+ );
+
+ document_service.set_team_slug_result(TeamSlugResult::NotFound("ENG-999".to_string()));
+ let missing_request = team_slug_request("ENG-999")
+ .header("authorization", format!("Bearer {JWT_TOKEN}"))
+ .body(Body::empty())
+ .expect("request should build");
+
+ assert_eq!(
+ send_status(&router, missing_request).await,
+ StatusCode::NOT_FOUND
+ );
+ assert!(access_service.document_access_calls().is_empty());
+ assert!(document_service.get_document_calls().is_empty());
+ assert!(document_service.internal_get_calls().is_empty());
+}
+
#[tokio::test]
async fn snapshot_upload_requires_internal_api_key() {
let snapshot = b"snapshot bytes";
- let (router, document_service, authorization_service) = test_router();
+ let (router, document_service, _access_service, authorization_service) = test_router();
let jwt_request = Request::put("/snapshot-document/snapshot")
.header("authorization", format!("Bearer {JWT_TOKEN}"))
@@ -670,7 +999,7 @@ async fn snapshot_upload_requires_internal_api_key() {
#[tokio::test]
async fn legacy_internal_headers_reach_the_internal_only_creation_path() {
let email_attachment_id = Uuid::new_v4();
- let (router, document_service, authorization_service) = test_router();
+ let (router, document_service, _access_service, authorization_service) = test_router();
let request = finish_request(
create_request()
.header(LEGACY_INTERNAL_API_KEY_HEADER, LEGACY_INTERNAL_KEY)
@@ -698,7 +1027,7 @@ async fn legacy_internal_headers_reach_the_internal_only_creation_path() {
#[tokio::test]
async fn standard_internal_headers_reach_the_document_service() {
- let (router, document_service, authorization_service) = test_router();
+ let (router, document_service, _access_service, authorization_service) = test_router();
let request = finish_request(
create_request()
.header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY)
@@ -726,7 +1055,7 @@ async fn standard_internal_headers_reach_the_document_service() {
#[tokio::test]
async fn standard_internal_headers_take_precedence_over_legacy_headers() {
- let (router, document_service, authorization_service) = test_router();
+ let (router, document_service, _access_service, authorization_service) = test_router();
let request = finish_request(
create_request()
.header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY)
@@ -762,7 +1091,7 @@ async fn standard_internal_headers_take_precedence_over_legacy_headers() {
#[tokio::test]
async fn jwt_user_cannot_create_a_document_for_an_email_attachment() {
let email_attachment_id = Uuid::new_v4();
- let (router, document_service, _authorization_service) = test_router();
+ let (router, document_service, _access_service, _authorization_service) = test_router();
let request = finish_request(
create_request().header("authorization", format!("Bearer {JWT_TOKEN}")),
Some(email_attachment_id),
diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rs
index 8dbfa5f1b7..0b12f75d1b 100644
--- a/crates/documents/src/outbound/pg_document_repo.rs
+++ b/crates/documents/src/outbound/pg_document_repo.rs
@@ -728,6 +728,25 @@ impl DocumentRepo for PgDocumentRepo {
}))
}
+ #[tracing::instrument(err, skip(self))]
+ async fn get_document_id_by_team_task_number(
+ &self,
+ team_id: &uuid::Uuid,
+ task_num: i32,
+ ) -> Result<Option<String>, Self::Err> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT document_id
+ FROM team_task
+ WHERE team_id = $1 AND task_num = $2
+ "#,
+ team_id,
+ task_num,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_branch_name_context(
&self,
diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rs
index bea723e7a8..0f968cd4a7 100644
--- a/crates/documents/src/outbound/pg_document_repo/tests.rs
+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs
@@ -296,7 +296,7 @@ async fn test_edit_document_set_file_type(pool: Pool<Postgres>) {
document_name: None,
project_id: None,
share_permission: None,
- file_type: Some(FileTypeUpdate::Set(model_file_type::FileType::Rs)),
+ file_type: Some(FileTypeUpdate::Set(model::document::FileType::Rs)),
})
.await
.unwrap();
@@ -834,6 +834,38 @@ async fn test_create_first_task_assigns_team_task_id_one(pool: Pool<Postgres>) {
assert_eq!(task_metadata.task_num, 1);
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_get_document_id_by_team_task_number(pool: Pool<Postgres>) {
+ insert_second_team(&pool).await;
+ let repo = PgDocumentRepo::new(pool);
+
+ let first_team_task = create_task_for_team(&repo, "macro|[email protected]", TEST_TEAM_ID).await;
+ let second_team_task =
+ create_task_for_team(&repo, "macro|[email protected]", SECOND_TEAM_ID).await;
+
+ assert_eq!(
+ repo.get_document_id_by_team_task_number(&TEST_TEAM_ID, 1)
+ .await
+ .unwrap(),
+ Some(first_team_task.document_id)
+ );
+ assert_eq!(
+ repo.get_document_id_by_team_task_number(&SECOND_TEAM_ID, 1)
+ .await
+ .unwrap(),
+ Some(second_team_task.document_id)
+ );
+ assert_eq!(
+ repo.get_document_id_by_team_task_number(&TEST_TEAM_ID, 2)
+ .await
+ .unwrap(),
+ None
+ );
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("documents_test_data"))
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index 8b8877c567..08545158c7 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -22,7 +22,8 @@ use documents::domain::{
},
};
use entity_access::domain::models::{
- EditAccessLevel, EntityAccessReceipt, EntityType, OwnerAccessLevel, ViewAccessLevel,
+ EditAccessLevel, EntityAccessReceipt, EntityType, MemberTeamRole, OwnerAccessLevel,
+ ViewAccessLevel,
};
use foreign_entity::domain::{
models::{
@@ -126,6 +127,13 @@ impl DocumentService for StubDocumentService {
) -> Result<DocumentBasic, DocumentError> {
unimplemented!()
}
+ async fn get_document_by_team_slug(
+ &self,
+ _team_receipt: EntityAccessReceipt<MemberTeamRole>,
+ _slug: &str,
+ ) -> Result<String, DocumentError> {
+ unimplemented!()
+ }
async fn get_short_id(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 3bb9b2db41..b38d6c7ea3 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -157,6 +157,7 @@ use utoipa::OpenApi;
// documents
documents::get_user_documents::get_user_documents_handler,
documents_hex::inbound::axum_router::get_document::get_document_handler,
+ documents_hex::inbound::axum_router::get_document_by_team_slug::get_document_by_team_slug_handler,
documents::get_document_version::handler,
documents_hex::inbound::axum_router::create_document::create_document_handler,
documents_hex::inbound::axum_router::create_markdown::create_markdown_handler,