Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sharing): improved link sharing (#5644)
Will Hutchinson748933a0666f
diff --git a/.sqlx/query-0d38256b23e9ce70797726f76b49889efcf4b3c2fbaec05c395de5e728b0fdbb.json b/.sqlx/query-0d38256b23e9ce70797726f76b49889efcf4b3c2fbaec05c395de5e728b0fdbb.jsondeleted file mode 100644index a3ceebc60d..0000000000--- a/.sqlx/query-0d38256b23e9ce70797726f76b49889efcf4b3c2fbaec05c395de5e728b0fdbb.json+++ /dev/null@@ -1,46 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n sp.id as id,\n sp.\"isPublic\" as is_public,\n sp.\"publicAccessLevel\" as \"public_access_level?\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "is_public",- "type_info": "Bool"- },- {- "ordinal": 2,- "name": "public_access_level?",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "channel_share_permissions?",- "type_info": "Json"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- true,- false,- null- ]- },- "hash": "0d38256b23e9ce70797726f76b49889efcf4b3c2fbaec05c395de5e728b0fdbb"-}diff --git a/.sqlx/query-0db3bbe78101fc309c3358271240926ee07c36bf29ff0031813a2fdbe1fd061d.json b/.sqlx/query-0db3bbe78101fc309c3358271240926ee07c36bf29ff0031813a2fdbe1fd061d.jsondeleted file mode 100644index faedc95f8b..0000000000--- a/.sqlx/query-0db3bbe78101fc309c3358271240926ee07c36bf29ff0031813a2fdbe1fd061d.json+++ /dev/null@@ -1,46 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n sp.id as id,\n sp.\"isPublic\" as is_public,\n sp.\"publicAccessLevel\" as \"public_access_level?\",\n d.\"owner\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"DocumentPermission\" dp\n JOIN \"SharePermission\" sp ON dp.\"sharePermissionId\" = sp.id\n JOIN \"Document\" d ON dp.\"documentId\" = d.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n dp.\"documentId\" = $1\n GROUP BY\n sp.id, d.\"owner\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "is_public",- "type_info": "Bool"- },- {- "ordinal": 2,- "name": "public_access_level?",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "channel_share_permissions?",- "type_info": "Json"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- true,- false,- null- ]- },- "hash": "0db3bbe78101fc309c3358271240926ee07c36bf29ff0031813a2fdbe1fd061d"-}diff --git a/.sqlx/query-1b7983a9a8a54322fd63d2bf169f27b45f853652a757123e3508017861b5c7c6.json b/.sqlx/query-1b7983a9a8a54322fd63d2bf169f27b45f853652a757123e3508017861b5c7c6.jsondeleted file mode 100644index f97907a55c..0000000000--- a/.sqlx/query-1b7983a9a8a54322fd63d2bf169f27b45f853652a757123e3508017861b5c7c6.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n \"publicAccessLevel\" as \"access_level!\"\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" = $1\n )\n\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- true- ]- },- "hash": "1b7983a9a8a54322fd63d2bf169f27b45f853652a757123e3508017861b5c7c6"-}diff --git a/.sqlx/query-1f8d142bdc2b0cb6c27bd33526becdf1a2f532bce63df0c858e5c317d1dc52ab.json b/.sqlx/query-1f8d142bdc2b0cb6c27bd33526becdf1a2f532bce63df0c858e5c317d1dc52ab.jsonnew file mode 100644index 0000000000..6f51a504bd--- /dev/null+++ b/.sqlx/query-1f8d142bdc2b0cb6c27bd33526becdf1a2f532bce63df0c858e5c317d1dc52ab.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'project'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: project link share permission\n SELECT\n sp.\"linkShareAccessLevel\"::text AS access_level\n FROM \"SharePermission\" sp\n WHERE sp.\"linkShareAccessLevel\" IS NOT NULL\n AND sp.id IN (\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" = $3\n )\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM \"Project\" p\n JOIN team_user owner_team ON owner_team.user_id = p.\"userId\"\n WHERE p.id = $3\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n ) AS combined_access\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "1f8d142bdc2b0cb6c27bd33526becdf1a2f532bce63df0c858e5c317d1dc52ab"+}diff --git a/.sqlx/query-2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31.json b/.sqlx/query-2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31.jsondeleted file mode 100644index 5e84f18efd..0000000000--- a/.sqlx/query-2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31.json+++ /dev/null@@ -1,24 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'email_thread'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: items share permission\n SELECT\n \"publicAccessLevel\"::text AS access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $3\n )\n\n UNION ALL\n -- Source 3: access to the thread's containing project grants View\n SELECT 'view' AS access_level\n FROM email_threads t\n JOIN entity_access pea ON pea.entity_id::text = t.project_id\n AND pea.entity_type = 'project'\n AND pea.source_id = ANY($2)\n WHERE t.id = $1::uuid\n ) AS combined_access\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "TextArray",- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "2038e9067126322569af303a5008cc0e58c09fa4cc0ac7d907ea2d7f0cf91e31"-}diff --git a/.sqlx/query-22889d5110796ee5c0581948d047f80ff7b54a17c6a0bb533e51933269e2479b.json b/.sqlx/query-22889d5110796ee5c0581948d047f80ff7b54a17c6a0bb533e51933269e2479b.jsonnew file mode 100644index 0000000000..07cabfaa50--- /dev/null+++ b/.sqlx/query-22889d5110796ee5c0581948d047f80ff7b54a17c6a0bb533e51933269e2479b.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n permission.id,\n permission.\"linkShare\" AS \"link_share?\",\n permission.\"linkShareAccessLevel\" AS \"link_share_access_level?: AccessLevel\",\n project.\"userId\" AS owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', channel.\"channel_id\",\n 'access_level', channel.\"access_level\"\n )) FILTER (WHERE channel.\"channel_id\" IS NOT NULL),\n '[]'\n ) AS \"channel_share_permissions?\"\n FROM \"ProjectPermission\" project_permission\n JOIN \"SharePermission\" permission\n ON project_permission.\"sharePermissionId\" = permission.id\n JOIN \"Project\" project ON project_permission.\"projectId\" = project.id\n LEFT JOIN \"ChannelSharePermission\" channel\n ON channel.\"share_permission_id\" = permission.id\n WHERE project_permission.\"projectId\" = $1\n GROUP BY permission.id, project.\"userId\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "link_share?",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "link_share_access_level?: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "channel_share_permissions?",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "22889d5110796ee5c0581948d047f80ff7b54a17c6a0bb533e51933269e2479b"+}diff --git a/.sqlx/query-2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb.json b/.sqlx/query-2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb.jsondeleted file mode 100644index 19bcc6aa4e..0000000000--- a/.sqlx/query-2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb.json+++ /dev/null@@ -1,20 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"SharePermission\" (\"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES (false, NULL, NOW(), NOW())\n RETURNING id as \"id!\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id!",- "type_info": "Text"- }- ],- "parameters": {- "Left": []- },- "nullable": [- false- ]- },- "hash": "2323566d1f90b640bf6cbd83beb86be825ff271d9a18921835dfd1864a78ebfb"-}diff --git a/.sqlx/query-2e5623dfbf4ecf94a1ba8080d1051e32faa99f49f106ed4050dcb38852eeb263.json b/.sqlx/query-2e5623dfbf4ecf94a1ba8080d1051e32faa99f49f106ed4050dcb38852eeb263.jsondeleted file mode 100644index 78478f839a..0000000000--- a/.sqlx/query-2e5623dfbf4ecf94a1ba8080d1051e32faa99f49f106ed4050dcb38852eeb263.json+++ /dev/null@@ -1,18 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE \"SharePermission\"\n SET\n \"isPublic\" = CASE WHEN $2 THEN $3 ELSE \"isPublic\" END,\n \"publicAccessLevel\" = CASE WHEN $4 THEN $5 ELSE \"publicAccessLevel\" END,\n \"updatedAt\" = NOW()\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Bool",- "Bool",- "Bool",- "Text"- ]- },- "nullable": []- },- "hash": "2e5623dfbf4ecf94a1ba8080d1051e32faa99f49f106ed4050dcb38852eeb263"-}diff --git a/.sqlx/query-357682d4dddfaa980129c516f38c4176352fa9b44242cdd5abe8b4ee18a62f8e.json b/.sqlx/query-357682d4dddfaa980129c516f38c4176352fa9b44242cdd5abe8b4ee18a62f8e.jsondeleted file mode 100644index cc59a6ec34..0000000000--- a/.sqlx/query-357682d4dddfaa980129c516f38c4176352fa9b44242cdd5abe8b4ee18a62f8e.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'call'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: items share permission\n SELECT\n \"publicAccessLevel\"::text AS access_level\n FROM \"SharePermission\"\n WHERE id in (\n SELECT share_permission_id\n FROM calls\n WHERE id = $1\n UNION ALL\n SELECT share_permission_id\n FROM call_records\n WHERE id = $1\n LIMIT 1\n )\n AND \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n ) AS combined_access\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "TextArray"- ]- },- "nullable": [- null- ]- },- "hash": "357682d4dddfaa980129c516f38c4176352fa9b44242cdd5abe8b4ee18a62f8e"-}diff --git a/.sqlx/query-377f7c130cc3d834870fa692f5ba36d070bce17512b9ab348d0cb40ebe4d1b08.json b/.sqlx/query-377f7c130cc3d834870fa692f5ba36d070bce17512b9ab348d0cb40ebe4d1b08.jsondeleted file mode 100644index 9348d25315..0000000000--- a/.sqlx/query-377f7c130cc3d834870fa692f5ba36d070bce17512b9ab348d0cb40ebe4d1b08.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n \"publicAccessLevel\" as \"access_level!\"\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $1\n )\n \n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- true- ]- },- "hash": "377f7c130cc3d834870fa692f5ba36d070bce17512b9ab348d0cb40ebe4d1b08"-}diff --git a/.sqlx/query-3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66.json b/.sqlx/query-3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66.jsonnew file mode 100644index 0000000000..5b63ce00be--- /dev/null+++ b/.sqlx/query-3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n m.\"user_id\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"MacroPromptPermission\" mpp\n JOIN \"SharePermission\" sp ON mpp.\"share_permission_id\" = sp.id\n JOIN \"MacroPrompt\" m ON mpp.\"macro_prompt_id\" = m.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n mpp.\"macro_prompt_id\" = $1\n GROUP BY\n sp.id, m.\"user_id\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "link_share?",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "link_share_access_level?: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "channel_share_permissions?",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "3d1a9b0be46b179bb49c528164c06da76897575d69f08613c01b6fc09f9b3a66"+}diff --git a/.sqlx/query-3d868403250366e7a222e6ad1767660b7fe784d879c69e1c0522f31812443924.json b/.sqlx/query-3d868403250366e7a222e6ad1767660b7fe784d879c69e1c0522f31812443924.jsonnew file mode 100644index 0000000000..75e42d203f--- /dev/null+++ b/.sqlx/query-3d868403250366e7a222e6ad1767660b7fe784d879c69e1c0522f31812443924.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n SELECT dp.\"documentId\"::uuid, 'document', u.user_id, 'user', sp.\"linkShareAccessLevel\"::\"AccessLevel\"\n FROM \"DocumentPermission\" dp\n JOIN \"SharePermission\" sp ON sp.id = dp.\"sharePermissionId\"\n CROSS JOIN UNNEST($2::text[]) AS u(user_id)\n WHERE dp.\"documentId\" = $1\n AND sp.\"linkShare\" IN ('PUBLIC', 'TEAM')\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "3d868403250366e7a222e6ad1767660b7fe784d879c69e1c0522f31812443924"+}diff --git a/.sqlx/query-3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f.json b/.sqlx/query-3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f.jsondeleted file mode 100644index 3f1f35a9f8..0000000000--- a/.sqlx/query-3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"SharePermission\" (\"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, NOW(), NOW())\n RETURNING id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Bool",- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f"-}diff --git a/.sqlx/query-3f5df39d7ee978e92a94f3e9c1d6f12e812b89f46a7a40cb0d4b0ff8397b1b2f.json b/.sqlx/query-3f5df39d7ee978e92a94f3e9c1d6f12e812b89f46a7a40cb0d4b0ff8397b1b2f.jsondeleted file mode 100644index b8ae88954d..0000000000--- a/.sqlx/query-3f5df39d7ee978e92a94f3e9c1d6f12e812b89f46a7a40cb0d4b0ff8397b1b2f.json+++ /dev/null@@ -1,24 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'chat'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: items share permission\n SELECT\n \"publicAccessLevel\"::text AS access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $3\n )\n ) AS combined_access\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "TextArray",- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "3f5df39d7ee978e92a94f3e9c1d6f12e812b89f46a7a40cb0d4b0ff8397b1b2f"-}diff --git a/.sqlx/query-42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5.json b/.sqlx/query-42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5.jsonnew file mode 100644index 0000000000..29ccc7f5e0--- /dev/null+++ b/.sqlx/query-42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: document link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"Document\" document\n JOIN \"DocumentPermission\" document_permission\n ON document_permission.\"documentId\" = document.id\n JOIN \"SharePermission\" share_permission\n ON share_permission.id = document_permission.\"sharePermissionId\"\n WHERE document.id = $3\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = document.owner\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n ) AS combined_access\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "42f11323f1ef8158152eac2e80b8c5f2565184548e269274b19ad675c8e414f5"+}diff --git a/.sqlx/query-44a05989da2597deae3eaded94e7270307a3e4f36625e76d489d4bc39b66e759.json b/.sqlx/query-44a05989da2597deae3eaded94e7270307a3e4f36625e76d489d4bc39b66e759.jsondeleted file mode 100644index fad533832f..0000000000--- a/.sqlx/query-44a05989da2597deae3eaded94e7270307a3e4f36625e76d489d4bc39b66e759.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n pp.\"sharePermissionId\" as share_permission_id\n FROM \"ProjectPermission\" pp\n WHERE pp.\"projectId\" = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "share_permission_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "44a05989da2597deae3eaded94e7270307a3e4f36625e76d489d4bc39b66e759"-}diff --git a/.sqlx/query-46594430e49cbe0309c7e6edad5c30cd734cfabfa06f5ca3da84a96facccc7ca.json b/.sqlx/query-46594430e49cbe0309c7e6edad5c30cd734cfabfa06f5ca3da84a96facccc7ca.jsonnew file mode 100644index 0000000000..d908b4a05a--- /dev/null+++ b/.sqlx/query-46594430e49cbe0309c7e6edad5c30cd734cfabfa06f5ca3da84a96facccc7ca.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"SharePermission\" (\n id, \"linkShare\", \"linkShareAccessLevel\", \"createdAt\", \"updatedAt\"\n )\n VALUES ($1, NULL, NULL, NOW(), NOW())",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "46594430e49cbe0309c7e6edad5c30cd734cfabfa06f5ca3da84a96facccc7ca"+}diff --git a/.sqlx/query-521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b.json b/.sqlx/query-521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b.jsonnew file mode 100644index 0000000000..9a0125fc0f--- /dev/null+++ b/.sqlx/query-521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level!: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "521e016780b024ace9d5c2863cbdf7bdd9f9488751a8121835d13bb8cb74e22b"+}diff --git a/.sqlx/query-581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7.json b/.sqlx/query-581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7.jsonnew file mode 100644index 0000000000..20022dc309--- /dev/null+++ b/.sqlx/query-581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n d.\"owner\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"DocumentPermission\" dp\n JOIN \"SharePermission\" sp ON dp.\"sharePermissionId\" = sp.id\n JOIN \"Document\" d ON dp.\"documentId\" = d.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n dp.\"documentId\" = $1\n GROUP BY\n sp.id, d.\"owner\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "link_share?",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "link_share_access_level?: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "channel_share_permissions?",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "581f7f1d0b0bdaf637c1ec9557bae1df7fead693e3f32fca43af8374abdb27c7"+}diff --git a/.sqlx/query-5915728325fe5163ae5f18a99350e0cb5153d368eceb75d03b4cf1adfd1f58bf.json b/.sqlx/query-5915728325fe5163ae5f18a99350e0cb5153d368eceb75d03b4cf1adfd1f58bf.jsondeleted file mode 100644index 514e8d9770..0000000000--- a/.sqlx/query-5915728325fe5163ae5f18a99350e0cb5153d368eceb75d03b4cf1adfd1f58bf.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n \"publicAccessLevel\" as \"access_level!\"\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"ChatPermission\" WHERE \"chatId\" = $1\n )\n\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- true- ]- },- "hash": "5915728325fe5163ae5f18a99350e0cb5153d368eceb75d03b4cf1adfd1f58bf"-}diff --git a/.sqlx/query-75816cd901a74a02731fa98de630b6bd52e62d1318224738584cde21648b24bb.json b/.sqlx/query-75816cd901a74a02731fa98de630b6bd52e62d1318224738584cde21648b24bb.jsonnew file mode 100644index 0000000000..26ad23fbf0--- /dev/null+++ b/.sqlx/query-75816cd901a74a02731fa98de630b6bd52e62d1318224738584cde21648b24bb.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"SharePermission\" (\n \"linkShare\",\n \"linkShareAccessLevel\",\n \"createdAt\",\n \"updatedAt\"\n )\n VALUES ($1, $2, NOW(), NOW())\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "75816cd901a74a02731fa98de630b6bd52e62d1318224738584cde21648b24bb"+}diff --git a/.sqlx/query-79c6974496c155f372a458d21240a09730630660ae75e8f6e5cfd8f5ba0ceb4e.json b/.sqlx/query-79c6974496c155f372a458d21240a09730630660ae75e8f6e5cfd8f5ba0ceb4e.jsondeleted file mode 100644index 06f69bc198..0000000000--- a/.sqlx/query-79c6974496c155f372a458d21240a09730630660ae75e8f6e5cfd8f5ba0ceb4e.json+++ /dev/null@@ -1,35 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"SharePermission\" (\"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, NOW(), NOW())\n RETURNING id, \"isPublic\" as is_public, \"publicAccessLevel\" as public_access_level;\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "is_public",- "type_info": "Bool"- },- {- "ordinal": 2,- "name": "public_access_level",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Bool",- "Text"- ]- },- "nullable": [- false,- false,- true- ]- },- "hash": "79c6974496c155f372a458d21240a09730630660ae75e8f6e5cfd8f5ba0ceb4e"-}diff --git a/.sqlx/query-9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951.json b/.sqlx/query-9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951.jsondeleted file mode 100644index ce58f8d552..0000000000--- a/.sqlx/query-9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"SharePermission\" (\"id\", \"isPublic\",\"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, NOW(), NOW())\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Bool",- "Text"- ]- },- "nullable": []- },- "hash": "9096710139da4a36b9a11809a30b65ae3b712a0b659b63e366e5f485b8630951"-}diff --git a/.sqlx/query-92136df44de0a1b98131e5dfdf14b751bdff538278d9df5a31ca0a4857fb0045.json b/.sqlx/query-92136df44de0a1b98131e5dfdf14b751bdff538278d9df5a31ca0a4857fb0045.jsonnew file mode 100644index 0000000000..c0935b54d0--- /dev/null+++ b/.sqlx/query-92136df44de0a1b98131e5dfdf14b751bdff538278d9df5a31ca0a4857fb0045.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n \"linkShareAccessLevel\" as \"access_level!: AccessLevel\"\n FROM \"SharePermission\"\n WHERE \"linkShare\" = 'PUBLIC'\n AND \"linkShareAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n )\n\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level!: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "92136df44de0a1b98131e5dfdf14b751bdff538278d9df5a31ca0a4857fb0045"+}diff --git a/.sqlx/query-9646eff91dc45b60761e4a188aa12e8d2845bf7c4d0ee906ef64a16e12bd2852.json b/.sqlx/query-9646eff91dc45b60761e4a188aa12e8d2845bf7c4d0ee906ef64a16e12bd2852.jsonnew file mode 100644index 0000000000..d79c4354ac--- /dev/null+++ b/.sqlx/query-9646eff91dc45b60761e4a188aa12e8d2845bf7c4d0ee906ef64a16e12bd2852.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'email_thread'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: item share permission\n SELECT\n sp.\"linkShareAccessLevel\"::text AS access_level\n FROM \"SharePermission\" sp\n WHERE sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM email_threads t\n JOIN email_links l ON l.id = t.link_id\n JOIN team_user owner_tu ON owner_tu.user_id = l.macro_id\n WHERE t.id = $1::uuid\n AND owner_tu.team_id::text = ANY($2)\n )\n )\n )\n AND sp.id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $3\n )\n\n UNION ALL\n -- Source 3: access to the thread's containing project grants View\n SELECT 'view' AS access_level\n FROM email_threads t\n JOIN entity_access pea ON pea.entity_id::text = t.project_id\n AND pea.entity_type = 'project'\n AND pea.source_id = ANY($2)\n WHERE t.id = $1::uuid\n ) AS combined_access\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "9646eff91dc45b60761e4a188aa12e8d2845bf7c4d0ee906ef64a16e12bd2852"+}diff --git a/.sqlx/query-97cece44dbf859191b631ee7b925b9666d61916e8bb3bc1cd513f94f9c089bf4.json b/.sqlx/query-97cece44dbf859191b631ee7b925b9666d61916e8bb3bc1cd513f94f9c089bf4.jsonnew file mode 100644index 0000000000..a50d2cb770--- /dev/null+++ b/.sqlx/query-97cece44dbf859191b631ee7b925b9666d61916e8bb3bc1cd513f94f9c089bf4.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n share_permission.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" share_permission\n JOIN \"DocumentPermission\" document_permission\n ON document_permission.\"sharePermissionId\" = share_permission.id\n WHERE share_permission.\"linkShare\" = 'PUBLIC'\n AND share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND document_permission.\"documentId\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level!: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "97cece44dbf859191b631ee7b925b9666d61916e8bb3bc1cd513f94f9c089bf4"+}diff --git a/.sqlx/query-a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843.json b/.sqlx/query-a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843.jsondeleted file mode 100644index 86dd19cf0a..0000000000--- a/.sqlx/query-a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "INSERT INTO \"SharePermission\" (id, \"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, false, NULL, NOW(), NOW())",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": []- },- "hash": "a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843"-}diff --git a/.sqlx/query-1787f623620cbe61083403a7e51577540398e8ce459156d6f83fcb8193fc2800.json b/.sqlx/query-a2c3074936b824cc328ea10dd4b37ffcb51798fc0fbe1bffaf48381eb18a2cff.jsonsimilarity index 64%rename from .sqlx/query-1787f623620cbe61083403a7e51577540398e8ce459156d6f83fcb8193fc2800.jsonrename to .sqlx/query-a2c3074936b824cc328ea10dd4b37ffcb51798fc0fbe1bffaf48381eb18a2cff.jsonindex da58536bad..51127a0a86 100644--- a/.sqlx/query-1787f623620cbe61083403a7e51577540398e8ce459156d6f83fcb8193fc2800.json+++ b/.sqlx/query-a2c3074936b824cc328ea10dd4b37ffcb51798fc0fbe1bffaf48381eb18a2cff.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1\n ),\n visible_calls AS (\n SELECT\n cr.id,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) THEN 'ATTENDED'\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = cr.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'\n ELSE 'UNATTENDED'\n END AS status\n FROM call_records cr\n WHERE (\n EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n AND ea.source_id IN (SELECT source_id FROM user_source_ids)\n ) OR EXISTS (\n SELECT 1 FROM \"SharePermission\" sp\n WHERE sp.id = cr.share_permission_id\n AND sp.\"isPublic\" = true\n AND sp.\"publicAccessLevel\" IS NOT NULL\n )\n )\n )\n SELECT id AS \"id!\"\n FROM visible_calls\n WHERE cardinality($2::text[]) = 0 OR status = ANY($2)\n ",+ "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1\n ),\n visible_calls AS (\n SELECT\n cr.id,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) THEN 'ATTENDED'\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = cr.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'\n ELSE 'UNATTENDED'\n END AS status\n FROM call_records cr\n WHERE (\n EXISTS (\n SELECT 1 FROM entity_access ea\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n AND ea.source_id IN (SELECT source_id FROM user_source_ids)\n ) OR EXISTS (\n SELECT 1 FROM \"SharePermission\" sp\n WHERE sp.id = cr.share_permission_id\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = cr.created_by\n AND owner_team.team_id::text IN (\n SELECT source_id FROM user_source_ids\n )\n )\n )\n )\n )\n )\n )\n SELECT id AS \"id!\"\n FROM visible_calls\n WHERE cardinality($2::text[]) = 0 OR status = ANY($2)\n ","describe": {"columns": [{@@ -19,5 +19,5 @@false]},- "hash": "1787f623620cbe61083403a7e51577540398e8ce459156d6f83fcb8193fc2800"+ "hash": "a2c3074936b824cc328ea10dd4b37ffcb51798fc0fbe1bffaf48381eb18a2cff"}diff --git a/.sqlx/query-a3637a7a136eefc6bf21f28a9ae693dd3ab1eb8b4f310528a43e630e233446cb.json b/.sqlx/query-a3637a7a136eefc6bf21f28a9ae693dd3ab1eb8b4f310528a43e630e233446cb.jsondeleted file mode 100644index 331cfdfd1d..0000000000--- a/.sqlx/query-a3637a7a136eefc6bf21f28a9ae693dd3ab1eb8b4f310528a43e630e233446cb.json+++ /dev/null@@ -1,24 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'document'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: items share permission\n SELECT\n \"publicAccessLevel\"::text AS access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"DocumentPermission\" WHERE \"documentId\" = $3\n )\n ) AS combined_access\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "TextArray",- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "a3637a7a136eefc6bf21f28a9ae693dd3ab1eb8b4f310528a43e630e233446cb"-}diff --git a/.sqlx/query-a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c.json b/.sqlx/query-a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c.jsonnew file mode 100644index 0000000000..7f73edd639--- /dev/null+++ b/.sqlx/query-a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "link_share?",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "link_share_access_level?: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "channel_share_permissions?",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c"+}diff --git a/.sqlx/query-a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147.json b/.sqlx/query-a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147.jsondeleted file mode 100644index 4ca3ec3920..0000000000--- a/.sqlx/query-a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147.json+++ /dev/null@@ -1,46 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n sp.id as id,\n sp.\"isPublic\" as is_public,\n sp.\"publicAccessLevel\" as \"public_access_level?\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "is_public",- "type_info": "Bool"- },- {- "ordinal": 2,- "name": "public_access_level?",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "channel_share_permissions?",- "type_info": "Json"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- true,- false,- null- ]- },- "hash": "a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147"-}diff --git a/.sqlx/query-a5801ca350ee73d531d912e4dcc1935265af572afbbf60702a4521e4c19b8468.json b/.sqlx/query-a5801ca350ee73d531d912e4dcc1935265af572afbbf60702a4521e4c19b8468.jsondeleted file mode 100644index a01572c827..0000000000--- a/.sqlx/query-a5801ca350ee73d531d912e4dcc1935265af572afbbf60702a4521e4c19b8468.json+++ /dev/null@@ -1,46 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n sp.id as id,\n sp.\"isPublic\" as is_public,\n sp.\"publicAccessLevel\" as \"public_access_level?\",\n m.\"user_id\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"MacroPromptPermission\" mpp\n JOIN \"SharePermission\" sp ON mpp.\"share_permission_id\" = sp.id\n JOIN \"MacroPrompt\" m ON mpp.\"macro_prompt_id\" = m.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n mpp.\"macro_prompt_id\" = $1\n GROUP BY\n sp.id, m.\"user_id\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "is_public",- "type_info": "Bool"- },- {- "ordinal": 2,- "name": "public_access_level?",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "channel_share_permissions?",- "type_info": "Json"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- true,- false,- null- ]- },- "hash": "a5801ca350ee73d531d912e4dcc1935265af572afbbf60702a4521e4c19b8468"-}diff --git a/.sqlx/query-ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c.json b/.sqlx/query-ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c.jsonnew file mode 100644index 0000000000..9b16994f4d--- /dev/null+++ b/.sqlx/query-ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"SharePermission\" (\n \"id\",\n \"linkShare\",\n \"linkShareAccessLevel\",\n \"createdAt\",\n \"updatedAt\"\n )\n VALUES ($1, $2, $3, NOW(), NOW())\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "ab6a9e7f91129125002b8d6db2776f8bf4160e5b5c67d2a1d937b4c376855f8c"+}diff --git a/.sqlx/query-ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d.json b/.sqlx/query-ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d.jsondeleted file mode 100644index 16c7afa6a3..0000000000--- a/.sqlx/query-ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)\n SELECT dp.\"documentId\"::uuid, 'document', u.user_id, 'user', sp.\"publicAccessLevel\"::\"AccessLevel\"\n FROM \"DocumentPermission\" dp\n JOIN \"SharePermission\" sp ON sp.id = dp.\"sharePermissionId\"\n CROSS JOIN UNNEST($2::text[]) AS u(user_id)\n WHERE dp.\"documentId\" = $1\n AND sp.\"isPublic\" = true\n AND sp.\"publicAccessLevel\" IS NOT NULL\n ON CONFLICT (entity_id, entity_type, source_id, source_type)\n WHERE granted_from_project_id IS NULL\n DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "TextArray"- ]- },- "nullable": []- },- "hash": "ab7417eb79789bfff9a6084c7881191a9b0ee849745041e1fecc7e4ba9b4fc5d"-}diff --git a/.sqlx/query-ba7fb52ae8726661e0725bc5fed9c6f1aed9c012c5bf1e381d46713faed0fa98.json b/.sqlx/query-ba7fb52ae8726661e0725bc5fed9c6f1aed9c012c5bf1e381d46713faed0fa98.jsonnew file mode 100644index 0000000000..8d211a46c2--- /dev/null+++ b/.sqlx/query-ba7fb52ae8726661e0725bc5fed9c6f1aed9c012c5bf1e381d46713faed0fa98.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" sp\n WHERE sp.\"linkShare\" = 'PUBLIC'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND sp.id IN (\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" = $1\n )\n\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level!: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "ba7fb52ae8726661e0725bc5fed9c6f1aed9c012c5bf1e381d46713faed0fa98"+}diff --git a/.sqlx/query-bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8.json b/.sqlx/query-bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8.jsonnew file mode 100644index 0000000000..4634d1485a--- /dev/null+++ b/.sqlx/query-bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8.json@@ -0,0 +1,58 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "link_share?",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "link_share_access_level?: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "channel_share_permissions?",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "bd3617e099b8f193c51f33d2bae4ef7cad029be4002f44f6a7de23b0ce50f5f8"+}diff --git a/.sqlx/query-bdb882d426cf81329dd6d824a5d945cfd0ea2fffa26b5324ef641dfe3e304682.json b/.sqlx/query-bdb882d426cf81329dd6d824a5d945cfd0ea2fffa26b5324ef641dfe3e304682.jsondeleted file mode 100644index 3ed3f3db5e..0000000000--- a/.sqlx/query-bdb882d426cf81329dd6d824a5d945cfd0ea2fffa26b5324ef641dfe3e304682.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n \"publicAccessLevel\" as \"access_level!\"\n FROM \"SharePermission\"\n WHERE id in (SELECT share_permission_id\n FROM calls\n WHERE id = $1\n UNION ALL\n SELECT share_permission_id\n FROM call_records\n WHERE id = $1\n LIMIT 1)\n AND \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- true- ]- },- "hash": "bdb882d426cf81329dd6d824a5d945cfd0ea2fffa26b5324ef641dfe3e304682"-}diff --git a/.sqlx/query-bf98ad9ab317aeb662ab9859a9a076ba4cb25186e0743845a7bb0fc5db1f4c99.json b/.sqlx/query-bf98ad9ab317aeb662ab9859a9a076ba4cb25186e0743845a7bb0fc5db1f4c99.jsondeleted file mode 100644index cf1488533f..0000000000--- a/.sqlx/query-bf98ad9ab317aeb662ab9859a9a076ba4cb25186e0743845a7bb0fc5db1f4c99.json+++ /dev/null@@ -1,46 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n permission.id,\n permission.\"isPublic\" AS \"is_public\",\n permission.\"publicAccessLevel\" AS \"public_access_level?\",\n project.\"userId\" AS owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', channel.\"channel_id\",\n 'access_level', channel.\"access_level\"\n )) FILTER (WHERE channel.\"channel_id\" IS NOT NULL),\n '[]'\n ) AS \"channel_share_permissions?\"\n FROM \"ProjectPermission\" project_permission\n JOIN \"SharePermission\" permission\n ON project_permission.\"sharePermissionId\" = permission.id\n JOIN \"Project\" project ON project_permission.\"projectId\" = project.id\n LEFT JOIN \"ChannelSharePermission\" channel\n ON channel.\"share_permission_id\" = permission.id\n WHERE project_permission.\"projectId\" = $1\n GROUP BY permission.id, project.\"userId\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "is_public",- "type_info": "Bool"- },- {- "ordinal": 2,- "name": "public_access_level?",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "channel_share_permissions?",- "type_info": "Json"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- true,- false,- null- ]- },- "hash": "bf98ad9ab317aeb662ab9859a9a076ba4cb25186e0743845a7bb0fc5db1f4c99"-}diff --git a/.sqlx/query-833f7916c7445825f248eac09769afd4b4971b517b12e578ec2f534038609572.json b/.sqlx/query-c6a7c0f79caa2cb4f5f29ee9c7e40a310aa3da512e914357ea6f9783c389a232.jsonsimilarity index 51%rename from .sqlx/query-833f7916c7445825f248eac09769afd4b4971b517b12e578ec2f534038609572.jsonrename to .sqlx/query-c6a7c0f79caa2cb4f5f29ee9c7e40a310aa3da512e914357ea6f9783c389a232.jsonindex 8b6519505d..b9ed77682b 100644--- a/.sqlx/query-833f7916c7445825f248eac09769afd4b4971b517b12e578ec2f534038609572.json+++ b/.sqlx/query-c6a7c0f79caa2cb4f5f29ee9c7e40a310aa3da512e914357ea6f9783c389a232.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text as source_id FROM comms_channel_participants cp\n WHERE cp.user_id = $2 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text FROM team_user t\n WHERE t.user_id = $2\n UNION ALL\n SELECT $2\n )\n SELECT\n chat_id,\n access_level\n FROM (\n -- Source 1: entity_access for chats\n SELECT\n ea.entity_id::text as chat_id,\n ea.access_level::text as access_level\n FROM entity_access ea\n WHERE ea.source_id = ANY(SELECT source_id FROM user_source_ids)\n AND ea.entity_id = ANY(SELECT id::uuid FROM \"Chat\" WHERE id = ANY($1) AND \"deletedAt\" IS NULL)\n AND ea.entity_type = 'chat'\n UNION ALL\n -- Source 2: Direct chat public permissions\n SELECT\n c.id as chat_id,\n sp.\"publicAccessLevel\" as access_level\n FROM \"Chat\" c\n JOIN \"ChatPermission\" cp ON cp.\"chatId\" = c.id\n JOIN \"SharePermission\" sp ON sp.id = cp.\"sharePermissionId\"\n AND sp.\"isPublic\" = true\n AND sp.\"publicAccessLevel\" IS NOT NULL\n WHERE c.id = ANY($1) AND c.\"deletedAt\" IS NULL\n ) as all_levels\n ",+ "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text as source_id FROM comms_channel_participants cp\n WHERE cp.user_id = $2 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text FROM team_user t\n WHERE t.user_id = $2\n UNION ALL\n SELECT $2\n )\n SELECT\n chat_id,\n access_level\n FROM (\n -- Source 1: entity_access for chats\n SELECT\n ea.entity_id::text as chat_id,\n ea.access_level::text as access_level\n FROM entity_access ea\n WHERE ea.source_id = ANY(SELECT source_id FROM user_source_ids)\n AND ea.entity_id = ANY(SELECT id::uuid FROM \"Chat\" WHERE id = ANY($1) AND \"deletedAt\" IS NULL)\n AND ea.entity_type = 'chat'\n UNION ALL\n -- Source 2: Direct chat link permissions\n SELECT\n c.id as chat_id,\n sp.\"linkShareAccessLevel\"::text as access_level\n FROM \"Chat\" c\n JOIN \"ChatPermission\" cp ON cp.\"chatId\" = c.id\n JOIN \"SharePermission\" sp ON sp.id = cp.\"sharePermissionId\"\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = c.\"userId\"\n AND owner_team.team_id::text = ANY(\n SELECT source_id FROM user_source_ids\n )\n )\n )\n )\n WHERE c.id = ANY($1) AND c.\"deletedAt\" IS NULL\n ) as all_levels\n ","describe": {"columns": [{@@ -25,5 +25,5 @@null]},- "hash": "833f7916c7445825f248eac09769afd4b4971b517b12e578ec2f534038609572"+ "hash": "c6a7c0f79caa2cb4f5f29ee9c7e40a310aa3da512e914357ea6f9783c389a232"}diff --git a/.sqlx/query-c6b4132d0587032f101b3511eb5716283afb9667a996b2624a896d26ee55ef18.json b/.sqlx/query-c6b4132d0587032f101b3511eb5716283afb9667a996b2624a896d26ee55ef18.jsonnew file mode 100644index 0000000000..394b465723--- /dev/null+++ b/.sqlx/query-c6b4132d0587032f101b3511eb5716283afb9667a996b2624a896d26ee55ef18.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.\"linkShareAccessLevel\" AS \"access_level!: AccessLevel\"\n FROM \"SharePermission\" sp\n JOIN \"ChatPermission\" cp ON cp.\"sharePermissionId\" = sp.id\n WHERE cp.\"chatId\" = $1\n AND sp.\"linkShare\" = 'PUBLIC'\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level!: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "c6b4132d0587032f101b3511eb5716283afb9667a996b2624a896d26ee55ef18"+}diff --git a/.sqlx/query-c9a21f261fc143fd36456c652291340c52fc82f67e12de24365525efdef0a0e3.json b/.sqlx/query-c9a21f261fc143fd36456c652291340c52fc82f67e12de24365525efdef0a0e3.jsonnew file mode 100644index 0000000000..3edcc842f5--- /dev/null+++ b/.sqlx/query-c9a21f261fc143fd36456c652291340c52fc82f67e12de24365525efdef0a0e3.json@@ -0,0 +1,30 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE \"SharePermission\"\n SET\n \"linkShare\" = CASE WHEN $2 THEN $3 ELSE \"linkShare\" END,\n \"linkShareAccessLevel\" = CASE\n WHEN $2 AND $3 IS NULL THEN NULL\n WHEN $2 THEN COALESCE($5::\"AccessLevel\", 'view')\n WHEN $4 AND \"linkShare\" IS NOT NULL THEN COALESCE($5::\"AccessLevel\", 'view')\n WHEN $4 THEN NULL\n ELSE \"linkShareAccessLevel\"\n END,\n \"updatedAt\" = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Bool",+ "Text",+ "Bool",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "c9a21f261fc143fd36456c652291340c52fc82f67e12de24365525efdef0a0e3"+}diff --git a/.sqlx/query-cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882.json b/.sqlx/query-cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882.jsonnew file mode 100644index 0000000000..11dd4ad825--- /dev/null+++ b/.sqlx/query-cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'call'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: call link share permission\n SELECT\n share_permission.\"linkShareAccessLevel\"::text AS access_level\n FROM \"SharePermission\" share_permission\n JOIN (\n SELECT share_permission_id, created_by\n FROM calls\n WHERE id = $1\n\n UNION ALL\n\n SELECT share_permission_id, created_by\n FROM call_records\n WHERE id = $1\n LIMIT 1\n ) call_item ON call_item.share_permission_id = share_permission.id\n WHERE share_permission.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n share_permission.\"linkShare\" = 'PUBLIC'\n OR (\n share_permission.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM team_user owner_team\n WHERE owner_team.user_id = call_item.created_by\n AND owner_team.team_id::text = ANY($2)\n )\n )\n )\n ) AS combined_access\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "cf72111cb8f0154305b4e2ad2cb1f1f26964a3068b3d2909c5450fbb5de66882"+}diff --git a/.sqlx/query-d0f5de1518cf48faa63380a71ff6633e40c9a0d9f8e87262e31fa218400752a7.json b/.sqlx/query-d0f5de1518cf48faa63380a71ff6633e40c9a0d9f8e87262e31fa218400752a7.jsondeleted file mode 100644index 90383258c6..0000000000--- a/.sqlx/query-d0f5de1518cf48faa63380a71ff6633e40c9a0d9f8e87262e31fa218400752a7.json+++ /dev/null@@ -1,27 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"MacroPrompt\" (user_id, title, prompt, icon, color, required_docs)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id;\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "Text",- "Text",- "Text",- "Text",- "Int4"- ]- },- "nullable": [- false- ]- },- "hash": "d0f5de1518cf48faa63380a71ff6633e40c9a0d9f8e87262e31fa218400752a7"-}diff --git a/.sqlx/query-d7689899580f3928cca462a572058dd54f85dc6082f369fbecb2afa873fda66b.json b/.sqlx/query-d7689899580f3928cca462a572058dd54f85dc6082f369fbecb2afa873fda66b.jsondeleted file mode 100644index 8a1d028baf..0000000000--- a/.sqlx/query-d7689899580f3928cca462a572058dd54f85dc6082f369fbecb2afa873fda66b.json+++ /dev/null@@ -1,24 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'project'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: items share permission\n SELECT\n \"publicAccessLevel\"::text AS access_level\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"ProjectPermission\" WHERE \"projectId\" = $3\n )\n ) AS combined_access\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid",- "TextArray",- "Text"- ]- },- "nullable": [- null- ]- },- "hash": "d7689899580f3928cca462a572058dd54f85dc6082f369fbecb2afa873fda66b"-}diff --git a/.sqlx/query-e35594f0b886c9eaba037a0b13ccb3baf21cd37b638190889fb5383180a8e437.json b/.sqlx/query-e35594f0b886c9eaba037a0b13ccb3baf21cd37b638190889fb5383180a8e437.jsondeleted file mode 100644index 3ac1b029f6..0000000000--- a/.sqlx/query-e35594f0b886c9eaba037a0b13ccb3baf21cd37b638190889fb5383180a8e437.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n \"publicAccessLevel\" as \"access_level!\"\n FROM \"SharePermission\"\n WHERE \"isPublic\" = true\n AND \"publicAccessLevel\" IS NOT NULL\n AND id IN (\n SELECT \"sharePermissionId\" FROM \"EmailThreadPermission\" WHERE \"threadId\" = $1\n )\n\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "access_level!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- true- ]- },- "hash": "e35594f0b886c9eaba037a0b13ccb3baf21cd37b638190889fb5383180a8e437"-}diff --git a/.sqlx/query-e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb.json b/.sqlx/query-e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb.jsondeleted file mode 100644index b6ac45e454..0000000000--- a/.sqlx/query-e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"SharePermission\" (\"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, NOW(), NOW())\n RETURNING id\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Bool",- "Text"- ]- },- "nullable": [- false- ]- },- "hash": "e3ceebff1df78cef1b26e165cc4967a55f7b5355b7ff835eed0f93b4b8458ceb"-}diff --git a/.sqlx/query-e79254bff8226c8ea440f816141c703551b16533c07d4d42aea2fce6033877f8.json b/.sqlx/query-e79254bff8226c8ea440f816141c703551b16533c07d4d42aea2fce6033877f8.jsonnew file mode 100644index 0000000000..459f32639b--- /dev/null+++ b/.sqlx/query-e79254bff8226c8ea440f816141c703551b16533c07d4d42aea2fce6033877f8.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"SharePermission\" (\n \"linkShare\",\n \"linkShareAccessLevel\",\n \"createdAt\",\n \"updatedAt\"\n )\n VALUES (NULL, NULL, NOW(), NOW())\n RETURNING id as \"id!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ false+ ]+ },+ "hash": "e79254bff8226c8ea440f816141c703551b16533c07d4d42aea2fce6033877f8"+}diff --git a/.sqlx/query-eb5df4d78a5fe9a4f59a061a12bef33bf55ef84c02418ca2ca95793b107d9ef1.json b/.sqlx/query-eb5df4d78a5fe9a4f59a061a12bef33bf55ef84c02418ca2ca95793b107d9ef1.jsonnew file mode 100644index 0000000000..6d8883b4c4--- /dev/null+++ b/.sqlx/query-eb5df4d78a5fe9a4f59a061a12bef33bf55ef84c02418ca2ca95793b107d9ef1.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT access_level FROM (\n -- Source 1: entity_access source_id match\n SELECT\n access_level::text FROM entity_access\n WHERE entity_id = $1\n AND entity_type = 'chat'\n AND source_id = ANY($2)\n\n UNION ALL\n -- Source 2: chat link share permission\n SELECT\n sp.\"linkShareAccessLevel\"::text AS access_level\n FROM \"SharePermission\" sp\n JOIN \"ChatPermission\" cp ON cp.\"sharePermissionId\" = sp.id\n WHERE cp.\"chatId\" = $3\n AND sp.\"linkShareAccessLevel\" IS NOT NULL\n AND (\n sp.\"linkShare\" = 'PUBLIC'\n OR (\n sp.\"linkShare\" = 'TEAM'\n AND EXISTS (\n SELECT 1\n FROM \"Chat\" c\n JOIN team_user owner_tu ON owner_tu.user_id = c.\"userId\"\n WHERE c.id = $3\n AND owner_tu.team_id::text = ANY($2)\n )\n )\n )\n ) AS combined_access\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "eb5df4d78a5fe9a4f59a061a12bef33bf55ef84c02418ca2ca95793b107d9ef1"+}diff --git a/.sqlx/query-f1a1237e538aed664d169a463789deee91c174311ff9f8304c5ae26fa96dc854.json b/.sqlx/query-f1a1237e538aed664d169a463789deee91c174311ff9f8304c5ae26fa96dc854.jsonnew file mode 100644index 0000000000..9565c2b415--- /dev/null+++ b/.sqlx/query-f1a1237e538aed664d169a463789deee91c174311ff9f8304c5ae26fa96dc854.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"SharePermission\" (\n \"linkShare\",\n \"linkShareAccessLevel\",\n \"createdAt\",\n \"updatedAt\"\n )\n VALUES ($1, $2, NOW(), NOW())\n RETURNING id;\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "f1a1237e538aed664d169a463789deee91c174311ff9f8304c5ae26fa96dc854"+}diff --git a/.sqlx/query-fe93b3b50a3a64b8b354903858cfef2cdff408625fa1a592977996a81e8b3f3c.json b/.sqlx/query-fe93b3b50a3a64b8b354903858cfef2cdff408625fa1a592977996a81e8b3f3c.jsondeleted file mode 100644index caa1a7dfef..0000000000--- a/.sqlx/query-fe93b3b50a3a64b8b354903858cfef2cdff408625fa1a592977996a81e8b3f3c.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"MacroPromptPermission\" (\"macro_prompt_id\", \"share_permission_id\")\n VALUES ($1, $2)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "fe93b3b50a3a64b8b354903858cfef2cdff408625fa1a592977996a81e8b3f3c"-}diff --git a/apps/web/src/features/block-email/util/makeAttachmentPublic.ts b/apps/web/src/features/block-email/util/makeAttachmentPublic.tsindex 2aaae06638..3fe40e1c86 100644--- a/apps/web/src/features/block-email/util/makeAttachmentPublic.ts+++ b/apps/web/src/features/block-email/util/makeAttachmentPublic.ts@@ -9,17 +9,19 @@ export const makeAttachmentPublic = async (attachmentId: string) => {const permissions = await storageServiceClient.getDocumentPermissions({document_id: attachmentId,});- if (!permissions.isErr()) {- if (permissions.value.isPublic) {- return;- }+ if (+ !permissions.isErr() &&+ permissions.value.linkShare === 'PUBLIC' &&+ permissions.value.linkShareAccessLevel === 'view'+ ) {+ return;}- // Change file permissions to public view-only+const result = await storageServiceClient.editDocument({documentId: attachmentId,sharePermission: {- isPublic: true,- publicAccessLevel: 'view',+ linkShare: 'PUBLIC',+ linkShareAccessLevel: 'view',},});if (!result.isErr()) {diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.tsindex e23a5f793b..0b88c7e422 100644--- a/apps/web/src/lib/analytics/app-events.ts+++ b/apps/web/src/lib/analytics/app-events.ts@@ -165,10 +165,12 @@ export type AppEvents = {share_entity: EntityEventPayload & {shareMethod?:| 'public_link'+ | 'team_link'| 'channel'| 'forward'| 'attachment_public'| (string & {});+ linkShare?: 'PUBLIC' | 'TEAM';};task_copy_branch_name: Record<string, unknown>;diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex daa4266135..0a7f283724 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -53,6 +53,7 @@ import {storageServiceClient,} from '@service-storage/client';import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';+import type { LinkShare } from '@service-storage/generated/schemas/linkShare';import type { SharePermissionV2ChannelSharePermissions } from '@service-storage/generated/schemas/sharePermissionV2ChannelSharePermissions';import { createCallback } from '@solid-primitives/rootless';import { useNavigate } from '@solidjs/router';@@ -62,7 +63,7 @@ import {cn,Dropdown,Panel,- ToggleSwitch,+ SegmentedControl,Tooltip,} from '@ui';import type { Result } from 'neverthrow';@@ -82,17 +83,26 @@ import {useContext,} from 'solid-js';import { Dynamic } from 'solid-js/web';-import { match } from 'ts-pattern';import { CustomScrollbar } from '../CustomScrollbar';import { ForwardToChannel } from '../ForwardToChannel';import { Permissions } from '../SharePermissions';import { toast } from '../Toast/Toast';import { ScrollIndicators } from '../VerticalScrollIndicators';import { openLoginModal } from './LoginButton';+import {+ buildLinkSharePayload,+ buildLinkShareScopePayload,+ getLinkShareScope,+ getLinkShareScopeCopy,+ getShareStatus,+ LINK_SHARE_SCOPE_OPTIONS,+ type LinkSharePayload,+ type LinkShareScope,+} from './linkShare';false && clickOutside;-const isPublicLinkDisabledForItem = (itemType: ItemType): boolean =>+const isLinkSharingDisabledForItem = (itemType: ItemType): boolean =>itemType === 'email' || itemType === 'project';interface IShareDialogContext {@@ -257,6 +267,70 @@ function GroupChannelLabel(props: { channelId: string; fallbackName: string }) {);}+interface LinkSharingControlsProps {+ linkShare: LinkShare | null | undefined;+ linkShareAccessLevel: AccessLevel | null | undefined;+ hasExplicitShares: boolean;+ setLinkShareScope: (scope: LinkShareScope) => void;+ setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;+ copyLink: () => void;+}++function LinkSharingControls(props: LinkSharingControlsProps) {+ const scope = () => getLinkShareScope(props.linkShare);+ const scopeCopy = () => getLinkShareScopeCopy(scope());+ const shareStatus = () =>+ getShareStatus(props.linkShare, props.hasExplicitShares);++ return (+ <div class="flex flex-col gap-3 p-4 text-sm text-ink">+ <div class="flex flex-wrap items-center justify-between gap-3">+ <div class="flex items-center gap-2">+ <span class="font-medium">{scopeCopy().title}</span>+ <Tooltip label={shareStatus().tooltip}>+ <div+ class={cn(+ 'flex items-center justify-center rounded-xl border px-2 py-0.5',+ shareStatus().label === 'Just me'+ ? 'border-edge-muted bg-edge-muted text-ink-extra-muted'+ : 'border-accent/30 bg-accent/10 text-accent'+ )}+ >+ <span class="text-xs font-medium whitespace-nowrap">+ {shareStatus().label}+ </span>+ </div>+ </Tooltip>+ </div>+ <SegmentedControl+ aria-label="Link sharing scope"+ size="sm"+ value={scope()}+ options={LINK_SHARE_SCOPE_OPTIONS}+ onChange={props.setLinkShareScope}+ />+ </div>+ <p class="text-sm text-ink-muted">{scopeCopy().description}</p>+ <Show when={scope() !== 'NONE'}>+ <div class="flex flex-wrap items-center justify-between gap-3">+ <div class="flex items-center gap-2 text-ink-muted">+ <span>Access level</span>+ <ShareOptions+ permissions={props.linkShareAccessLevel ?? 'view'}+ hideNoAccess={true}+ setPermissions={props.setLinkShareAccessLevel}+ />+ </div>+ <Button variant="base" onClick={props.copyLink}>+ <CopyIcon class="size-4" />+ <span>Copy Link</span>+ </Button>+ </div>+ </Show>+ </div>+ );+}+interface MobileShareDrawerProps {isOpen: boolean;setIsOpen: (value: boolean) => void;@@ -269,7 +343,8 @@ interface MobileShareDrawerProps {recipients: SharePermissionV2ChannelSharePermissions | undefined;channelNameMap: Map<string, { name: string; type: string }>;formattedOwner: string;- publicAccessLevel: AccessLevel | null | undefined;+ linkShare: LinkShare | null | undefined;+ linkShareAccessLevel: AccessLevel | null | undefined;refetch: () => void;navigateToChannel: (channelId: string) => void;removeChannelAccess: (channelId: string) => void;@@ -278,8 +353,9 @@ interface MobileShareDrawerProps {accessLevel: AccessLevel,hideSuccessToast?: boolean) => void;- setPublicPermissions: (accessLevel: AccessLevel | null) => void;- copyPublicLink: () => void;+ setLinkShareScope: (scope: LinkShareScope) => void;+ setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;+ copyLink: () => void;}function MobileShareDrawer(props: MobileShareDrawerProps) {@@ -298,7 +374,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {tabs.push({ value: 'people', label: 'People' });if (props.userPermissions === Permissions.OWNER &&- !isPublicLinkDisabledForItem(props.itemType)+ !isLinkSharingDisabledForItem(props.itemType))tabs.push({ value: 'link', label: 'Link' });return tabs;@@ -465,62 +541,14 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {</div></Show><Show when={effectiveActiveTab() === 'link'}>- <div class="text-ink flex flex-col">- <div- class={cn(- 'flex flex-col gap-3 px-3 py-2 text-sm font-medium',- props.publicAccessLevel != null &&- 'border-b border-edge-muted'- )}- >- <div class="flex items-center gap-2">- Public link- <div- class={cn(- 'px-2 rounded-xl border py-0.5 flex justify-center items-center',- props.publicAccessLevel != null- ? 'border-accent/30 bg-accent/10'- : 'border-edge-muted bg-edge-muted'- )}- >- <span- class={cn(- 'text-xs font-medium whitespace-nowrap',- props.publicAccessLevel != null- ? 'text-accent'- : 'text-ink-extra-muted'- )}- >- {props.publicAccessLevel != null ? 'ENABLED' : 'DISABLED'}- </span>- </div>- </div>- <ToggleSwitch- onChange={(checked) =>- props.setPublicPermissions(checked ? 'view' : null)- }- checked={props.publicAccessLevel != null}- labelClass="whitespace-nowrap"- label="Enable public link"- />- </div>- <Show when={props.publicAccessLevel != null}>- <div class="flex flex-col gap-3 px-3 py-2">- <span class="text-sm text-ink-muted flex items-center">- <span class="px-2">Anyone with the link can</span>- <ShareOptions- permissions={props.publicAccessLevel ?? null}- hideNoAccess={true}- setPermissions={props.setPublicPermissions}- />- </span>- <Button variant="base" onClick={props.copyPublicLink}>- <CopyIcon class="size-4" />- <span>Copy Link</span>- </Button>- </div>- </Show>- </div>+ <LinkSharingControls+ linkShare={props.linkShare}+ linkShareAccessLevel={props.linkShareAccessLevel}+ hasExplicitShares={(props.recipients?.length ?? 0) > 0}+ setLinkShareScope={props.setLinkShareScope}+ setLinkShareAccessLevel={props.setLinkShareAccessLevel}+ copyLink={props.copyLink}+ /></Show></MobileDrawer.Content></MobileDrawer.Portal>@@ -569,7 +597,7 @@ export function ShareModal(props: ShareModalProps) {const referralCode = useReferralCode();- const copyPublicLink = createCallback(() => {+ const copyLink = createCallback(() => {const params: Record<string, string> = {};const code = referralCode();if (code) {@@ -804,119 +832,102 @@ export function ShareModal(props: ShareModalProps) {});- const publicAccessLevel = createMemo(() => {+ const linkShare = createMemo(() => {+ const currentPermissions = permissionsResource.latest;+ if (!currentPermissions || currentPermissions.isErr()) {+ return;+ }++ return currentPermissions.value.linkShare;+ });++ const linkShareAccessLevel = createMemo(() => {const currentPermissions = permissionsResource.latest;if (!currentPermissions || currentPermissions.isErr()) {return;}- const sharePermission = currentPermissions.value;- return sharePermission.publicAccessLevel;+ return currentPermissions.value.linkShareAccessLevel;});- const setPublicPermissions = createCallback(- async (accessLevel: AccessLevel | null) => {+ const updateLinkSharePermissions = createCallback(+ async (sharePermission: LinkSharePayload) => {+ const scope = getLinkShareScope(sharePermission.linkShare);+ let result: Result<any, ResultError<any>[]> | undefined;+if (props.itemType === 'chat') {- const result = await cognitionApiServiceClient.updateChatPermissions({- sharePermission: {- publicAccessLevel: accessLevel,- isPublic: accessLevel != null,- },+ result = await cognitionApiServiceClient.updateChatPermissions({+ sharePermission,chat_id: props.id,});- if (!result.isErr()) {- refetch();-- if (accessLevel === null) {- toast.success('Made chat private', {- subtext: 'Only shared users can access this chat',- });- } else {- toast.success('Updated public link sharing', {- subtext: `Anyone with the link can ${accessLevel} this chat`,- });-- analytics.track('share_entity', {- entityType: 'chat',- entityId: props.id,- shareMethod: 'public_link',- accessLevel,- isPublic: true,- });- }- } else {- toast.alert('Failed to change chat access', {- subtext: 'Please try again',- });- console.error(result);- }} else if (props.itemType === 'document') {- const result = await storageServiceClient.editDocument({- sharePermission: {- publicAccessLevel: accessLevel,- isPublic: accessLevel != null,- },+ result = await storageServiceClient.editDocument({+ sharePermission,documentId: props.id,});- if (!result.isErr()) {- refetch();- if (accessLevel === null) {- toast.success('Made document private', {- subtext: 'Only shared users can access this document',- });- } else {- toast.success('Updated public link sharing', {- subtext: `Anyone with the link can ${accessLevel} this document`,- });-- analytics.track('share_entity', {- entityType: 'document',- entityId: props.id,- shareMethod: 'public_link',- accessLevel,- isPublic: true,- });- }- } else {- toast.alert('Failed to change document access', {- subtext: 'Please try again',- });- console.error(result);- }} else if (props.itemType === 'project') {- const result = await storageServiceClient.projects.edit({- sharePermission: {- publicAccessLevel: accessLevel,- isPublic: accessLevel != null,- },+ result = await storageServiceClient.projects.edit({+ sharePermission,id: props.id,});- if (!result.isErr()) {- refetch();- if (accessLevel === null) {- toast.success('Made folder private', {- subtext: 'Only shared users can access this folder',- });- } else {- toast.success('Updated public link sharing', {- subtext: `Anyone with the link can ${accessLevel} this folder`,- });-- analytics.track('share_entity', {- entityType: 'project',- entityId: props.id,- shareMethod: 'public_link',- accessLevel,- isPublic: true,- });- }- } else {- toast.alert('Failed to change folder access', {- subtext: 'Please try again',- });- console.error(result);- }}++ const entityLabel =+ props.itemType === 'project' ? 'folder' : props.itemType;+ if (!result || result.isErr()) {+ toast.alert(`Failed to change ${entityLabel} access`, {+ subtext: 'Please try again',+ });+ console.error(result);+ return;+ }++ refetch();+ if (scope === 'NONE') {+ toast.success(`Made ${entityLabel} private`, {+ subtext: `Only shared users can access this ${entityLabel}`,+ });+ return;+ }++ const effectiveAccessLevel =+ sharePermission.linkShareAccessLevel ?? 'view';+ const audience =+ scope === 'PUBLIC'+ ? 'Anyone with the link'+ : "Members of the owner's team with the link";+ toast.success(`Updated ${getLinkShareScopeCopy(scope).title} sharing`, {+ subtext: `${audience} can ${accessLevelText(effectiveAccessLevel).toLowerCase()} this ${entityLabel}`,+ });++ analytics.track('share_entity', {+ entityType: props.itemType,+ entityId: props.id,+ shareMethod: scope === 'PUBLIC' ? 'public_link' : 'team_link',+ accessLevel: effectiveAccessLevel,+ linkShare: scope,+ });+ }+ );++ const setLinkShareScope = createCallback((scope: LinkShareScope) => {+ const sharePermission = buildLinkShareScopePayload(+ getLinkShareScope(linkShare()),+ scope,+ linkShareAccessLevel()+ );+ return updateLinkSharePermissions(sharePermission);+ });++ const setLinkShareAccessLevel = createCallback(+ (accessLevel: AccessLevel | null) => {+ const scope = getLinkShareScope(linkShare());+ if (scope === 'NONE' || accessLevel === null) {+ return;+ }+ return updateLinkSharePermissions(+ buildLinkSharePayload(scope, accessLevel)+ );});@@ -944,13 +955,15 @@ export function ShareModal(props: ShareModalProps) {recipients={recipients()}channelNameMap={channelNameMap()}formattedOwner={formattedOwner()}- publicAccessLevel={publicAccessLevel()}+ linkShare={linkShare()}+ linkShareAccessLevel={linkShareAccessLevel()}refetch={refetch}navigateToChannel={navigateToChannel}removeChannelAccess={removeChannelAccess}setChannelPermissions={setChannelPermissions}- setPublicPermissions={setPublicPermissions}- copyPublicLink={copyPublicLink}+ setLinkShareScope={setLinkShareScope}+ setLinkShareAccessLevel={setLinkShareAccessLevel}+ copyLink={copyLink}/>}>@@ -1129,72 +1142,24 @@ export function ShareModal(props: ShareModalProps) {</Panel></Show>- {/* Card 3: Public link — plain border */}+ {/* Card 3: Link sharing — plain border */}<Showwhen={props.userPermissions === Permissions.OWNER &&- !isPublicLinkDisabledForItem(props.itemType)+ !isLinkSharingDisabledForItem(props.itemType)}><Panel depth={2} class="rounded-xl">- <Panel.Header- class={cn(- 'justify-between px-4',- publicAccessLevel() == null && 'border-b-0'- )}- >- <div class="flex items-center gap-2">- <span class="text-sm font-medium">Public link</span>- <div- class={cn(- 'px-2 rounded-xl border py-0.5 flex justify-center items-center',- publicAccessLevel() != null- ? 'border-accent/30 bg-accent/10'- : 'border-edge-muted bg-edge-muted'- )}- >- <span- class={cn(- 'text-xs font-medium whitespace-nowrap',- publicAccessLevel() != null- ? 'text-accent'- : 'text-ink-extra-muted'- )}- >- {publicAccessLevel() != null ? 'ENABLED' : 'DISABLED'}- </span>- </div>- </div>- <ToggleSwitch- label="Enable public link"- labelClass="text-xs whitespace-nowrap"- checked={publicAccessLevel() != null}- onChange={(on) =>- setPublicPermissions(on ? 'view' : null)- }+ <Panel.Body>+ <LinkSharingControls+ linkShare={linkShare()}+ linkShareAccessLevel={linkShareAccessLevel()}+ hasExplicitShares={(recipients()?.length ?? 0) > 0}+ setLinkShareScope={setLinkShareScope}+ setLinkShareAccessLevel={setLinkShareAccessLevel}+ copyLink={copyLink}/>- </Panel.Header>- <Show when={publicAccessLevel() != null}>- <Panel.Body class="text-ink">- <div class="flex items-center p-4 justify-between">- <Button variant="base" onClick={copyPublicLink}>- <CopyIcon class="size-4" />- <span class="hidden sm:inline">Copy Link</span>- </Button>- <span class="text-sm text-ink-muted flex items-center">- <span class="px-2 hidden sm:inline">- Anyone with the link can- </span>- <span class="px-2 sm:hidden">Permissions:</span>- <ShareOptions- permissions={publicAccessLevel() ?? null}- hideNoAccess={true}- setPermissions={setPublicPermissions}- />- </span>- </div>- </Panel.Body>- </Show>+ </Panel.Body></Panel></Show></Dialog.Content>@@ -1261,34 +1226,22 @@ export function ShareTrigger(props: { copyLink?: () => void }) {icon: IconLink,}));- const shareAccessLevelText = createMemo(() => {+ const shareStatus = createMemo(() => {const result = permissionsBlockResource[0].latest;- if (!result || result.isErr()) return '';+ if (!result || result.isErr()) return;+const sharePermission = result.value;- if (sharePermission.isPublic) return 'Public';- if (sharePermission.channelSharePermissions?.length) return 'Shared';- return 'Just me';+ return getShareStatus(+ sharePermission.linkShare,+ (sharePermission.channelSharePermissions?.length ?? 0) > 0+ );});- const shareAccessTooltip = () =>- match(shareAccessLevelText())- .when(- (level) => level === 'Public',- () => 'Anyone with the link can access this item'- )- .when(- (level) => level === 'Shared',- () => 'Shared with specific people or channels'- )- .when(- (level) => level === 'Just me',- () => 'Only you can access this item'- )- .otherwise(() => 'This item has been shared with you');-return (<ButtonGroup variant="base" size="sm" class="bg-surface" depth={2}>- <Tooltip label={shareAccessTooltip()}>+ <Tooltip+ label={shareStatus()?.tooltip ?? 'This item has been shared with you.'}+ ><ButtononClick={() => {if (!isAuthenticated()) {diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.test.ts b/apps/web/src/lib/core/component/TopBar/linkShare.test.tsnew file mode 100644index 0000000000..fd72531afd--- /dev/null+++ b/apps/web/src/lib/core/component/TopBar/linkShare.test.ts@@ -0,0 +1,111 @@+import { describe, expect, it } from 'vitest';+import {+ buildLinkSharePayload,+ buildLinkShareScopePayload,+ getLinkShareScope,+ getLinkShareScopeCopy,+ getShareStatus,+ LINK_SHARE_SCOPE_OPTIONS,+} from './linkShare';++describe('getLinkShareScope', () => {+ it.each([null, undefined])('maps %s to NONE', (linkShare) => {+ expect(getLinkShareScope(linkShare)).toBe('NONE');+ });++ it.each(['PUBLIC', 'TEAM'] as const)('preserves %s', (linkShare) => {+ expect(getLinkShareScope(linkShare)).toBe(linkShare);+ });+});++describe('buildLinkSharePayload', () => {+ it('clears the scope and access level when link sharing is disabled', () => {+ expect(buildLinkSharePayload('NONE', 'edit')).toEqual({+ linkShare: null,+ linkShareAccessLevel: null,+ });+ });++ it.each(['PUBLIC', 'TEAM'] as const)(+ 'defaults a newly enabled %s link to view access',+ (scope) => {+ expect(buildLinkSharePayload(scope, null)).toEqual({+ linkShare: scope,+ linkShareAccessLevel: 'view',+ });+ }+ );++ it('keeps the selected access level independent from the link scope', () => {+ expect(buildLinkSharePayload('TEAM', 'edit')).toEqual({+ linkShare: 'TEAM',+ linkShareAccessLevel: 'edit',+ });+ });+});++describe('buildLinkShareScopePayload', () => {+ it('uses view when enabling a new link even if a stale access level exists', () => {+ expect(buildLinkShareScopePayload('NONE', 'PUBLIC', 'edit')).toEqual({+ linkShare: 'PUBLIC',+ linkShareAccessLevel: 'view',+ });+ });++ it('preserves the access level when switching an enabled link scope', () => {+ expect(buildLinkShareScopePayload('PUBLIC', 'TEAM', 'edit')).toEqual({+ linkShare: 'TEAM',+ linkShareAccessLevel: 'edit',+ });+ });+});++describe('link share copy', () => {+ it('provides None, Public, and Team selector options', () => {+ expect(LINK_SHARE_SCOPE_OPTIONS).toEqual([+ { value: 'NONE', label: 'None' },+ { value: 'PUBLIC', label: 'Public' },+ { value: 'TEAM', label: 'Team' },+ ]);+ });++ it('explains public links', () => {+ expect(getLinkShareScopeCopy('PUBLIC')).toEqual({+ label: 'Public',+ title: 'Public link',+ description: 'Anyone with the link can access this item.',+ });+ });++ it('distinguishes team links from explicit team or channel sharing', () => {+ const copy = getLinkShareScopeCopy('TEAM');++ expect(copy.title).toBe('Team link');+ expect(copy.description).toContain("Members of the owner's team");+ expect(copy.description).toContain(+ 'does not share it directly with a team or channel'+ );+ });+});++describe('getShareStatus', () => {+ it.each([+ ['PUBLIC', true, 'Public'],+ ['TEAM', true, 'Team'],+ [null, true, 'Shared'],+ [null, false, 'Just me'],+ ] as const)(+ 'uses %s with explicit shares %s for the %s status',+ (linkShare, hasExplicitShares, expectedLabel) => {+ expect(getShareStatus(linkShare, hasExplicitShares).label).toBe(+ expectedLabel+ );+ }+ );++ it('uses link-specific tooltip copy for team links', () => {+ expect(getShareStatus('TEAM', false).tooltip).toBe(+ getLinkShareScopeCopy('TEAM').description+ );+ });+});diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.ts b/apps/web/src/lib/core/component/TopBar/linkShare.tsnew file mode 100644index 0000000000..20d0c40e79--- /dev/null+++ b/apps/web/src/lib/core/component/TopBar/linkShare.ts@@ -0,0 +1,119 @@+import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';+import type { LinkShare } from '@service-storage/generated/schemas/linkShare';+import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';++export const NO_LINK_SHARE = 'NONE' as const;++export type LinkShareScope = LinkShare | typeof NO_LINK_SHARE;++export type LinkSharePayload = Required<+ Pick<UpdateSharePermissionRequestV2, 'linkShare' | 'linkShareAccessLevel'>+>;++type LinkShareScopeCopy = {+ label: string;+ title: string;+ description: string;+};++export type ShareStatus = {+ label: 'Public' | 'Team' | 'Shared' | 'Just me';+ tooltip: string;+};++const LINK_SHARE_SCOPE_COPY: Record<LinkShareScope, LinkShareScopeCopy> = {+ NONE: {+ label: 'None',+ title: 'Link sharing off',+ description:+ 'Only people and channels you explicitly share with can access this item.',+ },+ PUBLIC: {+ label: 'Public',+ title: 'Public link',+ description: 'Anyone with the link can access this item.',+ },+ TEAM: {+ label: 'Team',+ title: 'Team link',+ description:+ "Members of the owner's team with the link can access this item. This does not share it directly with a team or channel.",+ },+};++export const LINK_SHARE_SCOPE_OPTIONS = (+ ['NONE', 'PUBLIC', 'TEAM'] as const+).map((scope) => ({+ value: scope,+ label: LINK_SHARE_SCOPE_COPY[scope].label,+}));++export function getLinkShareScope(+ linkShare: LinkShare | null | undefined+): LinkShareScope {+ return linkShare ?? NO_LINK_SHARE;+}++export function buildLinkSharePayload(+ scope: LinkShareScope,+ accessLevel?: AccessLevel | null+): LinkSharePayload {+ if (scope === NO_LINK_SHARE) {+ return {+ linkShare: null,+ linkShareAccessLevel: null,+ };+ }++ return {+ linkShare: scope,+ linkShareAccessLevel: accessLevel ?? 'view',+ };+}++export function buildLinkShareScopePayload(+ currentScope: LinkShareScope,+ nextScope: LinkShareScope,+ currentAccessLevel?: AccessLevel | null+): LinkSharePayload {+ const accessLevel =+ currentScope === NO_LINK_SHARE ? null : currentAccessLevel;+ return buildLinkSharePayload(nextScope, accessLevel);+}++export function getLinkShareScopeCopy(+ scope: LinkShareScope+): LinkShareScopeCopy {+ return LINK_SHARE_SCOPE_COPY[scope];+}++export function getShareStatus(+ linkShare: LinkShare | null | undefined,+ hasExplicitShares: boolean+): ShareStatus {+ if (linkShare === 'PUBLIC') {+ return {+ label: 'Public',+ tooltip: LINK_SHARE_SCOPE_COPY.PUBLIC.description,+ };+ }++ if (linkShare === 'TEAM') {+ return {+ label: 'Team',+ tooltip: LINK_SHARE_SCOPE_COPY.TEAM.description,+ };+ }++ if (hasExplicitShares) {+ return {+ label: 'Shared',+ tooltip: 'Shared with specific people or channels.',+ };+ }++ return {+ label: 'Just me',+ tooltip: 'Only you can access this item.',+ };+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.tsindex c94e6314f4..b906a1c707 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts@@ -139,6 +139,7 @@ export * from './linearIssueMetaIdentifier';export * from './linearIssueMetaPriority';export * from './linearIssueMetaStatus';export * from './linearIssueMetaUrl';+export * from './linkShare';export * from './macroUserIdStr';export * from './mcpAuthCallbackParams';export * from './memoryErrorBody';@@ -183,7 +184,8 @@ export * from './serverResponse';export * from './setPricingRequest';export * from './sharePermissionV2';export * from './sharePermissionV2ChannelSharePermissions';-export * from './sharePermissionV2PublicAccessLevel';+export * from './sharePermissionV2LinkShare';+export * from './sharePermissionV2LinkShareAccessLevel';export * from './slackChannelMeta';export * from './slackChannelMetaChannelId';export * from './slackChannelMetaPurpose';@@ -220,8 +222,8 @@ export * from './updateServerRequestEnabled';export * from './updateServerRequestServerName';export * from './updateSharePermissionRequestV2';export * from './updateSharePermissionRequestV2ChannelSharePermissions';-export * from './updateSharePermissionRequestV2IsPublic';-export * from './updateSharePermissionRequestV2PublicAccessLevel';+export * from './updateSharePermissionRequestV2LinkShare';+export * from './updateSharePermissionRequestV2LinkShareAccessLevel';export * from './updateToolCallRequest';export * from './updateToolResponseRequest';export * from './upsertProjectionRequest';diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/linkShare.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/linkShare.tsnew file mode 100644index 0000000000..9226a86bb7--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/linkShare.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Defines who can access an item through its share link.+ */+export type LinkShare = (typeof LinkShare)[keyof typeof LinkShare];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const LinkShare = {+ PUBLIC: 'PUBLIC',+ TEAM: 'TEAM',+} as const;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.tsindex cea1ffeed8..cdcc07caa1 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2.ts@@ -5,16 +5,16 @@* OpenAPI spec version: 1.0.0*/import type { SharePermissionV2ChannelSharePermissions } from './sharePermissionV2ChannelSharePermissions';-import type { SharePermissionV2PublicAccessLevel } from './sharePermissionV2PublicAccessLevel';+import type { SharePermissionV2LinkShare } from './sharePermissionV2LinkShare';+import type { SharePermissionV2LinkShareAccessLevel } from './sharePermissionV2LinkShareAccessLevel';export interface SharePermissionV2 {/** The channel share permissions for the item */channelSharePermissions?: SharePermissionV2ChannelSharePermissions;/** The share permission id */id: string;- /** If the item is publicly accessible */- isPublic: boolean;+ linkShare?: SharePermissionV2LinkShare;+ linkShareAccessLevel?: SharePermissionV2LinkShareAccessLevel;/** The owner of the item */owner: string;- publicAccessLevel?: SharePermissionV2PublicAccessLevel;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2IsPublic.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2LinkShare.tssimilarity index 53%rename from apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2IsPublic.tsrename to apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2LinkShare.tsindex 57d1685090..33fd6ba378 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2IsPublic.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2LinkShare.ts@@ -4,8 +4,6 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/+import type { LinkShare } from './linkShare';-/**- * If the item is publicly accessible- */-export type UpdateSharePermissionRequestV2IsPublic = boolean | null;+export type SharePermissionV2LinkShare = null | LinkShare;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2PublicAccessLevel.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2LinkShareAccessLevel.tssimilarity index 71%rename from apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2PublicAccessLevel.tsrename to apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2LinkShareAccessLevel.tsindex 317c015fe3..57054342f3 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2PublicAccessLevel.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/sharePermissionV2LinkShareAccessLevel.ts@@ -6,4 +6,4 @@*/import type { AccessLevel } from './accessLevel';-export type SharePermissionV2PublicAccessLevel = null | AccessLevel;+export type SharePermissionV2LinkShareAccessLevel = null | AccessLevel;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.tsindex 4f721fe694..2bf6c0533d 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2.ts@@ -5,13 +5,12 @@* OpenAPI spec version: 1.0.0*/import type { UpdateSharePermissionRequestV2ChannelSharePermissions } from './updateSharePermissionRequestV2ChannelSharePermissions';-import type { UpdateSharePermissionRequestV2IsPublic } from './updateSharePermissionRequestV2IsPublic';-import type { UpdateSharePermissionRequestV2PublicAccessLevel } from './updateSharePermissionRequestV2PublicAccessLevel';+import type { UpdateSharePermissionRequestV2LinkShare } from './updateSharePermissionRequestV2LinkShare';+import type { UpdateSharePermissionRequestV2LinkShareAccessLevel } from './updateSharePermissionRequestV2LinkShareAccessLevel';export interface UpdateSharePermissionRequestV2 {/** Any channel share permissions to be created/updated/removed */channelSharePermissions?: UpdateSharePermissionRequestV2ChannelSharePermissions;- /** If the item is publicly accessible */- isPublic?: UpdateSharePermissionRequestV2IsPublic;- publicAccessLevel?: UpdateSharePermissionRequestV2PublicAccessLevel;+ linkShare?: UpdateSharePermissionRequestV2LinkShare;+ linkShareAccessLevel?: UpdateSharePermissionRequestV2LinkShareAccessLevel;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2LinkShare.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2LinkShare.tsnew file mode 100644index 0000000000..d96bee0da5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2LinkShare.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { LinkShare } from './linkShare';++export type UpdateSharePermissionRequestV2LinkShare = null | LinkShare;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2PublicAccessLevel.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.tssimilarity index 75%rename from apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2PublicAccessLevel.tsrename to apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.tsindex 97eda2feae..5387ce72ca 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2PublicAccessLevel.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.ts@@ -6,5 +6,5 @@*/import type { AccessLevel } from './accessLevel';-export type UpdateSharePermissionRequestV2PublicAccessLevel =+export type UpdateSharePermissionRequestV2LinkShareAccessLevel =null | AccessLevel;diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.jsonindex fa427b660d..236f94b6d0 100644--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json@@ -3417,6 +3417,11 @@}}},+ "LinkShare": {+ "type": "string",+ "description": "Defines who can access an item through its share link.",+ "enum": ["PUBLIC", "TEAM"]+ },"MacroUserIdStr": {"type": "string"},@@ -3867,7 +3872,7 @@},"SharePermissionV2": {"type": "object",- "required": ["id", "isPublic", "owner"],+ "required": ["id", "owner"],"properties": {"channelSharePermissions": {"type": ["array", "null"],@@ -3880,24 +3885,31 @@"type": "string","description": "The share permission id"},- "isPublic": {- "type": "boolean",- "description": "If the item is publicly accessible"- },- "owner": {- "type": "string",- "description": "The owner of the item"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link"+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The level of access granted through the share link"}]+ },+ "owner": {+ "type": "string",+ "description": "The owner of the item"}}},@@ -4184,18 +4196,25 @@},"description": "Any channel share permissions to be created/updated/removed"},- "isPublic": {- "type": ["boolean", "null"],- "description": "If the item is publicly accessible"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link. Omit to leave unchanged or pass `null` to\ndisable link sharing."+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."}]}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex 58d3b85ce7..91e5a68779 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -728,6 +728,7 @@ export * from './latestMessage';export * from './latestMessageLatestMessage';export * from './latestMessageLatestNonThreadMessage';export * from './leaveCallResponse';+export * from './linkShare';export * from './listOccurrencesParams';export * from './listRemindersEntityType';export * from './listRemindersParams';@@ -955,7 +956,8 @@ export * from './setPropertyValueOneOfType';export * from './sharedEmailFilter';export * from './sharePermissionV2';export * from './sharePermissionV2ChannelSharePermissions';-export * from './sharePermissionV2PublicAccessLevel';+export * from './sharePermissionV2LinkShare';+export * from './sharePermissionV2LinkShareAccessLevel';export * from './shortIdResponse';export * from './simpleMention';export * from './soupApiItem';@@ -1153,8 +1155,8 @@ export * from './updateOperation';export * from './updateReminderRequest';export * from './updateSharePermissionRequestV2';export * from './updateSharePermissionRequestV2ChannelSharePermissions';-export * from './updateSharePermissionRequestV2IsPublic';-export * from './updateSharePermissionRequestV2PublicAccessLevel';+export * from './updateSharePermissionRequestV2LinkShare';+export * from './updateSharePermissionRequestV2LinkShareAccessLevel';export * from './uploadDocumentStatus';export * from './uploadExtractFolderHandler200';export * from './uploadExtractFolderHandler200DataOneOf';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkShare.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkShare.tsnew file mode 100644index 0000000000..054a9038db--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/linkShare.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Defines who can access an item through its share link.+ */+export type LinkShare = (typeof LinkShare)[keyof typeof LinkShare];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const LinkShare = {+ PUBLIC: 'PUBLIC',+ TEAM: 'TEAM',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.tsindex 6a6e55c3bc..743eb74c47 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2.ts@@ -5,16 +5,16 @@* OpenAPI spec version: 0.1.0*/import type { SharePermissionV2ChannelSharePermissions } from './sharePermissionV2ChannelSharePermissions';-import type { SharePermissionV2PublicAccessLevel } from './sharePermissionV2PublicAccessLevel';+import type { SharePermissionV2LinkShare } from './sharePermissionV2LinkShare';+import type { SharePermissionV2LinkShareAccessLevel } from './sharePermissionV2LinkShareAccessLevel';export interface SharePermissionV2 {/** The channel share permissions for the item */channelSharePermissions?: SharePermissionV2ChannelSharePermissions;/** The share permission id */id: string;- /** If the item is publicly accessible */- isPublic: boolean;+ linkShare?: SharePermissionV2LinkShare;+ linkShareAccessLevel?: SharePermissionV2LinkShareAccessLevel;/** The owner of the item */owner: string;- publicAccessLevel?: SharePermissionV2PublicAccessLevel;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2IsPublic.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2LinkShare.tssimilarity index 52%rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2IsPublic.tsrename to apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2LinkShare.tsindex 6e7788d0d8..353321e7a5 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2IsPublic.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2LinkShare.ts@@ -4,8 +4,6 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { LinkShare } from './linkShare';-/**- * If the item is publicly accessible- */-export type UpdateSharePermissionRequestV2IsPublic = boolean | null;+export type SharePermissionV2LinkShare = null | LinkShare;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2PublicAccessLevel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2LinkShareAccessLevel.tssimilarity index 71%rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2PublicAccessLevel.tsrename to apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2LinkShareAccessLevel.tsindex 95fbeb18a3..fb6d0c58e5 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2PublicAccessLevel.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/sharePermissionV2LinkShareAccessLevel.ts@@ -6,4 +6,4 @@*/import type { AccessLevel } from './accessLevel';-export type SharePermissionV2PublicAccessLevel = null | AccessLevel;+export type SharePermissionV2LinkShareAccessLevel = null | AccessLevel;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.tsindex 43372a2913..5c2dfa70b6 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2.ts@@ -5,13 +5,12 @@* OpenAPI spec version: 0.1.0*/import type { UpdateSharePermissionRequestV2ChannelSharePermissions } from './updateSharePermissionRequestV2ChannelSharePermissions';-import type { UpdateSharePermissionRequestV2IsPublic } from './updateSharePermissionRequestV2IsPublic';-import type { UpdateSharePermissionRequestV2PublicAccessLevel } from './updateSharePermissionRequestV2PublicAccessLevel';+import type { UpdateSharePermissionRequestV2LinkShare } from './updateSharePermissionRequestV2LinkShare';+import type { UpdateSharePermissionRequestV2LinkShareAccessLevel } from './updateSharePermissionRequestV2LinkShareAccessLevel';export interface UpdateSharePermissionRequestV2 {/** Any channel share permissions to be created/updated/removed */channelSharePermissions?: UpdateSharePermissionRequestV2ChannelSharePermissions;- /** If the item is publicly accessible */- isPublic?: UpdateSharePermissionRequestV2IsPublic;- publicAccessLevel?: UpdateSharePermissionRequestV2PublicAccessLevel;+ linkShare?: UpdateSharePermissionRequestV2LinkShare;+ linkShareAccessLevel?: UpdateSharePermissionRequestV2LinkShareAccessLevel;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2LinkShare.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2LinkShare.tsnew file mode 100644index 0000000000..d748e877f9--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2LinkShare.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { LinkShare } from './linkShare';++export type UpdateSharePermissionRequestV2LinkShare = null | LinkShare;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2PublicAccessLevel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.tssimilarity index 75%rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2PublicAccessLevel.tsrename to apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.tsindex 940200af42..474619726c 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2PublicAccessLevel.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/updateSharePermissionRequestV2LinkShareAccessLevel.ts@@ -6,5 +6,5 @@*/import type { AccessLevel } from './accessLevel';-export type UpdateSharePermissionRequestV2PublicAccessLevel =+export type UpdateSharePermissionRequestV2LinkShareAccessLevel =null | AccessLevel;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.tsindex 62e3967b34..b647231e7b 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@@ -1465,11 +1465,17 @@ export const editCallRecordBody = zod.describe('Any channel share permissions to be created\/updated\/removed'),- isPublic: zod- .boolean()- .nullish()- .describe('If the item is publicly accessible'),- publicAccessLevel: zod+ linkShare: zod+ .union([+ zod.null(),+ zod+ .enum(['PUBLIC', 'TEAM'])+ .describe(+ 'Defines who can access an item through its share link.'+ ),+ ])+ .optional(),+ linkShareAccessLevel: zod.union([zod.null(),zod@@ -6271,11 +6277,17 @@ export const editDocumentBody = zod.describe('Any channel share permissions to be created\/updated\/removed'),- isPublic: zod- .boolean()- .nullish()- .describe('If the item is publicly accessible'),- publicAccessLevel: zod+ linkShare: zod+ .union([+ zod.null(),+ zod+ .enum(['PUBLIC', 'TEAM'])+ .describe(+ 'Defines who can access an item through its share link.'+ ),+ ])+ .optional(),+ linkShareAccessLevel: zod.union([zod.null(),zod@@ -25923,9 +25935,15 @@ export const getProjectPermissionsV2Response = zod.object({.nullish().describe('The channel share permissions for the item'),id: zod.string().describe('The share permission id'),- isPublic: zod.boolean().describe('If the item is publicly accessible'),- owner: zod.string().describe('The owner of the item'),- publicAccessLevel: zod+ linkShare: zod+ .union([+ zod.null(),+ zod+ .enum(['PUBLIC', 'TEAM'])+ .describe('Defines who can access an item through its share link.'),+ ])+ .optional(),+ linkShareAccessLevel: zod.union([zod.null(),zod@@ -25933,6 +25951,7 @@ export const getProjectPermissionsV2Response = zod.object({.describe('Ordered from least to most access top -> bottom'),]).optional(),+ owner: zod.string().describe('The owner of the item'),});/**@@ -26670,11 +26689,17 @@ export const editThreadV2Body = zod.object({.describe('Any channel share permissions to be created\/updated\/removed'),- isPublic: zod- .boolean()- .nullish()- .describe('If the item is publicly accessible'),- publicAccessLevel: zod+ linkShare: zod+ .union([+ zod.null(),+ zod+ .enum(['PUBLIC', 'TEAM'])+ .describe(+ 'Defines who can access an item through its share link.'+ ),+ ])+ .optional(),+ linkShareAccessLevel: zod.union([zod.null(),zod@@ -26755,9 +26780,15 @@ export const getDocumentPermissionsV2Response = zod.object({.nullish().describe('The channel share permissions for the item'),id: zod.string().describe('The share permission id'),- isPublic: zod.boolean().describe('If the item is publicly accessible'),- owner: zod.string().describe('The owner of the item'),- publicAccessLevel: zod+ linkShare: zod+ .union([+ zod.null(),+ zod+ .enum(['PUBLIC', 'TEAM'])+ .describe('Defines who can access an item through its share link.'),+ ])+ .optional(),+ linkShareAccessLevel: zod.union([zod.null(),zod@@ -26765,6 +26796,7 @@ export const getDocumentPermissionsV2Response = zod.object({.describe('Ordered from least to most access top -> bottom'),]).optional(),+ owner: zod.string().describe('The owner of the item'),}),});@@ -26806,11 +26838,17 @@ export const editProjectV2Body = zod.object({.describe('Any channel share permissions to be created\/updated\/removed'),- isPublic: zod- .boolean()- .nullish()- .describe('If the item is publicly accessible'),- publicAccessLevel: zod+ linkShare: zod+ .union([+ zod.null(),+ zod+ .enum(['PUBLIC', 'TEAM'])+ .describe(+ 'Defines who can access an item through its share link.'+ ),+ ])+ .optional(),+ linkShareAccessLevel: zod.union([zod.null(),zoddiff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex e4f673ab4e..1395f601d7 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts@@ -36,14 +36,17 @@ export type EntityRefInput = {type: GraphqlEntityType;};-/** Shared public/channel share-policy update. */+/** Shared link/channel share-policy update. */export type EntitySharePolicyInput = {/** Channel access entries to add, remove, or replace. */channelSharePermissions?: Array<ChannelSharePolicyInput> | null | undefined;- /** Whether public access should be enabled. */- isPublic?: boolean | null | undefined;- /** Public access level when public access is enabled. */- publicAccessLevel?: GraphqlEntityAccessLevel | null | undefined;+ /** Link-sharing audience. Omit to leave unchanged or pass null to disable link sharing. */+ linkShare?: GraphqlLinkShare | null | undefined;+ /**+ * Link access level. Omit to leave unchanged or pass null to reset it to the default level+ * when a link share exists.+ */+ linkShareAccessLevel?: GraphqlEntityAccessLevel | null | undefined;};/** The two operands of a recursive `CalendarEventFilterExpr` binary expression. */@@ -658,6 +661,13 @@ export type GraphqlGroupByInput = {propertyDefinitionId?: string | number | null | undefined;};+/** Audience allowed to access an entity through its share link. */+export type GraphqlLinkShare =+ /** Anyone with the link can access the entity. */+ | 'PUBLIC'+ /** Members of the owner's team with the link can access the entity. */+ | 'TEAM';+/** GraphQL channel type used by notification metadata. */export type GraphqlNotificationChannelType =/** Direct-message channel. */@@ -1064,7 +1074,7 @@ export type SoupInput =export type UpdateEntitySharePolicyInput = {/** Entity whose share policy should change. */entity: EntityRefInput;- /** New public/channel policy values. */+ /** New link/channel policy values. */policy: EntitySharePolicyInput;};diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 3360637a0f..2d7adb683c 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -19558,6 +19558,11 @@}}},+ "LinkShare": {+ "type": "string",+ "description": "Defines who can access an item through its share link.",+ "enum": ["PUBLIC", "TEAM"]+ },"ListWebhooksResponse": {"type": "object","description": "Webhooks visible to the caller across their personal and team workspaces.",@@ -21692,7 +21697,7 @@},"SharePermissionV2": {"type": "object",- "required": ["id", "isPublic", "owner"],+ "required": ["id", "owner"],"properties": {"channelSharePermissions": {"type": ["array", "null"],@@ -21705,24 +21710,31 @@"type": "string","description": "The share permission id"},- "isPublic": {- "type": "boolean",- "description": "If the item is publicly accessible"- },- "owner": {- "type": "string",- "description": "The owner of the item"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link"+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The level of access granted through the share link"}]+ },+ "owner": {+ "type": "string",+ "description": "The owner of the item"}}},@@ -23834,18 +23846,25 @@},"description": "Any channel share permissions to be created/updated/removed"},- "isPublic": {- "type": ["boolean", "null"],- "description": "If the item is publicly accessible"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link. Omit to leave unchanged or pass `null` to\ndisable link sharing."+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."}]}diff --git a/apps/web/tests/e2e/fixtures/local-e2e-seed.ts b/apps/web/tests/e2e/fixtures/local-e2e-seed.tsindex d693091400..454097abcb 100644--- a/apps/web/tests/e2e/fixtures/local-e2e-seed.ts+++ b/apps/web/tests/e2e/fixtures/local-e2e-seed.ts@@ -78,7 +78,8 @@ export type SeedDocument = {document_id: string;document_name: string;file_name: string;- is_public: boolean;+ link_share: 'PUBLIC' | 'TEAM' | null;+ link_share_access_level: 'view' | 'comment' | 'edit' | null;};export type SeedChannel = {diff --git a/crates/call/fixtures/call_repo.sql b/crates/call/fixtures/call_repo.sqlindex b50305eb72..69f0f4c316 100644--- a/crates/call/fixtures/call_repo.sql+++ b/crates/call/fixtures/call_repo.sql@@ -21,8 +21,8 @@ INSERT INTO comms_channel_participants (channel_id, user_id, role, joined_at) VA('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'member', '2024-01-01 00:00:00+00');-- share permission for call1-INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel", "createdAt", "updatedAt") VALUES- ('00000000-0000-0000-0000-00000000sp01', false, NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');+INSERT INTO "SharePermission" (id, "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt") VALUES+ ('00000000-0000-0000-0000-00000000sp01', NULL, NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');INSERT INTO "ChannelSharePermission" (share_permission_id, channel_id, access_level) VALUES('00000000-0000-0000-0000-00000000sp01', '00000000-0000-0000-0000-000000000c01', 'view');@@ -39,8 +39,8 @@ INSERT INTO call_participants (call_id, user_id, joined_at) VALUES('00000000-0000-0000-0000-0000000ca110', 'macro|[email protected]', '2024-01-01 12:01:00+00');-- share permission for the archived call-INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel", "createdAt", "updatedAt") VALUES- ('00000000-0000-0000-0000-00000000sp02', false, NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');+INSERT INTO "SharePermission" (id, "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt") VALUES+ ('00000000-0000-0000-0000-00000000sp02', NULL, NULL, '2024-01-01 00:00:00+00', '2024-01-01 00:00:00+00');INSERT INTO "ChannelSharePermission" (share_permission_id, channel_id, access_level) VALUES('00000000-0000-0000-0000-00000000sp02', '00000000-0000-0000-0000-000000000c01', 'view');diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rsindex 7125d8e965..9b7e8ad883 100644--- a/crates/call/src/domain/service/test.rs+++ b/crates/call/src/domain/service/test.rs@@ -1443,8 +1443,10 @@ async fn edit_call_record_publishes_updated_event_for_share_permission_only() {EditCallRecordRequest {share_permission: Some(models_permissions::share_permission::UpdateSharePermissionRequestV2 {- is_public: Some(true),- public_access_level: None,+ link_share: Some(Some(+ models_permissions::share_permission::LinkShare::Public,+ )),+ link_share_access_level: None,channel_share_permissions: None,},),diff --git a/crates/call/src/outbound/pg_call_repo.rs b/crates/call/src/outbound/pg_call_repo.rsindex b658d9cd77..2e8958a1b3 100644--- a/crates/call/src/outbound/pg_call_repo.rs+++ b/crates/call/src/outbound/pg_call_repo.rs@@ -311,29 +311,34 @@ impl CallRepository for PgCallRepo {let share_permission_id = uuid::Uuid::now_v7();let share_permission = SharePermissionV2 {id: share_permission_id.to_string(),- is_public: false,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,owner: created_by.to_string(),channel_share_permissions: Some(vec![ChannelSharePermission {channel_id: channel_id.to_string(),access_level: AccessLevel::Edit,}]),};+ let link_share = share_permission.link_share.map(|value| value.to_string());+ let link_share_access_level = share_permission.link_share_access_level;let mut tx = self.pool.begin().await?;// insert share permissionsqlx::query!(r#"- INSERT INTO "SharePermission" ("id", "isPublic","publicAccessLevel", "createdAt", "updatedAt")+ INSERT INTO "SharePermission" (+ "id",+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt"+ )VALUES ($1, $2, $3, NOW(), NOW())- "#,+ "#,share_permission.id,- share_permission.is_public,- share_permission- .public_access_level- .as_ref()- .map(|s| s.to_string()),+ link_share,+ link_share_access_level as _,).execute(tx.as_mut()).await?;diff --git a/crates/call/src/outbound/pg_call_repo/edit.rs b/crates/call/src/outbound/pg_call_repo/edit.rsindex b553570fc5..4a9cb95c25 100644--- a/crates/call/src/outbound/pg_call_repo/edit.rs+++ b/crates/call/src/outbound/pg_call_repo/edit.rs@@ -4,7 +4,7 @@ use entity_access_db_utils::{AccessLevel, EntityAccessSourceType};use model_entity::EntityType;use models_permissions::share_permission::UpdateSharePermissionRequestV2;use models_permissions::share_permission::channel_share_permission::UpdateOperation;-use sqlx::{Postgres, Transaction};+use sqlx::{Postgres, QueryBuilder, Transaction};use uuid::Uuid;use crate::domain::models::CustomSpeakerAssignment;@@ -223,81 +223,46 @@ pub(super) async fn set_custom_speakers(Ok(())}-/// Update the SharePermission row (isPublic, publicAccessLevel).-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]+/// Update the SharePermission row.+#[allow(+ clippy::disallowed_methods,+ reason = "the optional fields require a dynamic SET clause; identifiers are trusted and values are bound"+)]async fn update_share_permission_row(transaction: &mut Transaction<'_, Postgres>,share_permission_id: &str,share_permission: &UpdateSharePermissionRequestV2,) -> Result<(), sqlx::Error> {- let mut set_parts = Vec::new();- let mut str_params: Vec<Option<String>> = Vec::new();- let mut bool_params: Vec<bool> = Vec::new();-- // Track parameter indices (starting at 2 since $1 is the share_permission_id)- let mut param_idx = 2u32;- enum ParamType {- Bool(usize),- Str(usize),- }- let mut param_order: Vec<ParamType> = Vec::new();-- let mut ignore_public_access_level = false;- if let Some(is_public) = share_permission.is_public {- set_parts.push(format!("\"isPublic\" = ${param_idx}"));- param_idx += 1;- bool_params.push(is_public);- param_order.push(ParamType::Bool(bool_params.len() - 1));-- if is_public && share_permission.public_access_level.is_none() {- set_parts.push(format!("\"publicAccessLevel\" = ${param_idx}"));- param_idx += 1;- str_params.push(Some("view".to_string()));- param_order.push(ParamType::Str(str_params.len() - 1));- }-- if !is_public {- ignore_public_access_level = true;- set_parts.push("\"publicAccessLevel\" = NULL".to_string());- }- }-- if let Some(public_access_level) = share_permission.public_access_level- && !ignore_public_access_level- {- set_parts.push(format!("\"publicAccessLevel\" = ${param_idx}"));- str_params.push(Some(public_access_level.to_string()));- param_order.push(ParamType::Str(str_params.len() - 1));- }-- if set_parts.is_empty() {- sqlx::query(r#"UPDATE "SharePermission" SET "updatedAt" = NOW() WHERE id = $1"#)- .bind(share_permission_id)- .execute(transaction.as_mut())- .await?;- return Ok(());+ let mut query =+ QueryBuilder::<Postgres>::new(r#"UPDATE "SharePermission" SET "updatedAt" = NOW()"#);++ if let Some(link_share) = share_permission.link_share {+ let access_level = link_share.map(|_| {+ share_permission+ .link_share_access_level+ .flatten()+ .unwrap_or(AccessLevel::View)+ });++ query+ .push(r#", "linkShare" = "#)+ .push_bind(link_share.map(|value| value.to_string()))+ .push(r#", "linkShareAccessLevel" = "#)+ .push_bind(access_level);+ } else if let Some(access_level) = share_permission.link_share_access_level {+ query+ .push(r#", "linkShareAccessLevel" = CASE WHEN "linkShare" IS NULL THEN NULL ELSE "#)+ .push_bind(access_level.unwrap_or(AccessLevel::View))+ .push(" END");}- let query_str = format!(- r#"UPDATE "SharePermission" SET {}, "updatedAt" = NOW() WHERE id = $1"#,- set_parts.join(", ")- );-- let mut query = sqlx::query(&query_str);- query = query.bind(share_permission_id.to_string());-- for param_type in ¶m_order {- match param_type {- ParamType::Bool(idx) => {- query = query.bind(bool_params[*idx]);- }- ParamType::Str(idx) => {- query = query.bind(str_params[*idx].clone());- }- }- }+ query+ .push(" WHERE id = ")+ .push_bind(share_permission_id)+ .build()+ .execute(transaction.as_mut())+ .await?;- query.execute(transaction.as_mut()).await?;Ok(())}diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rsindex ecc26465a8..e19a1bd95e 100644--- a/crates/call/src/outbound/pg_call_repo/test.rs+++ b/crates/call/src/outbound/pg_call_repo/test.rs@@ -14,11 +14,11 @@ use item_filters::{};use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use models_permissions::share_permission::UpdateSharePermissionRequestV2;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::{UpdateChannelSharePermission, UpdateOperation,};+use models_permissions::share_permission::{LinkShare, UpdateSharePermissionRequestV2};use sqlx::{Pool, Postgres};use uuid::Uuid;@@ -189,7 +189,7 @@ async fn insert_user_mapping(migrator = "MACRO_DB_MIGRATIONS")]async fn create_call_returns_call(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = repo(pool);+ let repo = repo(pool.clone());let id = Uuid::now_v7();let call = repo.create_call(&id, &CH2, "room-ch2", USER_B.deref().copied())@@ -200,6 +200,32 @@ async fn create_call_returns_call(pool: Pool<Postgres>) -> anyhow::Result<()> {assert_eq!(call.channel_id, CH2);assert_eq!(call.room_name, "room-ch2");assert_eq!(call.created_by, USER_B.as_ref());++ let share_permission_id =+ sqlx::query_scalar!(r#"SELECT share_permission_id FROM calls WHERE id = $1"#, id,)+ .fetch_one(&pool)+ .await?;+ let permission = get_stored_share_permission(&pool, &share_permission_id).await?;+ assert_eq!(+ permission,+ StoredSharePermission {+ link_share: None,+ link_share_access_level: None,+ }+ );++ let channel_access_level = sqlx::query_scalar!(+ r#"+ SELECT csp.access_level::text AS "access_level!"+ FROM "ChannelSharePermission" csp+ WHERE csp.share_permission_id = $1 AND csp.channel_id = $2+ "#,+ share_permission_id,+ CH2.to_string(),+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(channel_access_level, "edit");Ok(())}@@ -2053,11 +2079,56 @@ async fn delete_call_record_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhow:const SP_ARCHIVED: &str = "00000000-0000-0000-0000-00000000sp02";+#[derive(Debug, Eq, PartialEq)]+struct StoredSharePermission {+ link_share: Option<String>,+ link_share_access_level: Option<String>,+}++async fn get_stored_share_permission(+ pool: &Pool<Postgres>,+ share_permission_id: &str,+) -> Result<StoredSharePermission, sqlx::Error> {+ sqlx::query_as!(+ StoredSharePermission,+ r#"+ SELECT+ "linkShare" AS "link_share?",+ "linkShareAccessLevel"::text AS "link_share_access_level?"+ FROM "SharePermission"+ WHERE id = $1+ "#,+ share_permission_id,+ )+ .fetch_one(pool)+ .await+}++async fn set_stored_share_permission(+ pool: &Pool<Postgres>,+ link_share: Option<&str>,+ access_level: Option<&str>,+) -> Result<(), sqlx::Error> {+ sqlx::query!(+ r#"+ UPDATE "SharePermission"+ SET "linkShare" = $2, "linkShareAccessLevel" = $3::text::"AccessLevel"+ WHERE id = $1+ "#,+ SP_ARCHIVED,+ link_share,+ access_level,+ )+ .execute(pool)+ .await?;+ Ok(())+}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("call_repo")),migrator = "MACRO_DB_MIGRATIONS")]-async fn patch_call_record_sets_is_public_true_defaults_view(+async fn patch_call_record_sets_public_link_and_defaults_level_to_view(pool: Pool<Postgres>,) -> anyhow::Result<()> {let repo = repo(pool.clone());@@ -2066,8 +2137,8 @@ async fn patch_call_record_sets_is_public_true_defaults_view(&CALL_ARCHIVED,&EditCallRecordRequest {share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: Some(true),- public_access_level: None,+ link_share: Some(Some(LinkShare::Public)),+ link_share_access_level: None,channel_share_permissions: None,}),share_with_team: None,@@ -2076,19 +2147,9 @@ async fn patch_call_record_sets_is_public_true_defaults_view().await?;- let row = sqlx::query!(- r#"- SELECT "isPublic" as "is_public!", "publicAccessLevel" as "public_access_level?"- FROM "SharePermission"- WHERE id = $1- "#,- SP_ARCHIVED,- )- .fetch_one(&pool)- .await?;-- assert!(row.is_public);- assert_eq!(row.public_access_level.as_deref(), Some("view"));+ let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;+ assert_eq!(permission.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(permission.link_share_access_level.as_deref(), Some("view"));Ok(())}@@ -2096,25 +2157,17 @@ async fn patch_call_record_sets_is_public_true_defaults_view(fixtures(path = "../../../fixtures", scripts("call_repo")),migrator = "MACRO_DB_MIGRATIONS")]-async fn patch_call_record_sets_is_public_false_clears_public_access_level(+async fn patch_call_record_sets_team_link_and_explicit_level(pool: Pool<Postgres>,) -> anyhow::Result<()> {let repo = repo(pool.clone());- // Seed a non-null public access level so the clear is observable.- sqlx::query!(- r#"UPDATE "SharePermission" SET "isPublic" = true, "publicAccessLevel" = 'edit' WHERE id = $1"#,- SP_ARCHIVED,- )- .execute(&pool)- .await?;-repo.patch_call_record(&CALL_ARCHIVED,&EditCallRecordRequest {share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: Some(false),- public_access_level: Some(AccessLevel::Edit),+ link_share: Some(Some(LinkShare::Team)),+ link_share_access_level: Some(Some(AccessLevel::Edit)),channel_share_permissions: None,}),share_with_team: None,@@ -2123,19 +2176,9 @@ async fn patch_call_record_sets_is_public_false_clears_public_access_level().await?;- let row = sqlx::query!(- r#"- SELECT "isPublic" as "is_public!", "publicAccessLevel" as "public_access_level?"- FROM "SharePermission"- WHERE id = $1- "#,- SP_ARCHIVED,- )- .fetch_one(&pool)- .await?;-- assert!(!row.is_public);- assert!(row.public_access_level.is_none());+ let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;+ assert_eq!(permission.link_share.as_deref(), Some("TEAM"));+ assert_eq!(permission.link_share_access_level.as_deref(), Some("edit"));Ok(())}@@ -2143,15 +2186,18 @@ async fn patch_call_record_sets_is_public_false_clears_public_access_level(fixtures(path = "../../../fixtures", scripts("call_repo")),migrator = "MACRO_DB_MIGRATIONS")]-async fn patch_call_record_sets_public_access_level(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn patch_call_record_explicit_null_disables_link_sharing(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {let repo = repo(pool.clone());+ set_stored_share_permission(&pool, Some("PUBLIC"), Some("edit")).await?;repo.patch_call_record(&CALL_ARCHIVED,&EditCallRecordRequest {share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: None,- public_access_level: Some(AccessLevel::Edit),+ link_share: Some(None),+ link_share_access_level: Some(Some(AccessLevel::Edit)),channel_share_permissions: None,}),share_with_team: None,@@ -2160,18 +2206,47 @@ async fn patch_call_record_sets_public_access_level(pool: Pool<Postgres>) -> any).await?;- let row = sqlx::query!(- r#"- SELECT "publicAccessLevel" as "public_access_level?"- FROM "SharePermission"- WHERE id = $1- "#,- SP_ARCHIVED,+ let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;+ assert_eq!(+ permission,+ StoredSharePermission {+ link_share: None,+ link_share_access_level: None,+ }+ );+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn patch_call_record_level_only_update_updates_link_share_access_level(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());+ set_stored_share_permission(&pool, Some("PUBLIC"), Some("view")).await?;++ repo.patch_call_record(+ &CALL_ARCHIVED,+ &EditCallRecordRequest {+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: Some(Some(AccessLevel::Comment)),+ channel_share_permissions: None,+ }),+ share_with_team: None,+ custom_name: None,+ },)- .fetch_one(&pool).await?;- assert_eq!(row.public_access_level.as_deref(), Some("edit"));+ let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;+ assert_eq!(permission.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(+ permission.link_share_access_level.as_deref(),+ Some("comment")+ );Ok(())}@@ -2189,8 +2264,8 @@ async fn patch_call_record_adds_channel_share_permission(&CALL_ARCHIVED,&EditCallRecordRequest {share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: None,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,channel_share_permissions: Some(vec![UpdateChannelSharePermission {operation: UpdateOperation::Add,channel_id: channel_id.clone(),@@ -2264,8 +2339,8 @@ async fn patch_call_record_removes_channel_share_permission(&CALL_ARCHIVED,&EditCallRecordRequest {share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: None,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,channel_share_permissions: Some(vec![UpdateChannelSharePermission {operation: UpdateOperation::Remove,channel_id: channel_id.clone(),@@ -2297,43 +2372,29 @@ async fn patch_call_record_removes_channel_share_permission(fixtures(path = "../../../fixtures", scripts("call_repo")),migrator = "MACRO_DB_MIGRATIONS")]-async fn patch_call_record_none_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn patch_call_record_empty_share_permission_update_is_noop(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {let repo = repo(pool.clone());-- let before = sqlx::query!(- r#"- SELECT "isPublic" as "is_public!", "publicAccessLevel" as "public_access_level?"- FROM "SharePermission"- WHERE id = $1- "#,- SP_ARCHIVED,- )- .fetch_one(&pool)- .await?;+ set_stored_share_permission(&pool, Some("TEAM"), Some("comment")).await?;+ let before = get_stored_share_permission(&pool, SP_ARCHIVED).await?;repo.patch_call_record(&CALL_ARCHIVED,&EditCallRecordRequest {- share_permission: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: None,+ channel_share_permissions: None,+ }),share_with_team: None,custom_name: None,},).await?;- let after = sqlx::query!(- r#"- SELECT "isPublic" as "is_public!", "publicAccessLevel" as "public_access_level?"- FROM "SharePermission"- WHERE id = $1- "#,- SP_ARCHIVED,- )- .fetch_one(&pool)- .await?;-- assert_eq!(before.is_public, after.is_public);- assert_eq!(before.public_access_level, after.public_access_level);+ let after = get_stored_share_permission(&pool, SP_ARCHIVED).await?;+ assert_eq!(before, after);Ok(())}diff --git a/crates/chat/src/domain/service/chat/test.rs b/crates/chat/src/domain/service/chat/test.rsindex 7224394528..2141419ec7 100644--- a/crates/chat/src/domain/service/chat/test.rs+++ b/crates/chat/src/domain/service/chat/test.rs@@ -383,8 +383,10 @@ fn build_service_with_tools(fn patch_args(share_permission_updated: bool) -> PatchChatArgs {let share_permission = share_permission_updated.then_some(models_permissions::share_permission::UpdateSharePermissionRequestV2 {- is_public: Some(true),- public_access_level: None,+ link_share: Some(Some(+ models_permissions::share_permission::LinkShare::Public,+ )),+ link_share_access_level: None,channel_share_permissions: None,},);diff --git a/crates/chat/src/outbound/postgres/queries/create_chat_permission.rs b/crates/chat/src/outbound/postgres/queries/create_chat_permission.rsindex 3511ba056d..976213eef7 100644--- a/crates/chat/src/outbound/postgres/queries/create_chat_permission.rs+++ b/crates/chat/src/outbound/postgres/queries/create_chat_permission.rs@@ -1,6 +1,7 @@//! Create a share permission and link it to a chat.use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::access_level::AccessLevel;use sqlx::{Postgres, Transaction};/// Create a share permission row and associate it with the given chat.@@ -10,17 +11,28 @@ pub(crate) async fn create_chat_permission(chat_id: &str,share_permission: &SharePermissionV2,) -> anyhow::Result<()> {+ let link_share = share_permission.link_share;+ let link_share_access_level = link_share.map(|_| {+ share_permission.link_share_access_level.unwrap_or_else(|| {+ tracing::warn!("link sharing was enabled without an access level, defaulting to view");+ AccessLevel::View+ })+ });+ let link_share = link_share.map(|value| value.to_string());+let permission_id = sqlx::query_scalar!(r#"- INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")+ INSERT INTO "SharePermission" (+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt"+ )VALUES ($1, $2, NOW(), NOW())RETURNING id"#,- share_permission.is_public,- share_permission- .public_access_level- .as_ref()- .map(|s| s.to_string()),+ link_share,+ link_share_access_level as _,).fetch_one(tx.as_mut()).await?;diff --git a/crates/chat/src/outbound/postgres/queries/edit_share_permission.rs b/crates/chat/src/outbound/postgres/queries/edit_share_permission.rsindex dcc4c47aeb..065388b349 100644--- a/crates/chat/src/outbound/postgres/queries/edit_share_permission.rs+++ b/crates/chat/src/outbound/postgres/queries/edit_share_permission.rs@@ -1,20 +1,14 @@//! Edit share permissions for a chat.use model_entity::EntityType;-use models_permissions::share_permission::UpdateSharePermissionRequestV2;use models_permissions::share_permission::channel_share_permission::{ChannelSharePermission, UpdateChannelSharePermission, UpdateOperation,};+use models_permissions::share_permission::{+ UpdateSharePermissionRequestV2, access_level::AccessLevel,+};use sqlx::{Postgres, Transaction};-/// Helper enum for dynamic query parameter binding.-enum Parameter {- /// A string value.- String(String),- /// A boolean value.- Bool(bool),-}-/// Edit a chat's share permission by looking up its `SharePermission` row.#[tracing::instrument(err, skip(tx))]pub(crate) async fn edit_chat_permission(@@ -39,67 +33,60 @@ pub(crate) async fn edit_chat_permission(/// Update a `SharePermission` row and its channel share permissions.#[tracing::instrument(err, skip(tx))]-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]async fn edit_share_permission(tx: &mut Transaction<'_, Postgres>,chat_id: &str,share_permission_id: &str,share_permission: &UpdateSharePermissionRequestV2,) -> anyhow::Result<()> {- let mut query = "UPDATE \"SharePermission\" SET ".to_string();- let mut parameters: Vec<Parameter> = Vec::new();- let mut set_parts = Vec::new();-- let mut ignore_public_access_level = false;- if let Some(is_public) = share_permission.is_public {- set_parts.push("\"isPublic\" = $".to_string() + &(set_parts.len() + 2).to_string());- parameters.push(Parameter::Bool(is_public));-- if is_public && share_permission.public_access_level.is_none() {- tracing::warn!(- "is_public was set to true but public access level was not provided, setting to view"- );- set_parts- .push("\"publicAccessLevel\" = $".to_string() + &(set_parts.len() + 2).to_string());- parameters.push(Parameter::String("view".to_string()));- }-- if !is_public {- ignore_public_access_level = true;- set_parts.push("\"publicAccessLevel\" = NULL".to_string());- }- }-- if let Some(public_access_level) = share_permission.public_access_level- && !ignore_public_access_level- {- set_parts- .push("\"publicAccessLevel\" = $".to_string() + &(set_parts.len() + 2).to_string());- parameters.push(Parameter::String(public_access_level.to_string()));- }-- query += &set_parts.join(", ");- if !set_parts.is_empty() {- query += ", ";- }-- query += "\"updatedAt\" = NOW() WHERE id = $1";-- let mut query = sqlx::query(&query);- query = query.bind(share_permission_id.to_string());-- for param in parameters {- match param {- Parameter::String(s) => {- query = query.bind(s);+ let update_link_share = share_permission.link_share.is_some();+ let link_share = share_permission.link_share.flatten();+ let (update_link_share_access_level, link_share_access_level) =+ match share_permission.link_share {+ Some(Some(_)) => {+ let access_level = share_permission+ .link_share_access_level+ .flatten()+ .unwrap_or_else(|| {+ tracing::warn!(+ "link sharing was enabled without an access level, defaulting to view"+ );+ AccessLevel::View+ });+ (true, Some(access_level))}- Parameter::Bool(b) => {- query = query.bind(b);- }- }- }+ Some(None) => (true, None),+ None => (+ share_permission.link_share_access_level.is_some(),+ share_permission.link_share_access_level.flatten(),+ ),+ };- query.execute(tx.as_mut()).await?;+ let link_share = link_share.map(|value| value.to_string());++ sqlx::query!(+ r#"+ UPDATE "SharePermission"+ SET+ "linkShare" = CASE WHEN $2 THEN $3 ELSE "linkShare" END,+ "linkShareAccessLevel" = CASE+ WHEN $2 AND $3 IS NULL THEN NULL+ WHEN $2 THEN COALESCE($5::"AccessLevel", 'view')+ WHEN $4 AND "linkShare" IS NOT NULL THEN COALESCE($5::"AccessLevel", 'view')+ WHEN $4 THEN NULL+ ELSE "linkShareAccessLevel"+ END,+ "updatedAt" = NOW()+ WHERE id = $1+ "#,+ share_permission_id,+ update_link_share,+ link_share,+ update_link_share_access_level,+ link_share_access_level as _,+ )+ .execute(tx.as_mut())+ .await?;if let Some(channel_share_permissions) = share_permission.channel_share_permissions.as_ref() {edit_channel_share_permissions(tx, share_permission_id, channel_share_permissions).await?;diff --git a/crates/chat/src/outbound/postgres/queries/get_permissions.rs b/crates/chat/src/outbound/postgres/queries/get_permissions.rsindex ce83b1c785..8671cc232c 100644--- a/crates/chat/src/outbound/postgres/queries/get_permissions.rs+++ b/crates/chat/src/outbound/postgres/queries/get_permissions.rs@@ -1,8 +1,8 @@//! Fetch share permissions for a chat.-use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;+use models_permissions::share_permission::{LinkShare, SharePermissionV2};use std::str::FromStr;/// Get the [`SharePermissionV2`] for a chat.@@ -15,8 +15,8 @@ pub(crate) async fn get_chat_share_permission(r#"SELECTsp.id as id,- sp."isPublic" as is_public,- sp."publicAccessLevel" as "public_access_level?",+ sp."linkShare" as "link_share?",+ sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",c."userId" as owner,COALESCE(json_agg(json_build_object(@@ -53,14 +53,14 @@ pub(crate) async fn get_chat_share_permission(None};- let public_access_level: Option<AccessLevel> = result- .public_access_level- .map(|s| AccessLevel::from_str(&s).unwrap());-+ let link_share = result+ .link_share+ .map(|value| LinkShare::from_str(&value))+ .transpose()?;Ok(SharePermissionV2 {id: result.id,- is_public: result.is_public,- public_access_level,+ link_share,+ link_share_access_level: result.link_share_access_level,owner: result.owner,channel_share_permissions,})diff --git a/crates/chat/src/outbound/postgres/test.rs b/crates/chat/src/outbound/postgres/test.rsindex d9130c53e0..7be51e1948 100644--- a/crates/chat/src/outbound/postgres/test.rs+++ b/crates/chat/src/outbound/postgres/test.rs@@ -6,12 +6,84 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model::chat::NewChatMessage;+use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::{LinkShare, UpdateSharePermissionRequestV2};use sqlx::{Pool, Postgres, Row};use super::PgChatRepo;use crate::domain::models::{ChatErr, CopyChatArgs, CreateChatArgs, PatchChatArgs};use crate::domain::ports::ChatRepo;+#[derive(Debug, Eq, PartialEq)]+struct StoredSharePermission {+ id: String,+ link_share: Option<String>,+ link_share_access_level: Option<String>,+}++async fn get_stored_share_permission(+ pool: &Pool<Postgres>,+ chat_id: &str,+) -> StoredSharePermission {+ let row = sqlx::query!(+ r#"+ SELECT+ sp.id,+ sp."linkShare" AS "link_share?",+ sp."linkShareAccessLevel"::text AS "link_share_access_level?"+ FROM "ChatPermission" cp+ JOIN "SharePermission" sp ON cp."sharePermissionId" = sp.id+ WHERE cp."chatId" = $1+ "#,+ chat_id,+ )+ .fetch_one(pool)+ .await+ .unwrap();++ StoredSharePermission {+ id: row.id,+ link_share: row.link_share,+ link_share_access_level: row.link_share_access_level,+ }+}++async fn create_test_chat(repo: &PgChatRepo, name: &str) -> String {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ repo.create(+ user_id,+ CreateChatArgs {+ name: name.to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap()+}++async fn patch_share_permission(+ repo: &PgChatRepo,+ chat_id: &str,+ share_permission: UpdateSharePermissionRequestV2,+) {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ repo.patch(+ user_id,+ chat_id,+ PatchChatArgs {+ name: None,+ project_id: None,+ share_permission: Some(share_permission),+ },+ )+ .await+ .unwrap();+}+async fn create_chat_with_message(repo: &PgChatRepo) -> (String, String) {let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()@@ -253,32 +325,14 @@ async fn nonexistent_message_does_not_bump_chat(pool: Pool<Postgres>) {migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "fixtures", scripts("users")))]-async fn create_chat_creates_permission(pool: Pool<Postgres>) {+async fn create_chat_creates_public_view_permission(pool: Pool<Postgres>) {let repo = PgChatRepo::new(pool.clone());- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned();-- let chat_id = repo- .create(- user_id,- CreateChatArgs {- name: "Perm Chat".to_string(),- project_id: None,- },- )- .await- .unwrap();-- let row =- sqlx::query(r#"SELECT "sharePermissionId" FROM "ChatPermission" WHERE "chatId" = $1"#)- .bind(&chat_id)- .fetch_one(&pool)- .await- .unwrap();+ let chat_id = create_test_chat(&repo, "Perm Chat").await;- let share_permission_id: String = row.get("sharePermissionId");- assert!(!share_permission_id.is_empty());+ let permission = get_stored_share_permission(&pool, &chat_id).await;+ assert!(!permission.id.is_empty());+ assert_eq!(permission.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(permission.link_share_access_level.as_deref(), Some("view"));}#[sqlx::test(@@ -884,26 +938,115 @@ async fn revert_delete_restores_chat(pool: Pool<Postgres>) {migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "fixtures", scripts("users")))]-async fn get_permissions_returns_share_permission(pool: Pool<Postgres>) {+async fn patch_chat_sets_team_share_and_defaults_explicit_null_level_to_view(pool: Pool<Postgres>) {let repo = PgChatRepo::new(pool.clone());- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")- .unwrap()- .into_owned();+ let chat_id = create_test_chat(&repo, "Team Chat").await;- let chat_id = repo- .create(- user_id,- CreateChatArgs {- name: "Perms Chat".to_string(),- project_id: None,- },- )- .await- .unwrap();+ patch_share_permission(+ &repo,+ &chat_id,+ UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Team)),+ link_share_access_level: Some(None),+ channel_share_permissions: None,+ },+ )+ .await;++ let permission = get_stored_share_permission(&pool, &chat_id).await;+ assert_eq!(permission.link_share.as_deref(), Some("TEAM"));+ assert_eq!(permission.link_share_access_level.as_deref(), Some("view"));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn patch_chat_defaults_explicit_null_level_for_existing_link_share(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Default View Chat").await;++ patch_share_permission(+ &repo,+ &chat_id,+ UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: Some(Some(AccessLevel::Edit)),+ channel_share_permissions: None,+ },+ )+ .await;+ patch_share_permission(+ &repo,+ &chat_id,+ UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: Some(None),+ channel_share_permissions: None,+ },+ )+ .await;++ let permission = get_stored_share_permission(&pool, &chat_id).await;+ assert_eq!(permission.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(permission.link_share_access_level.as_deref(), Some("view"));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn patch_chat_disables_link_sharing_and_clears_both_levels(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Private Chat").await;++ patch_share_permission(+ &repo,+ &chat_id,+ UpdateSharePermissionRequestV2 {+ link_share: Some(None),+ link_share_access_level: Some(Some(AccessLevel::Edit)),+ channel_share_permissions: None,+ },+ )+ .await;++ let permission = get_stored_share_permission(&pool, &chat_id).await;+ assert_eq!(permission.link_share, None);+ assert_eq!(permission.link_share_access_level, None);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn get_permissions_reads_link_share_columns(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Perms Chat").await;++ let permission = repo.get_permissions(&chat_id).await.unwrap();+ assert_eq!(permission.link_share, Some(LinkShare::Public));+ assert_eq!(permission.link_share_access_level, Some(AccessLevel::View));++ sqlx::query!(+ r#"+ UPDATE "SharePermission" sp+ SET+ "linkShare" = 'TEAM',+ "linkShareAccessLevel" = 'edit'+ FROM "ChatPermission" cp+ WHERE cp."sharePermissionId" = sp.id AND cp."chatId" = $1+ "#,+ &chat_id,+ )+ .execute(&pool)+ .await+ .unwrap();- let perms = repo.get_permissions(&chat_id).await.unwrap();+ let permission = repo.get_permissions(&chat_id).await.unwrap();- assert!(!perms.id.is_empty());- assert_eq!(perms.owner, "macro|[email protected]");- assert!(perms.is_public);+ assert!(!permission.id.is_empty());+ assert_eq!(permission.owner, "macro|[email protected]");+ assert_eq!(permission.link_share, Some(LinkShare::Team));+ assert_eq!(permission.link_share_access_level, Some(AccessLevel::Edit));}diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rsindex 9bb22b3600..6550ba7f96 100644--- a/crates/complete_graph/src/lib.rs+++ b/crates/complete_graph/src/lib.rs@@ -31,9 +31,9 @@ pub use graphql_email::{pub use graphql_entity_mutation::{ChannelSharePolicyInput, DuplicateEntityInput, EntityMutationPayload, EntityMutationRoot,EntityRefInput, EntitySharePolicyInput, GraphqlEntityMutationError,- GraphqlEntityMutationErrorCode, GraphqlEntityMutationResult, GraphqlMutationError,- GraphqlMutationSuccess, GraphqlSharePolicyOperation, MoveEntityInput, RenameEntityInput,- UpdateEntitySharePolicyInput,+ GraphqlEntityMutationErrorCode, GraphqlEntityMutationResult, GraphqlLinkShare,+ GraphqlMutationError, GraphqlMutationSuccess, GraphqlSharePolicyOperation, MoveEntityInput,+ RenameEntityInput, UpdateEntitySharePolicyInput,};pub use graphql_favorite::{EntityFavoriteEdgeReader, EntityFavoriteLoader, entity_favorite_loader,diff --git a/crates/documents/fixtures/document_pdf_comments_and_highlights.sql b/crates/documents/fixtures/document_pdf_comments_and_highlights.sqlindex 84a383bebd..0641b77df5 100644--- a/crates/documents/fixtures/document_pdf_comments_and_highlights.sql+++ b/crates/documents/fixtures/document_pdf_comments_and_highlights.sql@@ -81,15 +81,15 @@ VALUESINSERT INTOpublic."SharePermission" ("id",- "isPublic",- "publicAccessLevel",+ "linkShare",+ "linkShareAccessLevel","createdAt","updatedAt")VALUES('sp-comments',- false,+ NULL,NULL,'2022-01-01 00:00:00','2022-01-01 00:00:00'diff --git a/crates/documents/fixtures/documents_test_data.sql b/crates/documents/fixtures/documents_test_data.sqlindex f6ee8923b8..808b4749a3 100644--- a/crates/documents/fixtures/documents_test_data.sql+++ b/crates/documents/fixtures/documents_test_data.sql@@ -106,8 +106,8 @@ INSERT INTO public.entity_access (entity_id, entity_type, source_id, source_typeVALUES ('d0000000-0000-0000-0000-000000000001', 'document', 'macro|[email protected]', 'user', 'owner');-- Share permissions for document-one-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")- (SELECT 'sp-doc-one', true, 'read', NOW(), NOW());+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+ (SELECT 'sp-doc-one', 'PUBLIC', 'view', NOW(), NOW());INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd0000000-0000-0000-0000-000000000001', 'sp-doc-one');@@ -122,8 +122,8 @@ INSERT INTO comms_channel_participants (user_id, channel_id, role) VALUES('macro|[email protected]', 'c0000000-0000-0000-0000-000000000001', 'member');-- Share permissions for document-two-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")- (SELECT 'sp-doc-two', false, NOW(), NOW());+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+ (SELECT 'sp-doc-two', NULL, NULL, NOW(), NOW());INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd0000000-0000-0000-0000-000000000002', 'sp-doc-two');@@ -142,8 +142,8 @@ INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "sha") (SELECT 'project_child_doc', 'd0000000-0000-0000-0000-000000000003', 'sha-three');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")- (SELECT 'sp-doc-three', false, NOW(), NOW());+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+ (SELECT 'sp-doc-three', NULL, NULL, NOW(), NOW());INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd0000000-0000-0000-0000-000000000003', 'sp-doc-three');diff --git a/crates/documents/src/domain/models.rs b/crates/documents/src/domain/models.rsindex 8336fe6f86..df5ae3e918 100644--- a/crates/documents/src/domain/models.rs+++ b/crates/documents/src/domain/models.rs@@ -367,6 +367,8 @@ pub struct EditDocumentRepoArgs {/// Updated share permissions.pub share_permission:Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,+ /// Whether to revoke direct non-owner user access in the edit transaction.+ pub revoke_non_owner_user_access: bool,/// New file type (None = no change).pub file_type: Option<FileTypeUpdate>,}diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rsindex e7b3ea3af9..78d16eef9c 100644--- a/crates/documents/src/domain/service.rs+++ b/crates/documents/src/domain/service.rs@@ -5,6 +5,7 @@ mod tests;use entity_access_management::domain::ports::EntityAccessManagementService;use model_entity::EntityType;+use models_permissions::share_permission::{LinkShare, UpdateSharePermissionRequestV2};use models_properties::EntityReference;use models_properties::api::SetPropertyValue;use std::borrow::Cow;@@ -131,6 +132,15 @@ fn pending_content_for_file_type(file_type: Option<FileType>) -> DocumentContent}}+fn should_revoke_non_owner_user_access(+ share_permission: Option<&UpdateSharePermissionRequestV2>,+) -> bool {+ match share_permission.and_then(|permission| permission.link_share) {+ Some(Some(LinkShare::Team)) | Some(None) => true,+ Some(Some(LinkShare::Public)) | None => false,+ }+}+/// The user id to attribute a document lifecycle event to, when the caller is/// an authenticated user.fn event_actor_user_id(auth: &EntityAccessAuth) -> Option<MacroUserIdStr<'static>> {@@ -1244,6 +1254,8 @@ impl<.map(|s| FileType::clean_document_name(&s).unwrap_or(s));let share_permission_updated = args.share_permission.is_some();+ let revoke_non_owner_user_access =+ should_revoke_non_owner_user_access(args.share_permission.as_ref());self.repo.edit_document(EditDocumentRepoArgs {@@ -1251,6 +1263,7 @@ impl<document_name: document_name.clone(),project_id: args.project_id.clone(),share_permission: args.share_permission,+ revoke_non_owner_user_access,file_type: args.file_type.clone(),}).awaitdiff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rsindex 4481f36536..ac1ec214a5 100644--- a/crates/documents/src/domain/service/tests.rs+++ b/crates/documents/src/domain/service/tests.rs@@ -1653,11 +1653,50 @@ async fn test_delete_document_publishes_no_event_when_repo_fails() {assert!(event_broker.published().lock().unwrap().is_empty());}+#[tokio::test]+async fn edit_document_sets_revocation_intent_from_link_share_target() {+ for (link_share, expected_revocation) in [+ (Some(Some(LinkShare::Team)), true),+ (Some(None), true),+ (Some(Some(LinkShare::Public)), false),+ (None, false),+ ] {+ let mut repo = make_mock_repo();+ repo.expect_edit_document()+ .withf(move |args| {+ args.revoke_non_owner_user_access == expected_revocation+ && args+ .share_permission+ .as_ref()+ .is_some_and(|permission| permission.link_share == link_share)+ })+ .return_once(|_| Box::pin(std::future::ready(Ok(()))));++ make_test_service(repo)+ .edit_document(+ edit_receipt("doc-1"),+ task_document_context("doc-1"),+ EditDocumentServiceArgs {+ document_name: None,+ project_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share,+ link_share_access_level: None,+ channel_share_permissions: None,+ }),+ file_type: None,+ },+ )+ .await+ .unwrap();+ }+}+#[tokio::test]async fn test_edit_document_publishes_document_updated_event() {let mut repo = make_mock_repo();repo.expect_edit_document()- .withf(|args| args.document_id == "doc-1")+ .withf(|args| args.document_id == "doc-1" && !args.revoke_non_owner_user_access).returning(|_| Box::pin(std::future::ready(Ok(()))));let (service, event_broker) = make_test_service_with_event_broker(repo);diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rsindex 63d86ffb70..a2a14f4572 100644--- a/crates/documents/src/outbound/pg_document_repo.rs+++ b/crates/documents/src/outbound/pg_document_repo.rs@@ -544,33 +544,23 @@ impl DocumentRepo for PgDocumentRepo {.await?;if let Some(ref share_permission) = args.share_permission {- let mut document_now_private = false;-- if let Some(is_public) = share_permission.is_public- && !is_public- {- document_now_private = true;- }-edit::update_share_permission(&mut transaction, &args.document_id, share_permission).await?;+ }- // The share permission changed, if the document became private we need to update- // entity_access- if document_now_private {- let owner = edit::get_document_owner(&mut transaction, &args.document_id).await?;+ if args.revoke_non_owner_user_access {+ let owner = edit::get_document_owner(&mut transaction, &args.document_id).await?;- // SAFETY: this will not fail- let entity_id = macro_uuid::string_to_uuid(&args.document_id).unwrap();+ // SAFETY: document IDs are UUID strings.+ let entity_id = macro_uuid::string_to_uuid(&args.document_id).unwrap();- entity_access_db_utils::remove_non_owner_user_entity_access(- &mut transaction,- &entity_id,- EntityType::Document,- &owner,- )- .await?;- }+ entity_access_db_utils::remove_non_owner_user_entity_access(+ &mut transaction,+ &entity_id,+ EntityType::Document,+ &owner,+ )+ .await?;}transaction.commit().await?;diff --git a/crates/documents/src/outbound/pg_document_repo/create.rs b/crates/documents/src/outbound/pg_document_repo/create.rsindex 5c0a5d1486..8291d274c4 100644--- a/crates/documents/src/outbound/pg_document_repo/create.rs+++ b/crates/documents/src/outbound/pg_document_repo/create.rs@@ -160,17 +160,25 @@ pub async fn set_share_permission() -> Result<SharePermissionV2, sqlx::Error> {// Create share permissionlet share_permission = SharePermissionV2::new_document_share_permission(file_type);+ let link_share = share_permission.link_share.map(|value| value.to_string());+ let link_share_access_level = share_permission.link_share_access_level;+let share_permission_row = sqlx::query!(- r#"- INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")- VALUES ($1, $2, NOW(), NOW())- RETURNING id- "#,- share_permission.is_public,- share_permission.public_access_level.map(|s| s.to_string()),+ r#"+ INSERT INTO "SharePermission" (+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt")- .fetch_one(transaction.as_mut())- .await?;+ VALUES ($1, $2, NOW(), NOW())+ RETURNING id+ "#,+ link_share,+ link_share_access_level as _,+ )+ .fetch_one(transaction.as_mut())+ .await?;// Link share permission to documentsqlx::query!(diff --git a/crates/documents/src/outbound/pg_document_repo/edit.rs b/crates/documents/src/outbound/pg_document_repo/edit.rsindex 949fb4d7cf..801972a36a 100644--- a/crates/documents/src/outbound/pg_document_repo/edit.rs+++ b/crates/documents/src/outbound/pg_document_repo/edit.rs@@ -2,8 +2,9 @@use model_entity::EntityType;use models_permissions::share_permission::UpdateSharePermissionRequestV2;+use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::UpdateOperation;-use sqlx::{Postgres, Transaction};+use sqlx::{Postgres, QueryBuilder, Transaction};pub(super) async fn get_document_owner(transaction: &mut Transaction<'_, Postgres>,@@ -108,84 +109,45 @@ pub(super) async fn update_share_permission(Ok(())}-/// Update the SharePermission row (isPublic, publicAccessLevel).-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]+/// Update the SharePermission row.+#[allow(+ clippy::disallowed_methods,+ reason = "the optional fields require a dynamic SET clause; identifiers are trusted and values are bound"+)]async fn update_share_permission_row(transaction: &mut Transaction<'_, Postgres>,share_permission_id: &str,share_permission: &UpdateSharePermissionRequestV2,) -> Result<(), sqlx::Error> {- let mut set_parts = Vec::new();- let mut str_params: Vec<Option<String>> = Vec::new();- let mut bool_params: Vec<bool> = Vec::new();-- // Track parameter indices (starting at 2 since $1 is the share_permission_id)- let mut param_idx = 2u32;- // We'll track which params are bool vs string to bind in order- enum ParamType {- Bool(usize),- Str(usize),- }- let mut param_order: Vec<ParamType> = Vec::new();-- let mut ignore_public_access_level = false;- if let Some(is_public) = share_permission.is_public {- set_parts.push(format!("\"isPublic\" = ${param_idx}"));- param_idx += 1;- bool_params.push(is_public);- param_order.push(ParamType::Bool(bool_params.len() - 1));-- if is_public && share_permission.public_access_level.is_none() {- set_parts.push(format!("\"publicAccessLevel\" = ${param_idx}"));- param_idx += 1;- str_params.push(Some("view".to_string()));- param_order.push(ParamType::Str(str_params.len() - 1));- }-- if !is_public {- ignore_public_access_level = true;- set_parts.push("\"publicAccessLevel\" = NULL".to_string());- }- }-- if let Some(public_access_level) = share_permission.public_access_level- && !ignore_public_access_level- {- set_parts.push(format!("\"publicAccessLevel\" = ${param_idx}"));- // param_idx += 1; (not needed, last usage)- str_params.push(Some(public_access_level.to_string()));- param_order.push(ParamType::Str(str_params.len() - 1));- }-- if set_parts.is_empty() {- // Nothing to update on the SharePermission row, but still update timestamp- sqlx::query(r#"UPDATE "SharePermission" SET "updatedAt" = NOW() WHERE id = $1"#)- .bind(share_permission_id)- .execute(transaction.as_mut())- .await?;- return Ok(());+ let mut query =+ QueryBuilder::<Postgres>::new(r#"UPDATE "SharePermission" SET "updatedAt" = NOW()"#);++ if let Some(link_share) = share_permission.link_share {+ let access_level = link_share.map(|_| {+ share_permission+ .link_share_access_level+ .flatten()+ .unwrap_or(AccessLevel::View)+ });++ query+ .push(r#", "linkShare" = "#)+ .push_bind(link_share.map(|value| value.to_string()))+ .push(r#", "linkShareAccessLevel" = "#)+ .push_bind(access_level);+ } else if let Some(access_level) = share_permission.link_share_access_level {+ query+ .push(r#", "linkShareAccessLevel" = "#)+ .push_bind(access_level);}- let query_str = format!(- r#"UPDATE "SharePermission" SET {}, "updatedAt" = NOW() WHERE id = $1"#,- set_parts.join(", ")- );-- let mut query = sqlx::query(&query_str);- query = query.bind(share_permission_id.to_string());-- for param_type in ¶m_order {- match param_type {- ParamType::Bool(idx) => {- query = query.bind(bool_params[*idx]);- }- ParamType::Str(idx) => {- query = query.bind(str_params[*idx].clone());- }- }- }+ query+ .push(" WHERE id = ")+ .push_bind(share_permission_id)+ .build()+ .execute(transaction.as_mut())+ .await?;- query.execute(transaction.as_mut()).await?;Ok(())}diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rsindex 0e96faa952..7ae651c213 100644--- a/crates/documents/src/outbound/pg_document_repo/tests.rs+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs@@ -1,11 +1,11 @@use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::cowlike::CowLike;use model_entity::EntityType;-use models_permissions::share_permission::UpdateSharePermissionRequestV2;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::{UpdateChannelSharePermission, UpdateOperation,};+use models_permissions::share_permission::{LinkShare, UpdateSharePermissionRequestV2};use sqlx::{Pool, Postgres, Row};use crate::domain::models::{@@ -17,6 +17,9 @@ use crate::outbound::pg_document_repo::PgDocumentRepo;const TEST_TEAM_ID: uuid::Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000001");const SECOND_TEAM_ID: uuid::Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000002");+const TEST_DOCUMENT_ID: &str = "d0000000-0000-0000-0000-000000000001";+const TEST_DOCUMENT_OWNER_ID: &str = "macro|[email protected]";+const TEST_DOCUMENT_NON_OWNER_ID: &str = "macro|[email protected]";fn user_id(user_id: &str) -> macro_user_id::user_id::MacroUserIdStr<'static> {macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)@@ -98,6 +101,70 @@ async fn insert_github_pr_task(.unwrap();}+#[derive(Debug, Eq, PartialEq)]+struct SharePermissionColumns {+ link_share: Option<String>,+ link_share_access_level: Option<String>,+}++async fn share_permission_columns(+ pool: &Pool<Postgres>,+ document_id: &str,+) -> SharePermissionColumns {+ sqlx::query_as!(+ SharePermissionColumns,+ r#"+ SELECT+ sp."linkShare" as "link_share?",+ sp."linkShareAccessLevel"::text as "link_share_access_level?"+ FROM "SharePermission" sp+ JOIN "DocumentPermission" dp ON dp."sharePermissionId" = sp.id+ WHERE dp."documentId" = $1+ "#,+ document_id,+ )+ .fetch_one(pool)+ .await+ .unwrap()+}++async fn insert_non_owner_user_access(pool: &Pool<Postgres>) {+ let document_id = macro_uuid::string_to_uuid(TEST_DOCUMENT_ID).unwrap();++ sqlx::query!(+ r#"+ INSERT INTO entity_access+ (entity_id, entity_type, source_id, source_type, access_level)+ VALUES ($1, 'document', $2, 'user', 'edit')+ "#,+ document_id,+ TEST_DOCUMENT_NON_OWNER_ID,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn direct_user_access_sources(pool: &Pool<Postgres>) -> Vec<String> {+ let document_id = macro_uuid::string_to_uuid(TEST_DOCUMENT_ID).unwrap();++ sqlx::query_scalar!(+ r#"+ SELECT source_id+ FROM entity_access+ WHERE entity_id = $1+ AND entity_type = 'document'+ AND source_type = 'user'+ AND granted_from_project_id IS NULL+ ORDER BY source_id+ "#,+ document_id,+ )+ .fetch_all(pool)+ .await+ .unwrap()+}+async fn insert_second_team(pool: &Pool<Postgres>) {sqlx::query(r#"@@ -297,6 +364,23 @@ async fn test_get_user_view_location(pool: Pool<Postgres>) {assert!(location.is_none());}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_create_document_writes_link_share_fields(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ let document = repo+ .create_document(create_document_args(TEST_DOCUMENT_OWNER_ID, false, None))+ .await+ .unwrap();++ let result = share_permission_columns(&pool, &document.document_id).await;++ assert_eq!(result.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(result.link_share_access_level.as_deref(), Some("edit"));+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data"))@@ -309,6 +393,7 @@ async fn test_edit_document_name(pool: Pool<Postgres>) {document_name: Some("new-name".to_string()),project_id: None,share_permission: None,+ revoke_non_owner_user_access: false,file_type: None,}).await@@ -333,6 +418,7 @@ async fn test_edit_document_set_file_type(pool: Pool<Postgres>) {document_name: None,project_id: None,share_permission: None,+ revoke_non_owner_user_access: false,file_type: Some(FileTypeUpdate::Set(model::document::FileType::Rs)),}).await@@ -357,6 +443,7 @@ async fn test_edit_document_clear_file_type(pool: Pool<Postgres>) {document_name: None,project_id: None,share_permission: None,+ revoke_non_owner_user_access: false,file_type: Some(FileTypeUpdate::Clear),}).await@@ -381,6 +468,7 @@ async fn test_edit_document_project(pool: Pool<Postgres>) {document_name: None,project_id: Some("d0000000-0000-0000-0000-100000000001".to_string()),share_permission: None,+ revoke_non_owner_user_access: false,file_type: None,}).await@@ -409,6 +497,7 @@ async fn test_edit_document_remove_project(pool: Pool<Postgres>) {document_name: None,project_id: Some("d0000000-0000-0000-0000-100000000001".to_string()),share_permission: None,+ revoke_non_owner_user_access: false,file_type: None,}).await@@ -429,6 +518,7 @@ async fn test_edit_document_remove_project(pool: Pool<Postgres>) {document_name: None,project_id: Some("".to_string()),share_permission: None,+ revoke_non_owner_user_access: false,file_type: None,}).await@@ -445,76 +535,121 @@ async fn test_edit_document_remove_project(pool: Pool<Postgres>) {migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data")))]-async fn test_edit_document_share_permission(pool: Pool<Postgres>) {+async fn test_edit_document_public_to_null_revokes_non_owner_access(pool: Pool<Postgres>) {let repo = PgDocumentRepo::new(pool.clone());+ insert_non_owner_user_access(&pool).await;repo.edit_document(EditDocumentRepoArgs {- document_id: "d0000000-0000-0000-0000-000000000001".to_string(),+ document_id: TEST_DOCUMENT_ID.to_string(),document_name: None,project_id: None,share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: Some(false),- public_access_level: None,+ link_share: Some(None),+ link_share_access_level: Some(None),channel_share_permissions: None,}),+ revoke_non_owner_user_access: true,file_type: None,}).await.unwrap();- // Verify the share permission was updated- let result = sqlx::query!(- r#"- SELECT sp."isPublic" as is_public, sp."publicAccessLevel" as "public_access_level?"- FROM "SharePermission" sp- JOIN "DocumentPermission" dp ON dp."sharePermissionId" = sp.id- WHERE dp."documentId" = $1- "#,- "d0000000-0000-0000-0000-000000000001"- )- .fetch_one(&pool)+ let result = share_permission_columns(&pool, TEST_DOCUMENT_ID).await;++ assert_eq!(result.link_share, None);+ assert_eq!(result.link_share_access_level, None);+ assert_eq!(+ direct_user_access_sources(&pool).await,+ vec![TEST_DOCUMENT_OWNER_ID.to_string()]+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_edit_document_public_to_team_revokes_non_owner_access(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool.clone());+ insert_non_owner_user_access(&pool).await;++ repo.edit_document(EditDocumentRepoArgs {+ document_id: TEST_DOCUMENT_ID.to_string(),+ document_name: None,+ project_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Team)),+ link_share_access_level: Some(Some(AccessLevel::Comment)),+ channel_share_permissions: None,+ }),+ revoke_non_owner_user_access: true,+ file_type: None,+ }).await.unwrap();- assert!(!result.is_public);- assert!(result.public_access_level.is_none());+ let result = share_permission_columns(&pool, TEST_DOCUMENT_ID).await;++ assert_eq!(result.link_share.as_deref(), Some("TEAM"));+ assert_eq!(result.link_share_access_level.as_deref(), Some("comment"));+ assert_eq!(+ direct_user_access_sources(&pool).await,+ vec![TEST_DOCUMENT_OWNER_ID.to_string()]+ );}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("documents_test_data")))]-async fn test_edit_document_set_public_access_level(pool: Pool<Postgres>) {+async fn test_edit_document_omitted_link_share_does_not_revoke(pool: Pool<Postgres>) {let repo = PgDocumentRepo::new(pool.clone());+ insert_non_owner_user_access(&pool).await;repo.edit_document(EditDocumentRepoArgs {- document_id: "d0000000-0000-0000-0000-000000000001".to_string(),+ document_id: TEST_DOCUMENT_ID.to_string(),document_name: None,project_id: None,share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: None,- public_access_level: Some(AccessLevel::Edit),+ link_share: None,+ link_share_access_level: Some(Some(AccessLevel::Edit)),channel_share_permissions: None,}),+ revoke_non_owner_user_access: false,file_type: None,}).await.unwrap();- let result = sqlx::query!(- r#"- SELECT sp."publicAccessLevel" as "public_access_level?"- FROM "SharePermission" sp- JOIN "DocumentPermission" dp ON dp."sharePermissionId" = sp.id- WHERE dp."documentId" = $1- "#,- "d0000000-0000-0000-0000-000000000001"- )- .fetch_one(&pool)+ let result = share_permission_columns(&pool, TEST_DOCUMENT_ID).await;++ assert_eq!(result.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(result.link_share_access_level.as_deref(), Some("edit"));++ repo.edit_document(EditDocumentRepoArgs {+ document_id: TEST_DOCUMENT_ID.to_string(),+ document_name: None,+ project_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: Some(None),+ channel_share_permissions: None,+ }),+ revoke_non_owner_user_access: false,+ file_type: None,+ }).await.unwrap();- assert_eq!(result.public_access_level, Some("edit".to_string()));+ let result = share_permission_columns(&pool, TEST_DOCUMENT_ID).await;+ assert_eq!(result.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(result.link_share_access_level, None);+ assert_eq!(+ direct_user_access_sources(&pool).await,+ vec![+ TEST_DOCUMENT_NON_OWNER_ID.to_string(),+ TEST_DOCUMENT_OWNER_ID.to_string(),+ ]+ );}#[sqlx::test(@@ -523,46 +658,41 @@ async fn test_edit_document_set_public_access_level(pool: Pool<Postgres>) {)]async fn test_edit_document_name_and_project(pool: Pool<Postgres>) {let repo = PgDocumentRepo::new(pool.clone());+ insert_non_owner_user_access(&pool).await;repo.edit_document(EditDocumentRepoArgs {document_id: "d0000000-0000-0000-0000-000000000001".to_string(),document_name: Some("renamed".to_string()),project_id: Some("d0000000-0000-0000-0000-100000000001".to_string()),share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: Some(true),- public_access_level: Some(AccessLevel::Edit),+ link_share: Some(Some(LinkShare::Public)),+ link_share_access_level: Some(Some(AccessLevel::Edit)),channel_share_permissions: None,}),+ revoke_non_owner_user_access: false,file_type: None,}).await.unwrap();- let doc = repo- .get_basic_document("d0000000-0000-0000-0000-000000000001")- .await- .unwrap();+ let doc = repo.get_basic_document(TEST_DOCUMENT_ID).await.unwrap();assert_eq!(doc.document_name, "renamed");assert_eq!(doc.project_id,Some("d0000000-0000-0000-0000-100000000001".to_string()));- let result = sqlx::query!(- r#"- SELECT sp."isPublic" as is_public, sp."publicAccessLevel" as "public_access_level?"- FROM "SharePermission" sp- JOIN "DocumentPermission" dp ON dp."sharePermissionId" = sp.id- WHERE dp."documentId" = $1- "#,- "d0000000-0000-0000-0000-000000000001"- )- .fetch_one(&pool)- .await- .unwrap();+ let result = share_permission_columns(&pool, TEST_DOCUMENT_ID).await;- assert!(result.is_public);- assert_eq!(result.public_access_level, Some("edit".to_string()));+ assert_eq!(result.link_share.as_deref(), Some("PUBLIC"));+ assert_eq!(result.link_share_access_level.as_deref(), Some("edit"));+ assert_eq!(+ direct_user_access_sources(&pool).await,+ vec![+ TEST_DOCUMENT_NON_OWNER_ID.to_string(),+ TEST_DOCUMENT_OWNER_ID.to_string(),+ ]+ );}#[sqlx::test(@@ -1241,14 +1371,15 @@ async fn test_edit_document_channel_share_creates_user_item_access(pool: Pool<Podocument_name: None,project_id: None,share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: None,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,channel_share_permissions: Some(vec![UpdateChannelSharePermission {operation: UpdateOperation::Add,channel_id: channel_id.to_string(),access_level: Some(AccessLevel::View),}]),}),+ revoke_non_owner_user_access: false,file_type: None,}).await@@ -1313,14 +1444,15 @@ async fn test_edit_document_channel_share_idempotent(pool: Pool<Postgres>) {document_name: None,project_id: None,share_permission: Some(UpdateSharePermissionRequestV2 {- is_public: None,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,channel_share_permissions: Some(vec![UpdateChannelSharePermission {operation: UpdateOperation::Add,channel_id: channel_id.to_string(),access_level: Some(AccessLevel::View),}]),}),+ revoke_non_owner_user_access: false,file_type: None,};diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/mod.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/mod.rsindex 8a32fc51a8..5ec904ea6c 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/mod.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/mod.rs@@ -19,25 +19,29 @@ pub async fn get_call_access(let access_level = sqlx::query_scalar!(r#"SELECT- "publicAccessLevel" as "access_level!"- FROM "SharePermission"- WHERE id in (SELECT share_permission_id- FROM calls- WHERE id = $1- UNION ALL- SELECT share_permission_id- FROM call_records- WHERE id = $1- LIMIT 1)- AND "isPublic" = true- AND "publicAccessLevel" IS NOT NULL+ share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel"+ FROM "SharePermission" share_permission+ JOIN (+ SELECT share_permission_id+ FROM calls+ WHERE id = $1++ UNION ALL++ SELECT share_permission_id+ FROM call_records+ WHERE id = $1+ LIMIT 1+ ) call_item ON call_item.share_permission_id = share_permission.id+ WHERE share_permission."linkShare" = 'PUBLIC'+ AND share_permission."linkShareAccessLevel" IS NOT NULL"#,- &call_id+ call_id,).fetch_optional(pool).await?;- return Ok(access_level.and_then(|level| AccessLevel::from_str(&level).ok()));+ return Ok(access_level);}let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(@@ -51,22 +55,35 @@ pub async fn get_call_access(AND source_id = ANY($2)UNION ALL- -- Source 2: items share permission+ -- Source 2: call link share permissionSELECT- "publicAccessLevel"::text AS access_level- FROM "SharePermission"- WHERE id in (- SELECT share_permission_id+ share_permission."linkShareAccessLevel"::text AS access_level+ FROM "SharePermission" share_permission+ JOIN (+ SELECT share_permission_id, created_byFROM callsWHERE id = $1+UNION ALL- SELECT share_permission_id++ SELECT share_permission_id, created_byFROM call_recordsWHERE id = $1LIMIT 1- )- AND "isPublic" = true- AND "publicAccessLevel" IS NOT NULL+ ) call_item ON call_item.share_permission_id = share_permission.id+ WHERE share_permission."linkShareAccessLevel" IS NOT NULL+ AND (+ share_permission."linkShare" = 'PUBLIC'+ OR (+ share_permission."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1+ FROM team_user owner_team+ WHERE owner_team.user_id = call_item.created_by+ AND owner_team.team_id::text = ANY($2)+ )+ )+ )) AS combined_access"#,call_id,diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rsindex df9a305ecb..ae88a7038f 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/call_access/test.rs@@ -1,258 +1,439 @@-#[allow(unused_imports)]use super::*;-use crate::domain::models::AccessLevel;use macro_db_migrator::MACRO_DB_MIGRATIONS;use sqlx::PgPool;use uuid::Uuid;-async fn insert_channel(pool: &PgPool, channel_id: Uuid) {+const OWNER_WITH_TEAM: &str = "macro|[email protected]";+const OWNER_WITHOUT_TEAM: &str = "macro|[email protected]";+const REQUESTER: &str = "macro|[email protected]";+const DIRECT_SOURCE_ID: &str = "macro|[email protected]";+const CHANNEL_SOURCE_ID: &str = "00000000-0000-0000-0000-00000000ca11";+const TEAM_SOURCE_ID: &str = "00000000-0000-0000-0000-000000007ea1";+const OWNER_TEAM: Uuid = Uuid::from_u128(0x000000000000000000000000000ca101);+const OTHER_TEAM: Uuid = Uuid::from_u128(0x000000000000000000000000000ca102);++#[derive(Clone, Copy, Debug)]+enum CallTable {+ Calls,+ CallRecords,+}++impl CallTable {+ const ALL: [Self; 2] = [Self::Calls, Self::CallRecords];+}++#[derive(Clone, Copy)]+struct LinkAccessCase {+ link_share: Option<&'static str>,+ link_access_level: Option<&'static str>,+ anonymous: Option<AccessLevel>,+ other_team: Option<AccessLevel>,+ same_team: Option<AccessLevel>,+}++const LINK_ACCESS_CASES: [LinkAccessCase; 4] = [+ LinkAccessCase {+ link_share: None,+ link_access_level: None,+ anonymous: None,+ other_team: None,+ same_team: None,+ },+ LinkAccessCase {+ link_share: Some("PUBLIC"),+ link_access_level: Some("view"),+ anonymous: Some(AccessLevel::View),+ other_team: Some(AccessLevel::View),+ same_team: Some(AccessLevel::View),+ },+ LinkAccessCase {+ link_share: Some("PUBLIC"),+ link_access_level: None,+ anonymous: None,+ other_team: None,+ same_team: None,+ },+ LinkAccessCase {+ link_share: Some("TEAM"),+ link_access_level: Some("comment"),+ anonymous: None,+ other_team: None,+ same_team: Some(AccessLevel::Comment),+ },+];++async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {+ let macro_user_id = Uuid::new_v4();+ let email = user_id.strip_prefix("macro|").unwrap_or(user_id);+sqlx::query!(r#"- INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id)- VALUES ($1, 'test', 'public', NULL, 'owner')+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $2)"#,- channel_id+ macro_user_id,+ user_id,+ email,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ user_id,+ email,+ macro_user_id,).execute(pool)- .await- .unwrap();+ .await?;++ Ok(())}-async fn insert_share_permission(- pool: &PgPool,- id: &str,- is_public: bool,- access_level: Option<&str>,-) {+async fn add_owner_to_team(pool: &PgPool, owner_id: &str, team_id: Uuid) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Call Owner Team', $2)"#,+ team_id,+ owner_id,+ )+ .execute(pool)+ .await?;+sqlx::query!(r#"- INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel")- VALUES ($1, $2, $3)+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, 'owner')"#,- id,- is_public,- access_level,+ owner_id,+ team_id,).execute(pool)- .await- .unwrap();+ .await?;++ Ok(())}-async fn insert_call(pool: &PgPool, call_id: Uuid, channel_id: Uuid, share_permission_id: &str) {+async fn insert_channel(pool: &PgPool, channel_id: Uuid, owner_id: &str) -> anyhow::Result<()> {sqlx::query!(r#"- INSERT INTO calls (id, channel_id, room_name, created_by, share_permission_id)- VALUES ($1, $2, 'room', 'creator', $3)+ INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id)+ VALUES ($1, 'Call Access Test', 'public', NULL, $2)"#,- call_id,channel_id,- share_permission_id,+ owner_id,).execute(pool)- .await- .unwrap();+ .await?;++ Ok(())}-async fn insert_call_record(+async fn insert_share_permission(pool: &PgPool,- call_id: Uuid,- channel_id: Uuid,- share_permission_id: &str,-) {+ link_share: Option<&str>,+ link_access_level: Option<&str>,+) -> anyhow::Result<String> {+ let share_permission_id = Uuid::new_v4().to_string();+sqlx::query!(r#"- INSERT INTO call_records (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms, share_permission_id)- VALUES ($1, $2, 'room', 'creator', NOW() - INTERVAL '1 hour', NOW(), 3600000, $3)+ INSERT INTO "SharePermission" (+ id,+ "linkShare",+ "linkShareAccessLevel"+ )+ VALUES ($1, $2, $3::text::"AccessLevel")"#,- call_id,- channel_id,share_permission_id,+ link_share,+ link_access_level,).execute(pool)- .await- .unwrap();+ .await?;++ Ok(share_permission_id)+}++async fn insert_link_shared_call(+ pool: &PgPool,+ call_table: CallTable,+ owner_id: &str,+ link_share: Option<&str>,+ link_access_level: Option<&str>,+) -> anyhow::Result<Uuid> {+ let call_id = Uuid::new_v4();+ let channel_id = Uuid::new_v4();+ let share_permission_id = insert_share_permission(pool, link_share, link_access_level).await?;+ insert_channel(pool, channel_id, owner_id).await?;++ match call_table {+ CallTable::Calls => {+ sqlx::query!(+ r#"+ INSERT INTO calls (+ id,+ channel_id,+ room_name,+ created_by,+ share_permission_id+ )+ VALUES ($1, $2, 'call-access-test', $3, $4)+ "#,+ call_id,+ channel_id,+ owner_id,+ share_permission_id,+ )+ .execute(pool)+ .await?;+ }+ CallTable::CallRecords => {+ sqlx::query!(+ r#"+ INSERT INTO call_records (+ id,+ channel_id,+ room_name,+ created_by,+ started_at,+ ended_at,+ duration_ms,+ share_permission_id+ )+ VALUES (+ $1,+ $2,+ 'call-access-test',+ $3,+ NOW() - INTERVAL '1 hour',+ NOW(),+ 3600000,+ $4+ )+ "#,+ call_id,+ channel_id,+ owner_id,+ share_permission_id,+ )+ .execute(pool)+ .await?;+ }+ }++ Ok(call_id)}async fn insert_entity_access(pool: &PgPool,- entity_id: Uuid,+ call_id: Uuid,source_id: &str,+ source_type: &str,access_level: AccessLevel,-) {- let level_str = access_level.to_string();+) -> anyhow::Result<()> {sqlx::query!(r#"- INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)- VALUES ($1, 'call', $2, 'user', $3::text::"AccessLevel")+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level+ )+ VALUES (+ $1,+ 'call',+ $2,+ $3::text::entity_access_source_type,+ $4::text::"AccessLevel"+ )"#,- entity_id,+ call_id,source_id,- level_str,+ source_type,+ access_level.to_string(),).execute(pool)- .await- .unwrap();-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_none_when_call_does_not_exist(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let source_ids = SourceIds(vec!["macro|[email protected]".to_string()]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;+ .await?;- assert_eq!(result, None);Ok(())}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_none_when_no_source_ids_and_not_public(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();-- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, false, None).await;- insert_call(&pool, call_id, channel_id, &sp_id).await;-- let source_ids = SourceIds(vec![]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;-- assert_eq!(result, None);- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_public_access_when_no_source_ids_and_public(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();-- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, true, Some("view")).await;- insert_call(&pool, call_id, channel_id, &sp_id).await;-- let source_ids = SourceIds(vec![]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;-- assert_eq!(result, Some(AccessLevel::View));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_direct_user_access_from_entity_access(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();- let user_id = "macro|[email protected]";-- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, false, None).await;- insert_call(&pool, call_id, channel_id, &sp_id).await;- insert_entity_access(&pool, call_id, user_id, AccessLevel::Edit).await;-- let source_ids = SourceIds(vec![user_id.to_string()]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;-- assert_eq!(result, Some(AccessLevel::Edit));- Ok(())-}--#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_highest_of_direct_and_public_access(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();- let user_id = "macro|[email protected]";-- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, true, Some("view")).await;- insert_call(&pool, call_id, channel_id, &sp_id).await;- insert_entity_access(&pool, call_id, user_id, AccessLevel::Edit).await;-- let source_ids = SourceIds(vec![user_id.to_string()]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;+async fn returns_none_when_call_does_not_exist(pool: PgPool) -> anyhow::Result<()> {+ let access = get_call_access(+ &pool,+ &Uuid::new_v4(),+ &SourceIds(vec![REQUESTER.to_string()]),+ )+ .await?;- assert_eq!(result, Some(AccessLevel::Edit));+ assert_eq!(access, None);Ok(())}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn public_access_wins_when_higher_than_direct(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();- let user_id = "macro|[email protected]";+async fn enforces_link_access_for_calls_and_call_records(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, OWNER_TEAM).await?;++ let anonymous = SourceIds(vec![]);+ let other_team = SourceIds(vec![REQUESTER.to_string(), OTHER_TEAM.to_string()]);+ let same_team = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);++ for call_table in CallTable::ALL {+ for case in LINK_ACCESS_CASES {+ let call_id = insert_link_shared_call(+ &pool,+ call_table,+ OWNER_WITH_TEAM,+ case.link_share,+ case.link_access_level,+ )+ .await?;++ assert_eq!(+ get_call_access(&pool, &call_id, &anonymous).await?,+ case.anonymous,+ "anonymous access for {call_table:?} with {:?}",+ case.link_share,+ );+ assert_eq!(+ get_call_access(&pool, &call_id, &other_team).await?,+ case.other_team,+ "other-team access for {call_table:?} with {:?}",+ case.link_share,+ );+ assert_eq!(+ get_call_access(&pool, &call_id, &same_team).await?,+ case.same_team,+ "same-team access for {call_table:?} with {:?}",+ case.link_share,+ );+ }+ }- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, true, Some("edit")).await;- insert_call(&pool, call_id, channel_id, &sp_id).await;- insert_entity_access(&pool, call_id, user_id, AccessLevel::View).await;-- let source_ids = SourceIds(vec![user_id.to_string()]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;-- assert_eq!(result, Some(AccessLevel::Edit));Ok(())}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_none_when_user_has_no_access(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();-- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, false, None).await;- insert_call(&pool, call_id, channel_id, &sp_id).await;+async fn team_link_denies_when_call_owner_has_no_team(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let requester = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);++ for call_table in CallTable::ALL {+ let call_id = insert_link_shared_call(+ &pool,+ call_table,+ OWNER_WITHOUT_TEAM,+ Some("TEAM"),+ Some("edit"),+ )+ .await?;++ assert_eq!(+ get_call_access(&pool, &call_id, &requester).await?,+ None,+ "TEAM access for {call_table:?}",+ );+ }- let source_ids = SourceIds(vec!["macro|[email protected]".to_string()]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;-- assert_eq!(result, None);Ok(())}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn resolves_access_from_call_records(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();-- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, true, Some("view")).await;- insert_call_record(&pool, call_id, channel_id, &sp_id).await;-- let source_ids = SourceIds(vec![]);+async fn preserves_user_channel_and_team_entity_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let grants = [+ (DIRECT_SOURCE_ID, "user", AccessLevel::View),+ (CHANNEL_SOURCE_ID, "channel", AccessLevel::Comment),+ (TEAM_SOURCE_ID, "team", AccessLevel::Edit),+ ];++ for call_table in CallTable::ALL {+ let call_id =+ insert_link_shared_call(&pool, call_table, OWNER_WITHOUT_TEAM, None, None).await?;++ for (source_id, source_type, access_level) in grants {+ insert_entity_access(&pool, call_id, source_id, source_type, access_level).await?;+ }++ for (source_id, _, access_level) in grants {+ let source_ids = SourceIds(vec![source_id.to_string()]);+ assert_eq!(+ get_call_access(&pool, &call_id, &source_ids).await?,+ Some(access_level),+ "{source_id} grant for {call_table:?}",+ );+ }++ let all_sources = SourceIds(+ grants+ .iter()+ .map(|(source_id, _, _)| source_id.to_string())+ .collect(),+ );+ assert_eq!(+ get_call_access(&pool, &call_id, &all_sources).await?,+ Some(AccessLevel::Edit),+ "highest explicit grant for {call_table:?}",+ );+ }- let result = get_call_access(&pool, &call_id, &source_ids).await?;-- assert_eq!(result, Some(AccessLevel::View));Ok(())}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn returns_owner_access_from_entity_access(pool: PgPool) -> anyhow::Result<()> {- let call_id = Uuid::new_v4();- let channel_id = Uuid::new_v4();- let sp_id = Uuid::new_v4().to_string();- let user_id = "macro|[email protected]";-- insert_channel(&pool, channel_id).await;- insert_share_permission(&pool, &sp_id, false, None).await;- insert_call(&pool, call_id, channel_id, &sp_id).await;- insert_entity_access(&pool, call_id, user_id, AccessLevel::Owner).await;-- let source_ids = SourceIds(vec![user_id.to_string()]);-- let result = get_call_access(&pool, &call_id, &source_ids).await?;+async fn returns_highest_link_or_explicit_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let requester = SourceIds(vec![DIRECT_SOURCE_ID.to_string()]);++ for call_table in CallTable::ALL {+ let explicit_wins = insert_link_shared_call(+ &pool,+ call_table,+ OWNER_WITHOUT_TEAM,+ Some("PUBLIC"),+ Some("view"),+ )+ .await?;+ insert_entity_access(+ &pool,+ explicit_wins,+ DIRECT_SOURCE_ID,+ "user",+ AccessLevel::Edit,+ )+ .await?;++ let link_wins = insert_link_shared_call(+ &pool,+ call_table,+ OWNER_WITHOUT_TEAM,+ Some("PUBLIC"),+ Some("edit"),+ )+ .await?;+ insert_entity_access(+ &pool,+ link_wins,+ DIRECT_SOURCE_ID,+ "user",+ AccessLevel::View,+ )+ .await?;++ assert_eq!(+ get_call_access(&pool, &explicit_wins, &requester).await?,+ Some(AccessLevel::Edit),+ "explicit access for {call_table:?}",+ );+ assert_eq!(+ get_call_access(&pool, &link_wins, &requester).await?,+ Some(AccessLevel::Edit),+ "link access for {call_table:?}",+ );+ }- assert_eq!(result, Some(AccessLevel::Owner));Ok(())}diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rsindex dc9a152600..659b9f3b5b 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access.rs@@ -1,5 +1,8 @@//! Query for chat access level.+#[cfg(test)]+mod test;+use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};use sqlx::PgPool;use std::str::FromStr;@@ -16,13 +19,12 @@ pub async fn get_chat_access(let access_level = sqlx::query_scalar!(r#"SELECT- "publicAccessLevel" as "access_level!"- FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL- AND id IN (- SELECT "sharePermissionId" FROM "ChatPermission" WHERE "chatId" = $1- )+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel"+ FROM "SharePermission" sp+ JOIN "ChatPermission" cp ON cp."sharePermissionId" = sp.id+ WHERE cp."chatId" = $1+ AND sp."linkShare" = 'PUBLIC'+ AND sp."linkShareAccessLevel" IS NOT NULL"#,&chat_id.to_string()@@ -30,7 +32,7 @@ pub async fn get_chat_access(.fetch_optional(pool).await?;- return Ok(access_level.and_then(|level| AccessLevel::from_str(&level).ok()));+ return Ok(access_level);}let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(@@ -44,15 +46,26 @@ pub async fn get_chat_access(AND source_id = ANY($2)UNION ALL- -- Source 2: items share permission+ -- Source 2: chat link share permissionSELECT- "publicAccessLevel"::text AS access_level- FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL- AND id IN (- SELECT "sharePermissionId" FROM "ChatPermission" WHERE "chatId" = $3- )+ sp."linkShareAccessLevel"::text AS access_level+ FROM "SharePermission" sp+ JOIN "ChatPermission" cp ON cp."sharePermissionId" = sp.id+ WHERE cp."chatId" = $3+ AND sp."linkShareAccessLevel" IS NOT NULL+ AND (+ sp."linkShare" = 'PUBLIC'+ OR (+ sp."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1+ FROM "Chat" c+ JOIN team_user owner_tu ON owner_tu.user_id = c."userId"+ WHERE c.id = $3+ AND owner_tu.team_id::text = ANY($2)+ )+ )+ )) AS combined_access"#,chat_id,diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access/test.rsnew file mode 100644index 0000000000..566e0dcc91--- /dev/null+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access/test.rs@@ -0,0 +1,238 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++const OWNER_WITH_TEAM: &str = "macro|[email protected]";+const OWNER_WITHOUT_TEAM: &str = "macro|[email protected]";+const REQUESTER: &str = "macro|[email protected]";+const OWNER_TEAM: Uuid = Uuid::from_u128(0x000000000000000000000000000c4a01);+const OTHER_TEAM: Uuid = Uuid::from_u128(0x000000000000000000000000000c4a02);++#[derive(Clone, Copy)]+struct LinkAccessCase {+ link_share: Option<&'static str>,+ link_access_level: Option<&'static str>,+ anonymous: Option<AccessLevel>,+ other_team: Option<AccessLevel>,+ same_team: Option<AccessLevel>,+}++// Complete link-only access matrix. Explicit grants are tested separately.+const LINK_ACCESS_CASES: [LinkAccessCase; 3] = [+ LinkAccessCase {+ link_share: None,+ link_access_level: None,+ anonymous: None,+ other_team: None,+ same_team: None,+ },+ LinkAccessCase {+ link_share: Some("PUBLIC"),+ link_access_level: Some("view"),+ anonymous: Some(AccessLevel::View),+ other_team: Some(AccessLevel::View),+ same_team: Some(AccessLevel::View),+ },+ LinkAccessCase {+ link_share: Some("TEAM"),+ link_access_level: Some("view"),+ anonymous: None,+ other_team: None,+ same_team: Some(AccessLevel::View),+ },+];++async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {+ let macro_user_id = Uuid::new_v4();+ let email = user_id.strip_prefix("macro|").unwrap_or(user_id);++ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $2)+ "#,+ macro_user_id,+ user_id,+ email,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ user_id,+ email,+ macro_user_id,+ )+ .execute(pool)+ .await?;+ Ok(())+}++async fn add_owner_to_team(pool: &PgPool, owner_id: &str, team_id: Uuid) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Chat Owner Team', $2)"#,+ team_id,+ owner_id,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, 'owner')"#,+ owner_id,+ team_id,+ )+ .execute(pool)+ .await?;+ Ok(())+}++async fn insert_chat(+ pool: &PgPool,+ owner_id: &str,+ link_share: Option<&str>,+ link_access_level: Option<&str>,+) -> anyhow::Result<Uuid> {+ let chat_id = Uuid::new_v4();+ let chat_id_string = chat_id.to_string();+ let share_permission_id = Uuid::new_v4().to_string();++ sqlx::query!(+ r#"+ INSERT INTO "SharePermission" (id, "linkShare", "linkShareAccessLevel")+ VALUES ($1, $2, $3::text::"AccessLevel")+ "#,+ share_permission_id,+ link_share,+ link_access_level,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"INSERT INTO "Chat" (id, "userId", name) VALUES ($1, $2, 'Test Chat')"#,+ chat_id_string,+ owner_id,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "ChatPermission" ("chatId", "sharePermissionId")+ VALUES ($1, $2)+ "#,+ chat_id_string,+ share_permission_id,+ )+ .execute(pool)+ .await?;++ Ok(chat_id)+}++async fn insert_explicit_access(+ pool: &PgPool,+ chat_id: Uuid,+ source_id: &str,+ access_level: AccessLevel,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level+ )+ VALUES ($1, 'chat', $2, 'user', $3)+ "#,+ chat_id,+ source_id,+ access_level as AccessLevel,+ )+ .execute(pool)+ .await?;+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn enforces_complete_link_access_matrix(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, OWNER_TEAM).await?;++ let anonymous = SourceIds(vec![]);+ let other_team = SourceIds(vec![REQUESTER.to_string(), OTHER_TEAM.to_string()]);+ let same_team = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);++ for case in LINK_ACCESS_CASES {+ let chat_id = insert_chat(+ &pool,+ OWNER_WITH_TEAM,+ case.link_share,+ case.link_access_level,+ )+ .await?;++ assert_eq!(+ get_chat_access(&pool, &chat_id, &anonymous).await?,+ case.anonymous,+ "anonymous access for {:?}",+ case.link_share,+ );+ assert_eq!(+ get_chat_access(&pool, &chat_id, &other_team).await?,+ case.other_team,+ "other-team access for {:?}",+ case.link_share,+ );+ assert_eq!(+ get_chat_access(&pool, &chat_id, &same_team).await?,+ case.same_team,+ "same-team access for {:?}",+ case.link_share,+ );+ }++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_access_when_owner_has_no_team(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let chat_id = insert_chat(&pool, OWNER_WITHOUT_TEAM, Some("TEAM"), Some("view")).await?;+ let requester = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);++ let access = get_chat_access(&pool, &chat_id, &requester).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn takes_maximum_of_link_and_explicit_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, OWNER_TEAM).await?;+ let requester = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);++ let explicit_wins_chat =+ insert_chat(&pool, OWNER_WITH_TEAM, Some("PUBLIC"), Some("view")).await?;+ insert_explicit_access(&pool, explicit_wins_chat, REQUESTER, AccessLevel::Edit).await?;++ let link_wins_chat = insert_chat(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("edit")).await?;+ insert_explicit_access(&pool, link_wins_chat, REQUESTER, AccessLevel::View).await?;++ assert_eq!(+ get_chat_access(&pool, &explicit_wins_chat, &requester).await?,+ Some(AccessLevel::Edit),+ );+ assert_eq!(+ get_chat_access(&pool, &link_wins_chat, &requester).await?,+ Some(AccessLevel::Edit),+ );+ Ok(())+}diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rsindex cb277297c2..44fa4ccce4 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access.rs@@ -1,5 +1,8 @@//! Query for document access level.+#[cfg(test)]+mod test;+use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};use sqlx::PgPool;use std::str::FromStr;@@ -16,21 +19,20 @@ pub async fn get_document_access(let access_level = sqlx::query_scalar!(r#"SELECT- "publicAccessLevel" as "access_level!"- FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL- AND id IN (- SELECT "sharePermissionId" FROM "DocumentPermission" WHERE "documentId" = $1- )-+ share_permission."linkShareAccessLevel" AS "access_level!: AccessLevel"+ FROM "SharePermission" share_permission+ JOIN "DocumentPermission" document_permission+ ON document_permission."sharePermissionId" = share_permission.id+ WHERE share_permission."linkShare" = 'PUBLIC'+ AND share_permission."linkShareAccessLevel" IS NOT NULL+ AND document_permission."documentId" = $1"#,&document_id.to_string()).fetch_optional(pool).await?;- return Ok(access_level.and_then(|level| AccessLevel::from_str(&level).ok()));+ return Ok(access_level);}let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(@@ -44,15 +46,28 @@ pub async fn get_document_access(AND source_id = ANY($2)UNION ALL- -- Source 2: items share permission+ -- Source 2: document link share permissionSELECT- "publicAccessLevel"::text AS access_level- FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL- AND id IN (- SELECT "sharePermissionId" FROM "DocumentPermission" WHERE "documentId" = $3- )+ share_permission."linkShareAccessLevel"::text AS access_level+ FROM "Document" document+ JOIN "DocumentPermission" document_permission+ ON document_permission."documentId" = document.id+ JOIN "SharePermission" share_permission+ ON share_permission.id = document_permission."sharePermissionId"+ WHERE document.id = $3+ AND share_permission."linkShareAccessLevel" IS NOT NULL+ AND (+ share_permission."linkShare" = 'PUBLIC'+ OR (+ share_permission."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1+ FROM team_user owner_team+ WHERE owner_team.user_id = document.owner+ AND owner_team.team_id::text = ANY($2)+ )+ )+ )) AS combined_access"#,document_id,diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rsnew file mode 100644index 0000000000..9f30b3019f--- /dev/null+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/document_access/test.rs@@ -0,0 +1,249 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++const OWNER_WITH_TEAM: &str = "macro|[email protected]";+const OWNER_WITHOUT_TEAM: &str = "macro|[email protected]";++async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {+ let macro_user_id = Uuid::new_v4();+ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $2, $2)+ "#,+ macro_user_id,+ user_id,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, $1, $2)+ "#,+ user_id,+ macro_user_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn add_owner_to_team(pool: &PgPool, owner: &str, team_id: Uuid) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO team (id, name, owner_id)+ VALUES ($1, 'Document Owner Team', $2)+ "#,+ team_id,+ owner,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, 'owner')+ "#,+ owner,+ team_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_link_shared_document(+ pool: &PgPool,+ owner: &str,+ link_share: Option<&str>,+ link_share_access_level: Option<&str>,+) -> anyhow::Result<Uuid> {+ let document_id = Uuid::new_v4();+ let document_id_string = document_id.to_string();+ let share_permission_id = Uuid::new_v4().to_string();++ sqlx::query!(+ r#"+ INSERT INTO "Document" (id, name, owner)+ VALUES ($1, 'Link Shared Document', $2)+ "#,+ document_id_string,+ owner,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "SharePermission" (+ id,+ "linkShare",+ "linkShareAccessLevel"+ )+ VALUES ($1, $2, $3::text::"AccessLevel")+ "#,+ share_permission_id,+ link_share,+ link_share_access_level,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "DocumentPermission" ("documentId", "sharePermissionId")+ VALUES ($1, $2)+ "#,+ document_id_string,+ share_permission_id,+ )+ .execute(pool)+ .await?;++ Ok(document_id)+}++async fn insert_document_entity_access(+ pool: &PgPool,+ document_id: Uuid,+ source_id: &str,+ access_level: AccessLevel,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level+ )+ VALUES ($1, 'document', $2, 'user', $3::text::"AccessLevel")+ "#,+ document_id,+ source_id,+ access_level.to_string(),+ )+ .execute(pool)+ .await?;++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn public_link_allows_anonymous_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let document_id =+ insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("PUBLIC"), Some("view"))+ .await?;++ let access = get_document_access(&pool, &document_id, &SourceIds(vec![])).await?;++ assert_eq!(access, Some(AccessLevel::View));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn null_link_denies_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let document_id = insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, None, None).await?;+ let source_ids = SourceIds(vec!["macro|[email protected]".to_string()]);++ let access = get_document_access(&pool, &document_id, &source_ids).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_allows_same_team_access(pool: PgPool) -> anyhow::Result<()> {+ let owner_team_id = Uuid::new_v4();+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, owner_team_id).await?;+ let document_id =+ insert_link_shared_document(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("comment")).await?;+ let source_ids = SourceIds(vec![owner_team_id.to_string()]);++ let access = get_document_access(&pool, &document_id, &source_ids).await?;++ assert_eq!(access, Some(AccessLevel::Comment));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_other_team_access(pool: PgPool) -> anyhow::Result<()> {+ let owner_team_id = Uuid::new_v4();+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, owner_team_id).await?;+ let document_id =+ insert_link_shared_document(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("comment")).await?;+ let source_ids = SourceIds(vec![Uuid::new_v4().to_string()]);++ let access = get_document_access(&pool, &document_id, &source_ids).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_anonymous_access(pool: PgPool) -> anyhow::Result<()> {+ let owner_team_id = Uuid::new_v4();+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, owner_team_id).await?;+ let document_id =+ insert_link_shared_document(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("edit")).await?;++ let access = get_document_access(&pool, &document_id, &SourceIds(vec![])).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_access_when_owner_has_no_team(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let document_id =+ insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("TEAM"), Some("edit")).await?;+ let source_ids = SourceIds(vec![Uuid::new_v4().to_string()]);++ let access = get_document_access(&pool, &document_id, &source_ids).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn public_link_requires_an_access_level(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let document_id =+ insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("PUBLIC"), None).await?;++ let access = get_document_access(&pool, &document_id, &SourceIds(vec![])).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn returns_highest_link_or_explicit_access_level(pool: PgPool) -> anyhow::Result<()> {+ const REQUESTER: &str = "macro|[email protected]";++ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let document_id =+ insert_link_shared_document(&pool, OWNER_WITHOUT_TEAM, Some("PUBLIC"), Some("comment"))+ .await?;+ insert_document_entity_access(&pool, document_id, REQUESTER, AccessLevel::Edit).await?;+ let source_ids = SourceIds(vec![REQUESTER.to_string()]);++ let access = get_document_access(&pool, &document_id, &source_ids).await?;++ assert_eq!(access, Some(AccessLevel::Edit));+ Ok(())+}diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rsindex d1c6b12fe5..2677fc7e46 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/project_access.rs@@ -1,5 +1,8 @@//! Query for project access level.+#[cfg(test)]+mod test;+use crate::{domain::models::AccessLevel, outbound::pg_access_repo::queries::SourceIds};use sqlx::PgPool;use std::str::FromStr;@@ -16,11 +19,11 @@ pub async fn get_project_access(let access_level = sqlx::query_scalar!(r#"SELECT- "publicAccessLevel" as "access_level!"- FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL- AND id IN (+ sp."linkShareAccessLevel" AS "access_level!: AccessLevel"+ FROM "SharePermission" sp+ WHERE sp."linkShare" = 'PUBLIC'+ AND sp."linkShareAccessLevel" IS NOT NULL+ AND sp.id IN (SELECT "sharePermissionId" FROM "ProjectPermission" WHERE "projectId" = $1)@@ -30,7 +33,7 @@ pub async fn get_project_access(.fetch_optional(pool).await?;- return Ok(access_level.and_then(|level| AccessLevel::from_str(&level).ok()));+ return Ok(access_level);}let all_level_strings: Vec<Option<String>> = sqlx::query_scalar!(@@ -44,15 +47,27 @@ pub async fn get_project_access(AND source_id = ANY($2)UNION ALL- -- Source 2: items share permission+ -- Source 2: project link share permissionSELECT- "publicAccessLevel"::text AS access_level- FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL- AND id IN (+ sp."linkShareAccessLevel"::text AS access_level+ FROM "SharePermission" sp+ WHERE sp."linkShareAccessLevel" IS NOT NULL+ AND sp.id IN (SELECT "sharePermissionId" FROM "ProjectPermission" WHERE "projectId" = $3)+ AND (+ sp."linkShare" = 'PUBLIC'+ OR (+ sp."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1+ FROM "Project" p+ JOIN team_user owner_team ON owner_team.user_id = p."userId"+ WHERE p.id = $3+ AND owner_team.team_id::text = ANY($2)+ )+ )+ )) AS combined_access"#,project_id,diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/project_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/project_access/test.rsnew file mode 100644index 0000000000..23008f064d--- /dev/null+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/project_access/test.rs@@ -0,0 +1,309 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++const OWNER: &str = "macro|[email protected]";+const REQUESTER: &str = "macro|[email protected]";++async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {+ let macro_user_id = Uuid::new_v4();+ let email = user_id.trim_start_matches("macro|");++ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $2)+ "#,+ macro_user_id,+ user_id,+ email,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ user_id,+ email,+ macro_user_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_project(pool: &PgPool, project_id: Uuid, owner_id: &str) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO "Project" (id, name, "userId") VALUES ($1, 'Test Project', $2)"#,+ project_id.to_string(),+ owner_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_link_share(+ pool: &PgPool,+ project_id: Uuid,+ link_share: Option<&str>,+ access_level: Option<&str>,+) -> anyhow::Result<()> {+ let share_permission_id = Uuid::new_v4().to_string();++ sqlx::query!(+ r#"+ INSERT INTO "SharePermission" (+ id,+ "linkShare",+ "linkShareAccessLevel"+ )+ VALUES ($1, $2, $3::text::"AccessLevel")+ "#,+ share_permission_id,+ link_share,+ access_level,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "ProjectPermission" ("projectId", "sharePermissionId")+ VALUES ($1, $2)+ "#,+ project_id.to_string(),+ share_permission_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_team(pool: &PgPool, team_id: Uuid, owner_id: &str) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'Test Team', $2)"#,+ team_id,+ owner_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn add_team_user(+ pool: &PgPool,+ team_id: Uuid,+ user_id: &str,+ role: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, $3::text::team_role)+ "#,+ user_id,+ team_id,+ role,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_entity_access(+ pool: &PgPool,+ project_id: Uuid,+ source_id: &str,+ access_level: AccessLevel,+ granted_from_project_id: Option<Uuid>,+) -> anyhow::Result<()> {+ let access_level = access_level.to_string();+ let granted_from_project_id = granted_from_project_id.map(|id| id.to_string());++ sqlx::query!(+ r#"+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level,+ granted_from_project_id+ )+ VALUES ($1, 'project', $2, 'user', $3::text::"AccessLevel", $4)+ "#,+ project_id,+ source_id,+ access_level,+ granted_from_project_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++fn anonymous_source_ids() -> SourceIds {+ SourceIds(Vec::new())+}++fn authenticated_source_ids(team_id: Option<Uuid>) -> SourceIds {+ let mut source_ids = vec![REQUESTER.to_string()];+ if let Some(team_id) = team_id {+ source_ids.push(team_id.to_string());+ }+ SourceIds(source_ids)+}++async fn setup_project(pool: &PgPool, link_share: Option<&str>) -> anyhow::Result<Uuid> {+ let project_id = Uuid::new_v4();+ insert_user(pool, OWNER).await?;+ insert_project(pool, project_id, OWNER).await?;+ insert_link_share(pool, project_id, link_share, link_share.map(|_| "comment")).await?;+ Ok(project_id)+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn public_link_grants_anonymous_access(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, Some("PUBLIC")).await?;++ let access = get_project_access(&pool, &project_id, &anonymous_source_ids()).await?;++ assert_eq!(access, Some(AccessLevel::Comment));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn public_link_grants_authenticated_access(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, Some("PUBLIC")).await?;++ let access = get_project_access(&pool, &project_id, &authenticated_source_ids(None)).await?;++ assert_eq!(access, Some(AccessLevel::Comment));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn null_link_denies_anonymous_access(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, None).await?;++ let access = get_project_access(&pool, &project_id, &anonymous_source_ids()).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn null_link_denies_authenticated_access(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, None).await?;++ let access = get_project_access(&pool, &project_id, &authenticated_source_ids(None)).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_anonymous_access(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, Some("TEAM")).await?;++ let access = get_project_access(&pool, &project_id, &anonymous_source_ids()).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_grants_same_team_access(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, Some("TEAM")).await?;+ let team_id = Uuid::new_v4();+ insert_user(&pool, REQUESTER).await?;+ insert_team(&pool, team_id, OWNER).await?;+ add_team_user(&pool, team_id, OWNER, "owner").await?;+ add_team_user(&pool, team_id, REQUESTER, "member").await?;++ let access =+ get_project_access(&pool, &project_id, &authenticated_source_ids(Some(team_id))).await?;++ assert_eq!(access, Some(AccessLevel::Comment));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_other_team_access(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, Some("TEAM")).await?;+ let owner_team_id = Uuid::new_v4();+ let requester_team_id = Uuid::new_v4();+ insert_user(&pool, REQUESTER).await?;+ insert_team(&pool, owner_team_id, OWNER).await?;+ add_team_user(&pool, owner_team_id, OWNER, "owner").await?;+ insert_team(&pool, requester_team_id, REQUESTER).await?;+ add_team_user(&pool, requester_team_id, REQUESTER, "owner").await?;++ let access = get_project_access(+ &pool,+ &project_id,+ &authenticated_source_ids(Some(requester_team_id)),+ )+ .await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_when_owner_has_no_team(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, Some("TEAM")).await?;+ let requester_team_id = Uuid::new_v4();+ insert_user(&pool, REQUESTER).await?;+ insert_team(&pool, requester_team_id, REQUESTER).await?;+ add_team_user(&pool, requester_team_id, REQUESTER, "owner").await?;++ let access = get_project_access(+ &pool,+ &project_id,+ &authenticated_source_ids(Some(requester_team_id)),+ )+ .await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn explicit_project_access_is_preserved(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, None).await?;+ insert_entity_access(&pool, project_id, REQUESTER, AccessLevel::Edit, None).await?;++ let access = get_project_access(&pool, &project_id, &authenticated_source_ids(None)).await?;++ assert_eq!(access, Some(AccessLevel::Edit));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn inherited_project_access_is_preserved(pool: PgPool) -> anyhow::Result<()> {+ let project_id = setup_project(&pool, None).await?;+ let parent_project_id = Uuid::new_v4();+ insert_project(&pool, parent_project_id, OWNER).await?;+ insert_entity_access(+ &pool,+ project_id,+ REQUESTER,+ AccessLevel::Edit,+ Some(parent_project_id),+ )+ .await?;++ let access = get_project_access(&pool, &project_id, &authenticated_source_ids(None)).await?;++ assert_eq!(access, Some(AccessLevel::Edit));+ Ok(())+}diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rsindex fe0c0bf341..2231c2ff1c 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access.rs@@ -94,10 +94,10 @@ pub async fn get_thread_access(let access_level = sqlx::query_scalar!(r#"SELECT- "publicAccessLevel" as "access_level!"+ "linkShareAccessLevel" as "access_level!: AccessLevel"FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL+ WHERE "linkShare" = 'PUBLIC'+ AND "linkShareAccessLevel" IS NOT NULLAND id IN (SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $1)@@ -108,7 +108,7 @@ pub async fn get_thread_access(.fetch_optional(pool).await?;- return Ok(access_level.and_then(|level| AccessLevel::from_str(&level).ok()));+ return Ok(access_level);}// Owner is handled above and short-circuits. The remaining sources —@@ -128,13 +128,26 @@ pub async fn get_thread_access(AND source_id = ANY($2)UNION ALL- -- Source 2: items share permission+ -- Source 2: item share permissionSELECT- "publicAccessLevel"::text AS access_level- FROM "SharePermission"- WHERE "isPublic" = true- AND "publicAccessLevel" IS NOT NULL- AND id IN (+ sp."linkShareAccessLevel"::text AS access_level+ FROM "SharePermission" sp+ WHERE sp."linkShareAccessLevel" IS NOT NULL+ AND (+ sp."linkShare" = 'PUBLIC'+ OR (+ sp."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1+ FROM email_threads t+ JOIN email_links l ON l.id = t.link_id+ JOIN team_user owner_tu ON owner_tu.user_id = l.macro_id+ WHERE t.id = $1::uuid+ AND owner_tu.team_id::text = ANY($2)+ )+ )+ )+ AND sp.id IN (SELECT "sharePermissionId" FROM "EmailThreadPermission" WHERE "threadId" = $3)diff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rsindex a147d90178..32fae3136b 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/thread_access/test.rs@@ -24,6 +24,18 @@ async fn access_as_requester(pool: &PgPool, thread_id: &Uuid) -> Option<AccessLe.unwrap()}+async fn access_as_requester_on_team(+ pool: &PgPool,+ thread_id: &Uuid,+ team_id: Uuid,+) -> Option<AccessLevel> {+ let requester = user(REQUESTER);+ let source_ids = SourceIds(vec![REQUESTER.to_string(), team_id.to_string()]);+ get_thread_access(pool, thread_id, &source_ids, Some(&*requester))+ .await+ .unwrap()+}+// ---------------------------------------------------------------------------// Fixture helpers// ---------------------------------------------------------------------------@@ -115,6 +127,39 @@ async fn insert_entity_access(pool: &PgPool, thread_id: Uuid, source_id: &str, l.unwrap();}+async fn insert_thread_share_permission(+ pool: &PgPool,+ thread_id: Uuid,+ owner_user_id: &str,+ link_share: Option<&str>,+ access_level: Option<AccessLevel>,+) {+ let share_permission_id = Uuid::new_v4().to_string();+ let access_level = access_level.map(|level| level.to_string());++ sqlx::query!(+ r#"INSERT INTO "SharePermission" (id, "linkShare", "linkShareAccessLevel")+ VALUES ($1, $2, $3::text::"AccessLevel")"#,+ share_permission_id,+ link_share,+ access_level,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"INSERT INTO "EmailThreadPermission" ("threadId", "sharePermissionId", "userId")+ VALUES ($1, $2, $3)"#,+ thread_id.to_string(),+ share_permission_id,+ owner_user_id,+ )+ .execute(pool)+ .await+ .unwrap();+}+async fn insert_email_contact(pool: &PgPool, link_id: Uuid, email: &str) -> Uuid {let id = Uuid::new_v4();sqlx::query!(@@ -450,7 +495,142 @@ async fn unauthenticated_user_never_gets_crm_access(pool: PgPool) -> anyhow::Res}// ----------------------------------------------------------------------------// Happy paths+// Link sharing+// ---------------------------------------------------------------------------++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn public_link_grants_anonymous_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_thread_share_permission(+ &pool,+ thread_id,+ OWNER,+ Some("PUBLIC"),+ Some(AccessLevel::Comment),+ )+ .await;++ let access = get_thread_access(&pool, &thread_id, &SourceIds(vec![]), None).await?;++ assert_eq!(access, Some(AccessLevel::Comment));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn null_link_share_denies_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, REQUESTER, "[email protected]").await;+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_thread_share_permission(&pool, thread_id, OWNER, None, None).await;++ assert_eq!(access_as_requester(&pool, &thread_id).await, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_grants_same_team_member(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, REQUESTER, "[email protected]").await;+ let team_id = Uuid::new_v4();+ insert_team_row(&pool, team_id, OWNER).await;+ add_team_member(&pool, team_id, OWNER).await;+ add_team_member(&pool, team_id, REQUESTER).await;+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_thread_share_permission(+ &pool,+ thread_id,+ OWNER,+ Some("TEAM"),+ Some(AccessLevel::Edit),+ )+ .await;++ assert_eq!(+ access_as_requester_on_team(&pool, &thread_id, team_id).await,+ Some(AccessLevel::Edit)+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_other_team_member(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, REQUESTER, "[email protected]").await;++ let owner_team_id = Uuid::new_v4();+ insert_team_row(&pool, owner_team_id, OWNER).await;+ add_team_member(&pool, owner_team_id, OWNER).await;++ let requester_team_id = Uuid::new_v4();+ insert_team_row(&pool, requester_team_id, REQUESTER).await;+ add_team_member(&pool, requester_team_id, REQUESTER).await;++ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_thread_share_permission(+ &pool,+ thread_id,+ OWNER,+ Some("TEAM"),+ Some(AccessLevel::View),+ )+ .await;++ assert_eq!(+ access_as_requester_on_team(&pool, &thread_id, requester_team_id).await,+ None+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_anonymous_access(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ let team_id = Uuid::new_v4();+ insert_team_row(&pool, team_id, OWNER).await;+ add_team_member(&pool, team_id, OWNER).await;+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_thread_share_permission(+ &pool,+ thread_id,+ OWNER,+ Some("TEAM"),+ Some(AccessLevel::View),+ )+ .await;++ let access = get_thread_access(&pool, &thread_id, &SourceIds(vec![]), None).await?;++ assert_eq!(access, None);+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_link_denies_when_owner_has_no_team(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, REQUESTER, "[email protected]").await;+ let requester_team_id = Uuid::new_v4();+ insert_team_row(&pool, requester_team_id, REQUESTER).await;+ add_team_member(&pool, requester_team_id, REQUESTER).await;+ let (_, thread_id) = create_link_and_thread(&pool, OWNER).await;+ insert_thread_share_permission(+ &pool,+ thread_id,+ OWNER,+ Some("TEAM"),+ Some(AccessLevel::View),+ )+ .await;++ assert_eq!(+ access_as_requester_on_team(&pool, &thread_id, requester_team_id).await,+ None+ );+ Ok(())+}++// ---------------------------------------------------------------------------+// CRM happy paths// ---------------------------------------------------------------------------#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]diff --git a/crates/entity_access/src/outbound/pg_access_repo/test.rs b/crates/entity_access/src/outbound/pg_access_repo/test.rsindex 493194add4..d28d05bfc2 100644--- a/crates/entity_access/src/outbound/pg_access_repo/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/test.rs@@ -463,16 +463,18 @@ async fn crm_contact_access_rejects_invalid_uuid(pool: PgPool) -> anyhow::Result}const PG_BOT_OWNER: &str = "macro|[email protected]";+const PG_OTHER_DOCUMENT_OWNER: &str = "macro|[email protected]";-async fn insert_pg_bot_user(pool: &PgPool) -> anyhow::Result<()> {+async fn insert_pg_user(pool: &PgPool, user_id: &str, email: &str) -> anyhow::Result<()> {let macro_user_id = Uuid::new_v4();sqlx::query!(r#"INSERT INTO macro_user (id, username, email, stripe_customer_id)- VALUES ($1, $2, '[email protected]', $2)+ VALUES ($1, $2, $3, $2)"#,macro_user_id,- PG_BOT_OWNER,+ user_id,+ email,).execute(pool).await?;@@ -480,9 +482,10 @@ async fn insert_pg_bot_user(pool: &PgPool) -> anyhow::Result<()> {sqlx::query!(r#"INSERT INTO "User" (id, email, macro_user_id)- VALUES ($1, '[email protected]', $2)+ VALUES ($1, $2, $3)"#,- PG_BOT_OWNER,+ user_id,+ email,macro_user_id,).execute(pool)@@ -491,18 +494,38 @@ async fn insert_pg_bot_user(pool: &PgPool) -> anyhow::Result<()> {Ok(())}-async fn insert_pg_bot_team(pool: &PgPool, team_id: Uuid) -> anyhow::Result<()> {- insert_pg_bot_user(pool).await?;+async fn insert_pg_team(+ pool: &PgPool,+ team_id: Uuid,+ owner_id: &str,+ name: &str,+) -> anyhow::Result<()> {sqlx::query!(- "INSERT INTO team (id, name, owner_id) VALUES ($1, 'PG Bot Team', $2)",+ "INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)",+ team_id,+ name,+ owner_id,+ )+ .execute(pool)+ .await?;+ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, 'owner')+ "#,+ owner_id,team_id,- PG_BOT_OWNER,).execute(pool).await?;Ok(())}+async fn insert_pg_bot_team(pool: &PgPool, team_id: Uuid) -> anyhow::Result<()> {+ insert_pg_user(pool, PG_BOT_OWNER, "[email protected]").await?;+ insert_pg_team(pool, team_id, PG_BOT_OWNER, "PG Bot Team").await+}+async fn insert_pg_bot(pool: &PgPool,bot_id: BotId,@@ -602,6 +625,53 @@ async fn insert_pg_bot_entity_access(Ok(())}+async fn insert_pg_link_shared_document(+ pool: &PgPool,+ document_id: Uuid,+ owner_id: &str,+ link_share: &str,+ access_level: AccessLevel,+) -> anyhow::Result<()> {+ let document_id = document_id.to_string();+ let permission_id = Uuid::new_v4().to_string();+ let access_level = access_level.to_string();++ sqlx::query!(+ r#"INSERT INTO "Document" (id, name, owner) VALUES ($1, 'Link Shared Document', $2)"#,+ document_id,+ owner_id,+ )+ .execute(pool)+ .await?;+ sqlx::query!(+ r#"+ INSERT INTO "SharePermission" (+ id,+ "linkShare",+ "linkShareAccessLevel"+ )+ VALUES ($1, $2, $3::text::"AccessLevel")+ "#,+ permission_id,+ link_share,+ access_level,+ )+ .execute(pool)+ .await?;+ sqlx::query!(+ r#"+ INSERT INTO "DocumentPermission" ("documentId", "sharePermissionId")+ VALUES ($1, $2)+ "#,+ document_id,+ permission_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn team_item_access_includes_team_channels_and_bot_grants(pool: PgPool,@@ -651,50 +721,101 @@ async fn team_item_access_includes_team_channels_and_bot_grants(}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]-async fn team_item_access_preserves_public_grants(pool: PgPool) -> anyhow::Result<()> {+async fn team_item_access_allows_public_link_sharing(pool: PgPool) -> anyhow::Result<()> {let team_id = Uuid::new_v4();let bot_id = BotId::new_from_uuid(Uuid::new_v4());let document_id = Uuid::new_v4();- let permission_id = Uuid::new_v4().to_string();insert_pg_bot_team(&pool, team_id).await?;insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;- sqlx::query!(- r#"INSERT INTO "Document" (id, name, owner) VALUES ($1, 'Public Document', $2)"#,- document_id.to_string(),+ insert_pg_link_shared_document(+ &pool,+ document_id,PG_BOT_OWNER,+ "PUBLIC",+ AccessLevel::Comment,)- .execute(&pool).await?;- sqlx::query!(- r#"- INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel")- VALUES ($1, true, 'comment')- "#,- permission_id.as_str(),++ let access = PgAccessRepository::new(pool)+ .get_team_entity_access(+ bot_id,+ team_id,+ &document_id.to_string(),+ EntityType::Document,+ )+ .await?;++ assert_eq!(access, Some(AccessLevel::Comment));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_item_access_allows_team_link_for_document_owner_team(+ pool: PgPool,+) -> anyhow::Result<()> {+ let team_id = Uuid::new_v4();+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let document_id = Uuid::new_v4();+ insert_pg_bot_team(&pool, team_id).await?;+ insert_pg_bot(&pool, bot_id, None, Some(team_id)).await?;+ insert_pg_link_shared_document(&pool, document_id, PG_BOT_OWNER, "TEAM", AccessLevel::Edit)+ .await?;++ let access = PgAccessRepository::new(pool)+ .get_team_entity_access(+ bot_id,+ team_id,+ &document_id.to_string(),+ EntityType::Document,+ )+ .await?;++ assert_eq!(access, Some(AccessLevel::Edit));+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn team_item_access_denies_team_link_for_another_document_owner_team(+ pool: PgPool,+) -> anyhow::Result<()> {+ let bot_team_id = Uuid::new_v4();+ let owner_team_id = Uuid::new_v4();+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());+ let document_id = Uuid::new_v4();+ insert_pg_bot_team(&pool, bot_team_id).await?;+ insert_pg_bot(&pool, bot_id, None, Some(bot_team_id)).await?;+ insert_pg_user(+ &pool,+ PG_OTHER_DOCUMENT_OWNER,+ "[email protected]",)- .execute(&pool).await?;- sqlx::query!(- r#"- INSERT INTO "DocumentPermission" ("documentId", "sharePermissionId")- VALUES ($1, $2)- "#,- document_id.to_string(),- permission_id.as_str(),+ insert_pg_team(+ &pool,+ owner_team_id,+ PG_OTHER_DOCUMENT_OWNER,+ "Other Document Owner Team",+ )+ .await?;+ insert_pg_link_shared_document(+ &pool,+ document_id,+ PG_OTHER_DOCUMENT_OWNER,+ "TEAM",+ AccessLevel::Edit,)- .execute(&pool).await?;let access = PgAccessRepository::new(pool).get_team_entity_access(bot_id,- team_id,+ bot_team_id,&document_id.to_string(),EntityType::Document,).await?;- assert_eq!(access, Some(AccessLevel::Comment));+ assert_eq!(access, None);Ok(())}diff --git a/crates/entity_mutation/src/models.rs b/crates/entity_mutation/src/models.rsindex 4be4368ad3..d20b6e9233 100644--- a/crates/entity_mutation/src/models.rs+++ b/crates/entity_mutation/src/models.rs@@ -38,7 +38,7 @@ pub struct DuplicateEntityRequest {pub display_name: Option<String>,}-/// Request to update an entity's public and channel share policy.+/// Request to update an entity's link and channel share policy.#[derive(Clone, Debug)]pub struct UpdateEntitySharePolicyRequest {/// Entity whose share policy should change.diff --git a/crates/graphql_entity_mutation/src/lib.rs b/crates/graphql_entity_mutation/src/lib.rsindex d3e9b8d24d..611c95521b 100644--- a/crates/graphql_entity_mutation/src/lib.rs+++ b/crates/graphql_entity_mutation/src/lib.rs@@ -9,7 +9,7 @@ mod mutations;pub use mutations::{ChannelSharePolicyInput, DuplicateEntityInput, EntityMutationPayload, EntityMutationRoot,EntityRefInput, EntitySharePolicyInput, GraphqlEntityMutationError,- GraphqlEntityMutationErrorCode, GraphqlEntityMutationResult, GraphqlMutationError,- GraphqlMutationSuccess, GraphqlSharePolicyOperation, MoveEntityInput, RenameEntityInput,- UpdateEntitySharePolicyInput,+ GraphqlEntityMutationErrorCode, GraphqlEntityMutationResult, GraphqlLinkShare,+ GraphqlMutationError, GraphqlMutationSuccess, GraphqlSharePolicyOperation, MoveEntityInput,+ RenameEntityInput, UpdateEntitySharePolicyInput,};diff --git a/crates/graphql_entity_mutation/src/mutations.rs b/crates/graphql_entity_mutation/src/mutations.rsindex 9b7aa8ba7e..77588fddf5 100644--- a/crates/graphql_entity_mutation/src/mutations.rs+++ b/crates/graphql_entity_mutation/src/mutations.rs@@ -1,6 +1,8 @@use std::{collections::HashSet, marker::PhantomData, sync::Arc};-use async_graphql::{Context, Enum, ErrorExtensions, ID, InputObject, Object, SimpleObject, Union};+use async_graphql::{+ Context, Enum, ErrorExtensions, ID, InputObject, MaybeUndefined, Object, SimpleObject, Union,+};use entity_mutation::{DuplicateEntityRequest, EntityMutationActor, EntityMutationEffect, EntityMutationErrorCode,EntityMutationService, EntityMutationSuccess, MoveEntityRequest, MutateEntitiesResult,@@ -11,7 +13,7 @@ use graphql_permission::GraphqlEntityAccessLevel;use graphql_soup::{SoupEntityEdges, SoupPatch};use model_entity::Entity;use models_permissions::share_permission::{- UpdateSharePermissionRequestV2,+ LinkShare, UpdateSharePermissionRequestV2,channel_share_permission::{UpdateChannelSharePermission, UpdateOperation},};@@ -203,13 +205,33 @@ impl ChannelSharePolicyInput {}}-/// Shared public/channel share-policy update.+/// Audience allowed to access an entity through its share link.+#[derive(Clone, Copy, Enum, Eq, PartialEq)]+pub enum GraphqlLinkShare {+ /// Anyone with the link can access the entity.+ Public,+ /// Members of the owner's team with the link can access the entity.+ Team,+}++impl GraphqlLinkShare {+ /// Convert this GraphQL audience into the permissions-domain model.+ pub fn into_model(self) -> LinkShare {+ match self {+ Self::Public => LinkShare::Public,+ Self::Team => LinkShare::Team,+ }+ }+}++/// Shared link/channel share-policy update.#[derive(InputObject)]pub struct EntitySharePolicyInput {- /// Whether public access should be enabled.- pub is_public: Option<bool>,- /// Public access level when public access is enabled.- pub public_access_level: Option<GraphqlEntityAccessLevel>,+ /// Link-sharing audience. Omit to leave unchanged or pass null to disable link sharing.+ pub link_share: MaybeUndefined<GraphqlLinkShare>,+ /// Link access level. Omit to leave unchanged or pass null to reset it to the default level+ /// when a link share exists.+ pub link_share_access_level: MaybeUndefined<GraphqlEntityAccessLevel>,/// Channel access entries to add, remove, or replace.pub channel_share_permissions: Option<Vec<ChannelSharePolicyInput>>,}@@ -218,10 +240,14 @@ impl EntitySharePolicyInput {/// Convert this GraphQL input into a shared permission update.pub fn into_model(self) -> UpdateSharePermissionRequestV2 {UpdateSharePermissionRequestV2 {- is_public: self.is_public,- public_access_level: self- .public_access_level- .map(GraphqlEntityAccessLevel::into_model),+ link_share: self+ .link_share+ .map_value(GraphqlLinkShare::into_model)+ .into(),+ link_share_access_level: self+ .link_share_access_level+ .map_value(GraphqlEntityAccessLevel::into_model)+ .into(),channel_share_permissions: self.channel_share_permissions.map(|entries| {entries.into_iter()@@ -237,7 +263,7 @@ impl EntitySharePolicyInput {pub struct UpdateEntitySharePolicyInput {/// Entity whose share policy should change.pub entity: EntityRefInput,- /// New public/channel policy values.+ /// New link/channel policy values.pub policy: EntitySharePolicyInput,}@@ -251,14 +277,14 @@ impl UpdateEntitySharePolicyInput {}}-/// Validate conditional fields required by public and channel share updates.+/// Validate conditional fields required by link and channel share updates.fn validate_share_policy_inputs(inputs: &[UpdateEntitySharePolicyInput],) -> async_graphql::Result<()> {for input in inputs {- if input.policy.is_public == Some(true) && input.policy.public_access_level.is_none() {+ if input.policy.link_share.is_value() && !input.policy.link_share_access_level.is_value() {return Err(invalid_request(- "publicAccessLevel is required when public access is enabled",+ "linkShareAccessLevel is required when link sharing is enabled",));}if let Some(entries) = &input.policy.channel_share_permissions {@@ -500,7 +526,7 @@ impl<S: EntityMutationService, E: SoupEntityEdges> EntityMutationRoot<S, E> {))}- /// Update public and channel share policies across supported entity kinds.+ /// Update link and channel share policies across supported entity kinds.async fn update_entity_share_policies(&self,ctx: &Context<'_>,diff --git a/crates/graphql_entity_mutation/src/mutations/test.rs b/crates/graphql_entity_mutation/src/mutations/test.rsindex dd4d5b9344..c0a501bf87 100644--- a/crates/graphql_entity_mutation/src/mutations/test.rs+++ b/crates/graphql_entity_mutation/src/mutations/test.rs@@ -1,12 +1,16 @@use std::sync::Arc;-use async_graphql::{Context, EmptySubscription, Object, Request, Schema, SimpleObject, value};+use async_graphql::{+ Context, EmptySubscription, MaybeUndefined, Object, Request, Schema, SimpleObject, value,+};use entity_mutation::{EntityMutationActor, EntityMutationEffect, UnavailableEntityMutationService,};+use graphql_permission::GraphqlEntityAccessLevel;use graphql_soup::SoupEntityEdges;use macro_user_id::user_id::MacroUserIdStr;use model_entity::{Entity, EntityType};+use models_permissions::share_permission::{LinkShare, access_level::AccessLevel};/// Minimal composed Soup edge object used by the isolated mutation schema.#[derive(Clone, SimpleObject)]@@ -186,16 +190,112 @@ fn batch_validation_rejects_oversized_and_duplicate_requests() {assert!(error.message.contains("duplicate entity"));}+fn share_policy_input(+ link_share: MaybeUndefined<super::GraphqlLinkShare>,+ link_share_access_level: MaybeUndefined<GraphqlEntityAccessLevel>,+) -> super::EntitySharePolicyInput {+ super::EntitySharePolicyInput {+ link_share,+ link_share_access_level,+ channel_share_permissions: None,+ }+}++fn share_policy_update_input(+ link_share: MaybeUndefined<super::GraphqlLinkShare>,+ link_share_access_level: MaybeUndefined<GraphqlEntityAccessLevel>,+) -> super::UpdateEntitySharePolicyInput {+ super::UpdateEntitySharePolicyInput {+ entity: super::EntityRefInput {+ entity_type: graphql_common::GraphqlEntityType::Document,+ id: "document-1".into(),+ },+ policy: share_policy_input(link_share, link_share_access_level),+ }+}++#[test]+fn share_policy_input_preserves_undefined_and_null_link_updates() {+ let unchanged =+ share_policy_input(MaybeUndefined::Undefined, MaybeUndefined::Undefined).into_model();+ assert_eq!(unchanged.link_share, None);+ assert_eq!(unchanged.link_share_access_level, None);++ let disabled = share_policy_input(MaybeUndefined::Null, MaybeUndefined::Null).into_model();+ assert_eq!(disabled.link_share, Some(None));+ assert_eq!(disabled.link_share_access_level, Some(None));+}++#[test]+fn share_policy_input_converts_public_and_team_link_updates() {+ let public = share_policy_input(+ MaybeUndefined::Value(super::GraphqlLinkShare::Public),+ MaybeUndefined::Value(GraphqlEntityAccessLevel::View),+ )+ .into_model();+ assert_eq!(public.link_share, Some(Some(LinkShare::Public)));+ assert_eq!(+ public.link_share_access_level,+ Some(Some(AccessLevel::View))+ );++ let team = share_policy_input(+ MaybeUndefined::Value(super::GraphqlLinkShare::Team),+ MaybeUndefined::Value(GraphqlEntityAccessLevel::Edit),+ )+ .into_model();+ assert_eq!(team.link_share, Some(Some(LinkShare::Team)));+ assert_eq!(team.link_share_access_level, Some(Some(AccessLevel::Edit)));+}+#[test]-fn share_policy_validation_requires_access_levels_for_grants() {+fn share_policy_validation_allows_undefined_and_null_link_updates() {+ let unchanged = [share_policy_update_input(+ MaybeUndefined::Undefined,+ MaybeUndefined::Undefined,+ )];+ super::validate_share_policy_inputs(&unchanged).unwrap();++ let disabled = [share_policy_update_input(+ MaybeUndefined::Null,+ MaybeUndefined::Undefined,+ )];+ super::validate_share_policy_inputs(&disabled).unwrap();+}++#[test]+fn share_policy_validation_requires_access_levels_for_public_and_team_links() {+ for link_share in [+ super::GraphqlLinkShare::Public,+ super::GraphqlLinkShare::Team,+ ] {+ for link_share_access_level in [MaybeUndefined::Undefined, MaybeUndefined::Null] {+ let inputs = [share_policy_update_input(+ MaybeUndefined::Value(link_share),+ link_share_access_level,+ )];+ let error = super::validate_share_policy_inputs(&inputs).unwrap_err();+ assert!(error.message.contains("linkShareAccessLevel is required"));+ }++ let inputs = [share_policy_update_input(+ MaybeUndefined::Value(link_share),+ MaybeUndefined::Value(GraphqlEntityAccessLevel::View),+ )];+ super::validate_share_policy_inputs(&inputs).unwrap();+ }+}++#[test]+fn share_policy_validation_requires_access_levels_for_channel_grants() {let inputs = [super::UpdateEntitySharePolicyInput {entity: super::EntityRefInput {entity_type: graphql_common::GraphqlEntityType::Document,id: "document-1".into(),},policy: super::EntitySharePolicyInput {- is_public: None,- public_access_level: None,+ link_share: MaybeUndefined::Undefined,+ link_share_access_level: MaybeUndefined::Undefined,channel_share_permissions: Some(vec![super::ChannelSharePolicyInput {operation: super::GraphqlSharePolicyOperation::Add,channel_id: "channel-1".into(),@@ -203,7 +303,6 @@ fn share_policy_validation_requires_access_levels_for_grants() {}]),},}];-let error = super::validate_share_policy_inputs(&inputs).unwrap_err();assert!(error.message.contains("accessLevel is required"));}diff --git a/crates/local_e2e_test_support/src/fixtures.rs b/crates/local_e2e_test_support/src/fixtures.rsindex 3573d1fa95..033cc1e04c 100644--- a/crates/local_e2e_test_support/src/fixtures.rs+++ b/crates/local_e2e_test_support/src/fixtures.rs@@ -98,8 +98,10 @@ pub struct SeedDocument {pub document_name: String,/// Source file name.pub file_name: String,- /// Whether the document is public.- pub is_public: bool,+ /// Who can access the document through its share link.+ pub link_share: Option<String>,+ /// Access level granted through the share link.+ pub link_share_access_level: Option<String>,}/// Channel row from `seed/channels.json`.@@ -291,6 +293,18 @@ mod tests {document.document_id,seed.manifest.documents.project_roadmap.id);+ assert_eq!(document.link_share, None);+ assert_eq!(document.link_share_access_level, None);++ let public_document = seed+ .documents+ .iter()+ .find(|document| document.link_share.as_deref() == Some("PUBLIC"))+ .expect("seed includes a public link-shared document");+ assert_eq!(+ public_document.link_share_access_level.as_deref(),+ Some("view")+ );let channel = seed.general_channel().unwrap();assert_eq!(channel.channel_id, seed.manifest.channels.general.id);diff --git a/crates/macro_db_client/fixtures/basic_user_history.sql b/crates/macro_db_client/fixtures/basic_user_history.sqlindex 482720c2ad..4e9842be47 100644--- a/crates/macro_db_client/fixtures/basic_user_history.sql+++ b/crates/macro_db_client/fixtures/basic_user_history.sql@@ -33,8 +33,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "upINSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'document-one', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-document1', true, 'read');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-document1', 'PUBLIC', 'view');INSERT INTO public."UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")(SELECT 'macro|[email protected]', 'document-one', 'document', '2019-10-16 00:00:00', '2019-10-16 00:00:00');diff --git a/crates/macro_db_client/fixtures/basic_user_with_documents.sql b/crates/macro_db_client/fixtures/basic_user_with_documents.sqlindex 3b6f09a71e..8988b7a1b5 100644--- a/crates/macro_db_client/fixtures/basic_user_with_documents.sql+++ b/crates/macro_db_client/fixtures/basic_user_with_documents.sql@@ -77,14 +77,14 @@ INSERT INTOINSERT INTOpublic."SharePermission" ("id",- "isPublic",- "publicAccessLevel",+ "linkShare",+ "linkShareAccessLevel","createdAt","updatedAt") (SELECT'sp-1',- TRUE,+ 'PUBLIC','view','2019-10-16 00:00:00','2019-10-16 00:00:00'@@ -100,14 +100,14 @@ INSERT INTOINSERT INTOpublic."SharePermission" ("id",- "isPublic",- "publicAccessLevel",+ "linkShare",+ "linkShareAccessLevel","createdAt","updatedAt") (SELECT'sp-2',- false,+ NULL,NULL,'2019-10-16 00:00:00','2019-10-16 00:00:00'diff --git a/crates/macro_db_client/fixtures/channel_share_permissions.sql b/crates/macro_db_client/fixtures/channel_share_permissions.sqlindex ad167750e3..8744859be9 100644--- a/crates/macro_db_client/fixtures/channel_share_permissions.sql+++ b/crates/macro_db_client/fixtures/channel_share_permissions.sql@@ -12,9 +12,9 @@ INSERT INTO public."Project" ("id","name","userId","parentId","createdAt","updatVALUES('p1', 'test_project_name','macro|[email protected]', NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")VALUES-('sp-p1', true, 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+('sp-p1', 'PUBLIC', 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES@@ -32,9 +32,9 @@ INSERT INTO public."Project" ("id","name","userId","parentId","createdAt","updatVALUES('p2', 'test_project_name','macro|[email protected]', NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")VALUES-('sp-p2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+('sp-p2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES@@ -45,10 +45,10 @@ VALUES('d1', 'test_document_name','macro|[email protected]', 'docx'),('d2', 'test_document_name','macro|[email protected]', 'pdf');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")VALUES-('sp-d1', true, 'edit'),-('sp-d2', false, NULL);+('sp-d1', 'PUBLIC', 'edit'),+('sp-d2', NULL, NULL);INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")VALUES@@ -65,10 +65,10 @@ VALUES('c1', 'test_chat_name','macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00'),('c2', 'test_chat_name','macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")VALUES-('sp-c1', true, 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00'),-('sp-c2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+('sp-c1', 'PUBLIC', 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00'),+('sp-c2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")VALUESdiff --git a/crates/macro_db_client/fixtures/chat_permissions.sql b/crates/macro_db_client/fixtures/chat_permissions.sqlindex 16e2c5950b..96081b2cb0 100644--- a/crates/macro_db_client/fixtures/chat_permissions.sql+++ b/crates/macro_db_client/fixtures/chat_permissions.sql@@ -10,8 +10,8 @@ INSERT INTO public."User" ("id","email","stripeCustomerId","macro_user_id")INSERT INTO public."Chat" ("id", "name", "userId", "createdAt", "updatedAt")(SELECT 'chat-one', 'test_chat_name','macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'chat-one', 'sp-1');@@ -19,8 +19,8 @@ INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")INSERT INTO public."Chat" ("id", "name", "userId", "createdAt", "updatedAt")(SELECT 'chat-two', 'test_chat_name','macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'chat-two', 'sp-2');diff --git a/crates/macro_db_client/fixtures/chats.sql b/crates/macro_db_client/fixtures/chats.sqlindex bc44342eed..6affd54727 100644--- a/crates/macro_db_client/fixtures/chats.sql+++ b/crates/macro_db_client/fixtures/chats.sql@@ -1,34 +1,34 @@INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt", "projectId")(SELECT 'c1', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00', 'p1');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-chat1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-chat1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'c1', 'sp-chat1');INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt", "projectId")(SELECT 'c2', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00', 'p10');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-chat2', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-chat2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'c2', 'sp-chat2');INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt", "projectId")(SELECT 'c3', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00', 'p11');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-chat3', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-chat3', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'c3', 'sp-chat3');INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt", "projectId")(SELECT 'c4', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00', 'p11');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-chat4', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-chat4', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'c4', 'sp-chat4');INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt", "projectId")(SELECT 'c5', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00', 'p11');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-chat5', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-chat5', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'c5', 'sp-chat5');diff --git a/crates/macro_db_client/fixtures/dcs_basic_user_with_documents.sql b/crates/macro_db_client/fixtures/dcs_basic_user_with_documents.sqlindex 8c273eb9f8..1bd36dd77f 100644--- a/crates/macro_db_client/fixtures/dcs_basic_user_with_documents.sql+++ b/crates/macro_db_client/fixtures/dcs_basic_user_with_documents.sql@@ -21,8 +21,8 @@ INSERT INTO public."Project" ("id", "name", "userId", "createdAt", "updatedAt")INSERT INTO public."Chat" ("id","name","userId", "model", "createdAt", "updatedAt")(SELECT 'chat-one', 'test-chat', 'macro|[email protected]', 'gpt-4o', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-1', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-1', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'chat-one', 'sp-1');diff --git a/crates/macro_db_client/fixtures/document_access_via_email_thread.sql b/crates/macro_db_client/fixtures/document_access_via_email_thread.sqlindex d1953315be..60f2b953d9 100644--- a/crates/macro_db_client/fixtures/document_access_via_email_thread.sql+++ b/crates/macro_db_client/fixtures/document_access_via_email_thread.sql@@ -60,9 +60,9 @@ VALUES ('dddddddd-dddd-dddd-dddd-100000000001', 'a0000000-0000-0000-0000-0000000-------------------------------------------------------------- Thread permissions (via EmailThreadPermission + SharePermission)-------------------------------------------------------------INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-VALUES ('sp-thread-1', false, NULL),- ('sp-thread-2', false, NULL);+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+VALUES ('sp-thread-1', NULL, NULL),+ ('sp-thread-2', NULL, NULL);INSERT INTO public."EmailThreadPermission" ("threadId", "sharePermissionId", "userId")VALUES ('a0000000-0000-0000-0000-000000000010', 'sp-thread-1', 'user-thread-access'),diff --git a/crates/macro_db_client/fixtures/document_pdf_comments_and_highlights.sql b/crates/macro_db_client/fixtures/document_pdf_comments_and_highlights.sqlindex 84a383bebd..0641b77df5 100644--- a/crates/macro_db_client/fixtures/document_pdf_comments_and_highlights.sql+++ b/crates/macro_db_client/fixtures/document_pdf_comments_and_highlights.sql@@ -81,15 +81,15 @@ VALUESINSERT INTOpublic."SharePermission" ("id",- "isPublic",- "publicAccessLevel",+ "linkShare",+ "linkShareAccessLevel","createdAt","updatedAt")VALUES('sp-comments',- false,+ NULL,NULL,'2022-01-01 00:00:00','2022-01-01 00:00:00'diff --git a/crates/macro_db_client/fixtures/document_permissions.sql b/crates/macro_db_client/fixtures/document_permissions.sqlindex d89379feeb..76eaadfabb 100644--- a/crates/macro_db_client/fixtures/document_permissions.sql+++ b/crates/macro_db_client/fixtures/document_permissions.sql@@ -14,8 +14,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "upINSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'document-one', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'document-one', 'sp-1');@@ -26,8 +26,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "upINSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'document-two', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'document-two', 'sp-2');diff --git a/crates/macro_db_client/fixtures/document_preview.sql b/crates/macro_db_client/fixtures/document_preview.sqlindex ea588a1b16..da99c4adc4 100644--- a/crates/macro_db_client/fixtures/document_preview.sql+++ b/crates/macro_db_client/fixtures/document_preview.sql@@ -9,8 +9,8 @@ VALUES ('macro|[email protected]', '[email protected]','stripe_iddfkjdfkdf', 'a2222222INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "updatedAt")VALUES ('document-one', 'test_document_name','pdf', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-VALUES ('share-permission-one', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+VALUES ('share-permission-one', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")VALUES ('document-one', 'share-permission-one');@@ -25,8 +25,8 @@ VALUES ('macro|[email protected]', 'document-one', 'document', 0, '2019-10-16 00:00:INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "updatedAt")VALUES ('document-two', 'test_document_name','pdf', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-VALUES ('share-permission-two', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+VALUES ('share-permission-two', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")VALUES ('document-two', 'share-permission-two');diff --git a/crates/macro_db_client/fixtures/documents.sql b/crates/macro_db_client/fixtures/documents.sqlindex 1931098075..2156b19d91 100644--- a/crates/macro_db_client/fixtures/documents.sql+++ b/crates/macro_db_client/fixtures/documents.sql@@ -2,8 +2,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "up(SELECT 'd1', 'test_document_name','pdf', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'p1');INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'd1', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-document1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-document1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd1', 'sp-document1');@@ -12,8 +12,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "up(SELECT 'd2', 'test_document_name','docx', 'macro|[email protected]', '2019-10-16 00:10:00', '2019-10-16 00:10:00', 'p6');INSERT INTO public."DocumentBom" ("documentId", "createdAt", "updatedAt")(SELECT 'd2', '2019-10-16 00:10:00', '2019-10-16 00:10:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-document2', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-document2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd2', 'sp-document2');@@ -22,8 +22,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "up(SELECT 'd3', 'test_document_name','md', 'macro|[email protected]', '2019-10-16 00:20:00', '2019-10-16 00:20:00', 'p1');INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'd3', '2019-10-16 00:10:00', '2019-10-16 00:10:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-document3', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-document3', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd3', 'sp-document3');@@ -31,8 +31,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "up(SELECT 'd4', 'test_document_name','md', 'macro|[email protected]', '2019-10-16 00:20:00', '2019-10-16 00:20:00', 'p11');INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'd4', '2019-10-16 00:10:00', '2019-10-16 00:10:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-document4', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-document4', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd4', 'sp-document4');@@ -40,7 +40,7 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "up(SELECT 'd5', 'test_document_name','md', 'macro|[email protected]', '2019-10-16 00:20:00', '2019-10-16 00:20:00', 'p11');INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'd5', '2019-10-16 00:10:00', '2019-10-16 00:10:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-document5', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-document5', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd5', 'sp-document5');diff --git a/crates/macro_db_client/fixtures/highest_access_level_for_chat.sql b/crates/macro_db_client/fixtures/highest_access_level_for_chat.sqlindex 49e44dadf8..1bd87b3260 100644--- a/crates/macro_db_client/fixtures/highest_access_level_for_chat.sql+++ b/crates/macro_db_client/fixtures/highest_access_level_for_chat.sql@@ -34,21 +34,21 @@ VALUES ('cccccccc-cccc-cccc-cccc-000000000001', 'Nested Chat', 'user-1', 'aaaaaa('cccccccc-cccc-cccc-cccc-000000000003', 'Private Chat', 'user-1', NULL);-- Add SharePermission records. This is the new data for testing public access.-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")VALUES-- A public 'edit' permission. We'll attach this to the grandparent project.- ('sp-public-edit', true, 'edit'),+ ('sp-public-edit', 'PUBLIC', 'edit'),-- A public 'view' permission. We'll attach this to the parent project.- ('sp-public-view', true, 'view'),- -- A *private* 'owner' permission. This MUST be ignored by the query.- ('sp-private-owner', false, 'owner');+ ('sp-public-view', 'PUBLIC', 'view'),+ -- A private permission with no link-level access.+ ('sp-private-owner', NULL, NULL);-- Link share permissions to projects.INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'sp-public-edit'),('aaaaaaaa-aaaa-aaaa-aaaa-000000000002', 'sp-public-view');--- Link the private share permission to the chat to test the "isPublic" filter.+-- Link the private share permission to the chat to test the NULL link share filter.INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")VALUES ('cccccccc-cccc-cccc-cccc-000000000001', 'sp-public-edit');diff --git a/crates/macro_db_client/fixtures/highest_access_level_for_document.sql b/crates/macro_db_client/fixtures/highest_access_level_for_document.sqlindex e703b4f0fc..0fbe5244e9 100644--- a/crates/macro_db_client/fixtures/highest_access_level_for_document.sql+++ b/crates/macro_db_client/fixtures/highest_access_level_for_document.sql@@ -34,21 +34,21 @@ VALUES ('dddddddd-dddd-dddd-dddd-000000000001', 'Nested Document', 'user-1', 'aa('dddddddd-dddd-dddd-dddd-000000000003', 'Private Document', 'user-1', NULL);-- Add SharePermission records. This is the new data for testing public access.-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")VALUES-- A public 'edit' permission. We'll attach this to the grandparent project.- ('sp-public-edit', true, 'edit'),+ ('sp-public-edit', 'PUBLIC', 'edit'),-- A public 'view' permission. We'll attach this to the parent project.- ('sp-public-view', true, 'view'),- -- A *private* 'owner' permission. This MUST be ignored by the query.- ('sp-private-owner', false, 'owner');+ ('sp-public-view', 'PUBLIC', 'view'),+ -- A private permission with no link-level access.+ ('sp-private-owner', NULL, NULL);-- Link share permissions to projects.INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'sp-public-edit'),('aaaaaaaa-aaaa-aaaa-aaaa-000000000002', 'sp-public-view');--- Link the private share permission to the document to test the "isPublic" filter.+-- Link the private share permission to the document to test the NULL link share filter.INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")VALUES ('dddddddd-dddd-dddd-dddd-000000000001', 'sp-public-edit');diff --git a/crates/macro_db_client/fixtures/highest_access_level_for_project.sql b/crates/macro_db_client/fixtures/highest_access_level_for_project.sqlindex 0171626ab0..0bb86bb71c 100644--- a/crates/macro_db_client/fixtures/highest_access_level_for_project.sql+++ b/crates/macro_db_client/fixtures/highest_access_level_for_project.sql@@ -22,14 +22,14 @@ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'Grandparent Project', 'user-1',('aaaaaaaa-aaaa-aaaa-aaaa-000000000004', 'Isolated Project', 'user-1', NULL);-- Add SharePermission records for public access.-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")VALUES-- A public 'edit' permission. We'll attach this to the grandparent project.- ('sp-public-edit-proj', true, 'edit'),+ ('sp-public-edit-proj', 'PUBLIC', 'edit'),-- A public 'view' permission. We'll attach this to the parent project.- ('sp-public-view-proj', true, 'view'),- -- A *private* 'owner' permission. This MUST be ignored by the query.- ('sp-private-owner-proj', false, 'owner');+ ('sp-public-view-proj', 'PUBLIC', 'view'),+ -- A private permission with no link-level access.+ ('sp-private-owner-proj', NULL, NULL);-- Link share permissions to projects.INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")diff --git a/crates/macro_db_client/fixtures/highest_access_level_for_thread.sql b/crates/macro_db_client/fixtures/highest_access_level_for_thread.sqlindex a5c94034db..f33b2d7c46 100644--- a/crates/macro_db_client/fixtures/highest_access_level_for_thread.sql+++ b/crates/macro_db_client/fixtures/highest_access_level_for_thread.sql@@ -21,26 +21,19 @@ VALUES ('aaaaaaaa-aaaa-aaaa-aaaa-000000000001', 'Grandparent Project', 'user-1',('aaaaaaaa-aaaa-aaaa-aaaa-000000000002', 'Parent Project', 'user-1', 'aaaaaaaa-aaaa-aaaa-aaaa-000000000001');-- Create placeholder SharePermission records. These are needed for the FK constraint in EmailThreadPermission.-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")VALUES-- For the nested thread- ('sp-thread-nested', false, NULL), -- this permission itself isn't used, just the link+ ('sp-thread-nested', NULL, NULL), -- this permission itself isn't used, just the link-- For the standalone thread- ('sp-thread-standalone', false, NULL),+ ('sp-thread-standalone', NULL, NULL),-- For the private thread- ('sp-thread-private', false, NULL),+ ('sp-thread-private', NULL, NULL),-- Public permissions that will be linked to projects- ('sp-public-edit-thread', true, 'edit'),- ('sp-public-view-thread', true, 'view'),- -- A *private* 'owner' permission to test the `isPublic` filter.- ('sp-private-owner-thread', false, 'owner');----- Link the private 'owner' permission directly to the nested thread.-UPDATE public."SharePermission"-SET "isPublic" = false,- "publicAccessLevel" = 'owner'-WHERE "id" = 'sp-thread-nested';+ ('sp-public-edit-thread', 'PUBLIC', 'edit'),+ ('sp-public-view-thread', 'PUBLIC', 'view'),+ -- A private permission with no link-level access.+ ('sp-private-owner-thread', NULL, NULL);-- Link public permissions to the project hierarchy.INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")diff --git a/crates/macro_db_client/fixtures/nested_share_permissions.sql b/crates/macro_db_client/fixtures/nested_share_permissions.sqlindex e1cc624b4f..8567448898 100644--- a/crates/macro_db_client/fixtures/nested_share_permissions.sql+++ b/crates/macro_db_client/fixtures/nested_share_permissions.sql@@ -15,10 +15,10 @@ VALUES('p2', 'test_project_name','macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'p1');-- Make project share permissions-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")VALUES-('sp-p1', true, 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00'),-('sp-p2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+('sp-p1', 'PUBLIC', 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00'),+('sp-p2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES@@ -37,10 +37,10 @@ VALUES('d1', 'test_document_name','macro|[email protected]', 'docx', NULL),('d2', 'test_document_name','macro|[email protected]', 'pdf', 'p2');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")VALUES-('sp-d1', true, 'edit'),-('sp-d2', false, NULL);+('sp-d1', 'PUBLIC', 'edit'),+('sp-d2', NULL, NULL);INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")VALUES@@ -59,10 +59,10 @@ VALUES('c1', 'test_chat_name','macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00', NULL),('c2', 'test_chat_name','macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'p2');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")VALUES-('sp-c1', true, 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00'),-('sp-c2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+('sp-c1', 'PUBLIC', 'edit', '2019-10-16 00:00:00', '2019-10-16 00:00:00'),+('sp-c2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")VALUESdiff --git a/crates/macro_db_client/fixtures/permissions.sql b/crates/macro_db_client/fixtures/permissions.sqlindex 60cf076e1d..69d26fe25b 100644--- a/crates/macro_db_client/fixtures/permissions.sql+++ b/crates/macro_db_client/fixtures/permissions.sql@@ -1,2 +1,2 @@-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp1', false, 'view', '2019-10-16 00:00:00', '2019-10-16 01:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp1', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 01:00:00');diff --git a/crates/macro_db_client/fixtures/populate_user_items.sql b/crates/macro_db_client/fixtures/populate_user_items.sqlindex f47a934783..0b520a85d1 100644--- a/crates/macro_db_client/fixtures/populate_user_items.sql+++ b/crates/macro_db_client/fixtures/populate_user_items.sql@@ -17,15 +17,15 @@ INSERT INTO public."User" ("id","email","stripeCustomerId", "organizationId","maINSERT INTO public."Project" ("id", "name", "userId", "createdAt", "updatedAt")(SELECT 'p1', 'a', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-project1', false, 'view', '2019-10-16 00:00:00', '2019-10-16 01:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-project1', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 01:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p1', 'sp-project1');INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p2', 'a1', 'macro|[email protected]', 'p1', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project2', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project2', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p2', 'sp-project2');@@ -33,8 +33,8 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "up(SELECT 'd1', 'test_document_name','pdf', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'p1');INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'd1', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-document1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-document1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd1', 'sp-document1');@@ -42,21 +42,21 @@ INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "up(SELECT 'd2', 'test_document_name','docx', 'macro|[email protected]', '2019-10-16 00:10:00', '2019-10-16 00:10:00');INSERT INTO public."DocumentBom" ("documentId", "createdAt", "updatedAt")(SELECT 'd2', '2019-10-16 00:10:00', '2019-10-16 00:10:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-document2', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-document2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd2', 'sp-document2');INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt", "projectId")(SELECT 'c1', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00', 'p1');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-chat1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-chat1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'c1', 'sp-chat1');INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt")(SELECT 'c2', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-chat2', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-chat2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ChatPermission" ("chatId", "sharePermissionId")(SELECT 'c2', 'sp-chat2');diff --git a/crates/macro_db_client/fixtures/project-content.sql b/crates/macro_db_client/fixtures/project-content.sqlindex 5cb206440b..d670aafd61 100644--- a/crates/macro_db_client/fixtures/project-content.sql+++ b/crates/macro_db_client/fixtures/project-content.sql@@ -54,14 +54,14 @@ INSERT INTO public."Chat" ("id","name","userId", "createdAt", "updatedAt", "proj(SELECT 'chat-one', 'test-chat', 'macro|[email protected]', '2019-10-16 01:01:00', '2019-10-16 01:01:00', 'p10');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'document-one', 'sp-1');-INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")-(SELECT 'sp-2', false, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'document-two', 'sp-2');diff --git a/crates/macro_db_client/fixtures/project_permissions.sql b/crates/macro_db_client/fixtures/project_permissions.sqlindex d1e7a6996c..6a7ebb453c 100644--- a/crates/macro_db_client/fixtures/project_permissions.sql+++ b/crates/macro_db_client/fixtures/project_permissions.sql@@ -10,8 +10,8 @@ INSERT INTO public."User" ("id","email","stripeCustomerId","macro_user_id")INSERT INTO public."Project" ("id","name","userId","parentId","createdAt","updatedAt")(SELECT 'project-one', 'test_project_name','macro|[email protected]', NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'project-one', 'sp-1');@@ -19,8 +19,8 @@ INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")INSERT INTO public."Project" ("id","name","userId","parentId","createdAt","updatedAt")(SELECT 'project-two', 'test_project_name','macro|[email protected]', NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'project-two', 'sp-2');diff --git a/crates/macro_db_client/fixtures/project_preview.sql b/crates/macro_db_client/fixtures/project_preview.sqlindex 3f47665ab5..29f865dd2f 100644--- a/crates/macro_db_client/fixtures/project_preview.sql+++ b/crates/macro_db_client/fixtures/project_preview.sql@@ -9,8 +9,8 @@ VALUES ('macro|[email protected]', '[email protected]','stripe_iddfkjdfkdf', 'a2222222INSERT INTO public."Project" ("id","name", "userId", "createdAt", "updatedAt")VALUES ('project-one', 'test_project_name', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-VALUES ('share-permission-one', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+VALUES ('share-permission-one', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES ('project-one', 'share-permission-one');@@ -22,8 +22,8 @@ VALUES ('macro|[email protected]', 'project-one', 'project', 0, '2019-10-16 00:00:00INSERT INTO public."Project" ("id","name", "userId", "createdAt", "updatedAt")VALUES ('project-two', 'test_project_name', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-VALUES ('share-permission-two', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+VALUES ('share-permission-two', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES ('project-two', 'share-permission-two');diff --git a/crates/macro_db_client/fixtures/projects.sql b/crates/macro_db_client/fixtures/projects.sqlindex b3dbca0f61..e0f814e293 100644--- a/crates/macro_db_client/fixtures/projects.sql+++ b/crates/macro_db_client/fixtures/projects.sql@@ -1,43 +1,43 @@INSERT INTO public."Project" ("id", "name", "userId", "createdAt", "updatedAt")(SELECT 'p1', 'a', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-project1', false, 'view', '2019-10-16 00:00:00', '2019-10-16 01:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-project1', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 01:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p1', 'sp-project1');INSERT INTO public."Project" ("id", "name", "userId", "createdAt", "updatedAt")(SELECT 'pb1', 'b', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-projectb1', true, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-projectb1', 'PUBLIC', 'view');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'pb1', 'sp-projectb1');-- Sub projects of p1INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p2', 'a1', 'macro|[email protected]', 'p1', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project2', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project2', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p2', 'sp-project2');INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p3', 'a2', 'macro|[email protected]', 'p1', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project3', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project3', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p3', 'sp-project3');INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p4', 'a3', 'macro|[email protected]', 'p1', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project4', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project4', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p4', 'sp-project4');INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p5', 'a4', 'macro|[email protected]', 'p1', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project5', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project5', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p5', 'sp-project5');@@ -45,45 +45,45 @@ INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")-- Sub projects of p2INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p6', 'b1', 'macro|[email protected]', 'p2', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project6', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project6', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p6', 'sp-project6');INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p7', 'b2', 'macro|[email protected]', 'p2', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project7', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project7', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p7', 'sp-project7');-- Sub projects of project-sixINSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p8', 'c1', 'macro|[email protected]', 'p6', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project8', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project8', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p8', 'sp-project8');-- Project 9 is a project user does not have access toINSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p9', 'd1', 'macro|[email protected]', 'p8', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project9', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project9', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p9', 'sp-project9');INSERT INTO public."Project" ("id", "name", "userId", "parentId", "createdAt", "updatedAt")(SELECT 'p10', 'e1', 'macro|[email protected]', 'p9', '2019-10-16 00:00:00', '2019-10-16 01:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")-(SELECT 'sp-project10', false, 'view');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+(SELECT 'sp-project10', NULL, NULL);INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p10', 'sp-project10');INSERT INTO public."Project" ("id", "name", "userId", "parentId")(SELECT 'p11', 'f1', 'macro|[email protected]', 'p2');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-project11', true, 'view', '2019-10-16 00:00:00', '2019-10-16 01:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-project11', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 01:00:00');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")(SELECT 'p11', 'sp-project11');diff --git a/crates/macro_db_client/fixtures/share_on_mention.sql b/crates/macro_db_client/fixtures/share_on_mention.sqlindex 5131b13a90..9f19784d3a 100644--- a/crates/macro_db_client/fixtures/share_on_mention.sql+++ b/crates/macro_db_client/fixtures/share_on_mention.sql@@ -28,8 +28,8 @@ VALUES ('2022-01-01 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-VALUES ('sp-public', true, 'comment', '2022-01-01 00:00:00', '2022-01-01 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+VALUES ('sp-public', 'PUBLIC', 'comment', '2022-01-01 00:00:00', '2022-01-01 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")VALUES ('11111111-1111-1111-1111-111111111111', 'sp-public');@@ -45,8 +45,8 @@ VALUES ('2022-01-01 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-VALUES ('sp-private', false, NULL, '2022-01-01 00:00:00', '2022-01-01 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+VALUES ('sp-private', NULL, NULL, '2022-01-01 00:00:00', '2022-01-01 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")VALUES ('22222222-2222-2222-2222-222222222222', 'sp-private');diff --git a/crates/macro_db_client/fixtures/share_permissions.sql b/crates/macro_db_client/fixtures/share_permissions.sqlindex 6228a9a7be..a25ba447f1 100644--- a/crates/macro_db_client/fixtures/share_permissions.sql+++ b/crates/macro_db_client/fixtures/share_permissions.sql@@ -8,14 +8,14 @@ INSERT INTO public."User" ("id","email","stripeCustomerId","macro_user_id")INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "updatedAt")(SELECT 'document-one', 'test_document_name','pdf', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-1', true, 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-1', 'PUBLIC', 'view', '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'document-one', 'sp-1');INSERT INTO public."Document" ("id","name","fileType", "owner", "createdAt", "updatedAt")(SELECT 'document-two', 'test_document_name','pdf', 'macro|[email protected]', '2019-10-16 00:00:00', '2019-10-16 00:00:00');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel", "createdAt", "updatedAt")-(SELECT 'sp-2', false, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt")+(SELECT 'sp-2', NULL, NULL, '2019-10-16 00:00:00', '2019-10-16 00:00:00');INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'document-two', 'sp-2');diff --git a/crates/macro_db_client/fixtures/uia_access_level_thread.sql b/crates/macro_db_client/fixtures/uia_access_level_thread.sqlindex 70f555af47..2e075fef76 100644--- a/crates/macro_db_client/fixtures/uia_access_level_thread.sql+++ b/crates/macro_db_client/fixtures/uia_access_level_thread.sql@@ -14,9 +14,9 @@ VALUES ('00000000-0000-0000-0000-000000aae002', 'Grandparent Project', 'user-1',('00000000-0000-0000-0000-000000aae001', 'Parent Project', 'user-1', '00000000-0000-0000-0000-000000aae002');-- Create placeholder SharePermission records required for foreign key constraints in EmailThreadPermission.-INSERT INTO public."SharePermission" ("id", "isPublic")-VALUES ('sp-thread-nested', false),- ('sp-thread-standalone', false);+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+VALUES ('sp-thread-nested', NULL, NULL),+ ('sp-thread-standalone', NULL, NULL);-- Create the EmailThreadPermission entries. This table links a thread to a user and optionally a project.INSERT INTO public."EmailThreadPermission" ("threadId", "sharePermissionId", "userId", "projectId")diff --git a/crates/macro_db_client/fixtures/user_item_access.sql b/crates/macro_db_client/fixtures/user_item_access.sqlindex cf0c920bed..65efe0e0f2 100644--- a/crates/macro_db_client/fixtures/user_item_access.sql+++ b/crates/macro_db_client/fixtures/user_item_access.sql@@ -34,8 +34,8 @@ INSERT INTO public."Document" ("id", "name", "fileType", "owner", "createdAt", "INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "createdAt", "updatedAt", "sha")(SELECT 'test_document_name', 'document-one', '2019-10-16 00:00:00', '2019-10-16 00:00:00', 'sha');-INSERT INTO public."SharePermission" ("id", "isPublic", "publicAccessLevel")- (SELECT 'sp-document1', true, 'read');+INSERT INTO public."SharePermission" ("id", "linkShare", "linkShareAccessLevel")+ (SELECT 'sp-document1', 'PUBLIC', 'view');INSERT INTO public."Document" ("id", "name", "fileType", "owner", "createdAt", "updatedAt")(SELECT 'document-two',diff --git a/crates/macro_db_client/migrations/20260813165731_add_link_share_columns.sql b/crates/macro_db_client/migrations/20260813165731_add_link_share_columns.sqlnew file mode 100644index 0000000000..45920614fe--- /dev/null+++ b/crates/macro_db_client/migrations/20260813165731_add_link_share_columns.sql@@ -0,0 +1,21 @@+-- Deployment prerequisite: check the number of public rows with+-- `SELECT count(*) FROM "SharePermission" WHERE "isPublic";` before applying+-- this migration. If there are more than approximately 10 million public rows,+-- replace this single-statement backfill with a batched migration.+ALTER TABLE "SharePermission"+ ADD COLUMN "linkShare" TEXT,+ ADD COLUMN "linkShareAccessLevel" "AccessLevel",+ ADD CONSTRAINT "SharePermission_linkShare_check"+ CHECK ("linkShare" IN ('PUBLIC', 'TEAM')),+ ADD CONSTRAINT "SharePermission_linkShareAccessLevel_check"+ CHECK ("linkShare" IS NOT NULL OR "linkShareAccessLevel" IS NULL),+ ALTER COLUMN "isPublic" SET DEFAULT false;++UPDATE "SharePermission"+SET "linkShare" = 'PUBLIC',+ "linkShareAccessLevel" = COALESCE(+ "publicAccessLevel"::"AccessLevel",+ 'view'::"AccessLevel"+ )+WHERE "isPublic";+diff --git a/crates/macro_db_client/migrations/20260813201032_drop_legacy_public_share_columns.sql b/crates/macro_db_client/migrations/20260813201032_drop_legacy_public_share_columns.sqlnew file mode 100644index 0000000000..c9a6148cd4--- /dev/null+++ b/crates/macro_db_client/migrations/20260813201032_drop_legacy_public_share_columns.sql@@ -0,0 +1,3 @@+ALTER TABLE "SharePermission"+ DROP COLUMN "isPublic",+ DROP COLUMN "publicAccessLevel";diff --git a/crates/macro_db_client/src/call_record/get.rs b/crates/macro_db_client/src/call_record/get.rsindex 058192cdd3..52fd4e64eb 100644--- a/crates/macro_db_client/src/call_record/get.rs+++ b/crates/macro_db_client/src/call_record/get.rs@@ -1,3 +1,6 @@+#[cfg(test)]+mod test;+use chrono::{DateTime, Utc};use uuid::Uuid;@@ -91,8 +94,21 @@ pub async fn get_accessible_call_ids() OR EXISTS (SELECT 1 FROM "SharePermission" spWHERE sp.id = cr.share_permission_id- AND sp."isPublic" = true- AND sp."publicAccessLevel" IS NOT NULL+ AND sp."linkShareAccessLevel" IS NOT NULL+ AND (+ sp."linkShare" = 'PUBLIC'+ OR (+ sp."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1+ FROM team_user owner_team+ WHERE owner_team.user_id = cr.created_by+ AND owner_team.team_id::text IN (+ SELECT source_id FROM user_source_ids+ )+ )+ )+ ))))diff --git a/crates/macro_db_client/src/call_record/get/test.rs b/crates/macro_db_client/src/call_record/get/test.rsnew file mode 100644index 0000000000..ea5068471a--- /dev/null+++ b/crates/macro_db_client/src/call_record/get/test.rs@@ -0,0 +1,223 @@+use super::*;+use sqlx::PgPool;++const REQUESTER: &str = "macro|[email protected]";+const SAME_TEAM_OWNER: &str = "macro|[email protected]";+const OTHER_TEAM_OWNER: &str = "macro|[email protected]";+const OWNER_WITHOUT_TEAM: &str = "macro|[email protected]";+const REQUESTER_TEAM: Uuid = Uuid::from_u128(0x00000000000000000000000000001101);+const OTHER_TEAM: Uuid = Uuid::from_u128(0x00000000000000000000000000001102);++async fn insert_user(pool: &PgPool, user_id: &str) -> anyhow::Result<()> {+ let macro_user_id = Uuid::new_v4();+ let email = user_id.strip_prefix("macro|").unwrap_or(user_id);++ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $2)+ "#,+ macro_user_id,+ user_id,+ email,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#,+ user_id,+ email,+ macro_user_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++async fn insert_team(+ pool: &PgPool,+ team_id: Uuid,+ owner_id: &str,+ member_ids: &[&str],+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#,+ team_id,+ format!("Call listing team {team_id}"),+ owner_id,+ )+ .execute(pool)+ .await?;++ for member_id in member_ids {+ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES ($1, $2, 'member')+ "#,+ member_id,+ team_id,+ )+ .execute(pool)+ .await?;+ }++ Ok(())+}++async fn insert_call_record(+ pool: &PgPool,+ owner_id: &str,+ link_share: Option<&str>,+) -> anyhow::Result<Uuid> {+ let call_id = Uuid::new_v4();+ let channel_id = Uuid::new_v4();+ let share_permission_id = Uuid::new_v4().to_string();++ sqlx::query!(+ r#"+ INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id)+ VALUES ($1, 'Call listing test', 'public', NULL, $2)+ "#,+ channel_id,+ owner_id,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "SharePermission" (+ id,+ "linkShare",+ "linkShareAccessLevel"+ )+ VALUES (+ $1,+ $2::text,+ CASE WHEN $2::text IS NULL THEN NULL ELSE 'view'::"AccessLevel" END+ )+ "#,+ share_permission_id,+ link_share,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO call_records (+ id,+ channel_id,+ room_name,+ created_by,+ started_at,+ ended_at,+ duration_ms,+ share_permission_id+ )+ VALUES ($1, $2, 'call-listing-test', $3, NOW(), NOW(), 0, $4)+ "#,+ call_id,+ channel_id,+ owner_id,+ share_permission_id,+ )+ .execute(pool)+ .await?;++ Ok(call_id)+}++fn assert_visibility(call_ids: &[Uuid], call_id: Uuid, visible: bool, case: &str) {+ assert_eq!(+ call_ids.contains(&call_id),+ visible,+ "unexpected visibility for {case} call record",+ );+}++#[sqlx::test]+async fn filters_link_shared_call_records_by_owner_team(pool: PgPool) -> anyhow::Result<()> {+ for user_id in [+ REQUESTER,+ SAME_TEAM_OWNER,+ OTHER_TEAM_OWNER,+ OWNER_WITHOUT_TEAM,+ ] {+ insert_user(&pool, user_id).await?;+ }++ insert_team(+ &pool,+ REQUESTER_TEAM,+ SAME_TEAM_OWNER,+ &[REQUESTER, SAME_TEAM_OWNER],+ )+ .await?;+ insert_team(&pool, OTHER_TEAM, OTHER_TEAM_OWNER, &[OTHER_TEAM_OWNER]).await?;++ let public = insert_call_record(&pool, OTHER_TEAM_OWNER, Some("PUBLIC")).await?;+ let no_link = insert_call_record(&pool, SAME_TEAM_OWNER, None).await?;+ let same_team = insert_call_record(&pool, SAME_TEAM_OWNER, Some("TEAM")).await?;+ let other_team = insert_call_record(&pool, OTHER_TEAM_OWNER, Some("TEAM")).await?;+ let owner_without_team = insert_call_record(&pool, OWNER_WITHOUT_TEAM, Some("TEAM")).await?;++ let call_ids = get_accessible_call_ids(&pool, REQUESTER, &[]).await?;++ assert_visibility(&call_ids, public, true, "PUBLIC");+ assert_visibility(&call_ids, no_link, false, "NULL");+ assert_visibility(&call_ids, same_team, true, "same-team TEAM");+ assert_visibility(&call_ids, other_team, false, "other-team TEAM");+ assert_visibility(+ &call_ids,+ owner_without_team,+ false,+ "TEAM with an owner without a team",+ );+ assert_eq!(call_ids.len(), 2);++ Ok(())+}++#[sqlx::test]+async fn preserves_explicit_access_and_status_filtering(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, REQUESTER).await?;+ insert_user(&pool, OWNER_WITHOUT_TEAM).await?;+ let call_id = insert_call_record(&pool, OWNER_WITHOUT_TEAM, None).await?;++ sqlx::query!(+ r#"+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level+ )+ VALUES ($1, 'call', $2, 'user', 'view')+ "#,+ call_id,+ REQUESTER,+ )+ .execute(&pool)+ .await?;++ assert_eq!(+ get_accessible_call_ids(&pool, REQUESTER, &[]).await?,+ vec![call_id],+ );+ assert_eq!(+ get_accessible_call_ids(&pool, REQUESTER, &["UNATTENDED".to_string()]).await?,+ vec![call_id],+ );+ assert!(+ get_accessible_call_ids(&pool, REQUESTER, &["ATTENDED".to_string()])+ .await?+ .is_empty(),+ );++ Ok(())+}diff --git a/crates/macro_db_client/src/lib.rs b/crates/macro_db_client/src/lib.rsindex 40225f8bb6..b27010286a 100644--- a/crates/macro_db_client/src/lib.rs+++ b/crates/macro_db_client/src/lib.rs@@ -26,7 +26,6 @@ pub mod job;pub mod macro_user;pub mod macro_user_email_verification;pub mod macro_user_links;-pub mod macros;pub mod notification;pub mod organization;pub mod pins;@@ -40,11 +39,3 @@ pub mod team;pub mod user;pub mod user_document_view_location;pub mod user_quota;--#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]-pub enum Parameters {- BigNumber(i64),- SmallNumber(i32),- String(String),- Bool(bool),-}diff --git a/crates/macro_db_client/src/macros/create.rs b/crates/macro_db_client/src/macros/create.rsdeleted file mode 100644index 3729db222e..0000000000--- a/crates/macro_db_client/src/macros/create.rs+++ /dev/null@@ -1,44 +0,0 @@-use models_permissions::share_permission::SharePermissionV2;--use crate::share_permission::create::create_macro_permission;--#[tracing::instrument(skip(db))]-#[expect(clippy::too_many_arguments, reason = "too annoying to fix")]-pub async fn create_macro(- db: &sqlx::Pool<sqlx::Postgres>,- user_id: &str,- title: &str,- prompt: &str,- icon: &str,- color: &str,- required_docs: Option<i32>,- share_permission: &SharePermissionV2,-) -> anyhow::Result<String> {- let mut transaction = db.begin().await?;-- let macro_item = sqlx::query!(- r#"- INSERT INTO "MacroPrompt" (user_id, title, prompt, icon, color, required_docs)- VALUES ($1, $2, $3, $4, $5, $6)- RETURNING id;- "#,- &user_id,- &title,- &prompt,- &icon,- &color,- required_docs,- )- .map(|row| row.id)- .fetch_one(&mut *transaction)- .await?;-- create_macro_permission(&mut transaction, ¯o_item, share_permission).await?;-- transaction.commit().await.map_err(|e| {- tracing::error!(error=?e, "create_macro transaction error");- anyhow::Error::from(e)- })?;-- Ok(macro_item)-}diff --git a/crates/macro_db_client/src/macros/mod.rs b/crates/macro_db_client/src/macros/mod.rsdeleted file mode 100644index c5fb369c1d..0000000000--- a/crates/macro_db_client/src/macros/mod.rs+++ /dev/null@@ -1 +0,0 @@-pub mod create;diff --git a/crates/macro_db_client/src/share_on_mention/mod.rs b/crates/macro_db_client/src/share_on_mention/mod.rsindex 228a3f0acc..db1a5776e9 100644--- a/crates/macro_db_client/src/share_on_mention/mod.rs+++ b/crates/macro_db_client/src/share_on_mention/mod.rs@@ -1,11 +1,10 @@-//! Auto-share a public document with users mentioned in its comments.+//! Auto-share a link-shared document with users mentioned in its comments.//!//! When a user is `@mentioned` in a document comment we notify them, but being//! notified isn't enough for the document to surface in their soup/inbox — that-//! requires an explicit `entity_access` row. For **public** documents we grant-//! the mentioned users access at the document's public access level so the-//! mention is actionable from their inbox. Private documents are left untouched-//! so a mention can't silently widen access beyond what was already public.+//! requires an explicit `entity_access` row. For documents shared by a PUBLIC or+//! TEAM link, every mentioned user is granted the selected link-share access+//! level. Documents without link sharing are left untouched.use macro_user_id::user_id::MacroUserIdStr;use sqlx::{Pool, Postgres};@@ -13,18 +12,20 @@ use sqlx::{Pool, Postgres};#[cfg(test)]mod test;-/// Grants the mentioned users `entity_access` to the document when it is public,-/// so the document appears in their soup.+/// Grants mentioned users `entity_access` to a link-shared document so it+/// appears in their soup.///-/// No-op when the document isn't public or no users are supplied. Existing-/// access rows are never downgraded (conflicts are ignored), and the owner row-/// is left intact.+/// PUBLIC and TEAM links grant every mentioned user the document's selected+/// link-share access level; TEAM grants are intentionally not filtered by team+/// membership. Documents without link sharing and empty recipient lists are+/// no-ops. Existing access rows are never downgraded because conflicts are+/// ignored, and the owner row is left intact.#[tracing::instrument(skip(db, mentioned_user_ids),fields(document_id = %document_id, user_count = mentioned_user_ids.len()),err)]-pub async fn share_public_document_with_mentioned_users(+pub async fn share_link_shared_document_with_mentioned_users(db: &Pool<Postgres>,document_id: &str,mentioned_user_ids: &[MacroUserIdStr<'_>],@@ -38,21 +39,19 @@ pub async fn share_public_document_with_mentioned_users(.map(|id| id.as_ref().to_string()).collect();- // Insert one access row per mentioned user, but only when the document is- // public — the join against `SharePermission` yields no rows otherwise, so- // the whole statement becomes a no-op for private documents. We grant the- // same level the document is public at, and `DO NOTHING` ensures we never- // clobber a user's pre-existing (possibly higher) access.+ // Insert one access row per mentioned user when the document has a PUBLIC+ // or TEAM link. The query deliberately does not filter recipients by team+ // membership. `DO NOTHING` preserves pre-existing (possibly higher) access.sqlx::query!(r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)- SELECT dp."documentId"::uuid, 'document', u.user_id, 'user', sp."publicAccessLevel"::"AccessLevel"+ SELECT dp."documentId"::uuid, 'document', u.user_id, 'user', sp."linkShareAccessLevel"::"AccessLevel"FROM "DocumentPermission" dpJOIN "SharePermission" sp ON sp.id = dp."sharePermissionId"CROSS JOIN UNNEST($2::text[]) AS u(user_id)WHERE dp."documentId" = $1- AND sp."isPublic" = true- AND sp."publicAccessLevel" IS NOT NULL+ AND sp."linkShare" IN ('PUBLIC', 'TEAM')+ AND sp."linkShareAccessLevel" IS NOT NULLON CONFLICT (entity_id, entity_type, source_id, source_type)WHERE granted_from_project_id IS NULLDO NOTHINGdiff --git a/crates/macro_db_client/src/share_on_mention/test.rs b/crates/macro_db_client/src/share_on_mention/test.rsindex 85dae35d50..0d63509f2c 100644--- a/crates/macro_db_client/src/share_on_mention/test.rs+++ b/crates/macro_db_client/src/share_on_mention/test.rs@@ -27,13 +27,19 @@ async fn access_level_for(}#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]-async fn shares_public_document_with_mentioned_users(pool: Pool<Postgres>) -> anyhow::Result<()> {+async fn shares_public_link_document_with_mentioned_users(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {let mentioned = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();- share_public_document_with_mentioned_users(&pool, PUBLIC_DOC, std::slice::from_ref(&mentioned))- .await?;+ share_link_shared_document_with_mentioned_users(+ &pool,+ PUBLIC_DOC,+ std::slice::from_ref(&mentioned),+ )+ .await?;- // The mentioned user gets access at the document's public access level.+ // The mentioned user gets access at the document's link-share access level.assert_eq!(access_level_for(&pool, PUBLIC_DOC, mentioned.as_ref()).await,Some("comment".to_string()),@@ -42,18 +48,72 @@ async fn shares_public_document_with_mentioned_users(pool: Pool<Postgres>) -> anOk(())}+#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]+async fn shares_team_link_document_with_off_team_mentioned_user(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO team (id, name, owner_id)+ VALUES ('33333333-3333-3333-3333-333333333333', 'Owner Team', 'macro|[email protected]')+ "#,+ )+ .execute(&pool)+ .await?;+ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES (+ 'macro|[email protected]',+ '33333333-3333-3333-3333-333333333333',+ 'owner'+ )+ "#,+ )+ .execute(&pool)+ .await?;+ sqlx::query!(+ r#"+ UPDATE "SharePermission"+ SET "linkShare" = 'TEAM',+ "linkShareAccessLevel" = 'view'+ WHERE id = 'sp-public'+ "#,+ )+ .execute(&pool)+ .await?;++ // This user has no team_user row and is therefore outside the owner's team.+ let off_team_mentioned =+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();++ share_link_shared_document_with_mentioned_users(+ &pool,+ PUBLIC_DOC,+ std::slice::from_ref(&off_team_mentioned),+ )+ .await?;++ assert_eq!(+ access_level_for(&pool, PUBLIC_DOC, off_team_mentioned.as_ref()).await,+ Some("view".to_string()),+ );++ Ok(())+}+#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]async fn does_not_share_private_document(pool: Pool<Postgres>) -> anyhow::Result<()> {let mentioned = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();- share_public_document_with_mentioned_users(+ share_link_shared_document_with_mentioned_users(&pool,PRIVATE_DOC,std::slice::from_ref(&mentioned),).await?;- // Private documents are left untouched — no access is granted.+ // Documents without link sharing are left untouched.assert_eq!(access_level_for(&pool, PRIVATE_DOC, mentioned.as_ref()).await,None,@@ -67,7 +127,7 @@ async fn does_not_downgrade_existing_access(pool: Pool<Postgres>) -> anyhow::Reslet mentioned = MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();let entity_id = macro_uuid::string_to_uuid(PUBLIC_DOC).unwrap();- // The user already has edit access to the public document.+ // The user already has edit access to the PUBLIC-link document.sqlx::query!(r#"INSERT INTO entity_access (entity_id, entity_type, source_id, source_type, access_level)@@ -79,8 +139,12 @@ async fn does_not_downgrade_existing_access(pool: Pool<Postgres>) -> anyhow::Res.execute(&pool).await?;- share_public_document_with_mentioned_users(&pool, PUBLIC_DOC, std::slice::from_ref(&mentioned))- .await?;+ share_link_shared_document_with_mentioned_users(+ &pool,+ PUBLIC_DOC,+ std::slice::from_ref(&mentioned),+ )+ .await?;// The pre-existing (higher) access level is preserved, not clobbered.assert_eq!(@@ -94,7 +158,7 @@ async fn does_not_downgrade_existing_access(pool: Pool<Postgres>) -> anyhow::Res#[sqlx::test(fixtures(path = "../../fixtures", scripts("share_on_mention")))]async fn empty_recipients_is_a_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {let entity_id = macro_uuid::string_to_uuid(PUBLIC_DOC).unwrap();- share_public_document_with_mentioned_users(&pool, PUBLIC_DOC, &[]).await?;+ share_link_shared_document_with_mentioned_users(&pool, PUBLIC_DOC, &[]).await?;let count = sqlx::query_scalar!(r#"SELECT COUNT(*) as "count!" FROM entity_access WHERE entity_id = $1"#,diff --git a/crates/macro_db_client/src/share_permission/access_level/chat.rs b/crates/macro_db_client/src/share_permission/access_level/chat.rsindex e1a41d2aa1..7c8f7e84ad 100644--- a/crates/macro_db_client/src/share_permission/access_level/chat.rs+++ b/crates/macro_db_client/src/share_permission/access_level/chat.rs@@ -49,15 +49,28 @@ pub async fn get_highest_access_level_for_chats(AND ea.entity_id = ANY(SELECT id::uuid FROM "Chat" WHERE id = ANY($1) AND "deletedAt" IS NULL)AND ea.entity_type = 'chat'UNION ALL- -- Source 2: Direct chat public permissions+ -- Source 2: Direct chat link permissionsSELECTc.id as chat_id,- sp."publicAccessLevel" as access_level+ sp."linkShareAccessLevel"::text as access_levelFROM "Chat" cJOIN "ChatPermission" cp ON cp."chatId" = c.idJOIN "SharePermission" sp ON sp.id = cp."sharePermissionId"- AND sp."isPublic" = true- AND sp."publicAccessLevel" IS NOT NULL+ AND sp."linkShareAccessLevel" IS NOT NULL+ AND (+ sp."linkShare" = 'PUBLIC'+ OR (+ sp."linkShare" = 'TEAM'+ AND EXISTS (+ SELECT 1+ FROM team_user owner_team+ WHERE owner_team.user_id = c."userId"+ AND owner_team.team_id::text = ANY(+ SELECT source_id FROM user_source_ids+ )+ )+ )+ )WHERE c.id = ANY($1) AND c."deletedAt" IS NULL) as all_levels"#,diff --git a/crates/macro_db_client/src/share_permission/access_level/chat_tests.rs b/crates/macro_db_client/src/share_permission/access_level/chat_tests.rsindex c6bdbbef37..71c0477b8e 100644--- a/crates/macro_db_client/src/share_permission/access_level/chat_tests.rs+++ b/crates/macro_db_client/src/share_permission/access_level/chat_tests.rs@@ -1,5 +1,64 @@use super::*;+async fn configure_team_link_access(pool: &sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO team (id, name, owner_id)+ VALUES+ ('dddddddd-dddd-dddd-dddd-000000000001', 'Chat owner team', 'user-1'),+ ('dddddddd-dddd-dddd-dddd-000000000002', 'Other team', 'user-2')+ "#,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO team_user (user_id, team_id, team_role)+ VALUES+ ('user-1', 'dddddddd-dddd-dddd-dddd-000000000001', 'owner'),+ ('user-3', 'dddddddd-dddd-dddd-dddd-000000000001', 'member'),+ ('user-2', 'dddddddd-dddd-dddd-dddd-000000000002', 'owner'),+ ('user-public-access-only', 'dddddddd-dddd-dddd-dddd-000000000002', 'member')+ "#,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ UPDATE "SharePermission"+ SET "linkShare" = 'TEAM', "linkShareAccessLevel" = 'comment'+ WHERE id = 'sp-public-edit'+ "#,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level+ )+ VALUES (+ 'cccccccc-cccc-cccc-cccc-000000000001',+ 'chat',+ 'user-3',+ 'user',+ 'view'+ )+ "#,+ )+ .execute(pool)+ .await?;++ Ok(())+}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]async fn test_batch_public_access_user(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {// SCENARIO: Get access for 'user-public-access-only' on multiple chats@@ -46,6 +105,48 @@ async fn test_batch_user_with_mixed_access(pool: sqlx::Pool<sqlx::Postgres>) ->Ok(())}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_team_link_access_for_same_team_user(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ configure_team_link_access(&pool).await?;+ let chat_id = "cccccccc-cccc-cccc-cccc-000000000001".to_string();++ let access_levels =+ get_highest_access_level_for_chats(&pool, std::slice::from_ref(&chat_id), "user-3").await?;++ assert_eq!(+ access_levels.get(&chat_id),+ Some(&Some(AccessLevel::Comment)),+ "expected TEAM link access to exceed the user's explicit view access"+ );++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]+async fn test_batch_team_link_denies_other_team_user(+ pool: sqlx::Pool<sqlx::Postgres>,+) -> anyhow::Result<()> {+ configure_team_link_access(&pool).await?;+ let chat_id = "cccccccc-cccc-cccc-cccc-000000000001".to_string();++ let access_levels = get_highest_access_level_for_chats(+ &pool,+ std::slice::from_ref(&chat_id),+ "user-public-access-only",+ )+ .await?;++ assert_eq!(+ access_levels.get(&chat_id),+ Some(&None),+ "expected no TEAM link access for a user on another team"+ );++ Ok(())+}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("highest_access_level_for_chat")))]async fn test_batch_empty_input(pool: sqlx::Pool<sqlx::Postgres>) -> anyhow::Result<()> {// SCENARIO: Test with empty chat_ids vectordiff --git a/crates/macro_db_client/src/share_permission/create.rs b/crates/macro_db_client/src/share_permission/create.rsindex d150d79ddc..6ff31355af 100644--- a/crates/macro_db_client/src/share_permission/create.rs+++ b/crates/macro_db_client/src/share_permission/create.rs@@ -1,9 +1,29 @@-use super::channel_permission::create::create_channel_share_permissions;use macro_user_id::user_id::MacroUserIdStr;use model::thread::EmailThreadPermission;-use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;-use std::str::FromStr;+use models_permissions::share_permission::{LinkShare, SharePermissionV2};++use super::channel_permission::create::create_channel_share_permissions;++pub(super) fn link_share_access_level_or_default(+ link_share_access_level: Option<AccessLevel>,+) -> AccessLevel {+ if let Some(access_level) = link_share_access_level {+ return access_level;+ }++ tracing::warn!(+ "link_share was enabled but link share access level was not provided, setting to view"+ );+ AccessLevel::View+}++fn normalize_link_share_access_level(+ link_share: Option<LinkShare>,+ link_share_access_level: Option<AccessLevel>,+) -> Option<AccessLevel> {+ link_share.map(|_| link_share_access_level_or_default(link_share_access_level))+}/// Creates a new share permission#[tracing::instrument(skip(transaction))]@@ -11,32 +31,37 @@ pub async fn create_share_permission(transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,share_permission: &SharePermissionV2,) -> anyhow::Result<SharePermissionV2> {- let result = sqlx::query!(+ let link_share = share_permission.link_share;+ let link_share_access_level =+ normalize_link_share_access_level(link_share, share_permission.link_share_access_level);+ let link_share_value = link_share.map(|value| value.to_string());++ let id = sqlx::query_scalar!(r#"- INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")+ INSERT INTO "SharePermission" (+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt"+ )VALUES ($1, $2, NOW(), NOW())- RETURNING id, "isPublic" as is_public, "publicAccessLevel" as public_access_level;+ RETURNING id;"#,- share_permission.is_public,- share_permission.public_access_level.as_ref().map(|s| s.to_string()),+ link_share_value,+ link_share_access_level as _,).fetch_one(transaction.as_mut()).await?;if let Some(channel_share_permissions) = share_permission.channel_share_permissions.as_ref() {- create_channel_share_permissions(transaction, &result.id, channel_share_permissions)- .await?;+ create_channel_share_permissions(transaction, &id, channel_share_permissions).await?;}- let public_access_level: Option<AccessLevel> = result- .public_access_level- .map(|s| AccessLevel::from_str(&s).unwrap());-Ok(SharePermissionV2 {- id: result.id,- is_public: result.is_public,- public_access_level,- owner: "".to_string(), // don't care about owner+ id,+ link_share,+ link_share_access_level,+ owner: String::new(), // Owner is not stored on the share permission row.channel_share_permissions: share_permission.channel_share_permissions.clone(),})}@@ -118,33 +143,6 @@ pub async fn create_chat_permission(Ok(updated_share_permission)}-/// Creates a new share permission and attaches it to the macro-#[tracing::instrument(skip(transaction))]-pub async fn create_macro_permission(- transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,- macro_id: &str,- share_permission: &SharePermissionV2,-) -> anyhow::Result<SharePermissionV2> {- let updated_share_permission = create_share_permission(transaction, share_permission).await?;-- sqlx::query!(- r#"- INSERT INTO "MacroPromptPermission" ("macro_prompt_id", "share_permission_id")- VALUES ($1, $2)- "#,- macro_id,- updated_share_permission.id,- )- .execute(transaction.as_mut())- .await- .map_err(|err| {- tracing::error!(error=?err, "unable to create macro permission");- err- })?;-- Ok(updated_share_permission)-}-/// Creates a new share permission and attaches it to the document#[tracing::instrument(skip(transaction))]pub async fn create_thread_permission(@@ -180,43 +178,4 @@ pub async fn create_thread_permission(}#[cfg(test)]-mod tests {- use super::*;- use models_permissions::share_permission::access_level::AccessLevel;- use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;- use sqlx::{Pool, Postgres};-- #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))]- async fn test_create_share_permission(pool: Pool<Postgres>) -> anyhow::Result<()> {- let mut transaction = pool.begin().await?;-- let share_permission = SharePermissionV2::new_project_share_permission();- let result = create_share_permission(&mut transaction, &share_permission).await?;-- assert_ne!(result.id, "".to_string());- assert!(result.channel_share_permissions.is_none());-- let share_permission = SharePermissionV2 {- id: "".to_string(),- owner: "".to_string(),- is_public: true,- public_access_level: Some(AccessLevel::Edit),- channel_share_permissions: Some(vec![- ChannelSharePermission {- channel_id: "channel-one".to_string(),- access_level: AccessLevel::View,- },- ChannelSharePermission {- channel_id: "channel-two".to_string(),- access_level: AccessLevel::Edit,- },- ]),- };- let result = create_share_permission(&mut transaction, &share_permission).await?;-- assert_ne!(result.id, "".to_string());- assert!(result.channel_share_permissions.is_some());-- Ok(())- }-}+mod test;diff --git a/crates/macro_db_client/src/share_permission/create/test.rs b/crates/macro_db_client/src/share_permission/create/test.rsnew file mode 100644index 0000000000..a5787564c9--- /dev/null+++ b/crates/macro_db_client/src/share_permission/create/test.rs@@ -0,0 +1,125 @@+use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;+use models_permissions::share_permission::{LinkShare, SharePermissionV2};+use sqlx::{Pool, Postgres, Transaction};++use super::*;++#[derive(Debug, PartialEq)]+struct StoredSharePermission {+ link_share: Option<String>,+ link_share_access_level: Option<String>,+}++fn share_permission(+ link_share: Option<LinkShare>,+ link_share_access_level: Option<AccessLevel>,+) -> SharePermissionV2 {+ SharePermissionV2 {+ id: String::new(),+ link_share,+ link_share_access_level,+ owner: String::new(),+ channel_share_permissions: None,+ }+}++async fn get_stored_share_permission(+ transaction: &mut Transaction<'_, Postgres>,+ id: &str,+) -> anyhow::Result<StoredSharePermission> {+ Ok(sqlx::query_as!(+ StoredSharePermission,+ r#"+ SELECT+ "linkShare" as link_share,+ "linkShareAccessLevel"::text as link_share_access_level+ FROM "SharePermission"+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(transaction.as_mut())+ .await?)+}++#[sqlx::test]+async fn create_share_permission_writes_link_columns(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let mut transaction = pool.begin().await?;++ let public_permission = SharePermissionV2 {+ channel_share_permissions: Some(vec![ChannelSharePermission {+ channel_id: "channel-one".to_string(),+ access_level: AccessLevel::View,+ }]),+ ..share_permission(Some(LinkShare::Public), Some(AccessLevel::Edit))+ };+ let public_result = create_share_permission(&mut transaction, &public_permission).await?;+ assert_eq!(public_result.link_share, Some(LinkShare::Public));+ assert_eq!(+ public_result.link_share_access_level,+ Some(AccessLevel::Edit)+ );+ assert_eq!(+ get_stored_share_permission(&mut transaction, &public_result.id).await?,+ StoredSharePermission {+ link_share: Some("PUBLIC".to_string()),+ link_share_access_level: Some("edit".to_string()),+ }+ );++ let team_result = create_share_permission(+ &mut transaction,+ &share_permission(Some(LinkShare::Team), Some(AccessLevel::Comment)),+ )+ .await?;+ assert_eq!(team_result.link_share, Some(LinkShare::Team));+ assert_eq!(+ get_stored_share_permission(&mut transaction, &team_result.id).await?,+ StoredSharePermission {+ link_share: Some("TEAM".to_string()),+ link_share_access_level: Some("comment".to_string()),+ }+ );++ let disabled_result = create_share_permission(+ &mut transaction,+ &share_permission(None, Some(AccessLevel::Owner)),+ )+ .await?;+ assert_eq!(disabled_result.link_share, None);+ assert_eq!(disabled_result.link_share_access_level, None);+ assert_eq!(+ get_stored_share_permission(&mut transaction, &disabled_result.id).await?,+ StoredSharePermission {+ link_share: None,+ link_share_access_level: None,+ }+ );++ Ok(())+}++#[sqlx::test]+async fn create_share_permission_defaults_enabled_links_to_view(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let mut transaction = pool.begin().await?;++ for link_share in [LinkShare::Public, LinkShare::Team] {+ let result =+ create_share_permission(&mut transaction, &share_permission(Some(link_share), None))+ .await?;++ assert_eq!(result.link_share_access_level, Some(AccessLevel::View));+ assert_eq!(+ get_stored_share_permission(&mut transaction, &result.id).await?,+ StoredSharePermission {+ link_share: Some(link_share.to_string()),+ link_share_access_level: Some("view".to_string()),+ }+ );+ }++ Ok(())+}diff --git a/crates/macro_db_client/src/share_permission/edit.rs b/crates/macro_db_client/src/share_permission/edit.rsindex fe50321ca2..7c1877afdb 100644--- a/crates/macro_db_client/src/share_permission/edit.rs+++ b/crates/macro_db_client/src/share_permission/edit.rs@@ -1,12 +1,15 @@-use crate::Parameters;use model_entity::EntityType;use models_permissions::share_permission::UpdateSharePermissionRequestV2;-use sqlx::{Postgres, Transaction};+use sqlx::{Postgres, QueryBuilder, Transaction};use super::channel_permission::edit::edit_channel_share_permission;+use super::create::link_share_access_level_or_default;#[tracing::instrument(skip(transaction))]-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]+#[allow(+ clippy::disallowed_methods,+ reason = "optional update fields require a dynamically assembled SQL query"+)]pub async fn edit_share_permission(transaction: &mut Transaction<'_, Postgres>,entity_id: &uuid::Uuid,@@ -14,69 +17,49 @@ pub async fn edit_share_permission(share_permission_id: &str,share_permission: &UpdateSharePermissionRequestV2,) -> anyhow::Result<()> {- let mut query = "UPDATE \"SharePermission\" SET ".to_string();- let mut parameters: Vec<Parameters> = Vec::new();- let mut set_parts = Vec::new();-- let mut ignore_public_access_level = false;- if let Some(is_public) = share_permission.is_public {- set_parts.push("\"isPublic\" = $".to_string() + &(set_parts.len() + 2).to_string());- parameters.push(Parameters::Bool(is_public));-- // is_public was set to true but public access level was not provided.- // we need to set the public access level to view- if is_public && share_permission.public_access_level.is_none() {- tracing::warn!(- "is_public was set to true but public access level was not provided, setting to view"+ // The optional update fields determine which assignments are present, so this query must be+ // assembled dynamically. Every value remains bound; only trusted SQL fragments are appended.+ let mut query =+ QueryBuilder::<Postgres>::new(r#"UPDATE "SharePermission" SET "updatedAt" = NOW()"#);++ match share_permission.link_share {+ Some(Some(link_share)) => {+ let access_level = link_share_access_level_or_default(+ share_permission.link_share_access_level.flatten(),);- set_parts- .push("\"publicAccessLevel\" = $".to_string() + &(set_parts.len() + 2).to_string());- parameters.push(Parameters::String("view".to_string()));- }- // if is_public is set to false, we need to set the public access level to none.- if !is_public {- ignore_public_access_level = true;- set_parts.push("\"publicAccessLevel\" = NULL".to_string());+ query+ .push(r#", "linkShare" = "#)+ .push_bind(link_share.to_string())+ .push(r#", "linkShareAccessLevel" = "#)+ .push_bind(access_level);}- }-- if let Some(public_access_level) = share_permission.public_access_level- && !ignore_public_access_level- {- set_parts- .push("\"publicAccessLevel\" = $".to_string() + &(set_parts.len() + 2).to_string());- parameters.push(Parameters::String(public_access_level.to_string()));- }-- query += &set_parts.join(", ");- if !set_parts.is_empty() {- query += ", ";- }-- query += "\"updatedAt\" = NOW() WHERE id = $1";-- let mut query = sqlx::query(&query);- query = query.bind(share_permission_id.to_string());-- for param in parameters {- match param {- Parameters::BigNumber(number) => {- query = query.bind(number);- }- Parameters::String(string) => {- query = query.bind(string);- }- Parameters::Bool(bool) => {- query = query.bind(bool);+ Some(None) => {+ query.push(r#", "linkShare" = NULL, "linkShareAccessLevel" = NULL"#);+ }+ None => match share_permission.link_share_access_level {+ Some(Some(access_level)) => {+ query+ .push(+ r#", "linkShareAccessLevel" = CASE WHEN "linkShare" IS NULL THEN NULL ELSE "#,+ )+ .push_bind(access_level)+ .push(" END");}- Parameters::SmallNumber(number) => {- query = query.bind(number);+ Some(None) => {+ query+ .push(+ r#", "linkShareAccessLevel" = CASE WHEN "linkShare" IS NULL THEN NULL ELSE "#,+ )+ .push_bind(link_share_access_level_or_default(None))+ .push(" END");}- }+ None => {}+ },}- query.execute(transaction.as_mut()).await?;+ query.push(" WHERE id = ").push_bind(share_permission_id);+ query.build().execute(transaction.as_mut()).await?;if let Some(channel_share_permissions) = share_permission.channel_share_permissions.as_ref() {edit_channel_share_permission(transaction, share_permission_id, channel_share_permissions)@@ -111,31 +94,5 @@ pub async fn edit_thread_permission(.await}-#[tracing::instrument(skip(transaction))]-pub async fn edit_project_permission(- transaction: &mut Transaction<'_, Postgres>,- project_id: &str,- share_permission: &UpdateSharePermissionRequestV2,-) -> anyhow::Result<()> {- let share_id: String = sqlx::query!(- r#"- SELECT- pp."sharePermissionId" as share_permission_id- FROM "ProjectPermission" pp- WHERE pp."projectId" = $1- "#,- project_id- )- .map(|row| row.share_permission_id)- .fetch_one(transaction.as_mut())- .await?;-- edit_share_permission(- transaction,- ¯o_uuid::string_to_uuid(project_id).unwrap(),- EntityType::Project,- &share_id,- share_permission,- )- .await-}+#[cfg(test)]+mod test;diff --git a/crates/macro_db_client/src/share_permission/edit/test.rs b/crates/macro_db_client/src/share_permission/edit/test.rsnew file mode 100644index 0000000000..09ad810c89--- /dev/null+++ b/crates/macro_db_client/src/share_permission/edit/test.rs@@ -0,0 +1,194 @@+use model_entity::EntityType;+use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::{+ LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,+};+use sqlx::{Pool, Postgres, Transaction};+use uuid::Uuid;++use super::*;+use crate::share_permission::create::create_share_permission;++#[derive(Debug, PartialEq)]+struct StoredSharePermission {+ link_share: Option<String>,+ link_share_access_level: Option<String>,+}++fn update_request(+ link_share: Option<Option<LinkShare>>,+ link_share_access_level: Option<Option<AccessLevel>>,+) -> UpdateSharePermissionRequestV2 {+ UpdateSharePermissionRequestV2 {+ link_share,+ link_share_access_level,+ channel_share_permissions: None,+ }+}++async fn get_stored_share_permission(+ transaction: &mut Transaction<'_, Postgres>,+ id: &str,+) -> anyhow::Result<StoredSharePermission> {+ Ok(sqlx::query_as!(+ StoredSharePermission,+ r#"+ SELECT+ "linkShare" as link_share,+ "linkShareAccessLevel"::text as link_share_access_level+ FROM "SharePermission"+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(transaction.as_mut())+ .await?)+}++async fn edit(+ transaction: &mut Transaction<'_, Postgres>,+ share_permission_id: &str,+ request: UpdateSharePermissionRequestV2,+) -> anyhow::Result<()> {+ edit_share_permission(+ transaction,+ &Uuid::nil(),+ EntityType::Document,+ share_permission_id,+ &request,+ )+ .await+}++#[sqlx::test]+async fn edit_share_permission_preserves_update_field_semantics(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let mut transaction = pool.begin().await?;+ let permission = create_share_permission(+ &mut transaction,+ &SharePermissionV2 {+ id: String::new(),+ link_share: Some(LinkShare::Public),+ link_share_access_level: Some(AccessLevel::Edit),+ owner: String::new(),+ channel_share_permissions: None,+ },+ )+ .await?;++ let serialized_omitted_request = serde_json::to_value(update_request(None, None))?;+ let omitted_request: UpdateSharePermissionRequestV2 =+ serde_json::from_value(serialized_omitted_request)?;+ assert_eq!(omitted_request.link_share, None);+ assert_eq!(omitted_request.link_share_access_level, None);++ edit(&mut transaction, &permission.id, omitted_request).await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: Some("PUBLIC".to_string()),+ link_share_access_level: Some("edit".to_string()),+ }+ );++ edit(+ &mut transaction,+ &permission.id,+ update_request(None, Some(None)),+ )+ .await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: Some("PUBLIC".to_string()),+ link_share_access_level: Some("view".to_string()),+ }+ );++ edit(+ &mut transaction,+ &permission.id,+ update_request(None, Some(Some(AccessLevel::Comment))),+ )+ .await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: Some("PUBLIC".to_string()),+ link_share_access_level: Some("comment".to_string()),+ }+ );++ edit(+ &mut transaction,+ &permission.id,+ update_request(Some(Some(LinkShare::Team)), Some(Some(AccessLevel::Edit))),+ )+ .await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: Some("TEAM".to_string()),+ link_share_access_level: Some("edit".to_string()),+ }+ );++ edit(+ &mut transaction,+ &permission.id,+ update_request(Some(Some(LinkShare::Public)), None),+ )+ .await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: Some("PUBLIC".to_string()),+ link_share_access_level: Some("view".to_string()),+ }+ );++ edit(+ &mut transaction,+ &permission.id,+ update_request(Some(None), Some(Some(AccessLevel::Owner))),+ )+ .await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: None,+ link_share_access_level: None,+ }+ );++ edit(+ &mut transaction,+ &permission.id,+ update_request(None, Some(Some(AccessLevel::Edit))),+ )+ .await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: None,+ link_share_access_level: None,+ }+ );++ edit(+ &mut transaction,+ &permission.id,+ update_request(Some(Some(LinkShare::Team)), Some(None)),+ )+ .await?;+ assert_eq!(+ get_stored_share_permission(&mut transaction, &permission.id).await?,+ StoredSharePermission {+ link_share: Some("TEAM".to_string()),+ link_share_access_level: Some("view".to_string()),+ }+ );++ Ok(())+}diff --git a/crates/macro_db_client/src/share_permission/get.rs b/crates/macro_db_client/src/share_permission/get.rsindex 03dcd94892..26e6328d47 100644--- a/crates/macro_db_client/src/share_permission/get.rs+++ b/crates/macro_db_client/src/share_permission/get.rs@@ -1,10 +1,37 @@use anyhow::Context;use model::thread::EmailThreadPermission;-use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;+use models_permissions::share_permission::{LinkShare, SharePermissionV2};use std::str::FromStr;+fn parse_share_permission(+ id: String,+ link_share: Option<String>,+ link_share_access_level: Option<AccessLevel>,+ owner: String,+ channel_share_permissions: Option<serde_json::Value>,+) -> anyhow::Result<SharePermissionV2> {+ let link_share = link_share+ .map(|value| {+ LinkShare::from_str(&value)+ .with_context(|| format!("invalid link share value {value:?}"))+ })+ .transpose()?;+ let channel_share_permissions = channel_share_permissions+ .map(serde_json::from_value::<Vec<ChannelSharePermission>>)+ .transpose()?+ .filter(|permissions| !permissions.is_empty());++ Ok(SharePermissionV2 {+ id,+ link_share,+ link_share_access_level,+ owner,+ channel_share_permissions,+ })+}+#[tracing::instrument(skip(db))]pub async fn get_share_permission_id(db: &sqlx::Pool<sqlx::Postgres>,@@ -113,8 +140,8 @@ pub async fn get_document_share_permission(r#"SELECTsp.id as id,- sp."isPublic" as is_public,- sp."publicAccessLevel" as "public_access_level?",+ sp."linkShare" as "link_share?",+ sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",d."owner" as owner,COALESCE(json_agg(json_build_object(@@ -138,29 +165,13 @@ pub async fn get_document_share_permission(.fetch_one(db).await?;- let channel_share_permissions: Option<Vec<ChannelSharePermission>> =- if let Some(channel_share_permissions) = result.channel_share_permissions {- let channel_share_permissions: Vec<ChannelSharePermission> =- serde_json::from_value(channel_share_permissions)?;- match channel_share_permissions.is_empty() {- true => None,- false => Some(channel_share_permissions),- }- } else {- None- };-- let public_access_level: Option<AccessLevel> = result- .public_access_level- .map(|s| AccessLevel::from_str(&s).unwrap());-- Ok(SharePermissionV2 {- id: result.id,- is_public: result.is_public,- public_access_level,- owner: result.owner,- channel_share_permissions,- })+ parse_share_permission(+ result.id,+ result.link_share,+ result.link_share_access_level,+ result.owner,+ result.channel_share_permissions,+ )}#[tracing::instrument(skip(db))]@@ -172,8 +183,8 @@ pub async fn get_chat_share_permission(r#"SELECTsp.id as id,- sp."isPublic" as is_public,- sp."publicAccessLevel" as "public_access_level?",+ sp."linkShare" as "link_share?",+ sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",c."userId" as owner,COALESCE(json_agg(json_build_object(@@ -197,29 +208,13 @@ pub async fn get_chat_share_permission(.fetch_one(db).await?;- let channel_share_permissions: Option<Vec<ChannelSharePermission>> =- if let Some(channel_share_permissions) = result.channel_share_permissions {- let channel_share_permissions: Vec<ChannelSharePermission> =- serde_json::from_value(channel_share_permissions)?;- match channel_share_permissions.is_empty() {- true => None,- false => Some(channel_share_permissions),- }- } else {- None- };-- let public_access_level: Option<AccessLevel> = result- .public_access_level- .map(|s| AccessLevel::from_str(&s).unwrap());-- Ok(SharePermissionV2 {- id: result.id,- is_public: result.is_public,- public_access_level,- owner: result.owner,- channel_share_permissions,- })+ parse_share_permission(+ result.id,+ result.link_share,+ result.link_share_access_level,+ result.owner,+ result.channel_share_permissions,+ )}#[tracing::instrument(skip(db))]@@ -231,8 +226,8 @@ pub async fn get_macro_share_permission(r#"SELECTsp.id as id,- sp."isPublic" as is_public,- sp."publicAccessLevel" as "public_access_level?",+ sp."linkShare" as "link_share?",+ sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",m."user_id" as owner,COALESCE(json_agg(json_build_object(@@ -256,29 +251,13 @@ pub async fn get_macro_share_permission(.fetch_one(db).await?;- let channel_share_permissions: Option<Vec<ChannelSharePermission>> =- if let Some(channel_share_permissions) = result.channel_share_permissions {- let channel_share_permissions: Vec<ChannelSharePermission> =- serde_json::from_value(channel_share_permissions)?;- match channel_share_permissions.is_empty() {- true => None,- false => Some(channel_share_permissions),- }- } else {- None- };-- let public_access_level: Option<AccessLevel> = result- .public_access_level- .map(|s| AccessLevel::from_str(&s).unwrap());-- Ok(SharePermissionV2 {- id: result.id,- is_public: result.is_public,- public_access_level,- owner: result.owner,- channel_share_permissions,- })+ parse_share_permission(+ result.id,+ result.link_share,+ result.link_share_access_level,+ result.owner,+ result.channel_share_permissions,+ )}#[tracing::instrument(skip(db))]@@ -405,73 +384,4 @@ pub async fn get_items_by_share_permission_ids(}#[cfg(test)]-mod tests {- use super::*;- use models_permissions::share_permission::access_level::AccessLevel;- use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;- #[sqlx::test(fixtures(path = "../../fixtures", scripts("channel_share_permissions")))]- async fn test_get_document_share_permission(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- let permission = get_document_share_permission(&pool, "d1").await?;- assert_eq!(permission.id, "sp-d1".to_string());- assert!(permission.is_public);- assert_eq!(permission.public_access_level, Some(AccessLevel::Edit));- assert_eq!(permission.owner, "macro|[email protected]".to_string());- assert_eq!(- permission.channel_share_permissions,- Some(vec![- ChannelSharePermission {- channel_id: "c1".to_string(),- access_level: AccessLevel::View,- },- ChannelSharePermission {- channel_id: "c2".to_string(),- access_level: AccessLevel::Edit,- }- ])- );-- let permission = get_document_share_permission(&pool, "d2").await?;- assert_eq!(permission.id, "sp-d2".to_string());- assert!(!permission.is_public);- assert!(permission.public_access_level.is_none());- assert_eq!(permission.owner, "macro|[email protected]".to_string());- assert!(permission.channel_share_permissions.is_none());-- Ok(())- }-- #[sqlx::test(fixtures(path = "../../fixtures", scripts("channel_share_permissions")))]- async fn test_get_chat_share_permission(- pool: sqlx::Pool<sqlx::Postgres>,- ) -> anyhow::Result<()> {- let permission = get_chat_share_permission(&pool, "c1").await?;- assert_eq!(permission.id, "sp-c1".to_string());- assert!(permission.is_public);- assert_eq!(permission.public_access_level, Some(AccessLevel::Edit));- assert_eq!(permission.owner, "macro|[email protected]".to_string());- assert_eq!(- permission.channel_share_permissions,- Some(vec![- ChannelSharePermission {- channel_id: "c1".to_string(),- access_level: AccessLevel::View,- },- ChannelSharePermission {- channel_id: "c2".to_string(),- access_level: AccessLevel::Edit,- }- ])- );-- let permission = get_chat_share_permission(&pool, "c2").await?;- assert_eq!(permission.id, "sp-c2".to_string());- assert!(!permission.is_public);- assert!(permission.public_access_level.is_none());- assert_eq!(permission.owner, "macro|[email protected]".to_string());- assert!(permission.channel_share_permissions.is_none());-- Ok(())- }-}+mod test;diff --git a/crates/macro_db_client/src/share_permission/get/test.rs b/crates/macro_db_client/src/share_permission/get/test.rsnew file mode 100644index 0000000000..a1a78471ef--- /dev/null+++ b/crates/macro_db_client/src/share_permission/get/test.rs@@ -0,0 +1,108 @@+use models_permissions::share_permission::LinkShare;+use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;+use sqlx::{Pool, Postgres};++use super::*;++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("channel_share_permissions")))]+async fn get_document_share_permission_reads_link_fields(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let public_permission = get_document_share_permission(&pool, "d1").await?;+ assert_eq!(public_permission.id, "sp-d1");+ assert_eq!(public_permission.link_share, Some(LinkShare::Public));+ assert_eq!(+ public_permission.link_share_access_level,+ Some(AccessLevel::Edit)+ );+ assert_eq!(public_permission.owner, "macro|[email protected]");+ assert_eq!(+ public_permission.channel_share_permissions,+ Some(vec![+ ChannelSharePermission {+ channel_id: "c1".to_string(),+ access_level: AccessLevel::View,+ },+ ChannelSharePermission {+ channel_id: "c2".to_string(),+ access_level: AccessLevel::Edit,+ }+ ])+ );++ let disabled_permission = get_document_share_permission(&pool, "d2").await?;+ assert_eq!(disabled_permission.id, "sp-d2");+ assert_eq!(disabled_permission.link_share, None);+ assert_eq!(disabled_permission.link_share_access_level, None);+ assert_eq!(disabled_permission.owner, "macro|[email protected]");+ assert_eq!(disabled_permission.channel_share_permissions, None);++ sqlx::query!(+ r#"+ UPDATE "SharePermission"+ SET+ "linkShare" = 'TEAM',+ "linkShareAccessLevel" = 'comment'+ WHERE id = 'sp-d2'+ "#,+ )+ .execute(&pool)+ .await?;++ let team_permission = get_document_share_permission(&pool, "d2").await?;+ assert_eq!(team_permission.link_share, Some(LinkShare::Team));+ assert_eq!(+ team_permission.link_share_access_level,+ Some(AccessLevel::Comment)+ );++ let error = sqlx::query!(+ r#"+ UPDATE "SharePermission"+ SET "linkShareAccessLevel" = $1::text::"AccessLevel"+ WHERE id = 'sp-d2'+ "#,+ "invalid",+ )+ .execute(&pool)+ .await+ .expect_err("the database must reject invalid access levels");+ assert!(error.to_string().contains("invalid input value for enum"));++ Ok(())+}++#[sqlx::test(fixtures(path = "../../../fixtures", scripts("channel_share_permissions")))]+async fn get_chat_share_permission_reads_link_fields(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let public_permission = get_chat_share_permission(&pool, "c1").await?;+ assert_eq!(public_permission.id, "sp-c1");+ assert_eq!(public_permission.link_share, Some(LinkShare::Public));+ assert_eq!(+ public_permission.link_share_access_level,+ Some(AccessLevel::Edit)+ );+ assert_eq!(public_permission.owner, "macro|[email protected]");+ assert_eq!(+ public_permission.channel_share_permissions,+ Some(vec![+ ChannelSharePermission {+ channel_id: "c1".to_string(),+ access_level: AccessLevel::View,+ },+ ChannelSharePermission {+ channel_id: "c2".to_string(),+ access_level: AccessLevel::Edit,+ }+ ])+ );++ let disabled_permission = get_chat_share_permission(&pool, "c2").await?;+ assert_eq!(disabled_permission.id, "sp-c2");+ assert_eq!(disabled_permission.link_share, None);+ assert_eq!(disabled_permission.link_share_access_level, None);+ assert_eq!(disabled_permission.owner, "macro|[email protected]");+ assert_eq!(disabled_permission.channel_share_permissions, None);++ Ok(())+}diff --git a/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs b/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rsindex 1d7b907af5..99680ac270 100644--- a/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs+++ b/crates/macro_middleware/src/cloud_storage/thread/ensure_thread_exists.rs@@ -68,8 +68,8 @@ pub async fn insert_thread_share_permissions(// Create a new share permissionlet share_permission = SharePermissionV2 {id: macro_uuid::generate_uuid_v7().to_string(),- is_public: false,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,owner: owner_id.to_string(),channel_share_permissions: None,};diff --git a/crates/models_permissions/src/share_permission/link_share.rs b/crates/models_permissions/src/share_permission/link_share.rsnew file mode 100644index 0000000000..8138477be4--- /dev/null+++ b/crates/models_permissions/src/share_permission/link_share.rs@@ -0,0 +1,69 @@+use std::str::FromStr;++use sqlx::{Decode, Encode, Postgres, Type};+use utoipa::ToSchema;++/// Defines who can access an item through its share link.+#[derive(+ serde::Serialize,+ serde::Deserialize,+ Eq,+ PartialEq,+ Debug,+ ToSchema,+ Clone,+ Copy,+ strum::EnumString,+ strum::Display,+)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]+pub enum LinkShare {+ /// Anyone with the link can access the item.+ Public,+ /// Members of the owner's team with the link can access the item.+ Team,+}++impl LinkShare {+ fn as_str(self) -> &'static str {+ match self {+ Self::Public => "PUBLIC",+ Self::Team => "TEAM",+ }+ }+}++impl Type<Postgres> for LinkShare {+ fn type_info() -> sqlx::postgres::PgTypeInfo {+ <String as Type<Postgres>>::type_info()+ }++ fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {+ <String as Type<Postgres>>::compatible(ty)+ }+}++impl<'query> Encode<'query, Postgres> for LinkShare {+ fn encode_by_ref(+ &self,+ buffer: &mut sqlx::postgres::PgArgumentBuffer,+ ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {+ let value = self.as_str();+ <&str as Encode<Postgres>>::encode_by_ref(&value, buffer)+ }++ fn size_hint(&self) -> usize {+ self.as_str().len()+ }+}++impl<'row> Decode<'row, Postgres> for LinkShare {+ fn decode(value: sqlx::postgres::PgValueRef<'row>) -> Result<Self, sqlx::error::BoxDynError> {+ let value = <String as Decode<Postgres>>::decode(value)?;+ LinkShare::from_str(&value).map_err(Into::into)+ }+}++#[cfg(test)]+mod test;diff --git a/crates/models_permissions/src/share_permission/link_share/test.rs b/crates/models_permissions/src/share_permission/link_share/test.rsnew file mode 100644index 0000000000..bc7dc630e9--- /dev/null+++ b/crates/models_permissions/src/share_permission/link_share/test.rs@@ -0,0 +1,60 @@+use std::str::FromStr;++use sqlx::{Decode, Encode, Postgres, Type, encode::IsNull, postgres::PgArgumentBuffer};++use super::LinkShare;++#[test]+fn serializes_and_deserializes_screaming_snake_case_values() {+ assert_eq!(+ serde_json::to_string(&LinkShare::Public).unwrap(),+ "\"PUBLIC\""+ );+ assert_eq!(serde_json::to_string(&LinkShare::Team).unwrap(), "\"TEAM\"");+ assert_eq!(+ serde_json::from_str::<LinkShare>("\"PUBLIC\"").unwrap(),+ LinkShare::Public+ );+ assert_eq!(+ serde_json::from_str::<LinkShare>("\"TEAM\"").unwrap(),+ LinkShare::Team+ );+}++#[test]+fn displays_and_parses_screaming_snake_case_values() {+ assert_eq!(LinkShare::Public.to_string(), "PUBLIC");+ assert_eq!(LinkShare::Team.to_string(), "TEAM");+ assert_eq!(LinkShare::from_str("PUBLIC").unwrap(), LinkShare::Public);+ assert_eq!(LinkShare::from_str("TEAM").unwrap(), LinkShare::Team);+ assert!(LinkShare::from_str("public").is_err());+}++#[test]+fn encodes_as_postgres_text() {+ assert_eq!(+ <LinkShare as Type<Postgres>>::type_info(),+ <String as Type<Postgres>>::type_info()+ );+ assert!(<LinkShare as Type<Postgres>>::compatible(+ &<String as Type<Postgres>>::type_info()+ ));++ let mut buffer = PgArgumentBuffer::default();+ let is_null = <LinkShare as Encode<Postgres>>::encode_by_ref(&LinkShare::Team, &mut buffer)+ .expect("TEAM should encode as PostgreSQL TEXT");++ assert!(matches!(is_null, IsNull::No));+ assert_eq!(buffer.as_slice(), b"TEAM");+}++#[test]+fn supports_postgres_text_decoding() {+ fn assert_decode<T>()+ where+ for<'value> T: Decode<'value, Postgres>,+ {+ }++ assert_decode::<LinkShare>();+}diff --git a/crates/models_permissions/src/share_permission/mod.rs b/crates/models_permissions/src/share_permission/mod.rsindex 6d696e2cd1..82719d9f18 100644--- a/crates/models_permissions/src/share_permission/mod.rs+++ b/crates/models_permissions/src/share_permission/mod.rs@@ -3,21 +3,25 @@ use crate::share_permission::channel_share_permission::{ChannelSharePermission, UpdateChannelSharePermission,};use model_file_type::FileType;+use serde::{Deserialize, Deserializer};use utoipa::ToSchema;+pub mod access_level;pub mod channel_share_permission;-pub mod user_permission;+mod link_share;++pub use link_share::LinkShare;#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, ToSchema, Clone)]#[serde(rename_all = "camelCase")]pub struct SharePermissionV2 {/// The share permission idpub id: String,- /// If the item is publicly accessible- pub is_public: bool,- /// The level of public access+ /// Who can access the item through its share link+ pub link_share: Option<LinkShare>,+ /// The level of access granted through the share link#[serde(skip_serializing_if = "Option::is_none")]- pub public_access_level: Option<AccessLevel>,+ pub link_share_access_level: Option<AccessLevel>,/// The owner of the itempub owner: String,/// The channel share permissions for the item@@ -26,44 +30,68 @@ pub struct SharePermissionV2 {}impl SharePermissionV2 {- fn new(is_public: bool, public_access_level: Option<AccessLevel>) -> Self {+ fn new(link_share: Option<LinkShare>, link_share_access_level: Option<AccessLevel>) -> Self {SharePermissionV2 {- id: "".to_string(),- is_public,- public_access_level,- owner: "".to_string(),+ id: String::new(),+ link_share,+ link_share_access_level,+ owner: String::new(),channel_share_permissions: None,}}/// Creates a new share permission object for a documentpub fn new_document_share_permission(file_type: Option<FileType>) -> Self {- let (is_public, public_access_level) = match file_type {- Some(FileType::Md) => (true, Some(AccessLevel::Edit)),- _ => (false, None),+ let (link_share, link_share_access_level) = match file_type {+ Some(FileType::Md) => (Some(LinkShare::Public), Some(AccessLevel::Edit)),+ _ => (None, None),};- Self::new(is_public, public_access_level)+ Self::new(link_share, link_share_access_level)}/// Creates a new share permission object for an ai chatpub fn new_chat_share_permission() -> Self {- Self::new(true, Some(AccessLevel::View))+ Self::new(Some(LinkShare::Public), Some(AccessLevel::View))}/// Creates a new share permission object for a projectpub fn new_project_share_permission() -> Self {- Self::new(false, None)+ Self::new(None, None)}}+/// Deserializes an optional field while preserving explicit `null` values.+fn double_option<'de, T, D>(deserializer: D) -> Result<Option<Option<T>>, D::Error>+where+ T: Deserialize<'de>,+ D: Deserializer<'de>,+{+ Deserialize::deserialize(deserializer).map(Some)+}+#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, ToSchema, Clone)]#[serde(rename_all = "camelCase")]pub struct UpdateSharePermissionRequestV2 {- /// If the item is publicly accessible- pub is_public: Option<bool>,- /// The level of public access- pub public_access_level: Option<AccessLevel>,+ /// Who can access the item through its share link. Omit to leave unchanged or pass `null` to+ /// disable link sharing.+ #[serde(+ default,+ deserialize_with = "double_option",+ skip_serializing_if = "Option::is_none"+ )]+ pub link_share: Option<Option<LinkShare>>,+ /// The link access level. Omit to leave unchanged or pass `null` to reset it to the default+ /// level when a link share exists.+ #[serde(+ default,+ deserialize_with = "double_option",+ skip_serializing_if = "Option::is_none"+ )]+ pub link_share_access_level: Option<Option<AccessLevel>>,/// Any channel share permissions to be created/updated/removedpub channel_share_permissions: Option<Vec<UpdateChannelSharePermission>>,}++#[cfg(test)]+mod test;diff --git a/crates/models_permissions/src/share_permission/test.rs b/crates/models_permissions/src/share_permission/test.rsnew file mode 100644index 0000000000..de79e2f38b--- /dev/null+++ b/crates/models_permissions/src/share_permission/test.rs@@ -0,0 +1,101 @@+use model_file_type::FileType;+use serde_json::json;++use super::{+ LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2, access_level::AccessLevel,+};++#[test]+fn document_constructor_uses_expected_link_share_defaults() {+ assert_eq!(+ SharePermissionV2::new_document_share_permission(Some(FileType::Md)),+ SharePermissionV2 {+ id: String::new(),+ link_share: Some(LinkShare::Public),+ link_share_access_level: Some(AccessLevel::Edit),+ owner: String::new(),+ channel_share_permissions: None,+ }+ );+ assert_eq!(+ SharePermissionV2::new_document_share_permission(Some(FileType::Pdf)),+ SharePermissionV2 {+ id: String::new(),+ link_share: None,+ link_share_access_level: None,+ owner: String::new(),+ channel_share_permissions: None,+ }+ );+}++#[test]+fn chat_constructor_enables_public_view_access() {+ assert_eq!(+ SharePermissionV2::new_chat_share_permission(),+ SharePermissionV2 {+ id: String::new(),+ link_share: Some(LinkShare::Public),+ link_share_access_level: Some(AccessLevel::View),+ owner: String::new(),+ channel_share_permissions: None,+ }+ );+}++#[test]+fn project_constructor_disables_link_sharing() {+ assert_eq!(+ SharePermissionV2::new_project_share_permission(),+ SharePermissionV2 {+ id: String::new(),+ link_share: None,+ link_share_access_level: None,+ owner: String::new(),+ channel_share_permissions: None,+ }+ );+}++#[test]+fn update_request_round_trip_preserves_omitted_fields() {+ let request = UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: None,+ channel_share_permissions: None,+ };++ let serialized = serde_json::to_value(&request).unwrap();+ assert!(serialized.get("linkShare").is_none());+ assert!(serialized.get("linkShareAccessLevel").is_none());++ let deserialized: UpdateSharePermissionRequestV2 = serde_json::from_value(serialized).unwrap();+ assert_eq!(deserialized.link_share, None);+ assert_eq!(deserialized.link_share_access_level, None);+}++#[test]+fn update_request_distinguishes_omitted_null_and_present_values() {+ let omitted: UpdateSharePermissionRequestV2 = serde_json::from_value(json!({})).unwrap();+ assert_eq!(omitted.link_share, None);+ assert_eq!(omitted.link_share_access_level, None);++ let cleared: UpdateSharePermissionRequestV2 = serde_json::from_value(json!({+ "linkShare": null,+ "linkShareAccessLevel": null+ }))+ .unwrap();+ assert_eq!(cleared.link_share, Some(None));+ assert_eq!(cleared.link_share_access_level, Some(None));++ let updated: UpdateSharePermissionRequestV2 = serde_json::from_value(json!({+ "linkShare": "TEAM",+ "linkShareAccessLevel": "comment"+ }))+ .unwrap();+ assert_eq!(updated.link_share, Some(Some(LinkShare::Team)));+ assert_eq!(+ updated.link_share_access_level,+ Some(Some(AccessLevel::Comment))+ );+}diff --git a/crates/models_permissions/src/share_permission/user_permission.rs b/crates/models_permissions/src/share_permission/user_permission.rsdeleted file mode 100644index a12eeb99e1..0000000000--- a/crates/models_permissions/src/share_permission/user_permission.rs+++ /dev/null@@ -1,40 +0,0 @@-use crate::share_permission::access_level::AccessLevel;--#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug, Clone)]-#[serde(rename_all = "camelCase")]-pub struct UserPermission {- /// The share permission id- pub id: String,- /// If the item is publicly accessible- pub is_public: bool,- /// The level of public access- pub public_access_level: Option<AccessLevel>,- /// The highest level of access granted to the user through channels they are a member of- pub channel_access_level: Option<AccessLevel>,- /// The owner of the item- pub owner: String,-}--// multi user permission info-#[derive(Eq, PartialEq, Debug)]-pub struct UsersPermission {- /// The share permission id- pub id: String,- /// If the item is publicly accessible- pub is_public: bool,- /// The level of public access- pub public_access_level: Option<AccessLevel>,- /// The owner of the item- pub owner: String,- /// Per‑user permission details- pub user_permissions: Vec<PerUserPermission>,-}--// subset of UserPermission with user specific access level info-#[derive(Eq, PartialEq, Debug)]-pub struct PerUserPermission {- /// The user id associated with the permission (provided even if the user record doesn’t exist)- pub user_id: String,- /// The highest level of access granted to the user through channels they are a member of- pub channel_access_level: Option<AccessLevel>,-}diff --git a/crates/projects/fixtures/projects_test_data.sql b/crates/projects/fixtures/projects_test_data.sqlindex 09327061f6..f8cfcd92e7 100644--- a/crates/projects/fixtures/projects_test_data.sql+++ b/crates/projects/fixtures/projects_test_data.sql@@ -28,8 +28,8 @@ VALUES('macro|[email protected]', '10000000-0000-0000-0000-000000000006', 'project'),('macro|[email protected]', '10000000-0000-0000-0000-000000000009', 'project');-INSERT INTO public."SharePermission" (id, "isPublic", "publicAccessLevel")-VALUES ('share-root', true, 'edit');+INSERT INTO public."SharePermission" (id, "linkShare", "linkShareAccessLevel")+VALUES ('share-root', 'PUBLIC', 'edit');INSERT INTO public."ProjectPermission" ("projectId", "sharePermissionId")VALUES ('10000000-0000-0000-0000-000000000001', 'share-root');INSERT INTO public."ChannelSharePermission" (share_permission_id, channel_id, access_level)diff --git a/crates/projects/src/domain/service/tests.rs b/crates/projects/src/domain/service/tests.rsindex 5d2d5a7a82..a25e109a41 100644--- a/crates/projects/src/domain/service/tests.rs+++ b/crates/projects/src/domain/service/tests.rs@@ -23,8 +23,8 @@ use models_bulk_upload::{BulkUploadRequest, BulkUploadRequestDocuments, ProjectDocumentStatus, UploadDocumentStatus,UploadExtractFolderRequest, UploadFolderStatus,};-use models_permissions::share_permission::UpdateSharePermissionRequestV2;use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::{LinkShare, UpdateSharePermissionRequestV2};use s3_key::BulkUploadStagingKey;use uuid::Uuid;@@ -497,8 +497,8 @@ fn patch_request(fn share_update() -> UpdateSharePermissionRequestV2 {UpdateSharePermissionRequestV2 {- is_public: Some(true),- public_access_level: Some(AccessLevel::View),+ link_share: Some(Some(LinkShare::Public)),+ link_share_access_level: Some(Some(AccessLevel::View)),channel_share_permissions: None,}}@@ -651,7 +651,8 @@ async fn create_uses_grapheme_limit_and_orchestrates_parent_side_effects() {.withf(move |args| {args.name == expected_name&& args.parent_id.as_deref() == Some(parent_id.to_string().as_str())- && !args.share_permission.is_public+ && args.share_permission.link_share.is_none()+ && args.share_permission.link_share_access_level.is_none()}).return_once(move |_| {Box::pin(async move {diff --git a/crates/projects/src/outbound/pg_project_repo/share.rs b/crates/projects/src/outbound/pg_project_repo/share.rsindex 690f2be032..997c9f9713 100644--- a/crates/projects/src/outbound/pg_project_repo/share.rs+++ b/crates/projects/src/outbound/pg_project_repo/share.rs@@ -5,10 +5,26 @@ use models_permissions::share_permission::channel_share_permission::{ChannelSharePermission, UpdateOperation,};use models_permissions::share_permission::{- SharePermissionV2, UpdateSharePermissionRequestV2, access_level::AccessLevel,+ LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2, access_level::AccessLevel,};use sqlx::{PgPool, Postgres, Transaction};+fn link_share_access_level_or_default(link_share_access_level: Option<AccessLevel>) -> AccessLevel {+ link_share_access_level.unwrap_or_else(|| {+ tracing::warn!(+ "link_share was enabled but link share access level was not provided, setting to view"+ );+ AccessLevel::View+ })+}++pub(super) fn normalize_link_share_access_level(+ link_share: Option<LinkShare>,+ link_share_access_level: Option<AccessLevel>,+) -> Option<AccessLevel> {+ link_share.map(|_| link_share_access_level_or_default(link_share_access_level))+}+pub(super) async fn get_project_share_permission(pool: &PgPool,project_id: &str,@@ -17,8 +33,8 @@ pub(super) async fn get_project_share_permission(r#"SELECTpermission.id,- permission."isPublic" AS "is_public",- permission."publicAccessLevel" AS "public_access_level?",+ permission."linkShare" AS "link_share?",+ permission."linkShareAccessLevel" AS "link_share_access_level?: AccessLevel",project."userId" AS owner,COALESCE(json_agg(json_build_object(@@ -47,17 +63,16 @@ pub(super) async fn get_project_share_permission(.transpose().map_err(|error| sqlx::Error::Decode(Box::new(error)))?.filter(|permissions| !permissions.is_empty());- let public_access_level = row- .public_access_level- .map(|level| {- AccessLevel::from_str(&level).map_err(|error| sqlx::Error::Decode(Box::new(error)))+ let link_share = row+ .link_share+ .map(|value| {+ LinkShare::from_str(&value).map_err(|error| sqlx::Error::Decode(Box::new(error)))}).transpose()?;-Ok(SharePermissionV2 {id: row.id,- is_public: row.is_public,- public_access_level,+ link_share,+ link_share_access_level: row.link_share_access_level,owner: row.owner,channel_share_permissions,})@@ -68,17 +83,24 @@ pub(super) async fn create_project_share_permission(project_id: &str,permission: &SharePermissionV2,) -> Result<(), sqlx::Error> {+ let link_share = permission.link_share;+ let link_share_access_level =+ normalize_link_share_access_level(link_share, permission.link_share_access_level);+ let link_share = link_share.map(|value| value.to_string());+let row = sqlx::query!(r#"- INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")+ INSERT INTO "SharePermission" (+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt"+ )VALUES ($1, $2, NOW(), NOW())RETURNING id"#,- permission.is_public,- permission- .public_access_level- .as_ref()- .map(ToString::to_string),+ link_share,+ link_share_access_level as _,).fetch_one(transaction.as_mut()).await?;@@ -122,33 +144,43 @@ pub(super) async fn edit_project_share_permission(.fetch_one(transaction.as_mut()).await?;- let clear_public_level = update.is_public == Some(false);- let default_public_level =- update.is_public == Some(true) && update.public_access_level.is_none();- let update_public_level =- clear_public_level || default_public_level || update.public_access_level.is_some();- let public_access_level = if clear_public_level {- None- } else if default_public_level {- Some("view".to_owned())- } else {- update.public_access_level.as_ref().map(ToString::to_string)+ let update_link_share = update.link_share.is_some();+ let link_share = update.link_share.flatten();+ let (update_link_share_access_level, link_share_access_level) = match update.link_share {+ Some(Some(_)) => (+ true,+ Some(link_share_access_level_or_default(+ update.link_share_access_level.flatten(),+ )),+ ),+ Some(None) => (true, None),+ None => (+ update.link_share_access_level.is_some(),+ update.link_share_access_level.flatten(),+ ),};+ let link_share = link_share.map(|value| value.to_string());sqlx::query!(r#"UPDATE "SharePermission"SET- "isPublic" = CASE WHEN $2 THEN $3 ELSE "isPublic" END,- "publicAccessLevel" = CASE WHEN $4 THEN $5 ELSE "publicAccessLevel" END,+ "linkShare" = CASE WHEN $2 THEN $3 ELSE "linkShare" END,+ "linkShareAccessLevel" = CASE+ WHEN $2 AND $3 IS NULL THEN NULL+ WHEN $2 THEN COALESCE($5::"AccessLevel", 'view')+ WHEN $4 AND "linkShare" IS NOT NULL THEN COALESCE($5::"AccessLevel", 'view')+ WHEN $4 THEN NULL+ ELSE "linkShareAccessLevel"+ END,"updatedAt" = NOW()WHERE id = $1"#,share_permission_id,- update.is_public.is_some(),- update.is_public,- update_public_level,- public_access_level,+ update_link_share,+ link_share,+ update_link_share_access_level,+ link_share_access_level as _,).execute(transaction.as_mut()).await?;diff --git a/crates/projects/src/outbound/pg_project_repo/tests.rs b/crates/projects/src/outbound/pg_project_repo/tests.rsindex c1d28be56f..9927a7791f 100644--- a/crates/projects/src/outbound/pg_project_repo/tests.rs+++ b/crates/projects/src/outbound/pg_project_repo/tests.rs@@ -6,7 +6,9 @@ use model::document::FileType;use model::folder::{FileSystemNode, FileSystemNodeWithIds, FolderItem};use model::item::Item;use model::project::ProjectPreviewV2;-use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::{+ LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2, access_level::AccessLevel,+};use sqlx::{Pool, Postgres};use super::PgProjectRepo;@@ -17,6 +19,34 @@ const ROOT_ID: &str = "10000000-0000-0000-0000-000000000001";const CHILD_ID: &str = "10000000-0000-0000-0000-000000000002";const DELETED_ID: &str = "10000000-0000-0000-0000-000000000009";+#[derive(Debug, Eq, PartialEq)]+struct StoredSharePermission {+ link_share: Option<String>,+ link_share_access_level: Option<String>,+}++async fn project_share_permission_columns(+ pool: &Pool<Postgres>,+ project_id: &str,+) -> StoredSharePermission {+ sqlx::query_as!(+ StoredSharePermission,+ r#"+ SELECT+ permission."linkShare" AS "link_share?",+ permission."linkShareAccessLevel"::text AS "link_share_access_level?"+ FROM "SharePermission" permission+ JOIN "ProjectPermission" project_permission+ ON project_permission."sharePermissionId" = permission.id+ WHERE project_permission."projectId" = $1+ "#,+ project_id,+ )+ .fetch_one(pool)+ .await+ .unwrap()+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("projects_test_data"))@@ -149,7 +179,8 @@ async fn reads_share_permissions_and_bumps_modified_timestamp(let permission = repo.get_project_share_permission(ROOT_ID).await?;assert_eq!(permission.id, "share-root");assert_eq!(permission.owner, "macro|[email protected]");- assert_eq!(permission.public_access_level, Some(AccessLevel::Edit));+ assert_eq!(permission.link_share, Some(LinkShare::Public));+ assert_eq!(permission.link_share_access_level, Some(AccessLevel::Edit));assert_eq!(permission.channel_share_permissions.expect("channel").len(),1@@ -176,8 +207,7 @@ async fn reads_share_permissions_and_bumps_modified_timestamp()]async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyhow::Result<()> {let repo = PgProjectRepo::new(pool.clone());- let permission =- models_permissions::share_permission::SharePermissionV2::new_project_share_permission();+ let permission = SharePermissionV2::new_project_share_permission();let project = repo.create_project(CreateProjectArgs {user_id: "macro|[email protected]".to_owned(),@@ -202,6 +232,13 @@ async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyh.fetch_one(&pool).await?;assert_eq!(metadata_count, 1);+ assert_eq!(+ project_share_permission_columns(&pool, &project.id).await,+ StoredSharePermission {+ link_share: None,+ link_share_access_level: None,+ }+ );assert!(repo.create_project(CreateProjectArgs {@@ -222,12 +259,43 @@ async fn create_is_atomic_and_inserts_all_metadata(pool: Pool<Postgres>) -> anyhOk(())}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn create_defaults_enabled_link_share_to_view(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PgProjectRepo::new(pool.clone());+ let mut permission = SharePermissionV2::new_project_share_permission();+ permission.link_share = Some(LinkShare::Team);++ let project = repo+ .create_project(CreateProjectArgs {+ user_id: "macro|[email protected]".to_owned(),+ name: "Team project".to_owned(),+ parent_id: None,+ share_permission: permission,+ })+ .await?;++ assert_eq!(+ project_share_permission_columns(&pool, &project.id).await,+ StoredSharePermission {+ link_share: Some("TEAM".to_owned()),+ link_share_access_level: Some("view".to_owned()),+ }+ );+ let permission = repo.get_project_share_permission(&project.id).await?;+ assert_eq!(permission.link_share, Some(LinkShare::Team));+ assert_eq!(permission.link_share_access_level, Some(AccessLevel::View));+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("projects_test_data")))]async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PgProjectRepo::new(pool);+ let repo = PgProjectRepo::new(pool.clone());let unchanged = repo.edit_project(EditProjectArgs {project_id: CHILD_ID.to_owned(),@@ -253,25 +321,112 @@ async fn edit_supports_parent_flags_and_sharing(pool: Pool<Postgres>) -> anyhow:Some("10000000-0000-0000-0000-000000000005"));- let cleared = repo+ let updated = repo.edit_project(EditProjectArgs {project_id: ROOT_ID.to_owned(),name: None,update_parent: true,parent_id: None,- share_permission: Some(- models_permissions::share_permission::UpdateSharePermissionRequestV2 {- is_public: Some(false),- public_access_level: Some(AccessLevel::Edit),- channel_share_permissions: None,- },- ),+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Team)),+ link_share_access_level: Some(None),+ channel_share_permissions: None,+ }),}).await?;- assert!(cleared.parent_id.is_none());+ assert!(updated.parent_id.is_none());+ assert_eq!(+ project_share_permission_columns(&pool, ROOT_ID).await,+ StoredSharePermission {+ link_share: Some("TEAM".to_owned()),+ link_share_access_level: Some("view".to_owned()),+ }+ );++ repo.edit_project(EditProjectArgs {+ project_id: ROOT_ID.to_owned(),+ name: None,+ update_parent: false,+ parent_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: Some(Some(AccessLevel::Comment)),+ channel_share_permissions: None,+ }),+ })+ .await?;+ assert_eq!(+ project_share_permission_columns(&pool, ROOT_ID).await,+ StoredSharePermission {+ link_share: Some("TEAM".to_owned()),+ link_share_access_level: Some("comment".to_owned()),+ }+ );++ repo.edit_project(EditProjectArgs {+ project_id: ROOT_ID.to_owned(),+ name: None,+ update_parent: false,+ parent_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Public)),+ link_share_access_level: Some(Some(AccessLevel::Edit)),+ channel_share_permissions: None,+ }),+ })+ .await?;+ let before_omitted_update = project_share_permission_columns(&pool, ROOT_ID).await;+ assert_eq!(+ before_omitted_update,+ StoredSharePermission {+ link_share: Some("PUBLIC".to_owned()),+ link_share_access_level: Some("edit".to_owned()),+ }+ );++ repo.edit_project(EditProjectArgs {+ project_id: ROOT_ID.to_owned(),+ name: None,+ update_parent: false,+ parent_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: None,+ channel_share_permissions: None,+ }),+ })+ .await?;+ assert_eq!(+ project_share_permission_columns(&pool, ROOT_ID).await,+ before_omitted_update+ );++ repo.edit_project(EditProjectArgs {+ project_id: ROOT_ID.to_owned(),+ name: None,+ update_parent: false,+ parent_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: Some(None),+ link_share_access_level: Some(Some(AccessLevel::Edit)),+ channel_share_permissions: None,+ }),+ })+ .await?;+ assert_eq!(+ project_share_permission_columns(&pool, ROOT_ID).await,+ StoredSharePermission {+ link_share: None,+ link_share_access_level: None,+ }+ );let permission = repo.get_project_share_permission(ROOT_ID).await?;- assert!(!permission.is_public);- assert_eq!(permission.public_access_level, None);+ assert_eq!(permission.link_share, None);+ assert_eq!(permission.link_share_access_level, None);+ assert_eq!(+ permission.channel_share_permissions.expect("channel").len(),+ 1+ );Ok(())}@@ -464,11 +619,12 @@ async fn upload_folder_preserves_tree_metadata_and_compensates(),("Empty".to_owned(), FileSystemNode::Folder(HashMap::new())),]));+ let mut share_permission = SharePermissionV2::new_project_share_permission();+ share_permission.link_share = Some(LinkShare::Team);let result = repo.upload_folder(UploadFolderRepoArgs {user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")?.into_owned(),- share_permission:- models_permissions::share_permission::SharePermissionV2::new_project_share_permission(),+ share_permission,root_folder,root_folder_name: "Upload".to_owned(),upload_request_id: "lambda-request-id".to_owned(),@@ -501,6 +657,30 @@ async fn upload_folder_preserves_tree_metadata_and_compensates(.iter().map(|document| document.document_id.clone()).collect::<Vec<_>>();+ let created_permissions = sqlx::query_scalar!(+ r#"+ WITH created_permission_ids AS (+ SELECT "sharePermissionId" AS id+ FROM "ProjectPermission"+ WHERE "projectId" = ANY($1)+ UNION+ SELECT "sharePermissionId" AS id+ FROM "DocumentPermission"+ WHERE "documentId" = ANY($2)+ )+ SELECT COUNT(*) AS "count!"+ FROM "SharePermission" permission+ WHERE permission.id IN (SELECT id FROM created_permission_ids)+ AND permission."linkShare" = 'TEAM'+ AND permission."linkShareAccessLevel" = 'view'+ "#,+ &result.project_ids,+ &document_ids,+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(created_permissions, 4);+repo.delete_uploaded_tree(&result.project_ids, &document_ids).await?;let remaining = sqlx::query_scalar!(diff --git a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs b/crates/projects/src/outbound/pg_project_repo/upload_folder.rsindex 8e13866421..c394a1e1a1 100644--- a/crates/projects/src/outbound/pg_project_repo/upload_folder.rs+++ b/crates/projects/src/outbound/pg_project_repo/upload_folder.rs@@ -264,17 +264,24 @@ async fn create_document_share_permission(document_id: &str,permission: &SharePermissionV2,) -> Result<(), sqlx::Error> {+ let link_share = permission.link_share;+ let link_share_access_level =+ share::normalize_link_share_access_level(link_share, permission.link_share_access_level);+ let link_share = link_share.map(|value| value.to_string());+let permission_id = sqlx::query_scalar!(r#"- INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")+ INSERT INTO "SharePermission" (+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt"+ )VALUES ($1, $2, NOW(), NOW())RETURNING id"#,- permission.is_public,- permission- .public_access_level- .as_ref()- .map(ToString::to_string),+ link_share,+ link_share_access_level as _,).fetch_one(transaction.as_mut()).await?;diff --git a/crates/share_permission_db_utils/src/lib.rs b/crates/share_permission_db_utils/src/lib.rsindex 46de530b4d..231fcc3a67 100644--- a/crates/share_permission_db_utils/src/lib.rs+++ b/crates/share_permission_db_utils/src/lib.rs@@ -164,8 +164,13 @@ pub async fn ensure_thread_share_permission(pool: &PgPool, thread_id: &str) -> alet mut transaction = pool.begin().await.context("failed to start transaction")?;let share_permission_id = sqlx::query_scalar!(r#"- INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")- VALUES (false, NULL, NOW(), NOW())+ INSERT INTO "SharePermission" (+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt"+ )+ VALUES (NULL, NULL, NOW(), NOW())RETURNING id as "id!""#,)diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex 9b3196d156..ac8d990fc3 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -1215,9 +1215,9 @@ export type InitGmailLinkData = {*/original_url: string;/**- * **OPTIONAL**. Also request the Google Calendar scope. Only honored when the deployment allows calendar scope requests; pass it from calendar entry points only, since the extra scope changes the Google consent screen.+ * **OPTIONAL**. Which capabilities to request consent for: `gmail` (default), `gmail_and_calendar`, or `calendar`. The calendar variants are only honored when the deployment allows calendar scope requests.*/- include_calendar?: boolean;+ scopes?: string;};url: '/link/gmail';};diff --git a/packages/sdk/generated/cognition/index.ts b/packages/sdk/generated/cognition/index.tsindex 52c1c27ec6..91417dde36 100644--- a/packages/sdk/generated/cognition/index.ts+++ b/packages/sdk/generated/cognition/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, TargetType, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';+export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, TargetType, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.tsindex 6e3edd236e..714683704e 100644--- a/packages/sdk/generated/cognition/types.gen.ts+++ b/packages/sdk/generated/cognition/types.gen.ts@@ -817,6 +817,11 @@ export type LinearIssueMeta = {url?: string | null;};+/**+ * Defines who can access an item through its share link.+ */+export type LinkShare = 'PUBLIC' | 'TEAM';+export type MacroUserIdStr = string;export type MemoryErrorBody = {@@ -1171,15 +1176,12 @@ export type SharePermissionV2 = {* The share permission id*/id: string;- /**- * If the item is publicly accessible- */- isPublic: boolean;+ linkShare?: null | LinkShare;+ linkShareAccessLevel?: null | AccessLevel;/*** The owner of the item*/owner: string;- publicAccessLevel?: null | AccessLevel;};/**@@ -1359,11 +1361,8 @@ export type UpdateSharePermissionRequestV2 = {* Any channel share permissions to be created/updated/removed*/channelSharePermissions?: Array<UpdateChannelSharePermission> | null;- /**- * If the item is publicly accessible- */- isPublic?: boolean | null;- publicAccessLevel?: null | AccessLevel;+ linkShare?: null | LinkShare;+ linkShareAccessLevel?: null | AccessLevel;};/**diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 4b880786c9..1720515c2e 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, Activity, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivitiesResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetRecentActivityHandlerData, GetRecentActivityHandlerError, GetRecentActivityHandlerErrors, GetRecentActivityHandlerResponse, GetRecentActivityHandlerResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserActivitiesResponse, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 6851440417..26305c6c5f 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -5406,6 +5406,11 @@ export type LeaveCallResponse = {callEnded: boolean;};+/**+ * Defines who can access an item through its share link.+ */+export type LinkShare = 'PUBLIC' | 'TEAM';+/*** Webhooks visible to the caller across their personal and team workspaces.*/@@ -6520,15 +6525,12 @@ export type SharePermissionV2 = {* The share permission id*/id: string;- /**- * If the item is publicly accessible- */- isPublic: boolean;+ linkShare?: null | LinkShare;+ linkShareAccessLevel?: null | AccessLevel;/*** The owner of the item*/owner: string;- publicAccessLevel?: null | AccessLevel;};/**@@ -7960,11 +7962,8 @@ export type UpdateSharePermissionRequestV2 = {* Any channel share permissions to be created/updated/removed*/channelSharePermissions?: Array<UpdateChannelSharePermission> | null;- /**- * If the item is publicly accessible- */- isPublic?: boolean | null;- publicAccessLevel?: null | AccessLevel;+ linkShare?: null | LinkShare;+ linkShareAccessLevel?: null | AccessLevel;};/**diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex da2bdcb59d..146c67288f 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -626,12 +626,12 @@}},{- "name": "include_calendar",+ "name": "scopes","in": "query",- "description": "**OPTIONAL**. Also request the Google Calendar scope. Only honored when the deployment allows calendar scope requests; pass it from calendar entry points only, since the extra scope changes the Google consent screen.",+ "description": "**OPTIONAL**. Which capabilities to request consent for: `gmail` (default), `gmail_and_calendar`, or `calendar`. The calendar variants are only honored when the deployment allows calendar scope requests.","required": false,"schema": {- "type": "boolean"+ "type": "string"}}],diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.jsonindex fa427b660d..236f94b6d0 100644--- a/packages/sdk/specs/cognition.json+++ b/packages/sdk/specs/cognition.json@@ -3417,6 +3417,11 @@}}},+ "LinkShare": {+ "type": "string",+ "description": "Defines who can access an item through its share link.",+ "enum": ["PUBLIC", "TEAM"]+ },"MacroUserIdStr": {"type": "string"},@@ -3867,7 +3872,7 @@},"SharePermissionV2": {"type": "object",- "required": ["id", "isPublic", "owner"],+ "required": ["id", "owner"],"properties": {"channelSharePermissions": {"type": ["array", "null"],@@ -3880,24 +3885,31 @@"type": "string","description": "The share permission id"},- "isPublic": {- "type": "boolean",- "description": "If the item is publicly accessible"- },- "owner": {- "type": "string",- "description": "The owner of the item"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link"+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The level of access granted through the share link"}]+ },+ "owner": {+ "type": "string",+ "description": "The owner of the item"}}},@@ -4184,18 +4196,25 @@},"description": "Any channel share permissions to be created/updated/removed"},- "isPublic": {- "type": ["boolean", "null"],- "description": "If the item is publicly accessible"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link. Omit to leave unchanged or pass `null` to\ndisable link sharing."+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."}]}diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 3360637a0f..2d7adb683c 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -19558,6 +19558,11 @@}}},+ "LinkShare": {+ "type": "string",+ "description": "Defines who can access an item through its share link.",+ "enum": ["PUBLIC", "TEAM"]+ },"ListWebhooksResponse": {"type": "object","description": "Webhooks visible to the caller across their personal and team workspaces.",@@ -21692,7 +21697,7 @@},"SharePermissionV2": {"type": "object",- "required": ["id", "isPublic", "owner"],+ "required": ["id", "owner"],"properties": {"channelSharePermissions": {"type": ["array", "null"],@@ -21705,24 +21710,31 @@"type": "string","description": "The share permission id"},- "isPublic": {- "type": "boolean",- "description": "If the item is publicly accessible"- },- "owner": {- "type": "string",- "description": "The owner of the item"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link"+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The level of access granted through the share link"}]+ },+ "owner": {+ "type": "string",+ "description": "The owner of the item"}}},@@ -23834,18 +23846,25 @@},"description": "Any channel share permissions to be created/updated/removed"},- "isPublic": {- "type": ["boolean", "null"],- "description": "If the item is publicly accessible"+ "linkShare": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/LinkShare",+ "description": "Who can access the item through its share link. Omit to leave unchanged or pass `null` to\ndisable link sharing."+ }+ ]},- "publicAccessLevel": {+ "linkShareAccessLevel": {"oneOf": [{"type": "null"},{"$ref": "#/components/schemas/AccessLevel",- "description": "The level of public access"+ "description": "The link access level. Omit to leave unchanged or pass `null` to reset it to the default\nlevel when a link share exists."}]}diff --git a/services/call_recording_preview_handler/src/db.rs b/services/call_recording_preview_handler/src/db.rsindex f90290811b..7054c93e2b 100644--- a/services/call_recording_preview_handler/src/db.rs+++ b/services/call_recording_preview_handler/src/db.rs@@ -73,13 +73,19 @@ mod test {}async fn insert_share_permission(pool: &Pool<Postgres>, id: &str) -> anyhow::Result<()> {- sqlx::query(+ sqlx::query!(r#"- INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel", "createdAt", "updatedAt")- VALUES ($1, FALSE, NULL, NOW(), NOW())+ INSERT INTO "SharePermission" (+ id,+ "linkShare",+ "linkShareAccessLevel",+ "createdAt",+ "updatedAt"+ )+ VALUES ($1, NULL, NULL, NOW(), NOW())"#,+ id,)- .bind(id).execute(pool).await?;diff --git a/services/delete_chat_handler/migrations/20240325143515_basic_schema_for_testing.sql b/services/delete_chat_handler/migrations/20240325143515_basic_schema_for_testing.sqlindex 4305b4c136..b994701e05 100644--- a/services/delete_chat_handler/migrations/20240325143515_basic_schema_for_testing.sql+++ b/services/delete_chat_handler/migrations/20240325143515_basic_schema_for_testing.sql@@ -903,10 +903,11 @@ CREATE TABLE public."RolesOnUsers" (CREATE TABLE public."SharePermission" (id text DEFAULT gen_random_uuid() NOT NULL,- "isPublic" boolean NOT NULL,- "publicAccessLevel" text,+ "linkShare" text,+ "linkShareAccessLevel" text,"createdAt" timestamp(3) without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- "updatedAt" timestamp(3) without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL+ "updatedAt" timestamp(3) without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,+ CONSTRAINT "SharePermission_linkShare_check" CHECK ("linkShare" IN ('PUBLIC', 'TEAM')));CREATE TABLE public."Thread" (diff --git a/services/document_cognition_service/src/api/swagger.rs b/services/document_cognition_service/src/api/swagger.rsindex 3039c880a5..f75aa1d439 100644--- a/services/document_cognition_service/src/api/swagger.rs+++ b/services/document_cognition_service/src/api/swagger.rs@@ -110,7 +110,7 @@ use utoipa::OpenApi;StringIDResponse,GenericErrorResponse,// Permissions V2- models_permissions::share_permission::access_level::AccessLevel, models_permissions::share_permission::SharePermissionV2, models_permissions::share_permission::UpdateSharePermissionRequestV2, // Share permission+ models_permissions::share_permission::LinkShare, models_permissions::share_permission::access_level::AccessLevel, models_permissions::share_permission::SharePermissionV2, models_permissions::share_permission::UpdateSharePermissionRequestV2, // Share permissionmodels_permissions::share_permission::channel_share_permission::ChannelSharePermission, models_permissions::share_permission::channel_share_permission::UpdateChannelSharePermission, // Channel share permissions// Chatdiff --git a/services/document_storage_service/src/api/annotations/create_comment.rs b/services/document_storage_service/src/api/annotations/create_comment.rsindex e5c61b2a9f..95b54d8087 100644--- a/services/document_storage_service/src/api/annotations/create_comment.rs+++ b/services/document_storage_service/src/api/annotations/create_comment.rs@@ -168,13 +168,13 @@ pub async fn create_comment_handler(if let Some(Mentions { mention_id, .. }) = &req.mentions&& !recipients.mention_recipients.is_empty(){- // If the document is public, grant the mentioned users access so- // the comment surfaces in their soup/inbox — a notification alone+ // If the document is link-shared, grant the mentioned users access+ // so the comment surfaces in their soup/inbox — a notification alone// isn't enough for the document to appear there.let mention_recipients: Vec<MacroUserIdStr<'_>> =recipients.mention_recipients.iter().cloned().collect();- let _ = macro_db_client::share_on_mention::share_public_document_with_mentioned_users(+ let _ = macro_db_client::share_on_mention::share_link_shared_document_with_mentioned_users(&db,&document_id,&mention_recipients,diff --git a/services/document_storage_service/src/api/annotations/edit_comment.rs b/services/document_storage_service/src/api/annotations/edit_comment.rsindex 53e813ff5e..3a66df5da8 100644--- a/services/document_storage_service/src/api/annotations/edit_comment.rs+++ b/services/document_storage_service/src/api/annotations/edit_comment.rs@@ -99,19 +99,19 @@ pub async fn edit_comment_handler(.filter_map(|id| MacroUserIdStr::try_from(id.clone()).ok()).collect();- // If the document is public, grant the mentioned users access so- // the comment surfaces in their soup/inbox — a notification alone+ // If the document is link-shared, grant the mentioned users access+ // so the comment surfaces in their soup/inbox — a notification alone// isn't enough for the document to appear there.let mention_recipients: Vec<MacroUserIdStr<'_>> =recipient_ids.iter().cloned().collect();- let _ = macro_db_client::share_on_mention::share_public_document_with_mentioned_users(+ let _ = macro_db_client::share_on_mention::share_link_shared_document_with_mentioned_users(&db,&res.document_id,&mention_recipients,).await- .inspect_err(|e| tracing::error!(error =? e, "couldn't share public document with mentioned users"));+ .inspect_err(|e| tracing::error!(error =? e, "couldn't share link-shared document with mentioned users"));let request = notif_ctx.build_mention_notif(recipient_ids, &mention_id)diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex ee497323ba..7ccefdc205 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -585,6 +585,7 @@ use utoipa::OpenApi;// Permissions V2+ models_permissions::share_permission::LinkShare,models_permissions::share_permission::access_level::AccessLevel,models_permissions::share_permission::SharePermissionV2,models_permissions::share_permission::UpdateSharePermissionRequestV2, // Share permissiondiff --git a/services/organization_retention_handler/migrations/20240325143515_basic_schema_for_testing.sql b/services/organization_retention_handler/migrations/20240325143515_basic_schema_for_testing.sqlindex 725a9e1a31..71a713df92 100644--- a/services/organization_retention_handler/migrations/20240325143515_basic_schema_for_testing.sql+++ b/services/organization_retention_handler/migrations/20240325143515_basic_schema_for_testing.sql@@ -256,10 +256,11 @@ CREATE TABLE "ChatMessage"CREATE TABLE "SharePermission"("id" TEXT PRIMARY KEY DEFAULT uuid_generate_v4(),- "isPublic" BOOLEAN NOT NULL,- "publicAccessLevel" TEXT,- "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),- "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()+ "linkShare" TEXT,+ "linkShareAccessLevel" TEXT,+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ CONSTRAINT "SharePermission_linkShare_check" CHECK ("linkShare" IN ('PUBLIC', 'TEAM')));CREATE TABLE "DocumentPermission"diff --git a/services/organization_retention_trigger/migrations/20240325143515_basic_schema_for_testing.sql b/services/organization_retention_trigger/migrations/20240325143515_basic_schema_for_testing.sqlindex 5c5d0f5f2b..b810ed1e48 100644--- a/services/organization_retention_trigger/migrations/20240325143515_basic_schema_for_testing.sql+++ b/services/organization_retention_trigger/migrations/20240325143515_basic_schema_for_testing.sql@@ -243,10 +243,11 @@ CREATE TABLE "ChatMessage"CREATE TABLE "SharePermission"("id" TEXT PRIMARY KEY DEFAULT uuid_generate_v4(),- "isPublic" BOOLEAN NOT NULL,- "publicAccessLevel" TEXT,- "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),- "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()+ "linkShare" TEXT,+ "linkShareAccessLevel" TEXT,+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ CONSTRAINT "SharePermission_linkShare_check" CHECK ("linkShare" IN ('PUBLIC', 'TEAM')));CREATE TABLE "DocumentPermission"diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 9250787e4e..dfec6e8175 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -47,7 +47,7 @@ type CompleteMutationRoot {"""moveEntities(inputs: [MoveEntityInput!]!): EntityMutationPayload!"""- Update public and channel share policies across supported entity kinds.+ Update link and channel share policies across supported entity kinds."""updateEntitySharePolicies(inputs: [UpdateEntitySharePolicyInput!]!): EntityMutationPayload!"""@@ -151,17 +151,18 @@ input EntityRefInput {}"""-Shared public/channel share-policy update.+Shared link/channel share-policy update."""input EntitySharePolicyInput {"""- Whether public access should be enabled.+ Link-sharing audience. Omit to leave unchanged or pass null to disable link sharing."""- isPublic: Boolean+ linkShare: GraphqlLinkShare"""- Public access level when public access is enabled.+ Link access level. Omit to leave unchanged or pass null to reset it to the default level+ when a link share exists."""- publicAccessLevel: GraphqlEntityAccessLevel+ linkShareAccessLevel: GraphqlEntityAccessLevel"""Channel access entries to add, remove, or replace."""@@ -2407,6 +2408,20 @@ type GraphqlLinkPropertyValue {urls: [String!]!}+"""+Audience allowed to access an entity through its share link.+"""+enum GraphqlLinkShare {+ """+ Anyone with the link can access the entity.+ """+ PUBLIC+ """+ Members of the owner's team with the link can access the entity.+ """+ TEAM+}+"""Metadata for a mention in a document comment."""@@ -5185,7 +5200,7 @@ input UpdateEntitySharePolicyInput {"""entity: EntityRefInput!"""- New public/channel policy values.+ New link/channel policy values."""policy: EntitySharePolicyInput!}diff --git a/tooling/seed_cli/seed/documents/documents.json b/tooling/seed_cli/seed/documents/documents.jsonindex 856e07b25e..e32dc014ca 100644--- a/tooling/seed_cli/seed/documents/documents.json+++ b/tooling/seed_cli/seed/documents/documents.json@@ -1,102 +1,102 @@[- { "document_id": "00000000-0000-0000-0002-000000000001", "document_name": "Project Roadmap", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000002", "document_name": "Meeting Notes", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000003", "document_name": "Architecture Diagram", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000004", "document_name": "Q3 Budget Report", "file_name": "pdf.pdf", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000005", "document_name": "Sprint Retro Notes", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000006", "document_name": "System Design", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000007", "document_name": "Employee Handbook", "file_name": "pdf.pdf", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000008", "document_name": "API Documentation", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000009", "document_name": "Wireframe Draft", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000000a", "document_name": "Sales Pitch Deck", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000000b", "document_name": "Release Checklist", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000000c", "document_name": "User Flow Diagram", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000000d", "document_name": "Annual Report", "file_name": "pdf.pdf", "is_public": true },- { "document_id": "00000000-0000-0000-0002-00000000000e", "document_name": "Onboarding Guide", "file_name": "md.md", "is_public": true },- { "document_id": "00000000-0000-0000-0002-00000000000f", "document_name": "Network Topology", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000010", "document_name": "Product Requirements", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000011", "document_name": "Dev Setup Guide", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000012", "document_name": "ER Diagram", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000013", "document_name": "Marketing Plan", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000014", "document_name": "Incident Postmortem", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000015", "document_name": "Component Layout", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000016", "document_name": "Security Audit", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000017", "document_name": "Changelog", "file_name": "md.md", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000018", "document_name": "Data Flow Sketch", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000019", "document_name": "Contract Template", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000001a", "document_name": "Team Standup Notes", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000001b", "document_name": "Infrastructure Map", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000001c", "document_name": "Compliance Report", "file_name": "pdf.pdf", "is_public": true },- { "document_id": "00000000-0000-0000-0002-00000000001d", "document_name": "Migration Plan", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000001e", "document_name": "Sequence Diagram", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000001f", "document_name": "Vendor Proposal", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000020", "document_name": "Troubleshooting Guide", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000021", "document_name": "Deployment Pipeline", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000022", "document_name": "Board Presentation", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000023", "document_name": "Feature Spec", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000024", "document_name": "Brainstorm Session", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000025", "document_name": "Investor Update", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000026", "document_name": "Code Review Checklist", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000027", "document_name": "Service Architecture", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000028", "document_name": "Performance Report", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000029", "document_name": "Testing Strategy", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000002a", "document_name": "Page Layout", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000002b", "document_name": "NDA Template", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000002c", "document_name": "Decision Log", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000002d", "document_name": "Mind Map", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000002e", "document_name": "Tax Filing", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000002f", "document_name": "Knowledge Base Entry", "file_name": "md.md", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000030", "document_name": "Org Chart", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000031", "document_name": "Training Material", "file_name": "pdf.pdf", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000032", "document_name": "Bug Report Template", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000033", "document_name": "Concept Sketch", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000034", "document_name": "Legal Review", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000035", "document_name": "Architecture Decision Record", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000036", "document_name": "Dashboard Mockup", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000037", "document_name": "SLA Agreement", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000038", "document_name": "Runbook", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000039", "document_name": "Workflow Diagram", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000003a", "document_name": "Research Paper", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000003b", "document_name": "RFC Draft", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000003c", "document_name": "Sitemap", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000003d", "document_name": "Expense Report", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000003e", "document_name": "Project Retrospective", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000003f", "document_name": "State Machine", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000040", "document_name": "Insurance Policy", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000041", "document_name": "Style Guide", "file_name": "md.md", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000042", "document_name": "UI Prototype", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000043", "document_name": "Partnership Agreement", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000044", "document_name": "API Changelog", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000045", "document_name": "Database Schema", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000046", "document_name": "Quarterly Review", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000047", "document_name": "Configuration Guide", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000048", "document_name": "Gantt Chart", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000049", "document_name": "Warranty Document", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000004a", "document_name": "Deployment Notes", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000004b", "document_name": "Class Diagram", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000004c", "document_name": "Customer Feedback Summary", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000004d", "document_name": "Contributing Guidelines", "file_name": "md.md", "is_public": true },- { "document_id": "00000000-0000-0000-0002-00000000004e", "document_name": "Login Flow", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000004f", "document_name": "Brand Guidelines", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000050", "document_name": "Monitoring Setup", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000051", "document_name": "Payment Flow", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000052", "document_name": "Privacy Policy", "file_name": "pdf.pdf", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000053", "document_name": "Environment Variables", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000054", "document_name": "Notification Flow", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000055", "document_name": "Terms of Service", "file_name": "pdf.pdf", "is_public": true },- { "document_id": "00000000-0000-0000-0002-000000000056", "document_name": "Dependency Audit", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000057", "document_name": "Search Architecture", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000058", "document_name": "Invoice Template", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000059", "document_name": "Capacity Planning", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000005a", "document_name": "Auth Flow", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000005b", "document_name": "Compliance Checklist", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000005c", "document_name": "Load Test Results", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000005d", "document_name": "Microservices Map", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000005e", "document_name": "Risk Assessment", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-00000000005f", "document_name": "Disaster Recovery Plan", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000060", "document_name": "CI Pipeline", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000061", "document_name": "Shipping Label", "file_name": "pdf.pdf", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000062", "document_name": "Benchmarks", "file_name": "md.md", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000063", "document_name": "Feature Flag Matrix", "file_name": "canvas.canvas", "is_public": false },- { "document_id": "00000000-0000-0000-0002-000000000064", "document_name": "Certificate", "file_name": "pdf.pdf", "is_public": false }+ { "document_id": "00000000-0000-0000-0002-000000000001", "document_name": "Project Roadmap", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000002", "document_name": "Meeting Notes", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000003", "document_name": "Architecture Diagram", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000004", "document_name": "Q3 Budget Report", "file_name": "pdf.pdf", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000005", "document_name": "Sprint Retro Notes", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000006", "document_name": "System Design", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000007", "document_name": "Employee Handbook", "file_name": "pdf.pdf", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000008", "document_name": "API Documentation", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000009", "document_name": "Wireframe Draft", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000000a", "document_name": "Sales Pitch Deck", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000000b", "document_name": "Release Checklist", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000000c", "document_name": "User Flow Diagram", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000000d", "document_name": "Annual Report", "file_name": "pdf.pdf", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-00000000000e", "document_name": "Onboarding Guide", "file_name": "md.md", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-00000000000f", "document_name": "Network Topology", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000010", "document_name": "Product Requirements", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000011", "document_name": "Dev Setup Guide", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000012", "document_name": "ER Diagram", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000013", "document_name": "Marketing Plan", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000014", "document_name": "Incident Postmortem", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000015", "document_name": "Component Layout", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000016", "document_name": "Security Audit", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000017", "document_name": "Changelog", "file_name": "md.md", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000018", "document_name": "Data Flow Sketch", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000019", "document_name": "Contract Template", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000001a", "document_name": "Team Standup Notes", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000001b", "document_name": "Infrastructure Map", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000001c", "document_name": "Compliance Report", "file_name": "pdf.pdf", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-00000000001d", "document_name": "Migration Plan", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000001e", "document_name": "Sequence Diagram", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000001f", "document_name": "Vendor Proposal", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000020", "document_name": "Troubleshooting Guide", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000021", "document_name": "Deployment Pipeline", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000022", "document_name": "Board Presentation", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000023", "document_name": "Feature Spec", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000024", "document_name": "Brainstorm Session", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000025", "document_name": "Investor Update", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000026", "document_name": "Code Review Checklist", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000027", "document_name": "Service Architecture", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000028", "document_name": "Performance Report", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000029", "document_name": "Testing Strategy", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000002a", "document_name": "Page Layout", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000002b", "document_name": "NDA Template", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000002c", "document_name": "Decision Log", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000002d", "document_name": "Mind Map", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000002e", "document_name": "Tax Filing", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000002f", "document_name": "Knowledge Base Entry", "file_name": "md.md", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000030", "document_name": "Org Chart", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000031", "document_name": "Training Material", "file_name": "pdf.pdf", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000032", "document_name": "Bug Report Template", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000033", "document_name": "Concept Sketch", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000034", "document_name": "Legal Review", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000035", "document_name": "Architecture Decision Record", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000036", "document_name": "Dashboard Mockup", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000037", "document_name": "SLA Agreement", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000038", "document_name": "Runbook", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000039", "document_name": "Workflow Diagram", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000003a", "document_name": "Research Paper", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000003b", "document_name": "RFC Draft", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000003c", "document_name": "Sitemap", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000003d", "document_name": "Expense Report", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000003e", "document_name": "Project Retrospective", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000003f", "document_name": "State Machine", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000040", "document_name": "Insurance Policy", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000041", "document_name": "Style Guide", "file_name": "md.md", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000042", "document_name": "UI Prototype", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000043", "document_name": "Partnership Agreement", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000044", "document_name": "API Changelog", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000045", "document_name": "Database Schema", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000046", "document_name": "Quarterly Review", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000047", "document_name": "Configuration Guide", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000048", "document_name": "Gantt Chart", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000049", "document_name": "Warranty Document", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000004a", "document_name": "Deployment Notes", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000004b", "document_name": "Class Diagram", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000004c", "document_name": "Customer Feedback Summary", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000004d", "document_name": "Contributing Guidelines", "file_name": "md.md", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-00000000004e", "document_name": "Login Flow", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000004f", "document_name": "Brand Guidelines", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000050", "document_name": "Monitoring Setup", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000051", "document_name": "Payment Flow", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000052", "document_name": "Privacy Policy", "file_name": "pdf.pdf", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000053", "document_name": "Environment Variables", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000054", "document_name": "Notification Flow", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000055", "document_name": "Terms of Service", "file_name": "pdf.pdf", "link_share": "PUBLIC", "link_share_access_level": "view" },+ { "document_id": "00000000-0000-0000-0002-000000000056", "document_name": "Dependency Audit", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000057", "document_name": "Search Architecture", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000058", "document_name": "Invoice Template", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000059", "document_name": "Capacity Planning", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000005a", "document_name": "Auth Flow", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000005b", "document_name": "Compliance Checklist", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000005c", "document_name": "Load Test Results", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000005d", "document_name": "Microservices Map", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000005e", "document_name": "Risk Assessment", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-00000000005f", "document_name": "Disaster Recovery Plan", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000060", "document_name": "CI Pipeline", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000061", "document_name": "Shipping Label", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000062", "document_name": "Benchmarks", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000063", "document_name": "Feature Flag Matrix", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null },+ { "document_id": "00000000-0000-0000-0002-000000000064", "document_name": "Certificate", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null }]diff --git a/tooling/seed_cli/seed/scenarios/team-perms.json b/tooling/seed_cli/seed/scenarios/team-perms.jsonindex fbb8d11470..66817e5f7e 100644--- a/tooling/seed_cli/seed/scenarios/team-perms.json+++ b/tooling/seed_cli/seed/scenarios/team-perms.json@@ -71,10 +71,17 @@"owner": "alice","name": "Handbook","file": "pdf.pdf",- "public": "view",+ "link_share": "PUBLIC",+ "link_share_access_level": "view","share": [{ "with": "user:erin", "level": "edit" }]},- "bob-notes": { "owner": "bob", "name": "Bob Notes", "file": "md.md" }+ "bob-notes": {+ "owner": "bob",+ "name": "Bob Notes",+ "file": "md.md",+ "link_share": "TEAM",+ "link_share_access_level": "view"+ }},"tasks": {"ship-tags": {diff --git a/tooling/seed_cli/src/entity/document/mod.rs b/tooling/seed_cli/src/entity/document/mod.rsindex e17d295cce..8a7ccfc8b1 100644--- a/tooling/seed_cli/src/entity/document/mod.rs+++ b/tooling/seed_cli/src/entity/document/mod.rs@@ -8,7 +8,9 @@ use clap::{Args, Subcommand};use macro_db_client::document::v2::create::CreateDocumentArgs;use macro_user_id::user_id::MacroUserIdStr;use model::document::FileType;-use models_permissions::share_permission::{SharePermissionV2, access_level::AccessLevel};+use models_permissions::share_permission::{+ LinkShare, SharePermissionV2, access_level::AccessLevel,+};use serde::Deserialize;use uuid::{NoContext, Timestamp, Uuid};@@ -43,13 +45,12 @@ pub struct CreateArgs {/// The path to the file you want to upload#[arg(long)]pub file_path: String,- /// Whether the document should be public or not. If enabled this will give- /// the document view access publicly- #[arg(long, default_value = "false")]- pub is_public: bool,- /// If you have a public document you need to provide the public access level+ /// Who can access the document through its share link.+ #[arg(long)]+ pub link_share: Option<LinkShare>,+ /// Access level granted through the share link.#[arg(long)]- pub public_access_level: Option<String>,+ pub link_share_access_level: Option<AccessLevel>,/// Name of the document./// Without the extension#[arg(long)]@@ -75,6 +76,7 @@ pub struct SeedArgs {/// A row in the seed JSON file.#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]struct SeedDocumentRow {/// Pre-defined document UUID.document_id: Uuid,@@ -82,8 +84,10 @@ struct SeedDocumentRow {document_name: String,/// File name from the seed/documents/files/ directory.file_name: String,- /// Whether the document is public.- is_public: bool,+ /// Who can access the document through its share link.+ link_share: Option<LinkShare>,+ /// Access level granted through the share link.+ link_share_access_level: Option<AccessLevel>,}impl DocumentArgs {@@ -132,11 +136,9 @@ async fn create(args: CreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {project_name: None,share_permission: &SharePermissionV2 {id: String::new(),+ link_share: args.link_share,+ link_share_access_level: args.link_share_access_level,owner: owner.as_ref().to_string(),- is_public: args.is_public,- public_access_level: args- .public_access_level- .map(|s| AccessLevel::from_str(&s).unwrap()),channel_share_permissions: None,},skip_history: args.skip_history,@@ -226,13 +228,9 @@ pub(crate) async fn seed_from_file_ref(project_name: None,share_permission: &SharePermissionV2 {id: String::new(),+ link_share: row.link_share,+ link_share_access_level: row.link_share_access_level,owner: owner.as_ref().to_string(),- is_public: row.is_public,- public_access_level: if row.is_public {- Some(AccessLevel::View)- } else {- None- },channel_share_permissions: None,},skip_history: true,diff --git a/tooling/seed_cli/src/entity/document/test.rs b/tooling/seed_cli/src/entity/document/test.rsindex 28019e9fcf..a3c895d7fb 100644--- a/tooling/seed_cli/src/entity/document/test.rs+++ b/tooling/seed_cli/src/entity/document/test.rs@@ -38,8 +38,8 @@ fn parse_document_create_minimal() {assert_eq!(create.owner, "macro|[email protected]");assert_eq!(create.file_path, "/tmp/test.pdf");assert_eq!(create.document_name, "My Document");- assert!(!create.is_public);- assert!(create.public_access_level.is_none());+ assert!(create.link_share.is_none());+ assert!(create.link_share_access_level.is_none());assert!(create.id.is_none());assert!(!create.skip_history);}@@ -59,8 +59,9 @@ fn parse_document_create_full() {"/tmp/test.pdf","--document-name","My Document",- "--is-public",- "--public-access-level",+ "--link-share",+ "PUBLIC",+ "--link-share-access-level","view","--id","custom-doc-id",@@ -76,8 +77,8 @@ fn parse_document_create_full() {assert_eq!(create.owner, "macro|[email protected]");assert_eq!(create.file_path, "/tmp/test.pdf");assert_eq!(create.document_name, "My Document");- assert!(create.is_public);- assert_eq!(create.public_access_level.as_deref(), Some("view"));+ assert_eq!(create.link_share, Some(LinkShare::Public));+ assert_eq!(create.link_share_access_level, Some(AccessLevel::View));assert_eq!(create.id.as_deref(), Some("custom-doc-id"));assert!(create.skip_history);}@@ -245,8 +246,8 @@ async fn create_document_success() {owner: "macro|[email protected]".to_string(),file_path: file.path().to_str().unwrap().to_string(),document_name: "My Document".to_string(),- is_public: false,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,id: None,skip_history: false,}),@@ -273,8 +274,8 @@ async fn create_document_db_failure_propagates() {owner: "macro|[email protected]".to_string(),file_path: file.path().to_str().unwrap().to_string(),document_name: "My Document".to_string(),- is_public: false,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,id: None,skip_history: false,}),@@ -306,8 +307,8 @@ async fn create_document_s3_failure_propagates() {owner: "macro|[email protected]".to_string(),file_path: file.path().to_str().unwrap().to_string(),document_name: "My Document".to_string(),- is_public: false,- public_access_level: None,+ link_share: None,+ link_share_access_level: None,id: None,skip_history: false,}),@@ -325,17 +326,31 @@ async fn seed_creates_all_documents() {let doc1 = Uuid::new_v4();let doc2 = Uuid::new_v4();let json = serde_json::json!([- { "document_id": doc1, "document_name": "Test PDF", "file_name": "pdf.pdf", "is_public": false },- { "document_id": doc2, "document_name": "Test Markdown", "file_name": "md.md", "is_public": true }+ { "document_id": doc1, "document_name": "Test PDF", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": doc2, "document_name": "Test Markdown", "file_name": "md.md", "link_share": "PUBLIC", "link_share_access_level": "view" }]).to_string();let file = write_temp_json(&json);+ let mut create_count = 0;let mut mock_db = Db::default();mock_db.expect_create_document().times(2)- .returning(|_| Ok(test_document_metadata()));+ .returning(move |args| {+ create_count += 1;+ if create_count == 1 {+ assert_eq!(args.share_permission.link_share, None);+ assert_eq!(args.share_permission.link_share_access_level, None);+ } else {+ assert_eq!(args.share_permission.link_share, Some(LinkShare::Public));+ assert_eq!(+ args.share_permission.link_share_access_level,+ Some(AccessLevel::View)+ );+ }+ Ok(test_document_metadata())+ });let mut mock_s3 = S3::default();mock_s3@@ -352,6 +367,27 @@ async fn seed_creates_all_documents() {assert!(result.is_ok());}+#[tokio::test]+async fn seed_rejects_legacy_public_field() {+ let json = serde_json::json!([{+ "document_id": Uuid::new_v4(),+ "document_name": "Legacy Document",+ "file_name": "pdf.pdf",+ "is_public": true+ }])+ .to_string();+ let file = write_temp_json(&json);++ let args = SeedArgs {+ user_id: "macro|[email protected]".to_string(),+ file_path: None,+ };+ let result = seed_from_file(args, mock_ctx(Db::default(), S3::default()), file.path()).await;++ let error = result.unwrap_err().to_string();+ assert!(error.contains("failed to parse json"), "{error}");+}+#[tokio::test]async fn seed_empty_json_fails() {let json = "[]";@@ -376,9 +412,9 @@ async fn seed_continues_on_db_failure() {let doc2 = Uuid::new_v4();let doc3 = Uuid::new_v4();let json = serde_json::json!([- { "document_id": doc1, "document_name": "Good Doc 1", "file_name": "pdf.pdf", "is_public": false },- { "document_id": doc2, "document_name": "Bad Doc", "file_name": "md.md", "is_public": false },- { "document_id": doc3, "document_name": "Good Doc 2", "file_name": "canvas.canvas", "is_public": false }+ { "document_id": doc1, "document_name": "Good Doc 1", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": doc2, "document_name": "Bad Doc", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": doc3, "document_name": "Good Doc 2", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null }]).to_string();let file = write_temp_json(&json);@@ -417,8 +453,8 @@ async fn seed_continues_on_s3_failure() {let doc1 = Uuid::new_v4();let doc2 = Uuid::new_v4();let json = serde_json::json!([- { "document_id": doc1, "document_name": "Good Doc", "file_name": "pdf.pdf", "is_public": false },- { "document_id": doc2, "document_name": "S3 Fail Doc", "file_name": "md.md", "is_public": false }+ { "document_id": doc1, "document_name": "Good Doc", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": doc2, "document_name": "S3 Fail Doc", "file_name": "md.md", "link_share": null, "link_share_access_level": null }]).to_string();let file = write_temp_json(&json);@@ -458,9 +494,9 @@ async fn seed_handles_all_file_types() {let doc2 = Uuid::new_v4();let doc3 = Uuid::new_v4();let json = serde_json::json!([- { "document_id": doc1, "document_name": "PDF Doc", "file_name": "pdf.pdf", "is_public": false },- { "document_id": doc2, "document_name": "Markdown Doc", "file_name": "md.md", "is_public": false },- { "document_id": doc3, "document_name": "Canvas Doc", "file_name": "canvas.canvas", "is_public": false }+ { "document_id": doc1, "document_name": "PDF Doc", "file_name": "pdf.pdf", "link_share": null, "link_share_access_level": null },+ { "document_id": doc2, "document_name": "Markdown Doc", "file_name": "md.md", "link_share": null, "link_share_access_level": null },+ { "document_id": doc3, "document_name": "Canvas Doc", "file_name": "canvas.canvas", "link_share": null, "link_share_access_level": null }]).to_string();let file = write_temp_json(&json);diff --git a/tooling/seed_cli/src/entity/scenario/apply.rs b/tooling/seed_cli/src/entity/scenario/apply.rsindex b8e71d3120..2bf6568472 100644--- a/tooling/seed_cli/src/entity/scenario/apply.rs+++ b/tooling/seed_cli/src/entity/scenario/apply.rs@@ -26,7 +26,7 @@ use models_email::email::service::label::{use models_email::email::service::link::{Link, UserProvider};use models_email::email::service::message::Message;use models_email::email::service::thread::Thread;-use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::{LinkShare, SharePermissionV2};use models_properties::service::property_value::PropertyValue;use uuid::Uuid;@@ -465,11 +465,13 @@ async fn seed_projects(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Res}apply_access_rows(ctx, &project_id, EntityType::Project, &rows).await?;- if let Some(level) = project.public {+ if let (Some(link_share), Some(access_level)) =+ (project.link_share, project.link_share_access_level)+ {ctx.db- .create_project_public_permission(+ .create_project_link_share_permission(&project_id,- &share_permission(spec, &project.owner, level),+ &share_permission(spec, &project.owner, link_share, access_level),).await?;}@@ -487,22 +489,29 @@ async fn seed_projects(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::ResOk(())}-fn share_permission(spec: &ScenarioSpec, owner_key: &str, level: ShareLevel) -> SharePermissionV2 {+fn permission_access_level(+ level: ShareLevel,+) -> models_permissions::share_permission::access_level::AccessLevel {+ match level {+ ShareLevel::View => models_permissions::share_permission::access_level::AccessLevel::View,+ ShareLevel::Comment => {+ models_permissions::share_permission::access_level::AccessLevel::Comment+ }+ ShareLevel::Edit => models_permissions::share_permission::access_level::AccessLevel::Edit,+ }+}++fn share_permission(+ spec: &ScenarioSpec,+ owner_key: &str,+ link_share: LinkShare,+ access_level: ShareLevel,+) -> SharePermissionV2 {SharePermissionV2 {id: String::new(),+ link_share: Some(link_share),+ link_share_access_level: Some(permission_access_level(access_level)),owner: spec.user_id(owner_key),- is_public: true,- public_access_level: Some(match level {- ShareLevel::View => {- models_permissions::share_permission::access_level::AccessLevel::View- }- ShareLevel::Comment => {- models_permissions::share_permission::access_level::AccessLevel::Comment- }- ShareLevel::Edit => {- models_permissions::share_permission::access_level::AccessLevel::Edit- }- }),channel_share_permissions: None,}}@@ -583,7 +592,6 @@ async fn seed_documents((None, None) => None,};- let is_public = document.public.is_some();let project_id = document.project.as_deref().map(|p| spec.project_id(p));let project_name = document.project.as_deref().map(|p| {spec.projects[p]@@ -603,19 +611,11 @@ async fn seed_documents(project_name: project_name.as_deref(),share_permission: &SharePermissionV2 {id: String::new(),+ link_share: document.link_share,+ link_share_access_level: document+ .link_share_access_level+ .map(permission_access_level),owner: owner_id.clone(),- is_public,- public_access_level: document.public.map(|level| match level {- ShareLevel::View => {- models_permissions::share_permission::access_level::AccessLevel::View- }- ShareLevel::Comment => {- models_permissions::share_permission::access_level::AccessLevel::Comment- }- ShareLevel::Edit => {- models_permissions::share_permission::access_level::AccessLevel::Edit- }- }),channel_share_permissions: None,},skip_history: true,@@ -713,9 +713,9 @@ async fn seed_tasks(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Resultproject_name: project_name.as_deref(),share_permission: &SharePermissionV2 {id: String::new(),+ link_share: None,+ link_share_access_level: None,owner: owner_id.clone(),- is_public: false,- public_access_level: None,channel_share_permissions: None,},skip_history: true,@@ -819,11 +819,13 @@ async fn seed_chats(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Resultrows.extend(chat.share.iter().map(|s| share_to_row(spec, s)));apply_access_rows(ctx, &chat_id, EntityType::Chat, &rows).await?;- if let Some(level) = chat.public {+ if let (Some(link_share), Some(access_level)) =+ (chat.link_share, chat.link_share_access_level)+ {ctx.db- .create_chat_public_permission(+ .create_chat_link_share_permission(&chat_id,- &share_permission(spec, &chat.owner, level),+ &share_permission(spec, &chat.owner, link_share, access_level),).await?;}diff --git a/tooling/seed_cli/src/entity/scenario/matrix.rs b/tooling/seed_cli/src/entity/scenario/matrix.rsindex 2ca790231b..9a66b23a78 100644--- a/tooling/seed_cli/src/entity/scenario/matrix.rs+++ b/tooling/seed_cli/src/entity/scenario/matrix.rs@@ -16,7 +16,7 @@ use entity_access::domain::service::EntityAccessServiceImpl;use entity_access::outbound::PgAccessRepository;use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;-use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::{LinkShare, access_level::AccessLevel};use super::apply;use super::spec::{ScenarioSpec, ShareLevel};@@ -62,7 +62,9 @@ fn user_sources(spec: &ScenarioSpec, user_key: &str) -> Vec<String> {fn levels_from_rows(spec: &ScenarioSpec,rows: &[apply::AccessRow],- public: Option<ShareLevel>,+ owner_key: &str,+ link_share: Option<LinkShare>,+ link_share_access_level: Option<ShareLevel>,) -> BTreeMap<String, AccessLevel> {let mut levels: BTreeMap<String, AccessLevel> = BTreeMap::new();for user_key in spec.users.keys() {@@ -72,8 +74,16 @@ fn levels_from_rows(apply::max_level(&mut levels, user_key, row.access_level);}}- if let Some(level) = public {- apply::max_level(&mut levels, user_key, share_level_to_access(level));++ let link_share_applies = match link_share {+ Some(LinkShare::Public) => true,+ Some(LinkShare::Team) => spec+ .team_of(owner_key)+ .is_some_and(|owner_team| spec.team_of(user_key) == Some(owner_team)),+ None => false,+ };+ if link_share_applies && let Some(access_level) = link_share_access_level {+ apply::max_level(&mut levels, user_key, share_level_to_access(access_level));}}levels@@ -133,7 +143,13 @@ pub fn expected_matrix(spec: &ScenarioSpec) -> Vec<ExpectedRow> {label: format!("project:{project_key}"),entity_id: spec.project_id(project_key),entity_type: EntityType::Project,- levels: levels_from_rows(spec, &access_rows, project.public),+ levels: levels_from_rows(+ spec,+ &access_rows,+ &project.owner,+ project.link_share,+ project.link_share_access_level,+ ),});}@@ -148,7 +164,13 @@ pub fn expected_matrix(spec: &ScenarioSpec) -> Vec<ExpectedRow> {label: format!("document:{document_key}"),entity_id: spec.document_id(document_key),entity_type: EntityType::Document,- levels: levels_from_rows(spec, &access_rows, document.public),+ levels: levels_from_rows(+ spec,+ &access_rows,+ &document.owner,+ document.link_share,+ document.link_share_access_level,+ ),});}@@ -172,7 +194,7 @@ pub fn expected_matrix(spec: &ScenarioSpec) -> Vec<ExpectedRow> {label: format!("task:{task_key}"),entity_id: spec.task_id(task_key),entity_type: EntityType::Document,- levels: levels_from_rows(spec, &access_rows, None),+ levels: levels_from_rows(spec, &access_rows, &task.owner, None, None),});}@@ -184,7 +206,13 @@ pub fn expected_matrix(spec: &ScenarioSpec) -> Vec<ExpectedRow> {label: format!("chat:{chat_key}"),entity_id: spec.chat_id(chat_key),entity_type: EntityType::Chat,- levels: levels_from_rows(spec, &access_rows, chat.public),+ levels: levels_from_rows(+ spec,+ &access_rows,+ &chat.owner,+ chat.link_share,+ chat.link_share_access_level,+ ),});}@@ -213,7 +241,7 @@ pub fn expected_matrix(spec: &ScenarioSpec) -> Vec<ExpectedRow> {label: format!("call:{call_key}"),entity_id: spec.call_id(call_key).to_string(),entity_type: EntityType::Call,- levels: levels_from_rows(spec, &access_rows, None),+ levels: levels_from_rows(spec, &access_rows, &call.created_by, None, None),});}@@ -229,7 +257,7 @@ pub fn expected_matrix(spec: &ScenarioSpec) -> Vec<ExpectedRow> {.iter().map(|s| apply::share_to_row(spec, s)).collect();- for (user, level) in levels_from_rows(spec, &share_rows, None) {+ for (user, level) in levels_from_rows(spec, &share_rows, &account.owner, None, None) {apply::max_level(&mut levels, &user, level);}rows.push(ExpectedRow {diff --git a/tooling/seed_cli/src/entity/scenario/matrix/test.rs b/tooling/seed_cli/src/entity/scenario/matrix/test.rsindex 7a57679f6c..a0275d248a 100644--- a/tooling/seed_cli/src/entity/scenario/matrix/test.rs+++ b/tooling/seed_cli/src/entity/scenario/matrix/test.rs@@ -67,8 +67,8 @@ fn expected_matrix_covers_owner_team_channel_public_edges() {assert_eq!(level(&rows, "document:design-doc", "carol"), None);assert_eq!(level(&rows, "document:design-doc", "eve"), None);- // Public document is visible to everyone.- for user in ["alice", "bob", "carol", "dave", "eve"] {+ // PUBLIC link sharing makes the document visible to everyone.+ for user in ["alice", "bob", "carol", "dave", "erin", "eve"] {assert!(level(&rows, "document:handbook", user).is_some(), "{user}");}assert_eq!(@@ -76,12 +76,19 @@ fn expected_matrix_covers_owner_team_channel_public_edges() {Some(AccessLevel::View));- // Unshared document stays private.+ // TEAM link sharing applies to the owner's team and not to outsiders.assert_eq!(level(&rows, "document:bob-notes", "bob"),Some(AccessLevel::Owner));- for user in ["alice", "carol", "dave", "eve"] {+ for user in ["alice", "carol", "erin"] {+ assert_eq!(+ level(&rows, "document:bob-notes", user),+ Some(AccessLevel::View),+ "{user}"+ );+ }+ for user in ["dave", "eve"] {assert_eq!(level(&rows, "document:bob-notes", user), None, "{user}");}@@ -191,6 +198,35 @@ fn mentions_grant_channel_view_to_projects_and_calls() {assert_eq!(level(&rows, "project:plans", "peer"), None);}+#[test]+fn team_link_share_fails_closed_when_owner_has_no_team() {+ let spec = ScenarioSpec::parse(+ &serde_json::json!({+ "scenario": "team-link-without-owner-team",+ "users": {+ "owner": { "email": "[email protected]" },+ "other": { "email": "[email protected]" }+ },+ "documents": {+ "doc": {+ "owner": "owner",+ "link_share": "TEAM",+ "link_share_access_level": "comment"+ }+ }+ })+ .to_string(),+ )+ .unwrap();+ let rows = expected_matrix(&spec);++ assert_eq!(+ level(&rows, "document:doc", "owner"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(level(&rows, "document:doc", "other"), None);+}+#[test]fn expected_matrix_row_count_matches_entities() {let spec = example();diff --git a/tooling/seed_cli/src/entity/scenario/spec.rs b/tooling/seed_cli/src/entity/scenario/spec.rsindex c2bce7a47f..770eaf625a 100644--- a/tooling/seed_cli/src/entity/scenario/spec.rs+++ b/tooling/seed_cli/src/entity/scenario/spec.rs@@ -12,6 +12,7 @@ mod test;use std::collections::{BTreeMap, BTreeSet};use std::fmt;+use models_permissions::share_permission::LinkShare;use serde::Deserialize;use sha2::{Digest, Sha256};use uuid::Uuid;@@ -19,7 +20,7 @@ use uuid::Uuid;/// Marker prefix (hex) carried by every seeded uuid.pub const SEED_MARKER: &str = "5eed";-/// Access level names accepted in scenario share/public declarations.+/// Access level names accepted in scenario share and link declarations.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]#[serde(rename_all = "snake_case")]pub enum ShareLevel {@@ -41,6 +42,23 @@ impl fmt::Display for ShareLevel {}}+fn check_link_share(+ errors: &mut Vec<String>,+ context: &str,+ link_share: Option<LinkShare>,+ link_share_access_level: Option<ShareLevel>,+) {+ match (link_share, link_share_access_level) {+ (Some(_), None) => errors.push(format!(+ "{context} sets link_share but not link_share_access_level"+ )),+ (None, Some(_)) => errors.push(format!(+ "{context} sets link_share_access_level but not link_share"+ )),+ _ => {}+ }+}+/// Team role names accepted in scenario team member declarations.#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]#[serde(rename_all = "snake_case")]@@ -196,9 +214,12 @@ pub struct ProjectSpec {/// Access grants on the project (inherited by contained entities).#[serde(default)]pub share: Vec<ShareSpec>,- /// Public link access level, if the project is public.+ /// Who can access the project through its share link.#[serde(default)]- pub public: Option<ShareLevel>,+ pub link_share: Option<LinkShare>,+ /// Access level granted through the share link.+ #[serde(default)]+ pub link_share_access_level: Option<ShareLevel>,}/// A document in the scenario.@@ -226,9 +247,12 @@ pub struct DocumentSpec {/// Access grants on the document.#[serde(default)]pub share: Vec<ShareSpec>,- /// Public link access level, if the document is public.+ /// Who can access the document through its share link.+ #[serde(default)]+ pub link_share: Option<LinkShare>,+ /// Access level granted through the share link.#[serde(default)]- pub public: Option<ShareLevel>,+ pub link_share_access_level: Option<ShareLevel>,}/// A task in the scenario: a markdown document with the task subtype plus@@ -275,9 +299,12 @@ pub struct ChatSpec {/// Access grants on the chat.#[serde(default)]pub share: Vec<ShareSpec>,- /// Public link access level, if the chat is public.+ /// Who can access the chat through its share link.+ #[serde(default)]+ pub link_share: Option<LinkShare>,+ /// Access level granted through the share link.#[serde(default)]- pub public: Option<ShareLevel>,+ pub link_share_access_level: Option<ShareLevel>,}/// A transcript segment of a seeded call.@@ -766,7 +793,14 @@ impl ScenarioSpec {"project `{key}` references unknown parent `{parent}`"));}- check_shares(&mut errors, &format!("project `{key}`"), &project.share);+ let context = format!("project `{key}`");+ check_shares(&mut errors, &context, &project.share);+ check_link_share(+ &mut errors,+ &context,+ project.link_share,+ project.link_share_access_level,+ );}for key in self.projects.keys() {@@ -797,7 +831,14 @@ impl ScenarioSpec {"document `{key}` sets both `file` and `content`; pick one"));}- check_shares(&mut errors, &format!("document `{key}`"), &document.share);+ let context = format!("document `{key}`");+ check_shares(&mut errors, &context, &document.share);+ check_link_share(+ &mut errors,+ &context,+ document.link_share,+ document.link_share_access_level,+ );}for (key, task) in &self.tasks {@@ -833,7 +874,14 @@ impl ScenarioSpec {for (key, chat) in &self.chats {user_exists(&mut errors, &format!("chat `{key}` owner"), &chat.owner);- check_shares(&mut errors, &format!("chat `{key}`"), &chat.share);+ let context = format!("chat `{key}`");+ check_shares(&mut errors, &context, &chat.share);+ check_link_share(+ &mut errors,+ &context,+ chat.link_share,+ chat.link_share_access_level,+ );}for (key, call) in &self.calls {diff --git a/tooling/seed_cli/src/entity/scenario/spec/test.rs b/tooling/seed_cli/src/entity/scenario/spec/test.rsindex 4fc6c156de..49832be273 100644--- a/tooling/seed_cli/src/entity/scenario/spec/test.rs+++ b/tooling/seed_cli/src/entity/scenario/spec/test.rs@@ -54,6 +54,14 @@ fn example_scenario_parses() {assert_eq!(spec.scenario, "team-perms");assert_eq!(spec.users.len(), 6);assert_eq!(spec.user_id("alice"), "macro|[email protected]");++ let handbook = &spec.documents["handbook"];+ assert_eq!(handbook.link_share, Some(LinkShare::Public));+ assert_eq!(handbook.link_share_access_level, Some(ShareLevel::View));++ let bob_notes = &spec.documents["bob-notes"];+ assert_eq!(bob_notes.link_share, Some(LinkShare::Team));+ assert_eq!(bob_notes.link_share_access_level, Some(ShareLevel::View));}#[test]@@ -203,6 +211,47 @@ fn rejects_unknown_fields() {assert!(result.unwrap_err().to_string().contains("unknown field"));}+#[test]+fn rejects_incomplete_link_share_policies() {+ let missing_access_level = minimal(serde_json::json!({+ "scenario": "bad",+ "users": { "alice": { "email": "[email protected]" } },+ "documents": {+ "doc": { "owner": "alice", "link_share": "TEAM" }+ }+ }));+ let error = missing_access_level.unwrap_err().to_string();+ assert!(+ error.contains("sets link_share but not link_share_access_level"),+ "{error}"+ );++ let missing_scope = minimal(serde_json::json!({+ "scenario": "bad",+ "users": { "alice": { "email": "[email protected]" } },+ "chats": {+ "chat": { "owner": "alice", "link_share_access_level": "view" }+ }+ }));+ let error = missing_scope.unwrap_err().to_string();+ assert!(+ error.contains("sets link_share_access_level but not link_share"),+ "{error}"+ );+}++#[test]+fn rejects_legacy_public_link_field() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": { "alice": { "email": "[email protected]" } },+ "projects": {+ "project": { "owner": "alice", "public": "view" }+ }+ }));+ assert!(result.unwrap_err().to_string().contains("unknown field"));+}+#[test]fn entity_ref_parsing() {assert_eq!(diff --git a/tooling/seed_cli/src/service/db/mod.rs b/tooling/seed_cli/src/service/db/mod.rsindex 5a7667d3dc..ffa4574c26 100644--- a/tooling/seed_cli/src/service/db/mod.rs+++ b/tooling/seed_cli/src/service/db/mod.rs@@ -420,9 +420,9 @@ impl SeedDb {Ok(())}- /// Create a public share permission attached to a project.+ /// Create a link share permission attached to a project.#[tracing::instrument(skip(self, share_permission), err)]- pub async fn create_project_public_permission(+ pub async fn create_project_link_share_permission(&self,project_id: &str,share_permission: &SharePermissionV2,@@ -438,9 +438,9 @@ impl SeedDb {Ok(())}- /// Create a public share permission attached to a chat.+ /// Create a link share permission attached to a chat.#[tracing::instrument(skip(self, share_permission), err)]- pub async fn create_chat_public_permission(+ pub async fn create_chat_link_share_permission(&self,chat_id: &str,share_permission: &SharePermissionV2,@@ -464,8 +464,10 @@ impl SeedDb {let mut transaction = self.inner.begin().await?;sqlx::query!(- r#"INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel", "createdAt", "updatedAt")- VALUES ($1, false, NULL, NOW(), NOW())"#,+ r#"INSERT INTO "SharePermission" (+ id, "linkShare", "linkShareAccessLevel", "createdAt", "updatedAt"+ )+ VALUES ($1, NULL, NULL, NOW(), NOW())"#,args.share_permission_id,).execute(transaction.as_mut())