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(tasks): share tasks with team (#1923)

Will Hutchinsonddbe38b10e94
diff --git a/rust/cloud-storage/documents/.sqlx/query-77bffdfa5963168a6eb6c908df6d5ad5f1733890733ae55d187f2bd24cc41449.json b/rust/cloud-storage/documents/.sqlx/query-77bffdfa5963168a6eb6c908df6d5ad5f1733890733ae55d187f2bd24cc41449.json
new file mode 100644
index 0000000000..eb7ed37fe4
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-77bffdfa5963168a6eb6c908df6d5ad5f1733890733ae55d187f2bd24cc41449.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT tu2.user_id\n FROM team_user tu1\n JOIN team_user tu2 ON tu1.team_id = tu2.team_id\n WHERE tu1.user_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "77bffdfa5963168a6eb6c908df6d5ad5f1733890733ae55d187f2bd24cc41449"
+}
diff --git a/rust/cloud-storage/documents/.sqlx/query-9f96b785a258c4286db939e1849991361c31618d132a49bf3b7d04ae729ac0dc.json b/rust/cloud-storage/documents/.sqlx/query-9f96b785a258c4286db939e1849991361c31618d132a49bf3b7d04ae729ac0dc.json
new file mode 100644
index 0000000000..224106f514
--- /dev/null
+++ b/rust/cloud-storage/documents/.sqlx/query-9f96b785a258c4286db939e1849991361c31618d132a49bf3b7d04ae729ac0dc.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO \"UserItemAccess\" (\n \"id\", \"user_id\", \"item_id\", \"item_type\", \"access_level\",\n \"granted_from_channel_id\", \"created_at\", \"updated_at\"\n )\n SELECT\n u.id,\n u.user_id,\n $1 AS item_id,\n 'document' AS item_type,\n 'comment' AS access_level,\n NULL AS granted_from_channel_id,\n NOW() AS created_at,\n NOW() AS updated_at\n FROM UNNEST($2::uuid[], $3::text[]) AS u(id, user_id)\n WHERE NOT EXISTS (\n SELECT 1 FROM \"UserItemAccess\" uia\n WHERE uia.\"user_id\" = u.user_id\n AND uia.\"item_id\" = $1\n AND uia.\"item_type\" = 'document'\n AND uia.\"granted_from_channel_id\" IS NULL\n )\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9f96b785a258c4286db939e1849991361c31618d132a49bf3b7d04ae729ac0dc"
+}
diff --git a/rust/cloud-storage/documents/fixtures/documents_test_data.sql b/rust/cloud-storage/documents/fixtures/documents_test_data.sql
index 376e4636f6..444c569223 100644
--- a/rust/cloud-storage/documents/fixtures/documents_test_data.sql
+++ b/rust/cloud-storage/documents/fixtures/documents_test_data.sql
@@ -67,6 +67,30 @@ INSERT INTO
);
+-- Additional users for team sharing tests
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id_t1', 1);
+
+INSERT INTO public."User" ("id", "email", "stripeCustomerId", "organizationId")
+ (SELECT 'macro|[email protected]', '[email protected]', 'stripe_id_t2', 1);
+
+-- Team and team_user for sharing tests
+INSERT INTO public."team" ("id", "name", "owner_id")
+ VALUES ('a0000000-0000-0000-0000-000000000001', 'test-team', 'macro|[email protected]');
+
+INSERT INTO public."team_user" ("user_id", "team_id", "team_role")
+ VALUES ('macro|[email protected]', 'a0000000-0000-0000-0000-000000000001', 'owner');
+
+INSERT INTO public."team_user" ("user_id", "team_id", "team_role")
+ VALUES ('macro|[email protected]', 'a0000000-0000-0000-0000-000000000001', 'member');
+
+INSERT INTO public."team_user" ("user_id", "team_id", "team_role")
+ VALUES ('macro|[email protected]', 'a0000000-0000-0000-0000-000000000001', 'member');
+
+-- Owner access for document-one (used in share_with_team tests)
+INSERT INTO public."UserItemAccess" ("id", "user_id", "item_id", "item_type", "access_level", "created_at", "updated_at")
+ VALUES ('b0000000-0000-0000-0000-000000000001', 'macro|[email protected]', 'document-one', 'document', 'owner', NOW(), NOW());
+
-- Share permissions for document-one
INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")
(SELECT 'sp-doc-one', true, 'read', NOW(), NOW());
diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rs
index bc4400e713..20ff68f327 100644
--- a/rust/cloud-storage/documents/src/domain/ports.rs
+++ b/rust/cloud-storage/documents/src/domain/ports.rs
@@ -120,6 +120,13 @@ pub trait DocumentRepo: Send + Sync + 'static {
&self,
document_id: &str,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Share a document with all members of the user's team.
+ fn share_with_team(
+ &self,
+ user_id: &str,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
/// Port for generating S3 presigned upload URLs.
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index db813c3930..72fd6f33d0 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -705,6 +705,14 @@ impl<R: DocumentRepo, U: PresignedUploadUrlPort, T: TaskPropertiesPort, C: Conne
.document_id
.clone();
+ let _ = self
+ .repo
+ .share_with_team(&plain_user_id, &document_id)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "failed to share task with team");
+ });
+
if let Some(properties) = request.property_values {
for property_input in properties {
let Ok(property_uuid) = uuid::Uuid::parse_str(&property_input.property_id) else {
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
index 040b62ad49..96c024f79e 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs
@@ -7,6 +7,7 @@ mod tests;
mod create;
mod edit;
+mod share;
use document_sub_type::DocumentSubType;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
@@ -540,4 +541,9 @@ impl DocumentRepo for PgDocumentRepo {
Ok(())
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn share_with_team(&self, user_id: &str, document_id: &str) -> Result<(), Self::Err> {
+ share::share_with_team(&self.pool, user_id, document_id).await
+ }
}
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs
new file mode 100644
index 0000000000..ee2049a5d9
--- /dev/null
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/share.rs
@@ -0,0 +1,76 @@
+use sqlx::PgPool;
+use uuid::Uuid;
+
+/// Share a document with all members of the given user's team.
+///
+/// Finds team members via the `team_user` join table, then bulk-inserts
+/// `UserItemAccess` rows with `comment` access and a NULL
+/// `granted_from_channel_id`. Skips users who already have a direct
+/// (non-channel) access row so existing permissions (e.g. the owner's
+/// `owner` row) are never downgraded. Channel-granted rows are left
+/// untouched and may coexist.
+#[tracing::instrument(err, skip(pool))]
+pub async fn share_with_team(
+ pool: &PgPool,
+ user_id: &str,
+ document_id: &str,
+) -> Result<(), sqlx::Error> {
+ // Find all users on the same team(s) as the given user.
+ let team_members: Vec<String> = sqlx::query_scalar!(
+ r#"
+ SELECT tu2.user_id
+ FROM team_user tu1
+ JOIN team_user tu2 ON tu1.team_id = tu2.team_id
+ WHERE tu1.user_id = $1
+ "#,
+ user_id,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ if team_members.is_empty() {
+ return Ok(());
+ }
+
+ let ids: Vec<Uuid> = team_members
+ .iter()
+ .map(|_| macro_uuid::generate_uuid_v7())
+ .collect();
+
+ // Insert comment access for team members who don't already have access.
+ // Uses WHERE NOT EXISTS instead of ON CONFLICT because the unique index
+ // includes granted_from_channel_id which can be NULL, and PostgreSQL
+ // treats NULLs as distinct in unique indexes.
+ sqlx::query!(
+ r#"
+ INSERT INTO "UserItemAccess" (
+ "id", "user_id", "item_id", "item_type", "access_level",
+ "granted_from_channel_id", "created_at", "updated_at"
+ )
+ SELECT
+ u.id,
+ u.user_id,
+ $1 AS item_id,
+ 'document' AS item_type,
+ 'comment' AS access_level,
+ NULL AS granted_from_channel_id,
+ NOW() AS created_at,
+ NOW() AS updated_at
+ FROM UNNEST($2::uuid[], $3::text[]) AS u(id, user_id)
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "UserItemAccess" uia
+ WHERE uia."user_id" = u.user_id
+ AND uia."item_id" = $1
+ AND uia."item_type" = 'document'
+ AND uia."granted_from_channel_id" IS NULL
+ )
+ "#,
+ document_id,
+ &ids,
+ &team_members,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
index 70a7c01a3d..a47d32cfda 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
@@ -293,3 +293,246 @@ async fn test_edit_document_name_and_project(pool: Pool<Postgres>) {
assert!(result.is_public);
assert_eq!(result.public_access_level, Some("edit".to_string()));
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_share_with_team_creates_access_for_team_members(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+
+ repo.share_with_team("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+
+ // All 3 team members should have access rows
+ let rows = sqlx::query!(
+ r#"
+ SELECT "user_id", "access_level"::text as "access_level"
+ FROM "UserItemAccess"
+ WHERE "item_id" = 'document-one' AND "item_type" = 'document'
+ ORDER BY "user_id"
+ "#,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(rows.len(), 3);
+
+ // Owner row should still be 'owner' (not downgraded)
+ let owner_row = rows
+ .iter()
+ .find(|r| r.user_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(owner_row.access_level, Some("owner".to_string()));
+
+ // Teammates should have 'comment' access
+ let t1 = rows
+ .iter()
+ .find(|r| r.user_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(t1.access_level, Some("comment".to_string()));
+
+ let t2 = rows
+ .iter()
+ .find(|r| r.user_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(t2.access_level, Some("comment".to_string()));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_share_with_team_no_op_when_user_not_on_team(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+
+ // teammate1 is on a team, but let's use a user that isn't on any team
+ // We'll use a non-existent user id to simulate no team membership
+ repo.share_with_team("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+
+ // Only the pre-existing owner row should exist
+ let count = sqlx::query_scalar!(
+ r#"
+ SELECT COUNT(*) as "count!"
+ FROM "UserItemAccess"
+ WHERE "item_id" = 'document-one' AND "item_type" = 'document'
+ "#,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(count, 1); // just the owner row from fixtures
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_share_with_team_idempotent(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+
+ // Call twice — second call should be a no-op
+ repo.share_with_team("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+ repo.share_with_team("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+
+ let count = sqlx::query_scalar!(
+ r#"
+ SELECT COUNT(*) as "count!"
+ FROM "UserItemAccess"
+ WHERE "item_id" = 'document-one' AND "item_type" = 'document'
+ "#,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(count, 3); // owner + 2 teammates, no duplicates
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_share_with_team_preserves_channel_granted_access(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+
+ // Give teammate1 access via a channel before team sharing
+ let channel_id = uuid::Uuid::now_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO "UserItemAccess"
+ ("id", "user_id", "item_id", "item_type", "access_level",
+ "granted_from_channel_id", "created_at", "updated_at")
+ VALUES ($1, $2, 'document-one', 'document', 'edit', $3, NOW(), NOW())
+ "#,
+ uuid::Uuid::now_v7(),
+ channel_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ repo.share_with_team("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+
+ // teammate1 should have both: channel-granted edit + team-shared comment
+ let rows = sqlx::query!(
+ r#"
+ SELECT "access_level"::text as "access_level", "granted_from_channel_id"
+ FROM "UserItemAccess"
+ WHERE "item_id" = 'document-one' AND "item_type" = 'document'
+ AND "user_id" = 'macro|[email protected]'
+ ORDER BY "granted_from_channel_id" NULLS LAST
+ "#,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(rows.len(), 2);
+ assert_eq!(rows[0].access_level, Some("edit".to_string()));
+ assert_eq!(rows[0].granted_from_channel_id, Some(channel_id));
+ assert_eq!(rows[1].access_level, Some("comment".to_string()));
+ assert!(rows[1].granted_from_channel_id.is_none());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_share_with_team_skips_user_with_existing_direct_access(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+
+ // Give teammate1 direct (non-channel) edit access before team sharing
+ sqlx::query!(
+ r#"
+ INSERT INTO "UserItemAccess"
+ ("id", "user_id", "item_id", "item_type", "access_level",
+ "granted_from_channel_id", "created_at", "updated_at")
+ VALUES ($1, $2, 'document-one', 'document', 'edit', NULL, NOW(), NOW())
+ "#,
+ uuid::Uuid::now_v7(),
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ repo.share_with_team("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+
+ // teammate1 should still have just their original edit row, not a second comment row
+ let rows = sqlx::query!(
+ r#"
+ SELECT "access_level"::text as "access_level"
+ FROM "UserItemAccess"
+ WHERE "item_id" = 'document-one' AND "item_type" = 'document'
+ AND "user_id" = 'macro|[email protected]'
+ "#,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].access_level, Some("edit".to_string()));
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_share_with_team_called_by_teammate(pool: Pool<Postgres>) {
+ let repo = PgDocumentRepo::new(pool.clone());
+
+ // A teammate (not the owner) triggers the share — should still find the
+ // same team and share with all members including the owner.
+ repo.share_with_team("macro|[email protected]", "document-one")
+ .await
+ .unwrap();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT "user_id", "access_level"::text as "access_level"
+ FROM "UserItemAccess"
+ WHERE "item_id" = 'document-one' AND "item_type" = 'document'
+ ORDER BY "user_id"
+ "#,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+
+ // Owner keeps their original owner row (no duplicate), teammates get comment
+ assert_eq!(rows.len(), 3);
+
+ let owner = rows
+ .iter()
+ .find(|r| r.user_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(owner.access_level, Some("owner".to_string()));
+
+ let t1 = rows
+ .iter()
+ .find(|r| r.user_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(t1.access_level, Some("comment".to_string()));
+
+ let t2 = rows
+ .iter()
+ .find(|r| r.user_id == "macro|[email protected]")
+ .unwrap();
+ assert_eq!(t2.access_level, Some("comment".to_string()));
+}