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
Seanaye/fix/properties architecture (#4572)
Sean Ayedd660e048122
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 8fd1a9779a..847d3136cf 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -98,7 +98,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -246,7 +245,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -692,7 +690,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -1336,7 +1333,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -1458,7 +1454,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","properties_service","rate_limit","readonly_pool",@@ -2427,7 +2422,6 @@"notification","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -2983,7 +2977,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -3085,7 +3078,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -3663,14 +3655,11 @@"cowlike","decode_jwt","document_sub_type",- "email_db_client",- "email_utils","entity_access","entity_access_db_utils","invite_email","last_online_tracker","macro_auth",- "macro_db_client","macro_env","macro_env_var","macro_service_urls",@@ -3684,30 +3673,17 @@"model_notifications","model_user","models_bulk_upload",- "models_dcs",- "models_email","models_entity_access_management",- "models_opensearch","models_pagination","models_permissions","models_properties",- "models_team","non_empty","notification","prompt","properties",- "properties_db_client","rate_limit","remote_env_var","system_properties",- "user_quota",- "workspace-hack"- ],- "properties_db_client": [- "document_sub_type",- "macro_uuid",- "models_properties",- "properties_db_client","workspace-hack"],"properties_service": [@@ -3720,8 +3696,6 @@"cowlike","decode_jwt","document_sub_type",- "email_db_client",- "email_utils","entity_access","entity_access_db_utils","invite_email",@@ -3744,7 +3718,6 @@"model_user","models_bulk_upload","models_dcs",- "models_email","models_entity_access_management","models_opensearch","models_pagination",@@ -3755,7 +3728,6 @@"notification","prompt","properties",- "properties_db_client","properties_service","rate_limit","remote_env_var",@@ -3905,7 +3877,6 @@"opensearch_query_builder","prompt","properties",- "properties_db_client","rate_limit","readonly_pool","remote_env_var",@@ -4001,7 +3972,7 @@"opensearch_client","opensearch_query_builder","prompt",- "properties_db_client",+ "properties","rate_limit","remote_env_var","s3_client",@@ -4084,7 +4055,7 @@"opensearch_client","opensearch_query_builder","prompt",- "properties_db_client",+ "properties","rate_limit","readonly_pool","remote_env_var",@@ -4401,7 +4372,7 @@"non_empty","notification","prompt",- "properties_db_client",+ "properties","rate_limit","readonly_pool","remote_env_var",diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.json b/rust/cloud-storage/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.jsonsimilarity index 100%rename from rust/cloud-storage/properties_db_client/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.jsonrename to rust/cloud-storage/.sqlx/query-089ddab77c715460d9e8573812b50ba5b5eb4ba617f613b80c1ac772db727669.jsondiff --git a/rust/cloud-storage/.sqlx/query-345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1.json b/rust/cloud-storage/.sqlx/query-345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1.jsondeleted file mode 100644index e4348b6a7f..0000000000--- a/rust/cloud-storage/.sqlx/query-345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1.json+++ /dev/null@@ -1,45 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n c.id as entity_id,\n c.name,\n regexp_replace(\n c.name,\n $6,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n c.\"updatedAt\" as updated_at\n FROM \"Chat\" c\n WHERE c.id = ANY($1)\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $2\n AND (\n $4::timestamptz IS NULL\n OR (c.\"updatedAt\", c.id) < ($4, $5)\n )\n ORDER BY c.\"updatedAt\" DESC, c.id DESC\n LIMIT $3\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "name_highlighted",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "updated_at",- "type_info": "Timestamp"- }- ],- "parameters": {- "Left": [- "TextArray",- "Text",- "Int8",- "Timestamptz",- "Text",- "Text"- ]- },- "nullable": [- false,- false,- null,- false- ]- },- "hash": "345333b49aa634cf527c0d5c10f6064359b93f5cadb52da18c5e12a50cf50ae1"-}diff --git a/rust/cloud-storage/.sqlx/query-38e82b085da3f67d3c6e5481e65e28f652a9a43504b3267876ec89d7f8d11180.json b/rust/cloud-storage/.sqlx/query-38e82b085da3f67d3c6e5481e65e28f652a9a43504b3267876ec89d7f8d11180.jsonnew file mode 100644index 0000000000..15846fcef7--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-38e82b085da3f67d3c6e5481e65e28f652a9a43504b3267876ec89d7f8d11180.json@@ -0,0 +1,64 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n FROM property_options \n WHERE property_definition_id = $1\n ORDER BY display_order, number_value, LOWER(string_value)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "display_order",+ "type_info": "Int4"+ },+ {+ "ordinal": 3,+ "name": "number_value",+ "type_info": "Float8"+ },+ {+ "ordinal": 4,+ "name": "string_value",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "color",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "38e82b085da3f67d3c6e5481e65e28f652a9a43504b3267876ec89d7f8d11180"+}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.json b/rust/cloud-storage/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.jsonsimilarity index 100%rename from rust/cloud-storage/properties_db_client/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.jsonrename to rust/cloud-storage/.sqlx/query-4cc83ea0dfe3d47bf30c18701f37f77a52760d279c5dbdeae68b88d329d8c124.jsondiff --git a/rust/cloud-storage/.sqlx/query-5af15793bf51546b08b4adcd66f18b1a53bb6212bc9e6f644d319fd0bf45a312.json b/rust/cloud-storage/.sqlx/query-5af15793bf51546b08b4adcd66f18b1a53bb6212bc9e6f644d319fd0bf45a312.jsonnew file mode 100644index 0000000000..d815f2e1c1--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-5af15793bf51546b08b4adcd66f18b1a53bb6212bc9e6f644d319fd0bf45a312.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT mui.profile_picture as \"profile_picture!\"\n FROM \"User\" u\n JOIN macro_user mu ON mu.id = u.macro_user_id\n JOIN macro_user_info mui ON mui.macro_user_id = mu.id\n WHERE u.id = $1 AND mui.profile_picture IS NOT NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "profile_picture!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "5af15793bf51546b08b4adcd66f18b1a53bb6212bc9e6f644d319fd0bf45a312"+}diff --git a/rust/cloud-storage/.sqlx/query-68b0c6a59cfac3aea87db77ec39f7fa9909e8f2cba6579969e99dfa8f8730e0c.json b/rust/cloud-storage/.sqlx/query-68b0c6a59cfac3aea87db77ec39f7fa9909e8f2cba6579969e99dfa8f8730e0c.jsonnew file mode 100644index 0000000000..05383cf0a6--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-68b0c6a59cfac3aea87db77ec39f7fa9909e8f2cba6579969e99dfa8f8730e0c.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT d.name\n FROM \"Document\" d\n WHERE d.\"id\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "name",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "68b0c6a59cfac3aea87db77ec39f7fa9909e8f2cba6579969e99dfa8f8730e0c"+}diff --git a/rust/cloud-storage/.sqlx/query-85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9.json b/rust/cloud-storage/.sqlx/query-85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9.jsondeleted file mode 100644index ee245078e2..0000000000--- a/rust/cloud-storage/.sqlx/query-85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9.json+++ /dev/null@@ -1,45 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n p.id as entity_id,\n p.name,\n regexp_replace(\n p.name,\n $6,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n p.\"updatedAt\" as updated_at\n FROM \"Project\" p\n WHERE p.id = ANY($1)\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $2\n AND (\n $4::timestamptz IS NULL\n OR (p.\"updatedAt\", p.id) < ($4, $5)\n )\n ORDER BY p.\"updatedAt\" DESC, p.id DESC\n LIMIT $3\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "name_highlighted",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "updated_at",- "type_info": "Timestamp"- }- ],- "parameters": {- "Left": [- "TextArray",- "Text",- "Int8",- "Timestamptz",- "Text",- "Text"- ]- },- "nullable": [- false,- false,- null,- false- ]- },- "hash": "85423841a8e715417d2e6c4c210b096a1aedea8c4bb63029e0024bce1e5029f9"-}diff --git a/rust/cloud-storage/.sqlx/query-9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64.json b/rust/cloud-storage/.sqlx/query-9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64.jsondeleted file mode 100644index b26f50c7f4..0000000000--- a/rust/cloud-storage/.sqlx/query-9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64.json+++ /dev/null@@ -1,46 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n c.id as entity_id,\n c.name,\n regexp_replace(\n c.name,\n $7,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n c.\"updatedAt\" as updated_at\n FROM \"Chat\" c\n WHERE (c.\"userId\" = $1 OR c.id = ANY($2))\n AND c.\"deletedAt\" IS NULL\n AND c.name ILIKE $3\n AND (\n $5::timestamptz IS NULL\n OR (c.\"updatedAt\", c.id) < ($5, $6)\n )\n ORDER BY c.\"updatedAt\" DESC, c.id DESC\n LIMIT $4\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "name_highlighted",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "updated_at",- "type_info": "Timestamp"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Text",- "Int8",- "Timestamptz",- "Text",- "Text"- ]- },- "nullable": [- false,- false,- null,- false- ]- },- "hash": "9460f97a5fe2c0ddb08e81f8ded812694d0f7408053c49c3e58ecca561d67c64"-}diff --git a/rust/cloud-storage/.sqlx/query-99da86046e545f64c14cf9bbe7e26bc401f17b3f4805434f587c02fe6fe50684.json b/rust/cloud-storage/.sqlx/query-99da86046e545f64c14cf9bbe7e26bc401f17b3f4805434f587c02fe6fe50684.jsonnew file mode 100644index 0000000000..9b20656173--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-99da86046e545f64c14cf9bbe7e26bc401f17b3f4805434f587c02fe6fe50684.json@@ -0,0 +1,64 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n FROM property_options \n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "display_order",+ "type_info": "Int4"+ },+ {+ "ordinal": 3,+ "name": "number_value",+ "type_info": "Float8"+ },+ {+ "ordinal": 4,+ "name": "string_value",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "color",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "99da86046e545f64c14cf9bbe7e26bc401f17b3f4805434f587c02fe6fe50684"+}diff --git a/rust/cloud-storage/.sqlx/query-a7a5b7e27a6ccd2190829af1f1e2fac36719f0f30b3a08cd818736dfd39e920e.json b/rust/cloud-storage/.sqlx/query-a7a5b7e27a6ccd2190829af1f1e2fac36719f0f30b3a08cd818736dfd39e920e.jsonnew file mode 100644index 0000000000..4a826b83e2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-a7a5b7e27a6ccd2190829af1f1e2fac36719f0f30b3a08cd818736dfd39e920e.json@@ -0,0 +1,64 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n FROM property_options \n WHERE property_definition_id = ANY($1)\n ORDER BY property_definition_id, display_order, number_value, LOWER(string_value)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "display_order",+ "type_info": "Int4"+ },+ {+ "ordinal": 3,+ "name": "number_value",+ "type_info": "Float8"+ },+ {+ "ordinal": 4,+ "name": "string_value",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "color",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "a7a5b7e27a6ccd2190829af1f1e2fac36719f0f30b3a08cd818736dfd39e920e"+}diff --git a/rust/cloud-storage/.sqlx/query-cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4.json b/rust/cloud-storage/.sqlx/query-cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4.jsondeleted file mode 100644index 75361e6ea2..0000000000--- a/rust/cloud-storage/.sqlx/query-cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4.json+++ /dev/null@@ -1,46 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n p.id as entity_id,\n p.name,\n regexp_replace(\n p.name,\n $7,\n '<macro_em>\\1</macro_em>',\n 'gi'\n ) as name_highlighted,\n p.\"updatedAt\" as updated_at\n FROM \"Project\" p\n WHERE (p.\"userId\" = $1 OR p.id = ANY($2))\n AND p.\"deletedAt\" IS NULL\n AND p.name ILIKE $3\n AND (\n $5::timestamptz IS NULL\n OR (p.\"updatedAt\", p.id) < ($5, $6)\n )\n ORDER BY p.\"updatedAt\" DESC, p.id DESC\n LIMIT $4\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "name_highlighted",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "updated_at",- "type_info": "Timestamp"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Text",- "Int8",- "Timestamptz",- "Text",- "Text"- ]- },- "nullable": [- false,- false,- null,- false- ]- },- "hash": "cebafd0d72b44d2f63bce484750fcab2a26f543e5a6ca992e38bdb662dc7c2f4"-}diff --git a/rust/cloud-storage/.sqlx/query-e1e3777c89af12e62da29c639a0806c4406f6450c7694133a3cd974275564566.json b/rust/cloud-storage/.sqlx/query-e1e3777c89af12e62da29c639a0806c4406f6450c7694133a3cd974275564566.jsonnew file mode 100644index 0000000000..5466cef82b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-e1e3777c89af12e62da29c639a0806c4406f6450c7694133a3cd974275564566.json@@ -0,0 +1,68 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE property_options\n SET number_value = $2,\n string_value = $3,\n color = $4,\n display_order = $5,\n updated_at = NOW()\n WHERE id = $1\n RETURNING\n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color,\n created_at,\n updated_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "display_order",+ "type_info": "Int4"+ },+ {+ "ordinal": 3,+ "name": "number_value",+ "type_info": "Float8"+ },+ {+ "ordinal": 4,+ "name": "string_value",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "color",+ "type_info": "Text"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Float8",+ "Text",+ "Text",+ "Int4"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ true,+ true,+ false,+ false+ ]+ },+ "hash": "e1e3777c89af12e62da29c639a0806c4406f6450c7694133a3cd974275564566"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 4527ffc26b..f143cdef4c 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4065,7 +4065,6 @@ dependencies = ["non_empty","notification","prompt",- "properties","readonly_pool","redis","regex",@@ -4189,7 +4188,6 @@ dependencies = ["opensearch_client","ordered-float","properties",- "properties_db_client","properties_service","rate_limit","rayon",@@ -8222,7 +8220,6 @@ dependencies = ["mcp_auth_proxy","notification","prompt",- "properties","readonly_pool","redis","rmcp",@@ -8297,7 +8294,6 @@ dependencies = ["macro_uuid","model_user","notification",- "properties","readonly_pool","search_service_client","serde",@@ -10495,22 +10491,22 @@ dependencies = ["ai_toolset","anyhow","async-trait",+ "axum","chrono",- "email_db_client","entity_access","entity_access_db_utils","futures",- "macro_db_client","macro_db_migrator","macro_user_id","macro_uuid","mockall",+ "model","model-entity","model_notifications",+ "model_user","models_permissions","models_properties","notification",- "properties_db_client","schemars 1.2.1","serde","serde_json",@@ -10518,25 +10514,9 @@ dependencies = ["system_properties","thiserror 2.0.18","tokio",+ "tower 0.5.3","tracing",- "uuid",- "workspace-hack",-]--[[package]]-name = "properties_db_client"-version = "0.1.0"-dependencies = [- "anyhow",- "chrono",- "macro_db_migrator",- "macro_uuid",- "models_properties",- "serde",- "serde_json",- "sqlx",- "thiserror 2.0.18",- "tracing",+ "utoipa","uuid","workspace-hack",]@@ -10545,39 +10525,14 @@ dependencies = [name = "properties_service"version = "0.1.0"dependencies = [- "anyhow",- "async-trait",- "aws-sdk-sqs","axum",- "chrono",- "email_db_client","entity_access",- "http-body-util",- "last_online_tracker",- "macro_auth",- "macro_env","macro_middleware",- "macro_user_id",- "macro_uuid",- "model",- "model-entity",- "models_permissions","models_properties","notification","properties",- "properties_db_client",- "serde","serde_json",- "serde_with",- "sqlx",- "system_properties",- "thiserror 2.0.18",- "tokio",- "tower 0.5.3",- "tower-http",- "tracing","utoipa",- "uuid","workspace-hack",]@@ -11908,7 +11863,7 @@ dependencies = ["nom 8.0.0","opensearch_client","pdfium-render",- "properties_db_client",+ "properties","rust-embed","s3_client","s3_key",@@ -11965,7 +11920,7 @@ dependencies = ["models_soup","name_search","opensearch_client",- "properties_db_client",+ "properties","readonly_pool","secretsmanager_client","serde",@@ -12747,7 +12702,7 @@ dependencies = ["models_soup","non_empty","ordered-float",- "properties_db_client",+ "properties","readonly_pool","recursion","rootcause",diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rsindex b1cdff3cfa..3624f86128 100644--- a/rust/cloud-storage/ai_tools/src/tool_context.rs+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs@@ -206,9 +206,11 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {) -> anyhow::Result<()> {use properties::PropertiesService as _;+ let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;+self.properties.set_entity_property(- user_id,+ &user_id,entity_id,models_properties::EntityType::Task,property_definition_id,@@ -504,15 +506,11 @@ pub struct NoOpNotificationService;impl properties::NotificationService for NoOpNotificationService {type Err = anyhow::Error;- async fn send_notification<'a>(+ async fn send_task_assigned<'a>(&self,- _message: notification::domain::models::SendNotificationRequest<- 'a,- model_notifications::TaskAssignedMetadata,- notification::domain::models::apple::PushNotificationData,- >,- ) -> Result<uuid::Uuid, Self::Err> {- Ok(uuid::Uuid::nil())+ _notification: properties::domain::model::TaskAssignedNotification<'a>,+ ) -> Result<(), Self::Err> {+ Ok(())}}diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 39fd700c32..73f39b118f 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -94,7 +94,6 @@ models_opensearch = { path = "../models_opensearch" }models_permissions = { path = "../models_permissions" }notification = { path = "../notification" }prompt = { path = "../prompt" }-properties = { path = "../properties", features = ["ai_tools"] }readonly_pool = { path = "../readonly_pool" }redis = { workspace = true, features = ["aio",diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 1fc217386e..91a9272f96 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -124,7 +124,6 @@ models_soup = { path = "../models_soup", features = ["schema"] }notification = { path = "../notification" }opensearch_client = { path = "../opensearch_client" }properties = { path = "../properties" }-properties_db_client = { path = "../properties_db_client" }properties_service = { path = "../properties_service" }rayon = "1.10.0"rate_limit = { path = "../rate_limit", default-features = false, features = ["axum"] }diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 5287f80389..a93d98c100 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -174,9 +174,11 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {) -> anyhow::Result<()> {use properties::PropertiesService as _;+ let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;+self.properties.set_entity_property(- user_id,+ &user_id,entity_id,models_properties::EntityType::Task,property_definition_id,@@ -381,11 +383,10 @@ env_var! {impl From<&ApiContext> for PropertiesHandlerState {fn from(ctx: &ApiContext) -> Self {- PropertiesHandlerState {- db: ctx.db.clone(),- properties_service: ctx.properties_service.clone(),- entity_access_service: ctx.entity_access_service.clone(),- }+ PropertiesHandlerState::new(+ ctx.properties_service.clone(),+ ctx.entity_access_service.clone(),+ )}}diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 504633c6ce..d72fe1989e 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -308,9 +308,12 @@ async fn main() -> anyhow::Result<()> {);let permission_checker = PermissionServiceImpl::new(db.clone(), entity_access_service.clone());- let notification_service = NotificationServiceImpl::new(SqsNotificationIngress {- queue: ingress_queue,- });+ let notification_service = NotificationServiceImpl::new(+ SqsNotificationIngress {+ queue: ingress_queue,+ },+ db.clone(),+ );let properties_service = Arc::new(PropertiesServiceImpl::new(PropertiesPgRepo::new(db.clone()),diff --git a/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/handle.rs b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/handle.rsindex f83cd75c83..406df57e6d 100644--- a/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/handle.rs+++ b/rust/cloud-storage/document_storage_service/src/service/delete_document_worker/handle.rs@@ -1,7 +1,7 @@use anyhow::Context;use documents_hex::domain::ports::editing::EditingWorkerService;use models_properties::{EntityReference, EntityType};-use properties_db_client::entity_properties::delete as entity_properties_delete;+use properties::outbound::entity_property_queries as entity_properties_delete;use super::DeleteDocumentWorkerContext;@@ -113,7 +113,7 @@ pub async fn handle(tracing::trace!(document_id=%document_id, "deleting document properties");let entity_reference = EntityReference::new(document_id, EntityType::Document);- let _ = entity_properties_delete::delete_entity(&ctx.db, &entity_reference)+ let _ = entity_properties_delete::delete_entity_properties(&ctx.db, &entity_reference).await.inspect_err(|e| tracing::error!(error=?e, "failed to delete entity properties"));tracing::trace!(document_id=%document_id, "deleted document properties");diff --git a/rust/cloud-storage/graphql_soup/Cargo.toml b/rust/cloud-storage/graphql_soup/Cargo.tomlindex d23275efcc..ff29cd947e 100644--- a/rust/cloud-storage/graphql_soup/Cargo.toml+++ b/rust/cloud-storage/graphql_soup/Cargo.toml@@ -21,7 +21,9 @@ models_pagination = { path = "../models_pagination" }models_properties = { path = "../models_properties" }models_soup = { path = "../models_soup" }notification = { path = "../notification" }-properties = { path = "../properties" }+properties = { path = "../properties", default-features = false, features = [+ "ports",+] }rootcause = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex df15c21433..529d81ff3e 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -70,7 +70,6 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./scheduled_action/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./notification_db_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./notification/.env- echo "DATABASE_URL={{ DATABASE_URL }}" >> ./properties_db_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./macro_db_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./email_db_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./email_refresh_handler/.envdiff --git a/rust/cloud-storage/mcp_service/Cargo.toml b/rust/cloud-storage/mcp_service/Cargo.tomlindex 723314857e..e8783c7073 100644--- a/rust/cloud-storage/mcp_service/Cargo.toml+++ b/rust/cloud-storage/mcp_service/Cargo.toml@@ -55,7 +55,6 @@ macro_middleware = { path = "../macro_middleware", default-features = false, feamacro_user_id = { path = "../macro_user_id" }notification = { path = "../notification", features = ["ai_tool"] }prompt = { path = "../prompt" }-properties = { path = "../properties", features = ["ai_tools"] }readonly_pool = { path = "../readonly_pool" }redis = { workspace = true, features = ["aio", "tokio-comp"] }roles_and_permissions = { path = "../roles_and_permissions" }diff --git a/rust/cloud-storage/memory/Cargo.toml b/rust/cloud-storage/memory/Cargo.tomlindex a6038a667f..56f0b25a5e 100644--- a/rust/cloud-storage/memory/Cargo.toml+++ b/rust/cloud-storage/memory/Cargo.toml@@ -42,7 +42,6 @@ frecency = { path = "../frecency" }lexical_client = { path = "../lexical_client" }macro_aws_config = { path = "../macro_aws_config" }notification = { path = "../notification", features = ["ai_tool"] }-properties = { path = "../properties" }readonly_pool = { path = "../readonly_pool" }search_service_client = { path = "../search_service_client" }soup = { path = "../soup", features = ["all"] }diff --git a/rust/cloud-storage/models_properties/src/db/mod.rs b/rust/cloud-storage/models_properties/src/db/mod.rsindex fb3b32e0a5..cc722d2c2b 100644--- a/rust/cloud-storage/models_properties/src/db/mod.rs+++ b/rust/cloud-storage/models_properties/src/db/mod.rs@@ -1,4 +1,4 @@-//! Database layer types - used only by properties_db_client.+//! Database layer types - used only by the properties crate's outbound adapters.//!//! These structs directly map to database tables and include all database fields.//! They should not be exposed outside of the db_client.diff --git a/rust/cloud-storage/models_properties/src/db/property_option.rs b/rust/cloud-storage/models_properties/src/db/property_option.rsindex 5e20c52c5b..4ea9b706c7 100644--- a/rust/cloud-storage/models_properties/src/db/property_option.rs+++ b/rust/cloud-storage/models_properties/src/db/property_option.rs@@ -22,23 +22,6 @@ pub struct PropertyOption {pub updated_at: DateTime<Utc>,}-impl<'r> sqlx::FromRow<'r, sqlx::postgres::PgRow> for PropertyOption {- fn from_row(row: &'r sqlx::postgres::PgRow) -> Result<Self, sqlx::Error> {- use sqlx::Row;-- Ok(PropertyOption {- id: row.try_get("id")?,- property_definition_id: row.try_get("property_definition_id")?,- display_order: row.try_get("display_order")?,- number_value: row.try_get("number_value")?,- string_value: row.try_get("string_value")?,- color: row.try_get("color")?,- created_at: row.try_get("created_at")?,- updated_at: row.try_get("updated_at")?,- })- }-}-// ===== Conversions =====impl std::convert::TryFrom<PropertyOption> for crate::service::property_option::PropertyOption {diff --git a/rust/cloud-storage/models_properties/src/lib.rs b/rust/cloud-storage/models_properties/src/lib.rsindex 87c52df62c..5dcd3500cf 100644--- a/rust/cloud-storage/models_properties/src/lib.rs+++ b/rust/cloud-storage/models_properties/src/lib.rs@@ -3,7 +3,7 @@//! This crate defines the data models for the properties system using a three-layer architecture://!//! - **shared**: Shared types (EntityType, DataType) used across all layers-//! - **db**: Database layer types (used only by properties_db_client)+//! - **db**: Database layer types (used only by the properties crate's outbound adapters)//! - **service**: Business logic layer types (used within properties_service)//! - **api**: API layer types (external-facing requests/responses)diff --git a/rust/cloud-storage/properties/Cargo.toml b/rust/cloud-storage/properties/Cargo.tomlindex 8d7bd4cd1a..fb396aec6f 100644--- a/rust/cloud-storage/properties/Cargo.toml+++ b/rust/cloud-storage/properties/Cargo.toml@@ -8,43 +8,77 @@ version = "0.1.0"ai_tools = ["dep:ai_toolset","dep:async-trait",- "dep:chrono","dep:schemars",+ "dep:serde",+ "dep:serde_json",+ "ports",]+default = ["ai_tools", "inbound", "outbound", "ports"]+inbound = [+ "dep:axum",+ "dep:entity_access",+ "dep:model",+ "dep:serde",+ "dep:serde_json",+ "dep:tokio",+ "dep:tower",+ "dep:utoipa",+ "entity_access/inbound",+ "ports",+]+outbound = [+ "dep:entity_access",+ "dep:entity_access_db_utils",+ "dep:futures",+ "dep:macro_uuid",+ "dep:model-entity",+ "dep:model_notifications",+ "dep:models_permissions",+ "dep:notification",+ "dep:serde_json",+ "dep:sqlx",+ "ports",+]+ports = [][dependencies]ai_toolset = { path = "../ai_toolset", optional = true }anyhow = { workspace = true }async-trait = { workspace = true, optional = true }-chrono = { workspace = true, optional = true }-entity_access = { path = "../entity_access" }-entity_access_db_utils = { path = "../entity_access_db_utils" }-futures = { workspace = true }-email_db_client = { path = "../email_db_client" }-macro_db_client = { path = "../macro_db_client" }-notification = { path = "../notification" }+axum = { workspace = true, optional = true }+chrono = { workspace = true }+entity_access = { path = "../entity_access", default-features = false, features = [+ "ports",+], optional = true }+entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }+futures = { workspace = true, optional = true }macro_user_id = { path = "../macro_user_id" }-macro_uuid = { path = "../macro_uuid" }-model_notifications = { path = "../model_notifications" }-model-entity = { path = "../model-entity" }-models_permissions = { path = "../models_permissions" }+macro_uuid = { path = "../macro_uuid", optional = true }+model = { path = "../model", optional = true }+model-entity = { path = "../model-entity", optional = true }+model_notifications = { path = "../model_notifications", optional = true }+model_user = { path = "../model_user", features = ["axum"] }+models_permissions = { path = "../models_permissions", optional = true }models_properties = { path = "../models_properties" }-properties_db_client = { path = "../properties_db_client" }+notification = { path = "../notification", optional = true }schemars = { workspace = true, optional = true }-serde = { workspace = true }-serde_json = { workspace = true }-sqlx = { workspace = true }+serde = { workspace = true, optional = true }+serde_json = { workspace = true, optional = true }+sqlx = { workspace = true, optional = true }system_properties = { path = "../system_properties" }thiserror = { workspace = true }+tokio = { workspace = true, features = ["macros"], optional = true }+tower = { workspace = true, optional = true }tracing = { workspace = true }+utoipa = { workspace = true, optional = true }uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]ai_toolset = { path = "../ai_toolset" }chrono = { workspace = true }-mockall = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }+mockall = { workspace = true }serde_json = { workspace = true }tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/rust/cloud-storage/properties_db_client/fixtures/properties.sql b/rust/cloud-storage/properties/fixtures/properties.sqlsimilarity index 87%rename from rust/cloud-storage/properties_db_client/fixtures/properties.sqlrename to rust/cloud-storage/properties/fixtures/properties.sqlindex 1fd2a9b038..8d3119a13d 100644--- a/rust/cloud-storage/properties_db_client/fixtures/properties.sql+++ b/rust/cloud-storage/properties/fixtures/properties.sql@@ -9,21 +9,21 @@ VALUESON CONFLICT (id) DO NOTHING;INSERT INTO "User" (id, email, name, "stripeCustomerId", macro_user_id)-VALUES ('user1', '[email protected]', 'Test User 1', 'cus_test1', 'a1111111-1111-1111-1111-111111111111'),- ('user2', '[email protected]', 'Test User 2', 'cus_test2', 'a2222222-2222-2222-2222-222222222222'),- ('user3', '[email protected]', 'Test User 3', 'cus_test3', 'a3333333-3333-3333-3333-333333333333')+VALUES ('macro|[email protected]', '[email protected]', 'Test User 1', 'cus_test1', 'a1111111-1111-1111-1111-111111111111'),+ ('macro|[email protected]', '[email protected]', 'Test User 2', 'cus_test2', 'a2222222-2222-2222-2222-222222222222'),+ ('macro|[email protected]', '[email protected]', 'Test User 3', 'cus_test3', 'a3333333-3333-3333-3333-333333333333')ON CONFLICT (id) DO NOTHING;-- Teams: Team 1 has two members (user1 owner, user3 member); Team 2 has user2.INSERT INTO team (id, name, owner_id)-VALUES ('0e000000-0000-0000-0000-000000000001', 'Test Team 1', 'user1'),- ('0e000000-0000-0000-0000-000000000002', 'Test Team 2', 'user2')+VALUES ('0e000000-0000-0000-0000-000000000001', 'Test Team 1', 'macro|[email protected]'),+ ('0e000000-0000-0000-0000-000000000002', 'Test Team 2', 'macro|[email protected]')ON CONFLICT (id) DO NOTHING;INSERT INTO team_user (user_id, team_id, team_role)-VALUES ('user1', '0e000000-0000-0000-0000-000000000001', 'owner'),- ('user3', '0e000000-0000-0000-0000-000000000001', 'member'),- ('user2', '0e000000-0000-0000-0000-000000000002', 'owner')+VALUES ('macro|[email protected]', '0e000000-0000-0000-0000-000000000001', 'owner'),+ ('macro|[email protected]', '0e000000-0000-0000-0000-000000000001', 'member'),+ ('macro|[email protected]', '0e000000-0000-0000-0000-000000000002', 'owner')ON CONFLICT DO NOTHING;-- Property definitions with various data types@@ -42,8 +42,8 @@ VALUES('99999999-9999-9999-9999-999999999999', '0e000000-0000-0000-0000-000000000001', NULL, 'Test Website', 'LINK', false, NULL),('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '0e000000-0000-0000-0000-000000000001', NULL, 'Test Relevant Documents', 'ENTITY', false, 'DOCUMENT'),-- User-owned properties (user1)- ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'user1', 'Test Personal Priority', 'SELECT_STRING', false, NULL),- ('cccccccc-cccc-cccc-cccc-cccccccccccc', NULL, 'user1', 'Test Notes', 'STRING', false, NULL),+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', NULL, 'macro|[email protected]', 'Test Personal Priority', 'SELECT_STRING', false, NULL),+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', NULL, 'macro|[email protected]', 'Test Notes', 'STRING', false, NULL),-- Team 2-owned property('dddddddd-dddd-dddd-dddd-dddddddddddd', '0e000000-0000-0000-0000-000000000002', NULL, 'Test Shared Status', 'SELECT_STRING', false, NULL);@@ -78,21 +78,21 @@ VALUES-- Document entities('e0111111-1111-1111-1111-111111111111', 'doc1', 'DOCUMENT', '11111111-1111-1111-1111-111111111111', '{"type": "SelectOption", "value": ["10111111-1111-1111-1111-111111111113"]}'),('e0111111-1111-1111-1111-111111111112', 'doc1', 'DOCUMENT', '22222222-2222-2222-2222-222222222222', '{"type": "SelectOption", "value": ["10222222-2222-2222-2222-222222222222"]}'),- ('e0111111-1111-1111-1111-111111111113', 'doc1', 'DOCUMENT', '33333333-3333-3333-3333-333333333333', '{"type": "EntityReference", "value": [{"entity_type": "USER", "entity_id": "user1"}]}'),+ ('e0111111-1111-1111-1111-111111111113', 'doc1', 'DOCUMENT', '33333333-3333-3333-3333-333333333333', '{"type": "EntityReference", "value": [{"entity_type": "USER", "entity_id": "macro|[email protected]"}]}'),('e0111111-1111-1111-1111-111111111114', 'doc1', 'DOCUMENT', '55555555-5555-5555-5555-555555555555', '{"type": "Boolean", "value": false}'),('e0111111-1111-1111-1111-111111111115', 'doc1', 'DOCUMENT', '66666666-6666-6666-6666-666666666666', '{"type": "Date", "value": "2025-12-31T23:59:59Z"}'),('e0111111-1111-1111-1111-111111111116', 'doc1', 'DOCUMENT', '88888888-8888-8888-8888-888888888888', '{"type": "String", "value": "Important document for testing"}'),-- Document 2('e0222222-2222-2222-2222-222222222221', 'doc2', 'DOCUMENT', '11111111-1111-1111-1111-111111111111', '{"type": "SelectOption", "value": ["10111111-1111-1111-1111-111111111111"]}'),('e0222222-2222-2222-2222-222222222222', 'doc2', 'DOCUMENT', '22222222-2222-2222-2222-222222222222', '{"type": "SelectOption", "value": ["10222222-2222-2222-2222-222222222222", "10222222-2222-2222-2222-222222222223"]}'),- ('e0222222-2222-2222-2222-222222222223', 'doc2', 'DOCUMENT', '33333333-3333-3333-3333-333333333333', '{"type": "EntityReference", "value": [{"entity_type": "USER", "entity_id": "user1"}, {"entity_type": "USER", "entity_id": "user2"}]}'),+ ('e0222222-2222-2222-2222-222222222223', 'doc2', 'DOCUMENT', '33333333-3333-3333-3333-333333333333', '{"type": "EntityReference", "value": [{"entity_type": "USER", "entity_id": "macro|[email protected]"}, {"entity_type": "USER", "entity_id": "macro|[email protected]"}]}'),('e0222222-2222-2222-2222-222222222224', 'doc2', 'DOCUMENT', '55555555-5555-5555-5555-555555555555', '{"type": "Boolean", "value": true}'),-- Project entities('e0333333-3333-3333-3333-333333333331', 'proj1', 'PROJECT', '11111111-1111-1111-1111-111111111111', '{"type": "SelectOption", "value": ["10111111-1111-1111-1111-111111111112"]}'),('e0333333-3333-3333-3333-333333333332', 'proj1', 'PROJECT', '44444444-4444-4444-4444-444444444444', '{"type": "SelectOption", "value": ["10444444-4444-4444-4444-444444444444"]}'),('e0333333-3333-3333-3333-333333333333', 'proj1', 'PROJECT', '77777777-7777-7777-7777-777777777777', '{"type": "Number", "value": 50000.50}'),('e0333333-3333-3333-3333-333333333334', 'proj1', 'PROJECT', '99999999-9999-9999-9999-999999999999', '{"type": "Link", "value": ["https://example.com"]}'),- ('e0333333-3333-3333-3333-333333333335', 'proj1', 'PROJECT', '33333333-3333-3333-3333-333333333333', '{"type": "EntityReference", "value": [{"entity_type": "USER", "entity_id": "user1"}]}'),+ ('e0333333-3333-3333-3333-333333333335', 'proj1', 'PROJECT', '33333333-3333-3333-3333-333333333333', '{"type": "EntityReference", "value": [{"entity_type": "USER", "entity_id": "macro|[email protected]"}]}'),-- Thread entities('e0555555-5555-5555-5555-555555555551', 'thread1', 'THREAD', '11111111-1111-1111-1111-111111111111', '{"type": "SelectOption", "value": ["10111111-1111-1111-1111-111111111114"]}'),-- Entities with NULL values (property attached but not set)diff --git a/rust/cloud-storage/properties_db_client/fixtures/tags.sql b/rust/cloud-storage/properties/fixtures/tags.sqlsimilarity index 86%rename from rust/cloud-storage/properties_db_client/fixtures/tags.sqlrename to rust/cloud-storage/properties/fixtures/tags.sqlindex ae63010943..fe51c190ec 100644--- a/rust/cloud-storage/properties_db_client/fixtures/tags.sql+++ b/rust/cloud-storage/properties/fixtures/tags.sql@@ -2,9 +2,9 @@-- Kept separate from properties.sql so definition-count assertions stay valid.INSERT INTO property_definitions (id, team_id, user_id, display_name, data_type, is_multi_select, specific_entity_type)VALUES- ('aa111111-1111-1111-1111-111111111111', NULL, 'user1', 'Tags', 'TAG', true, NULL),+ ('aa111111-1111-1111-1111-111111111111', NULL, 'macro|[email protected]', 'Tags', 'TAG', true, NULL),('aa222222-2222-2222-2222-222222222222', '0e000000-0000-0000-0000-000000000001', NULL, 'Tags', 'TAG', true, NULL),- ('aa333333-3333-3333-3333-333333333333', NULL, 'user2', 'Tags', 'TAG', true, NULL)+ ('aa333333-3333-3333-3333-333333333333', NULL, 'macro|[email protected]', 'Tags', 'TAG', true, NULL)ON CONFLICT (id) DO NOTHING;-- tagdoc1 carries a regular select plus one tag application per owner above.diff --git a/rust/cloud-storage/properties/src/domain.rs b/rust/cloud-storage/properties/src/domain.rsindex e8b9ee5d3d..63f50f1e03 100644--- a/rust/cloud-storage/properties/src/domain.rs+++ b/rust/cloud-storage/properties/src/domain.rs@@ -1,4 +1,5 @@pub mod error;+pub mod metadata;pub mod model;pub mod ports;pub mod service;diff --git a/rust/cloud-storage/properties/src/domain/error.rs b/rust/cloud-storage/properties/src/domain/error.rsindex cdc37708d8..c2ac8e745a 100644--- a/rust/cloud-storage/properties/src/domain/error.rs+++ b/rust/cloud-storage/properties/src/domain/error.rs@@ -13,6 +13,30 @@ pub enum PropertiesErr {#[error("Access denied")]PermissionDenied,+ /// Requested resource not found - maps to 404+ #[error("Property definition not found")]+ NotFound,++ /// Property option not found - maps to 404+ #[error("Property option not found")]+ OptionNotFound,++ /// Entity property not found - maps to 404+ #[error("Entity property not found")]+ EntityPropertyNotFound,++ /// The property is required for the entity type - maps to 403+ #[error("This property is required and cannot be removed from this entity")]+ RequiredProperty,++ /// An option with the requested value already exists - maps to 409+ #[error("An option with that value already exists")]+ DuplicateOptionValue,++ /// System properties cannot be modified - maps to 403+ #[error("Cannot modify system properties")]+ SystemPropertyNotModifiable,+/// Repository/database errors - maps to 500#[error(transparent)]Repo(#[from] anyhow::Error),diff --git a/rust/cloud-storage/properties_service/src/api/properties/metadata.rs b/rust/cloud-storage/properties/src/domain/metadata.rssimilarity index 73%rename from rust/cloud-storage/properties_service/src/api/properties/metadata.rsrename to rust/cloud-storage/properties/src/domain/metadata.rsindex 5b0632fbe4..5ad2edf0d6 100644--- a/rust/cloud-storage/properties_service/src/api/properties/metadata.rs+++ b/rust/cloud-storage/properties/src/domain/metadata.rs@@ -1,42 +1,58 @@+//! Read-only metadata properties computed on-the-fly from entity data.+//!+//! These are never persisted in the properties tables: they surface fields of+//! the entity itself (name, owner, timestamps, ...) in the property response+//! shape. They share a special [`METADATA_PROPERTY_ID`] and are marked with+//! `is_metadata = true`.++use models_properties::service::document_metadata::DocumentMetadata;use models_properties::service::entity_property::EntityProperty;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::project_metadata::ProjectMetadata;use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_value::PropertyValue;+use models_properties::service::thread_metadata::ThreadMetadata;use models_properties::{EntityReference, EntityType};-use properties_db_client::error::PropertiesDatabaseError;-use sqlx::{Pool, Postgres};-use thiserror::Error;use uuid::Uuid;-use crate::constants::{METADATA_PROPERTY_ID, metadata};+/// Special UUID used for system-generated metadata properties.+/// This distinguishes metadata properties from user-created properties.+pub const METADATA_PROPERTY_ID: Uuid = Uuid::from_u128(0xFFFFFFFF_FFFF_FFFF_FFFF_FFFFFFFFFFFF);++/// Metadata property display names+pub mod display_names {+ // Common (shared across entity types)+ pub const OWNER: &str = "Owner";+ pub const CREATED_AT: &str = "Created At";+ pub const LAST_UPDATED: &str = "Last Updated";++ // Document metadata+ pub const DOCUMENT_NAME: &str = "Document Name";+ pub const DOCUMENT_PROJECT: &str = "Project";-#[derive(Debug, Error)]-pub enum MetadataError {- #[error("Document not found")]- NotFound,+ // Thread metadata+ pub const THREAD_SUBJECT: &str = "Subject";+ pub const THREAD_STARTED: &str = "Thread Started";+ pub const THREAD_LAST_RECEIVED: &str = "Last Received";+ pub const THREAD_LAST_SENT: &str = "Last Sent";+ pub const THREAD_MESSAGES: &str = "Messages";- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),+ // Project metadata+ pub const PROJECT_NAME: &str = "Project Name";+ pub const PROJECT_PARENT: &str = "Parent Project";}-/// Get document metadata properties from macrodb-#[tracing::instrument(skip(db), err)]-pub async fn get_document_metadata_properties(- db: &Pool<Postgres>,- document_id: &str,+/// Build the metadata properties for a document (or task, which is stored as a document).+pub fn document_metadata_properties(+ document_metadata: DocumentMetadata,entity_type: EntityType,-) -> Result<Vec<EntityPropertyWithDefinition>, MetadataError> {- let document_metadata =- properties_db_client::document_metadata::get::get_document_metadata(db, document_id)- .await?- .ok_or(MetadataError::NotFound)?;-+) -> Vec<EntityPropertyWithDefinition> {let mut metadata_properties = Vec::new();// 1. Document name propertylet name = (!document_metadata.name.is_empty()).then_some(document_metadata.name);metadata_properties.push(create_metadata_property_str(- metadata::DOCUMENT_NAME,+ display_names::DOCUMENT_NAME,models_properties::DataType::String,name,entity_type,@@ -46,7 +62,7 @@ pub async fn get_document_metadata_properties(let owner = (!document_metadata.owner.is_empty()).then(|| EntityReference::new(document_metadata.owner, EntityType::User));metadata_properties.push(create_metadata_property_entity_ref(- metadata::OWNER,+ display_names::OWNER,models_properties::DataType::Entity,owner,entity_type,@@ -55,7 +71,7 @@ pub async fn get_document_metadata_properties(// 3. Created time propertymetadata_properties.push(create_metadata_property_date(- metadata::CREATED_AT,+ display_names::CREATED_AT,models_properties::DataType::Date,Some(document_metadata.created_at),entity_type,@@ -63,7 +79,7 @@ pub async fn get_document_metadata_properties(// 4. Last updated time propertymetadata_properties.push(create_metadata_property_date(- metadata::LAST_UPDATED,+ display_names::LAST_UPDATED,models_properties::DataType::Date,Some(document_metadata.updated_at),entity_type,@@ -74,81 +90,65 @@ pub async fn get_document_metadata_properties(.project_id.map(|id| EntityReference::new(id, EntityType::Project));metadata_properties.push(create_metadata_property_entity_ref(- metadata::DOCUMENT_PROJECT,+ display_names::DOCUMENT_PROJECT,models_properties::DataType::Entity,project,entity_type,Some(EntityType::Project),));- Ok(metadata_properties)+ metadata_properties}-/// Get thread metadata properties from macrodb-#[tracing::instrument(skip(db), err)]-pub async fn get_thread_metadata_properties(- db: &Pool<Postgres>,- thread_id: Uuid,-) -> Result<Vec<EntityPropertyWithDefinition>, MetadataError> {- let thread_metadata =- properties_db_client::thread_metadata::get::get_thread_metadata(db, thread_id)- .await?- .ok_or(MetadataError::NotFound)?;-+/// Build the metadata properties for an email thread.+pub fn thread_metadata_properties(+ thread_metadata: ThreadMetadata,+) -> Vec<EntityPropertyWithDefinition> {let entity_type = EntityType::Thread;- let metadata_properties = vec![+ vec![// 1. Subject propertycreate_metadata_property_str(- metadata::THREAD_SUBJECT,+ display_names::THREAD_SUBJECT,models_properties::DataType::String,thread_metadata.subject.clone(),entity_type,),// 2. Thread Started propertycreate_metadata_property_date(- metadata::THREAD_STARTED,+ display_names::THREAD_STARTED,models_properties::DataType::Date,thread_metadata.thread_started,entity_type,),// 3. Last Received propertycreate_metadata_property_date(- metadata::THREAD_LAST_RECEIVED,+ display_names::THREAD_LAST_RECEIVED,models_properties::DataType::Date,thread_metadata.last_received,entity_type,),// 4. Last Sent propertycreate_metadata_property_date(- metadata::THREAD_LAST_SENT,+ display_names::THREAD_LAST_SENT,models_properties::DataType::Date,thread_metadata.last_sent,entity_type,),// 5. Messages property (count)create_metadata_property_number(- metadata::THREAD_MESSAGES,+ display_names::THREAD_MESSAGES,models_properties::DataType::Number,thread_metadata.message_count,entity_type,),- ];-- Ok(metadata_properties)+ ]}-/// Get project metadata properties from macrodb-#[tracing::instrument(skip(db), err)]-pub async fn get_project_metadata_properties(- db: &Pool<Postgres>,- project_id: &str,-) -> Result<Vec<EntityPropertyWithDefinition>, MetadataError> {- let project_metadata =- properties_db_client::project_metadata::get::get_project_metadata(db, project_id)- .await?- .ok_or(MetadataError::NotFound)?;-+/// Build the metadata properties for a project.+pub fn project_metadata_properties(+ project_metadata: ProjectMetadata,+) -> Vec<EntityPropertyWithDefinition> {let entity_type = EntityType::Project;// 1. Project name property@@ -163,15 +163,15 @@ pub async fn get_project_metadata_properties(.parent_id.map(|id| EntityReference::new(id, EntityType::Project));- let metadata_properties = vec![+ vec![create_metadata_property_str(- metadata::PROJECT_NAME,+ display_names::PROJECT_NAME,models_properties::DataType::String,name,entity_type,),create_metadata_property_entity_ref(- metadata::OWNER,+ display_names::OWNER,models_properties::DataType::Entity,owner,entity_type,@@ -179,36 +179,28 @@ pub async fn get_project_metadata_properties(),// 3. Created time propertycreate_metadata_property_date(- metadata::CREATED_AT,+ display_names::CREATED_AT,models_properties::DataType::Date,Some(project_metadata.created_at),entity_type,),// 4. Last updated time propertycreate_metadata_property_date(- metadata::LAST_UPDATED,+ display_names::LAST_UPDATED,models_properties::DataType::Date,Some(project_metadata.updated_at),entity_type,),create_metadata_property_entity_ref(- metadata::PROJECT_PARENT,+ display_names::PROJECT_PARENT,models_properties::DataType::Entity,parent,entity_type,Some(EntityType::Project),),- ];-- Ok(metadata_properties)+ ]}-// ===== Metadata Property Helpers =====-//-// These helpers create read-only metadata properties that are computed on-the-fly-// from entity data (not stored in the properties tables). They share a special-// METADATA_PROPERTY_ID and are marked with is_metadata=true.-/// Create a metadata property with a string value (e.g., document name, subject)pub fn create_metadata_property_str(display_name: &str,diff --git a/rust/cloud-storage/properties/src/domain/model.rs b/rust/cloud-storage/properties/src/domain/model.rsindex 5a33817457..f20d5a9df2 100644--- a/rust/cloud-storage/properties/src/domain/model.rs+++ b/rust/cloud-storage/properties/src/domain/model.rs@@ -1,6 +1,8 @@//! Domain models for properties.-use models_properties::service::property_option::PropertyOptionValue;+use macro_user_id::user_id::MacroUserIdStr;+use models_properties::service::property_definition::PropertyDefinition;+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::service::property_value::PropertyValue;use models_properties::{DataType, EntityReference, EntityType};use uuid::Uuid;@@ -50,3 +52,71 @@ pub struct PropertyOptionInfo {/// The option's value.pub value: PropertyOptionValue,}++/// The owner of a user- or team-created property definition. Encodes the+/// "exactly one of user / team" invariant in the type, so neither a both-owners+/// nor a no-owner row is representable. System properties are not created here.+#[derive(Debug, Clone, Copy)]+pub enum PropertyDefinitionOwner<'a> {+ /// Owned by a single user.+ User(&'a MacroUserIdStr<'a>),+ /// Owned by a team.+ Team(Uuid),+}++impl<'a> PropertyDefinitionOwner<'a> {+ /// Split into the nullable (team_id, user_id) columns the row stores.+ pub fn into_ids(self) -> (Option<Uuid>, Option<&'a MacroUserIdStr<'a>>) {+ match self {+ PropertyDefinitionOwner::User(user_id) => (None, Some(user_id)),+ PropertyDefinitionOwner::Team(team_id) => (Some(team_id), None),+ }+ }+}++/// Which owner a tag set belongs to.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TagScope {+ /// The caller's personal tag set.+ User,+ /// The caller's team tag set.+ Team,+}++/// A tag set the caller can use. `definition` is `None` until the set is+/// provisioned (on first label create), in which case `options` is empty.+#[derive(Debug, Clone)]+pub struct TagSet {+ /// The owner scope of the tag set.+ pub scope: TagScope,+ /// The tag property definition, if provisioned.+ pub definition: Option<PropertyDefinition>,+ /// The tag options (labels) in the set.+ pub options: Vec<PropertyOption>,+}++/// Outcome of an in-place property option update.+#[derive(Debug, Clone)]+pub enum UpdatePropertyOptionOutcome {+ /// The option was updated.+ Updated(PropertyOption),+ /// No option with the given id exists.+ NotFound,+ /// Another option on the same property already has the requested value.+ DuplicateValue,+}++/// A task-assignment notification expressed in domain terms.+///+/// Outbound adapters enrich this (task name, sender profile picture) and+/// translate it to the concrete notification infrastructure, fanning out one+/// notification per recipient.+#[derive(Debug, Clone)]+pub struct TaskAssignedNotification<'a> {+ /// The task the recipients were assigned to.+ pub task_id: Uuid,+ /// The user who assigned the task.+ pub assigned_by: MacroUserIdStr<'a>,+ /// The newly assigned users to notify.+ pub recipient_ids: Vec<MacroUserIdStr<'a>>,+}diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsindex 116da7f371..6aadd0f123 100644--- a/rust/cloud-storage/properties/src/domain/ports.rs+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -6,15 +6,21 @@use std::collections::HashMap;use macro_user_id::user_id::MacroUserIdStr;-use model_notifications::TaskAssignedMetadata;+use models_properties::service::document_metadata::DocumentMetadata;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::project_metadata::ProjectMetadata;use models_properties::service::property_definition::PropertyDefinition;+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::service::property_value::PropertyValue;-use models_properties::{EntityReference, EntityType};-use notification::domain::models::SendNotificationRequest;+use models_properties::service::thread_metadata::ThreadMetadata;+use models_properties::{DataType, EntityPropertyReference, EntityReference, EntityType};use uuid::Uuid;-use super::model::{EntityPropertiesKey, EntityPropertyInfo};+use super::model::{+ EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TaskAssignedNotification,+ UpdatePropertyOptionOutcome,+};/// Repository trait for property operations.///@@ -31,6 +37,120 @@ pub trait PropertiesRepo: Send + Sync + 'static {property_definition_id: Uuid,) -> impl Future<Output = Result<Option<PropertyDefinition>, Self::Err>> + Send;+ /// Get a property definition by ID with ownership validation.+ /// Returns `None` if the property doesn't exist, if the caller doesn't own it,+ /// or if it's a system property. The caller owns it when it is their user+ /// property, or a property of the team they belong to.+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn get_property_definition_with_owner<'a>(+ &self,+ property_definition_id: Uuid,+ user_id: &MacroUserIdStr<'a>,+ team_id: Option<Uuid>,+ ) -> impl Future<Output = Result<Option<PropertyDefinition>, Self::Err>> + Send;++ /// List property definitions owned by the given team and/or user.+ /// Set `include_system` to true to also include system properties.+ /// Returns definitions sorted by display name.+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn list_property_definitions<'a>(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&'a MacroUserIdStr<'a>>,+ include_system: bool,+ ) -> impl Future<Output = Result<Vec<PropertyDefinition>, Self::Err>> + Send;++ /// List property definitions with their options, owned by the given team and/or user.+ /// Set `include_system` to true to also include system properties.+ /// Returns definitions sorted by display name.+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn list_property_definitions_with_options<'a>(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&'a MacroUserIdStr<'a>>,+ include_system: bool,+ ) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, Self::Err>> + Send;++ /// Create a property definition, optionally with select options+ /// (atomically when options are provided).+ fn create_property_definition<'a>(+ &self,+ owner: PropertyDefinitionOwner<'a>,+ display_name: &str,+ data_type: DataType,+ is_multi_select: bool,+ specific_entity_type: Option<EntityType>,+ options: Vec<PropertyOption>,+ ) -> impl Future<Output = Result<PropertyDefinition, Self::Err>> + Send;++ /// Delete a property definition and all associated data (cascades).+ /// A no-op if the definition doesn't exist.+ fn delete_property_definition(+ &self,+ property_definition_id: Uuid,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Get a single property option by ID.+ /// Returns `None` if the option doesn't exist.+ fn get_property_option(+ &self,+ option_id: Uuid,+ ) -> impl Future<Output = Result<Option<PropertyOption>, Self::Err>> + Send;++ /// Get all options for a property definition, ordered for display.+ fn get_property_options(+ &self,+ property_definition_id: Uuid,+ ) -> impl Future<Output = Result<Vec<PropertyOption>, Self::Err>> + Send;++ /// Create a new property option.+ fn create_property_option(+ &self,+ property_definition_id: Uuid,+ display_order: i32,+ value: PropertyOptionValue,+ color: Option<String>,+ ) -> impl Future<Output = Result<PropertyOption, Self::Err>> + Send;++ /// Update a property option's value, color, and display order in place.+ /// The option id is preserved, so every entity referencing it reflects the+ /// change with no per-entity rewrite.+ fn update_property_option(+ &self,+ option_id: Uuid,+ value: PropertyOptionValue,+ color: Option<String>,+ display_order: i32,+ ) -> impl Future<Output = Result<UpdatePropertyOptionOutcome, Self::Err>> + Send;++ /// Delete a property option and strip its id from every entity value that+ /// references it, atomically. Returns `true` if the option was deleted,+ /// `false` if it didn't exist.+ fn delete_property_option(+ &self,+ property_definition_id: Uuid,+ option_id: Uuid,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Get the single tag definition owned by the given owner, if it exists.+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn get_tag_definition<'a>(+ &self,+ owner: PropertyDefinitionOwner<'a>,+ ) -> impl Future<Output = Result<Option<PropertyDefinition>, Self::Err>> + Send;++ /// Return the owner's tag definition, creating it on first use.+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn get_or_create_tag_definition<'a>(+ &self,+ owner: PropertyDefinitionOwner<'a>,+ ) -> impl Future<Output = Result<PropertyDefinition, Self::Err>> + Send;+/// Count how many of the provided option IDs exist for the property definition.fn count_valid_property_options(&self,@@ -133,20 +253,70 @@ pub trait PropertiesRepo: Send + Sync + 'static {Output = Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, Self::Err>,> + Send;- /// Get the name of a document.- /// Returns `None` if the document doesn't exist or has no name.- /// Tasks are stored as documents, so this works for both documents and tasks.- fn get_document_name(+ /// Get the properties attached to multiple entities, filtered by property+ /// definition IDs, keyed by entity id and type. When `tag_viewer_user_id`+ /// is set, also returns TAG properties whose definition is owned by that+ /// user or their team.+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn get_entity_properties_batch_filtered<'a>(+ &self,+ entity_refs: Vec<EntityReference>,+ property_ids: Vec<Uuid>,+ tag_viewer_user_id: Option<&'a MacroUserIdStr<'a>>,+ ) -> impl Future<+ Output = Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, Self::Err>,+ > + Send;++ /// Get an entity's properties with definitions, values, and options,+ /// sorted by display name.+ fn get_entity_properties_with_definitions(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<Vec<EntityPropertyWithDefinition>, Self::Err>> + Send;++ /// Look up an entity property by its ID.+ /// Returns the entity reference (for permissions) and definition ID+ /// (for required property checks), or `None` if it doesn't exist.+ fn lookup_entity_property(+ &self,+ entity_property_id: Uuid,+ ) -> impl Future<Output = Result<Option<EntityPropertyReference>, Self::Err>> + Send;++ /// Delete an entity property by its ID. A no-op if it doesn't exist.+ fn delete_entity_property(+ &self,+ entity_property_id: Uuid,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Delete all properties attached to an entity.+ fn delete_entity_properties(&self,- id: &str,- ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;+ entity_reference: &EntityReference,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Get a document's metadata (name, owner, timestamps, project).+ /// Returns `None` if the document doesn't exist.+ /// Tasks are stored as documents, so this works for both.+ fn get_document_metadata(+ &self,+ document_id: &str,+ ) -> impl Future<Output = Result<Option<DocumentMetadata>, Self::Err>> + Send;- /// Get the profile picture URL for a user.- /// Returns `None` if the user doesn't exist or has no profile picture.- fn get_user_profile_picture(+ /// Get an email thread's metadata (subject, timestamps, message count).+ /// Returns `None` if the thread doesn't exist.+ fn get_thread_metadata(&self,- user_id: &str,- ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;+ thread_id: Uuid,+ ) -> impl Future<Output = Result<Option<ThreadMetadata>, Self::Err>> + Send;++ /// Get a project's metadata (name, owner, timestamps, parent).+ /// Returns `None` if the project doesn't exist or is deleted.+ fn get_project_metadata(+ &self,+ project_id: &str,+ ) -> impl Future<Output = Result<Option<ProjectMetadata>, Self::Err>> + Send;}/// Permission service trait for entity access control.@@ -166,9 +336,24 @@ pub trait PermissionService: Send + Sync + 'static {/// Check if a user has edit access to an entity./// Returns an error if the user does not have edit or owner access.- fn check_entity_edit_permission(+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn check_entity_edit_permission<'a>(&self,- user_id: &str,+ user_id: &MacroUserIdStr<'a>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// Check if a user has view access to an entity (any access level).+ /// The owner always has access; deleted entities are only visible to their+ /// owner. For anonymous users (`None`), only allows access to+ /// publicly shared entities.+ // Explicit lifetime required by mockall's automock expansion.+ #[allow(clippy::needless_lifetimes)]+ fn check_entity_view_permission<'a>(+ &self,+ user_id: Option<&'a MacroUserIdStr<'a>>,entity_id: &str,entity_type: EntityType,) -> impl Future<Output = Result<(), Self::Err>> + Send;@@ -185,21 +370,18 @@ pub trait PermissionService: Send + Sync + 'static {/// Notification service trait for sending notifications.////// This trait abstracts notification operations, allowing for different implementations-/// (e.g., notification-service-backed, mock for testing).+/// (e.g., notification-service-backed, mock for testing). Adapters are expected to+/// enrich the domain-level notification (task name, sender profile picture) and fan+/// out delivery per recipient on a best-effort basis.#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]pub trait NotificationService: Send + Sync + 'static {type Err;- /// Send a notification message.- /// Returns the notification ID if successful.- fn send_notification<'a>(+ /// Notify the recipients that they were assigned to a task.+ fn send_task_assigned<'a>(&self,- message: SendNotificationRequest<- 'a,- TaskAssignedMetadata,- notification::domain::models::apple::PushNotificationData,- >,- ) -> impl Future<Output = Result<uuid::Uuid, Self::Err>> + Send;+ notification: TaskAssignedNotification<'a>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;}/// Port for keeping an entity's indexed properties in sync after a mutation.diff --git a/rust/cloud-storage/properties/src/domain/service.rs b/rust/cloud-storage/properties/src/domain/service.rsindex 26551f1ad7..b46235e15a 100644--- a/rust/cloud-storage/properties/src/domain/service.rs+++ b/rust/cloud-storage/properties/src/domain/service.rs@@ -2,15 +2,22 @@use std::collections::HashMap;+use macro_user_id::user_id::MacroUserIdStr;use models_properties::api::requests::SetPropertyValue;+use models_properties::api::{+ AddPropertyOptionRequest, CreatePropertyDefinitionRequest, UpdatePropertyOptionRequest,+};use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::property_definition::PropertyDefinition;+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;+use models_properties::service::property_option::PropertyOption;use models_properties::service::property_value::PropertyValue;use models_properties::{EntityReference, EntityType};use system_properties::SystemPropertyKey;use uuid::Uuid;use super::error::PropertiesErr;-use super::model::{EntityPropertiesKey, EntityPropertyInfo};+use super::model::{EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TagSet};/// Service trait for property operations.pub trait PropertiesService: Send + Sync + 'static {@@ -90,7 +97,7 @@ pub trait PropertiesService: Send + Sync + 'static {/// Requires edit access to the entity.fn set_entity_property(&self,- user_id: &str,+ user_id: &MacroUserIdStr<'_>,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,@@ -104,7 +111,7 @@ pub trait PropertiesService: Send + Sync + 'static {/// concurrent changes instead of clobbering them.fn add_entity_property_option(&self,- user_id: &str,+ user_id: &MacroUserIdStr<'_>,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,@@ -115,7 +122,7 @@ pub trait PropertiesService: Send + Sync + 'static {/// A no-op if absent. Requires edit access.fn remove_entity_property_option(&self,- user_id: &str,+ user_id: &MacroUserIdStr<'_>,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,@@ -128,4 +135,168 @@ pub trait PropertiesService: Send + Sync + 'static {entity_id: &str,entity_type: EntityType,) -> impl Future<Output = Result<(String, bool), PropertiesErr>> + Send;++ /// List property definitions owned by the given team and/or user, sorted by+ /// display name. Set `include_system` to true to also include system properties.+ /// When `for_entity_type` is provided, definitions that cannot be attached to+ /// that entity type are excluded.+ fn list_property_definitions(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+ for_entity_type: Option<EntityType>,+ ) -> impl Future<Output = Result<Vec<PropertyDefinition>, PropertiesErr>> + Send;++ /// Same as [`Self::list_property_definitions`], but including each definition's+ /// select options.+ fn list_property_definitions_with_options(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+ for_entity_type: Option<EntityType>,+ ) -> impl Future<Output = Result<Vec<PropertyDefinitionWithOptions>, PropertiesErr>> + Send;++ /// Create a property definition owned by the given user or team.+ /// Validates the request and creates any select options atomically.+ fn create_property_definition(+ &self,+ owner: PropertyDefinitionOwner<'_>,+ request: &CreatePropertyDefinitionRequest,+ ) -> impl Future<Output = Result<PropertyDefinition, PropertiesErr>> + Send;++ /// Delete a property definition owned by the caller.+ ///+ /// Fails with [`PropertiesErr::NotFound`] if the definition doesn't exist or+ /// isn't owned by the caller (their user property or a property of their team),+ /// and with [`PropertiesErr::SystemPropertyNotModifiable`] for system properties.+ fn delete_property_definition(+ &self,+ property_definition_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;++ /// Get all options for a property definition readable by the caller (for dropdowns).+ fn get_property_options(+ &self,+ property_definition_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> impl Future<Output = Result<Vec<PropertyOption>, PropertiesErr>> + Send;++ /// Add a new option to a select property owned by the caller.+ /// Validates the request against the property's data type, including the+ /// tag color rules.+ fn add_property_option(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ property_definition_id: Uuid,+ request: &AddPropertyOptionRequest,+ ) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;++ /// Update a property option in place (rename / recolor / reorder) on a+ /// property owned by the caller. The option id is preserved, so the change+ /// is reflected on every entity that references it.+ fn update_property_option(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ property_definition_id: Uuid,+ option_id: Uuid,+ request: &UpdatePropertyOptionRequest,+ ) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;++ /// Delete a property option on a property owned by the caller, stripping+ /// its id from every entity value that references it.+ fn delete_property_option(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ property_definition_id: Uuid,+ option_id: Uuid,+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;++ /// List the caller's tag sets: their personal set, plus their team's set+ /// when on a team. Pure read - a scope with no provisioned definition yet+ /// returns an empty set.+ fn list_tag_sets(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> impl Future<Output = Result<Vec<TagSet>, PropertiesErr>> + Send;++ /// Provision (get-or-create) the owner's tag set and return it.+ fn ensure_tag_set(+ &self,+ owner: PropertyDefinitionOwner<'_>,+ ) -> impl Future<Output = Result<TagSet, PropertiesErr>> + Send;++ /// Get an entity's stored properties with definitions, values, and options,+ /// sorted by display name. Does not include computed metadata properties+ /// (see [`Self::get_entity_metadata_properties`]).+ fn get_entity_properties_with_definitions(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<Vec<EntityPropertyWithDefinition>, PropertiesErr>> + Send;++ /// Get an entity's read-only metadata properties, computed on-the-fly from+ /// the entity itself (name, owner, timestamps, ...).+ /// Returns `None` when the entity doesn't exist (or the id is malformed);+ /// entity types without metadata yield `Some(vec![])`.+ fn get_entity_metadata_properties(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<Option<Vec<EntityPropertyWithDefinition>>, PropertiesErr>> + Send;++ /// Get properties for multiple entities, keyed by entity id and type.+ /// An empty `property_ids` fetches all properties for the given entities;+ /// otherwise only the requested definitions are returned.+ fn get_bulk_entity_properties(+ &self,+ entity_refs: Vec<EntityReference>,+ property_ids: Vec<Uuid>,+ ) -> impl Future<+ Output = Result<+ HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>,+ PropertiesErr,+ >,+ > + Send;++ /// Delete all properties attached to an entity (internal operation, no+ /// permission checks).+ fn delete_entity_properties(+ &self,+ entity_reference: &EntityReference,+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;++ /// Delete a single entity property by its ID on behalf of a user.+ /// Fails when the property doesn't exist, is required for the entity type,+ /// or the user lacks edit access to the entity.+ fn delete_entity_property(+ &self,+ entity_property_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;++ /// Check that a user has view access to an entity (any access level).+ /// For anonymous users (`None`), only allows publicly shared entities.+ fn check_entity_view_permission(+ &self,+ user_id: Option<&MacroUserIdStr<'_>>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;++ /// Check that a user has edit access to an entity (Edit or Owner level).+ fn check_entity_edit_permission(+ &self,+ user_id: &MacroUserIdStr<'_>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;}diff --git a/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs b/rust/cloud-storage/properties/src/domain/service_impl/helpers.rsindex 0cfb15368e..032b3b7873 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs@@ -5,7 +5,7 @@ use models_properties::service::property_value::PropertyValue;use system_properties::SystemPropertyKey;use uuid::Uuid;-/// Extract option IDs from a PropertyValue (matches properties_db_client pattern).+/// Extract option IDs from a PropertyValue.pub fn extract_option_ids_from_property_value(value: &Option<PropertyValue>) -> Vec<Uuid> {match value {Some(PropertyValue::SelectOption(ids)) => ids.clone(),diff --git a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rsindex 45ee8a9437..1137c1a713 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs@@ -5,9 +5,18 @@ mod task_properties;use std::collections::HashMap;+use macro_user_id::user_id::MacroUserIdStr;+use models_properties::DataType;use models_properties::api::requests::SetPropertyValue;+use models_properties::api::{+ AddPropertyOptionRequest, CreatePropertyDefinitionRequest, PropertyDataType,+ UpdatePropertyOptionRequest, is_valid_hex_color,+};use models_properties::convert_set_property_value_to_property_value;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::property_definition::PropertyDefinition;+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::service::property_value::PropertyValue;use models_properties::{EntityReference, EntityType};use system_properties::{StatusOption, SystemPropertyKey};@@ -16,7 +25,11 @@ use uuid::Uuid;use std::sync::Arc;use super::error::PropertiesErr;-use super::model::{EntityPropertiesKey, EntityPropertyInfo};+use super::metadata;+use super::model::{+ EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, TagScope, TagSet,+ UpdatePropertyOptionOutcome,+};use super::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer};use super::service::PropertiesService;@@ -94,6 +107,66 @@ where}}+ /// Fetch a property definition, ensuring it exists, isn't a system+ /// property, and is owned by the caller (their user property or a property+ /// of their team).+ async fn owned_modifiable_definition(+ &self,+ property_definition_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> Result<PropertyDefinition, PropertiesErr>+ where+ anyhow::Error: From<R::Err>,+ {+ let property = self+ .repository+ .get_property_definition(property_definition_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::NotFound)?;++ if property.is_system {+ return Err(PropertiesErr::SystemPropertyNotModifiable);+ }++ self.repository+ .get_property_definition_with_owner(property_definition_id, user_id, team_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::NotFound)+ }++ /// Resolve a tag set's options. A missing definition yields an empty set.+ async fn build_tag_set(+ &self,+ scope: TagScope,+ definition: Option<PropertyDefinition>,+ ) -> Result<TagSet, PropertiesErr>+ where+ anyhow::Error: From<R::Err>,+ {+ match definition {+ Some(definition) => {+ let options = self+ .repository+ .get_property_options(definition.id)+ .await+ .map_err(anyhow::Error::from)?;+ Ok(TagSet {+ scope,+ definition: Some(definition),+ options,+ })+ }+ None => Ok(TagSet {+ scope,+ definition: None,+ options: Vec::new(),+ }),+ }+ }+/// Validate that the given option IDs exist for the property definition./// Returns an error if any option ID is invalid.pub async fn validate_property_options(@@ -253,7 +326,7 @@ where)]async fn set_entity_property(&self,- user_id: &str,+ user_id: &MacroUserIdStr<'_>,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,@@ -367,7 +440,7 @@ where)]async fn add_entity_property_option(&self,- user_id: &str,+ user_id: &MacroUserIdStr<'_>,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,@@ -430,7 +503,7 @@ where)]async fn remove_entity_property_option(&self,- user_id: &str,+ user_id: &MacroUserIdStr<'_>,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,@@ -476,4 +549,589 @@ where}Err(PropertiesErr::PermissionServiceNotConfigured)}++ #[tracing::instrument(skip(self), err)]+ async fn list_property_definitions(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+ for_entity_type: Option<EntityType>,+ ) -> Result<Vec<PropertyDefinition>, PropertiesErr> {+ let definitions = self+ .repository+ .list_property_definitions(team_id, user_id, include_system)+ .await+ .map_err(anyhow::Error::from)?;++ Ok(definitions+ .into_iter()+ .filter(|d| {+ for_entity_type+ .map(|et| is_property_applicable_to(d.id, et))+ .unwrap_or(true)+ })+ .collect())+ }++ #[tracing::instrument(skip(self), err)]+ async fn list_property_definitions_with_options(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+ for_entity_type: Option<EntityType>,+ ) -> Result<Vec<PropertyDefinitionWithOptions>, PropertiesErr> {+ let definitions = self+ .repository+ .list_property_definitions_with_options(team_id, user_id, include_system)+ .await+ .map_err(anyhow::Error::from)?;++ Ok(definitions+ .into_iter()+ .filter(|d| {+ for_entity_type+ .map(|et| is_property_applicable_to(d.definition.id, et))+ .unwrap_or(true)+ })+ .collect())+ }++ #[tracing::instrument(skip(self, request), fields(display_name = %request.display_name), err)]+ async fn create_property_definition(+ &self,+ owner: PropertyDefinitionOwner<'_>,+ request: &CreatePropertyDefinitionRequest,+ ) -> Result<PropertyDefinition, PropertiesErr> {+ if let Err(err) = request.validate() {+ return Err(PropertiesErr::Validation(err.to_string()));+ }++ let property_options = match &request.data_type {+ PropertyDataType::SelectString { options, .. } => options+ .iter()+ .map(|opt| {+ build_property_option(+ opt.display_order,+ PropertyOptionValue::String(opt.value.clone()),+ )+ })+ .collect(),+ PropertyDataType::SelectNumber { options, .. } => options+ .iter()+ .map(|opt| {+ build_property_option(opt.display_order, PropertyOptionValue::Number(opt.value))+ })+ .collect(),+ _ => Vec::new(),+ };++ let property = self+ .repository+ .create_property_definition(+ owner,+ &request.display_name,+ request.data_type.to_data_type(),+ request.data_type.is_multi_select(),+ request.data_type.specific_entity_type(),+ property_options,+ )+ .await+ .map_err(anyhow::Error::from)?;++ tracing::info!(+ property_id = %property.id,+ data_type = ?property.data_type,+ "successfully created property definition"+ );++ Ok(property)+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_property_definition(+ &self,+ property_definition_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> Result<(), PropertiesErr> {+ // First check if the property exists and if it's a system property.+ let property = self+ .repository+ .get_property_definition(property_definition_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::NotFound)?;++ if property.is_system || SystemPropertyKey::is_system_uuid(property_definition_id) {+ return Err(PropertiesErr::SystemPropertyNotModifiable);+ }++ // Then verify ownership.+ self.repository+ .get_property_definition_with_owner(property_definition_id, user_id, team_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::NotFound)?;++ self.repository+ .delete_property_definition(property_definition_id)+ .await+ .map_err(anyhow::Error::from)?;++ tracing::info!("successfully deleted property definition");++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_property_options(+ &self,+ property_definition_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> Result<Vec<PropertyOption>, PropertiesErr> {+ let definition = self+ .repository+ .get_property_definition(property_definition_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::NotFound)?;++ if !definition.is_system {+ self.repository+ .get_property_definition_with_owner(property_definition_id, user_id, team_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::NotFound)?;+ }++ Ok(self+ .repository+ .get_property_options(property_definition_id)+ .await+ .map_err(anyhow::Error::from)?)+ }++ #[tracing::instrument(skip(self, request), fields(request = ?request), err)]+ async fn add_property_option(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ property_definition_id: Uuid,+ request: &AddPropertyOptionRequest,+ ) -> Result<PropertyOption, PropertiesErr> {+ let definition = self+ .owned_modifiable_definition(property_definition_id, user_id, team_id)+ .await?;++ request+ .validate()+ .map_err(|e| PropertiesErr::Validation(e.to_string()))?;+ request+ .validate_compatibility(&definition.data_type)+ .map_err(|e| PropertiesErr::Validation(e.to_string()))?;++ let (display_order, option_value, color) = match request {+ AddPropertyOptionRequest::SelectString { option } => (+ option.display_order,+ PropertyOptionValue::String(option.value.clone()),+ option.color.clone(),+ ),+ AddPropertyOptionRequest::SelectNumber { option } => (+ option.display_order,+ PropertyOptionValue::Number(option.value),+ None,+ ),+ };++ validate_option_color(&definition.data_type, color.as_deref(), color.as_deref())?;++ let option = self+ .repository+ .create_property_option(property_definition_id, display_order, option_value, color)+ .await+ .map_err(anyhow::Error::from)?;++ tracing::info!(+ option_id = %option.id,+ display_order = option.display_order,+ "successfully added property option"+ );++ Ok(option)+ }++ #[tracing::instrument(skip(self, request), fields(request = ?request), err)]+ async fn update_property_option(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ property_definition_id: Uuid,+ option_id: Uuid,+ request: &UpdatePropertyOptionRequest,+ ) -> Result<PropertyOption, PropertiesErr> {+ let definition = self+ .owned_modifiable_definition(property_definition_id, user_id, team_id)+ .await?;++ let option = self+ .repository+ .get_property_option(option_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::OptionNotFound)?;++ if option.property_definition_id != property_definition_id {+ return Err(PropertiesErr::OptionNotFound);+ }++ let new_value = match &request.value {+ Some(value) => match definition.data_type {+ DataType::SelectString | DataType::Tag => {+ if value.trim().is_empty() {+ return Err(PropertiesErr::Validation(+ "value cannot be empty".to_string(),+ ));+ }+ PropertyOptionValue::String(value.clone())+ }+ _ => {+ return Err(PropertiesErr::Validation(+ "value updates are only supported for string and tag options".to_string(),+ ));+ }+ },+ None => option.value.clone(),+ };++ let new_color = request.color.clone().or_else(|| option.color.clone());+ validate_option_color(+ &definition.data_type,+ request.color.as_deref(),+ new_color.as_deref(),+ )?;++ let new_display_order = request.display_order.unwrap_or(option.display_order);++ match self+ .repository+ .update_property_option(option_id, new_value, new_color, new_display_order)+ .await+ .map_err(anyhow::Error::from)?+ {+ UpdatePropertyOptionOutcome::Updated(updated) => Ok(updated),+ UpdatePropertyOptionOutcome::NotFound => Err(PropertiesErr::OptionNotFound),+ UpdatePropertyOptionOutcome::DuplicateValue => Err(PropertiesErr::DuplicateOptionValue),+ }+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_property_option(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ property_definition_id: Uuid,+ option_id: Uuid,+ ) -> Result<(), PropertiesErr> {+ self.owned_modifiable_definition(property_definition_id, user_id, team_id)+ .await?;++ let option = self+ .repository+ .get_property_option(option_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::OptionNotFound)?;++ if option.property_definition_id != property_definition_id {+ return Err(PropertiesErr::OptionNotFound);+ }++ let deleted = self+ .repository+ .delete_property_option(property_definition_id, option_id)+ .await+ .map_err(anyhow::Error::from)?;++ if deleted {+ tracing::info!("successfully deleted property option");+ Ok(())+ } else {+ Err(PropertiesErr::OptionNotFound)+ }+ }++ #[tracing::instrument(skip(self), err)]+ async fn list_tag_sets(+ &self,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> Result<Vec<TagSet>, PropertiesErr> {+ let mut sets = Vec::new();++ let user_definition = self+ .repository+ .get_tag_definition(PropertyDefinitionOwner::User(user_id))+ .await+ .map_err(anyhow::Error::from)?;+ sets.push(self.build_tag_set(TagScope::User, user_definition).await?);++ if let Some(team_id) = team_id {+ let team_definition = self+ .repository+ .get_tag_definition(PropertyDefinitionOwner::Team(team_id))+ .await+ .map_err(anyhow::Error::from)?;+ sets.push(self.build_tag_set(TagScope::Team, team_definition).await?);+ }++ Ok(sets)+ }++ #[tracing::instrument(skip(self), err)]+ async fn ensure_tag_set(+ &self,+ owner: PropertyDefinitionOwner<'_>,+ ) -> Result<TagSet, PropertiesErr> {+ let scope = match owner {+ PropertyDefinitionOwner::User(_) => TagScope::User,+ PropertyDefinitionOwner::Team(_) => TagScope::Team,+ };++ let definition = self+ .repository+ .get_or_create_tag_definition(owner)+ .await+ .map_err(anyhow::Error::from)?;++ self.build_tag_set(scope, Some(definition)).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_entity_properties_with_definitions(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Vec<EntityPropertyWithDefinition>, PropertiesErr> {+ Ok(self+ .repository+ .get_entity_properties_with_definitions(entity_id, entity_type)+ .await+ .map_err(anyhow::Error::from)?)+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_entity_metadata_properties(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Option<Vec<EntityPropertyWithDefinition>>, PropertiesErr> {+ let properties = match entity_type {+ EntityType::Document | EntityType::Task => self+ .repository+ .get_document_metadata(entity_id)+ .await+ .map_err(anyhow::Error::from)?+ .map(|meta| metadata::document_metadata_properties(meta, entity_type)),+ EntityType::Thread => {+ let Ok(thread_id) = Uuid::parse_str(entity_id) else {+ tracing::error!(entity_id = %entity_id, "invalid thread UUID");+ return Ok(None);+ };+ self.repository+ .get_thread_metadata(thread_id)+ .await+ .map_err(anyhow::Error::from)?+ .map(metadata::thread_metadata_properties)+ }+ EntityType::Project => self+ .repository+ .get_project_metadata(entity_id)+ .await+ .map_err(anyhow::Error::from)?+ .map(metadata::project_metadata_properties),+ _ => {+ tracing::debug!(+ entity_type = ?entity_type,+ "no metadata properties available for this entity type"+ );+ Some(Vec::new())+ }+ };++ Ok(properties)+ }++ #[tracing::instrument(skip(self, entity_refs, property_ids), fields(entity_count = entity_refs.len(), property_count = property_ids.len()), err)]+ async fn get_bulk_entity_properties(+ &self,+ entity_refs: Vec<EntityReference>,+ property_ids: Vec<Uuid>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, PropertiesErr>+ {+ // An empty property_ids means "fetch all properties"; otherwise only+ // the requested definitions are returned.+ let result = if property_ids.is_empty() {+ self.repository+ .get_entity_properties_batch(entity_refs)+ .await+ .map_err(anyhow::Error::from)?+ } else {+ self.repository+ .get_entity_properties_batch_filtered(entity_refs, property_ids, None)+ .await+ .map_err(anyhow::Error::from)?+ };++ Ok(result)+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_entity_properties(+ &self,+ entity_reference: &EntityReference,+ ) -> Result<(), PropertiesErr> {+ Ok(self+ .repository+ .delete_entity_properties(entity_reference)+ .await+ .map_err(anyhow::Error::from)?)+ }++ #[tracing::instrument(skip(self), fields(entity_property_id = %entity_property_id, user_id = %user_id), err)]+ async fn delete_entity_property(+ &self,+ entity_property_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ ) -> Result<(), PropertiesErr> {+ let property_info = self+ .repository+ .lookup_entity_property(entity_property_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::EntityPropertyNotFound)?;++ tracing::debug!(+ entity_id = %property_info.entity_id,+ entity_type = ?property_info.entity_type,+ property_definition_id = %property_info.property_definition_id,+ "fetched entity property info"+ );++ // Check if this property is required for the entity type (e.g., Task properties)+ if SystemPropertyKey::is_required_for_entity(+ property_info.property_definition_id,+ property_info.entity_type,+ ) {+ tracing::warn!(+ entity_type = ?property_info.entity_type,+ property_definition_id = %property_info.property_definition_id,+ "attempted to remove required property"+ );+ return Err(PropertiesErr::RequiredProperty);+ }++ let permission_service = self+ .permission_service+ .as_ref()+ .ok_or(PropertiesErr::PermissionDenied)?;+ permission_service+ .check_entity_edit_permission(+ user_id,+ &property_info.entity_id,+ property_info.entity_type,+ )+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)?;++ self.repository+ .delete_entity_property(entity_property_id)+ .await+ .map_err(anyhow::Error::from)?;++ tracing::info!("successfully removed entity property");++ Ok(())+ }++ #[tracing::instrument(skip(self), err)]+ async fn check_entity_view_permission(+ &self,+ user_id: Option<&MacroUserIdStr<'_>>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<(), PropertiesErr> {+ let permission_service = self+ .permission_service+ .as_ref()+ .ok_or(PropertiesErr::PermissionServiceNotConfigured)?;++ permission_service+ .check_entity_view_permission(user_id, entity_id, entity_type)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)+ }++ #[tracing::instrument(skip(self), err)]+ async fn check_entity_edit_permission(+ &self,+ user_id: &MacroUserIdStr<'_>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<(), PropertiesErr> {+ let permission_service = self+ .permission_service+ .as_ref()+ .ok_or(PropertiesErr::PermissionServiceNotConfigured)?;++ permission_service+ .check_entity_edit_permission(user_id, entity_id, entity_type)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)+ }+}++/// Validate the color rules for a property option: colors are only supported+/// on tag options (as hex strings), and tag options must end up with a color.+/// `provided_color` is the color supplied in the request; `effective_color` is+/// the color the option would have after the operation.+fn validate_option_color(+ data_type: &DataType,+ provided_color: Option<&str>,+ effective_color: Option<&str>,+) -> Result<(), PropertiesErr> {+ if provided_color.is_some() && *data_type != DataType::Tag {+ return Err(PropertiesErr::Validation(+ "color is only supported on tag options".to_string(),+ ));+ }+ if let Some(color) = provided_color+ && !is_valid_hex_color(color)+ {+ return Err(PropertiesErr::Validation(+ "color must be a hex string like #RRGGBB".to_string(),+ ));+ }+ if *data_type == DataType::Tag && effective_color.is_none() {+ return Err(PropertiesErr::Validation(+ "tag options require a color".to_string(),+ ));+ }+ Ok(())+}++/// Build a [`PropertyOption`] for creation. IDs and timestamps are placeholders+/// replaced by the database on insert.+fn build_property_option(display_order: i32, value: PropertyOptionValue) -> PropertyOption {+ PropertyOption {+ id: Uuid::nil(), // Temporary ID, will be replaced by DB+ property_definition_id: Uuid::nil(), // Temporary ID, will be replaced by DB+ display_order,+ value,+ color: None,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ }}diff --git a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rsindex 5b36aa0f09..5dd9dd262b 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs@@ -2,17 +2,16 @@use std::collections::HashSet;-use futures::future::join_all;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use models_properties::EntityType;use models_properties::api::requests::SetPropertyValue;use models_properties::service::property_value::PropertyValue;-use notification::domain::models::SendNotificationRequestBuilder;use system_properties::SystemPropertyKey;use uuid::Uuid;use crate::domain::error::PropertiesErr;+use crate::domain::model::TaskAssignedNotification;use crate::domain::ports::{NotificationService, PermissionService, PropertiesRepo};use crate::domain::service::PropertiesService;use crate::domain::service_impl::PropertiesServiceImpl;@@ -98,7 +97,7 @@ where&self,entity_id: &str,value: Option<SetPropertyValue>,- assigned_by_user_id: &str,+ assigned_by_user_id: &MacroUserIdStr<'_>,) -> Result<(), PropertiesErr> {let Some(SetPropertyValue::MultiEntityReference { references }) = &value else {if value.is_some() {@@ -133,7 +132,7 @@ where&self,task_id: Uuid,assignee_ids: &[MacroUserIdStr<'_>],- assigned_by_user_id: &str,+ assigned_by_user_id: &MacroUserIdStr<'_>,) -> Result<(), PropertiesErr> {if assignee_ids.is_empty() {return Ok(());@@ -168,7 +167,8 @@ wherelet recipient_ids: Vec<MacroUserIdStr<'_>> = assignee_ids.iter().filter(|id| {- !current_assignee_ids.contains(id.as_ref()) && id.as_ref() != assigned_by_user_id+ !current_assignee_ids.contains(id.as_ref())+ && id.as_ref() != assigned_by_user_id.as_ref()}).map(|id| id.copied()).collect();@@ -178,74 +178,18 @@ wherereturn Ok(());}- let task_name = self- .repository- .get_document_name(&task_id.to_string())+ let assigned_by = assigned_by_user_id.copied();++ notification_service+ .send_task_assigned(TaskAssignedNotification {+ task_id,+ assigned_by,+ recipient_ids,+ }).await.map_err(anyhow::Error::from).map_err(PropertiesErr::Repo)?;- let assigned_by =- macro_user_id::user_id::MacroUserIdStr::parse_from_str(assigned_by_user_id)- .map_err(|e| PropertiesErr::Validation(format!("Invalid user ID format: {}", e)))?- .into_owned();-- let notification_entity =- model_entity::EntityType::Document.with_entity_string(task_id.to_string());-- let sender_profile_picture_url = self- .repository- .get_user_profile_picture(assigned_by_user_id)- .await- .ok()- .flatten();-- let notification_futures: Vec<_> = recipient_ids- .iter()- .map(|recipient_id| {- let metadata = model_notifications::TaskAssignedMetadata {- task_id: task_id.to_string(),- task_name: task_name.clone(),- sub_type: Some(model_notifications::NotificationDocumentSubType::Task),- assigned_by: assigned_by.clone(),- sender_profile_picture_url: sender_profile_picture_url.clone(),- };-- let request = SendNotificationRequestBuilder {- notification_entity: notification_entity.clone(),- secondary_notification_entity: None,- notification: metadata,- sender_id: Some(assigned_by.clone()),- recipient_ids: HashSet::from([recipient_id.copied()]),- }- .into_request()- .with_apns()- .with_conn_gateway();-- let recipient_id_for_log = recipient_id.clone();- async move {- let send_result = notification_service.send_notification(request).await;- match send_result {- Ok(notification_id) => {- tracing::debug!(- recipient_id = %recipient_id_for_log,- notification_id = %notification_id,- "sent task assignment notification"- );- }- Err(_e) => {- tracing::error!(- recipient_id = %recipient_id_for_log,- "failed to send task assignment notification"- );- }- }- }- })- .collect();-- join_all(notification_futures).await;-Ok(())}diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rsindex c970ac5f04..fbcba0a243 100644--- a/rust/cloud-storage/properties/src/domain/test.rs+++ b/rust/cloud-storage/properties/src/domain/test.rs@@ -483,7 +483,6 @@ struct NotificationTestCase {assigned_by: String,assignees: Vec<MacroUserIdStr<'static>>,existing_assignees: Vec<String>,- task_name: Option<String>,expected_notification_count: usize,expected_recipient_ids: Option<Vec<String>>,notification_service_available: bool,@@ -497,7 +496,6 @@ async fn check_notifications(test_case: NotificationTestCase) {let assigned_by = test_case.assigned_by.clone();let assignees = test_case.assignees.clone();let existing_assignees = test_case.existing_assignees.clone();- let task_name = test_case.task_name.clone();// Mock: get current assigneesrepo.expect_get_entity_property_value()@@ -525,28 +523,28 @@ async fn check_notifications(test_case: NotificationTestCase) {}});- // Mock: get task name and profile picture (only if we expect notifications)- if test_case.expected_notification_count > 0 {- let task_id_clone = task_id;- let task_name_result = task_name.clone();- repo.expect_get_document_name()- .withf(move |id| id == task_id_clone.to_string())- .returning(move |_| {- let name = task_name_result.clone();- Box::pin(async move { Ok(name) })- });- repo.expect_get_user_profile_picture()- .returning(|_| Box::pin(async { Ok(None) }));- }-- // Mock: send notifications+ // Mock: send notifications (one batched call covering all new assignees)if test_case.notification_service_available && test_case.expected_notification_count > 0 {let expected_count = test_case.expected_notification_count;- let _expected_recipients = test_case.expected_recipient_ids.clone();+ let expected_recipients = test_case.expected_recipient_ids.clone();+ let expected_assigned_by = assigned_by.clone();notif_service- .expect_send_notification()- .times(expected_count)- .returning(|_| Box::pin(async { Ok(Uuid::new_v4()) }));+ .expect_send_task_assigned()+ .times(1)+ .withf(move |notification| {+ notification.task_id == task_id+ && notification.assigned_by.as_ref() == expected_assigned_by.as_str()+ && notification.recipient_ids.len() == expected_count+ && expected_recipients.as_ref().is_none_or(|expected| {+ expected.iter().all(|id| {+ notification+ .recipient_ids+ .iter()+ .any(|r| r.as_ref() == id.as_str())+ })+ })+ })+ .returning(|_| Box::pin(async { Ok(()) }));}let service = if test_case.notification_service_available {@@ -559,6 +557,7 @@ async fn check_notifications(test_case: NotificationTestCase) {)};+ let assigned_by = MacroUserIdStr::parse_from_str(&assigned_by).unwrap();service.handle_task_assignee_notifications(task_id, &assignees, &assigned_by).await@@ -576,7 +575,6 @@ async fn test_handle_task_assignee_notifications_sends_to_new_assignees_only() {MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(), // existing, should not get notification],existing_assignees: vec!["macro|[email protected]".to_string()],- task_name: Some("Test Task".to_string()),expected_notification_count: 2, // user1 and user2, but not user3 (existing) or assignerexpected_recipient_ids: None,notification_service_available: true,@@ -594,7 +592,6 @@ async fn test_handle_task_assignee_notifications_filters_out_assigner() {MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),],existing_assignees: vec![],- task_name: Some("Test Task".to_string()),expected_notification_count: 1, // only user1, not assignerexpected_recipient_ids: Some(vec!["macro|[email protected]".to_string()]),notification_service_available: true,@@ -609,7 +606,6 @@ async fn test_handle_task_assignee_notifications_no_new_assignees() {assigned_by: "macro|[email protected]".to_string(),assignees: vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],existing_assignees: vec!["macro|[email protected]".to_string()],- task_name: None, // Should not call get_entity_nameexpected_notification_count: 0, // no new assigneesexpected_recipient_ids: None,notification_service_available: true,@@ -621,10 +617,9 @@ async fn test_handle_task_assignee_notifications_no_new_assignees() {async fn test_handle_task_assignee_notifications_no_service() {check_notifications(NotificationTestCase {task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),- assigned_by: "assigner".to_string(),+ assigned_by: "macro|[email protected]".to_string(),assignees: vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],existing_assignees: vec![],- task_name: None, // Should not call get_entity_name when no serviceexpected_notification_count: 0,expected_recipient_ids: None,notification_service_available: false,@@ -636,10 +631,9 @@ async fn test_handle_task_assignee_notifications_no_service() {async fn test_handle_task_assignee_notifications_empty_assignees() {check_notifications(NotificationTestCase {task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),- assigned_by: "assigner".to_string(),+ assigned_by: "macro|[email protected]".to_string(),assignees: vec![],existing_assignees: vec![],- task_name: None, // Should not call get_entity_nameexpected_notification_count: 0,expected_recipient_ids: None,notification_service_available: true,@@ -647,21 +641,6 @@ async fn test_handle_task_assignee_notifications_empty_assignees() {.await;}-#[tokio::test]-async fn test_handle_task_assignee_notifications_task_name_none() {- check_notifications(NotificationTestCase {- task_id: Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc),- assigned_by: "macro|[email protected]".to_string(),- assignees: vec![MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()],- existing_assignees: vec![],- task_name: None, // task doesn't exist yet- expected_notification_count: 1,- expected_recipient_ids: None,- notification_service_available: true,- })- .await;-}-// ============================================================================// handle_task_assignees_property integration tests// ============================================================================@@ -697,14 +676,6 @@ async fn test_handle_task_assignees_property_calls_both_handlers() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Ok(None) }));- // Mock: get task name- repo.expect_get_document_name()- .returning(|_| Box::pin(async { Ok(Some("Test Task".to_string())) }));-- // Mock: get sender profile picture- repo.expect_get_user_profile_picture()- .returning(|_| Box::pin(async { Ok(None) }));-// Mock: permissions should be granted to all assigneeslet entity_id_clone = entity_id.clone();perm_service@@ -713,14 +684,16 @@ async fn test_handle_task_assignees_property_calls_both_handlers() {.withf(move |user_ids, tid| user_ids.len() == 2 && tid == entity_id_clone).returning(|_, _| Box::pin(async { Ok(()) }));- // Mock: notifications should be sent+ // Mock: notifications should be sent to both new assignees in one batchnotif_service- .expect_send_notification()- .times(2) // user1 and user2- .returning(|_| Box::pin(async { Ok(Uuid::new_v4()) }));+ .expect_send_task_assigned()+ .times(1)+ .withf(|notification| notification.recipient_ids.len() == 2)+ .returning(|_| Box::pin(async { Ok(()) }));let service = PropertiesServiceImpl::new(repo, Some(perm_service), Some(notif_service));+ let assigned_by = MacroUserIdStr::parse_from_str(&assigned_by).unwrap();service.handle_task_assignees_property(&entity_id, value, &assigned_by).await@@ -740,7 +713,11 @@ async fn test_handle_task_assignees_property_clearing_assignees() {// Should return Ok without calling any handlersservice- .handle_task_assignees_property(&entity_id, None, "assigner")+ .handle_task_assignees_property(+ &entity_id,+ None,+ &MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ ).await.unwrap();}@@ -749,6 +726,10 @@ async fn test_handle_task_assignees_property_clearing_assignees() {// add/remove_entity_property_option unit tests// ============================================================================+fn caller_user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}+fn multi_select_definition(id: Uuid, is_multi_select: bool) -> PropertyDefinition {PropertyDefinition {id,@@ -791,7 +772,13 @@ async fn test_add_entity_property_option_happy_path() {);service- .add_entity_property_option("user1", "doc1", EntityType::Document, def_id, option_id)+ .add_entity_property_option(+ &caller_user_id(),+ "doc1",+ EntityType::Document,+ def_id,+ option_id,+ ).await.unwrap();}@@ -813,7 +800,7 @@ async fn test_add_entity_property_option_rejects_single_select() {let err = service.add_entity_property_option(- "user1",+ &caller_user_id(),"doc1",EntityType::Document,def_id,@@ -848,7 +835,7 @@ async fn test_add_entity_property_option_rejects_invalid_option() {let err = service.add_entity_property_option(- "user1",+ &caller_user_id(),"doc1",EntityType::Document,def_id,@@ -874,7 +861,7 @@ async fn test_add_entity_property_option_no_permission_service() {let err = service.add_entity_property_option(- "user1",+ &caller_user_id(),"doc1",EntityType::Document,Uuid::from_u128(0xA1),@@ -911,7 +898,13 @@ async fn test_remove_entity_property_option_happy_path() {);service- .remove_entity_property_option("user1", "doc1", EntityType::Document, def_id, option_id)+ .remove_entity_property_option(+ &caller_user_id(),+ "doc1",+ EntityType::Document,+ def_id,+ option_id,+ ).await.unwrap();}diff --git a/rust/cloud-storage/properties/src/inbound.rs b/rust/cloud-storage/properties/src/inbound.rsindex aafe2c65cb..968f804801 100644--- a/rust/cloud-storage/properties/src/inbound.rs+++ b/rust/cloud-storage/properties/src/inbound.rs@@ -1,2 +1,4 @@+#[cfg(feature = "inbound")]+pub mod axum_router;#[cfg(feature = "ai_tools")]pub mod toolset;diff --git a/rust/cloud-storage/properties/src/inbound/axum_router.rs b/rust/cloud-storage/properties/src/inbound/axum_router.rsnew file mode 100644index 0000000000..f0c2021492--- /dev/null+++ b/rust/cloud-storage/properties/src/inbound/axum_router.rs@@ -0,0 +1,176 @@+//! Axum inbound adapter for the properties domain.+//!+//! Exposes the property definition / option / tag / entity property endpoints+//! as a [`Router`] generic over the [`PropertiesService`] implementation and+//! the entity access service (used for team-membership extraction).+//!+//! The composition root supplies the concrete services via+//! [`PropertiesRouterState`] plus the authentication middleware layer applied+//! to the routes that require an authenticated user.++pub mod definitions;+pub mod entities;+pub mod options;+pub mod tags;++use std::convert::Infallible;+use std::sync::Arc;++use axum::{+ Router,+ extract::{FromRef, Request},+ http::StatusCode,+ response::IntoResponse,+ routing::{Route, delete, get, patch, post, put},+};+use entity_access::domain::models::MemberTeamRole;+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractor;+use tower::{Layer, Service};+use uuid::Uuid;++use crate::domain::error::PropertiesErr;+use crate::domain::service::PropertiesService;++/// State for the properties router.+pub struct PropertiesRouterState<S, A> {+ properties_service: Arc<S>,+ entity_access_service: Arc<A>,+}++impl<S, A> Clone for PropertiesRouterState<S, A> {+ fn clone(&self) -> Self {+ Self {+ properties_service: self.properties_service.clone(),+ entity_access_service: self.entity_access_service.clone(),+ }+ }+}++impl<S: PropertiesService, A: EntityAccessService> PropertiesRouterState<S, A> {+ /// Create a router state wrapping the properties service and entity access service.+ pub fn new(properties_service: Arc<S>, entity_access_service: Arc<A>) -> Self {+ Self {+ properties_service,+ entity_access_service,+ }+ }+}++/// Lets the entity access extractors pull the access service out of the state.+impl<S, A> FromRef<PropertiesRouterState<S, A>> for Arc<A> {+ fn from_ref(state: &PropertiesRouterState<S, A>) -> Self {+ state.entity_access_service.clone()+ }+}++/// Team extractor used by property definition endpoints. Resolves the caller's team+/// membership without failing when they have no team. Member role is required, matching+/// the model where anyone on a team can manage that team's properties.+pub type PropertyTeamExtractor<A> = OptionalMacroUserTeamExtractor<MemberTeamRole, A>;++/// The team the caller belongs to, if any. A `None` team scopes the caller to their own+/// user properties.+pub fn caller_team_id<A>(team: &PropertyTeamExtractor<A>) -> Option<Uuid> {+ team.entity_access_receipt+ .as_ref()+ .and_then(|receipt| Uuid::parse_str(&receipt.entity().entity_id).ok())+}++/// Map a domain [`PropertiesErr`] to the HTTP status code it represents.+pub fn properties_err_status(e: &PropertiesErr) -> StatusCode {+ match e {+ PropertiesErr::Validation(_) => StatusCode::BAD_REQUEST,+ PropertiesErr::NotFound+ | PropertiesErr::OptionNotFound+ | PropertiesErr::EntityPropertyNotFound => StatusCode::NOT_FOUND,+ PropertiesErr::DuplicateOptionValue => StatusCode::CONFLICT,+ PropertiesErr::PermissionDenied+ | PropertiesErr::SystemPropertyNotModifiable+ | PropertiesErr::RequiredProperty => StatusCode::FORBIDDEN,+ PropertiesErr::Repo(_) | PropertiesErr::PermissionServiceNotConfigured => {+ StatusCode::INTERNAL_SERVER_ERROR+ }+ }+}++/// Creates the properties router.+///+/// `ensure_user_exists` is the authentication middleware layer applied to every+/// route that requires an authenticated user (all except the anonymous-capable+/// entity property GET and the internal endpoints).+pub fn router<S, A, L>(ensure_user_exists: L) -> Router<PropertiesRouterState<S, A>>+where+ S: PropertiesService,+ A: EntityAccessService,+ L: Layer<Route> + Clone + Send + Sync + 'static,+ L::Service: Service<Request> + Clone + Send + Sync + 'static,+ <L::Service as Service<Request>>::Response: IntoResponse + 'static,+ <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,+ <L::Service as Service<Request>>::Future: Send + 'static,+{+ Router::new()+ // Property Definition Management - requires authentication+ .route(+ "/definitions",+ get(definitions::list_properties::<S, A>)+ .post(definitions::create_property_definition::<S, A>)+ .layer(ensure_user_exists.clone()),+ )+ .route(+ "/definitions/{definition_id}",+ delete(definitions::delete_property_definition::<S, A>)+ .layer(ensure_user_exists.clone()),+ )+ // Property Options Management - requires authentication+ .route(+ "/definitions/{definition_id}/options",+ get(options::get_property_options::<S, A>)+ .post(options::add_property_option::<S, A>)+ .layer(ensure_user_exists.clone()),+ )+ .route(+ "/definitions/{definition_id}/options/{option_id}",+ delete(options::delete_property_option::<S, A>)+ .patch(options::update_property_option::<S, A>)+ .layer(ensure_user_exists.clone()),+ )+ .route(+ "/tags",+ get(tags::list_tags::<S, A>)+ .post(tags::ensure_tag_set::<S, A>)+ .layer(ensure_user_exists.clone()),+ )+ // Entity Property Operations+ // GET allows anonymous access for public entities+ .route(+ "/entities/{entity_type}/{entity_id}",+ get(entities::get_entity_properties::<S, A>),+ )+ // Bulk entity properties - requires authentication+ .route(+ "/entities/bulk",+ post(entities::get_bulk_entity_properties::<S, A>).layer(ensure_user_exists.clone()),+ )+ // PUT/DELETE require authentication+ .route(+ "/entities/{entity_type}/{entity_id}/{property_id}",+ put(entities::set_entity_property::<S, A>).layer(ensure_user_exists.clone()),+ )+ // Atomic single-option delta on a multi-select value (merges concurrent edits)+ .route(+ "/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",+ post(entities::add_entity_property_option::<S, A>)+ .delete(entities::remove_entity_property_option::<S, A>)+ .layer(ensure_user_exists.clone()),+ )+ .route(+ "/entity_properties/{entity_property_id}",+ delete(entities::delete_entity_property::<S, A>).layer(ensure_user_exists.clone()),+ )+ // Status shortcut - requires authentication+ .route(+ "/entities/{entity_type}/{entity_id}/status/complete",+ patch(entities::set_property_status_complete::<S, A>).layer(ensure_user_exists),+ )+}diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/definitions.rs b/rust/cloud-storage/properties/src/inbound/axum_router/definitions.rsnew file mode 100644index 0000000000..0787d7dbf9--- /dev/null+++ b/rust/cloud-storage/properties/src/inbound/axum_router/definitions.rs@@ -0,0 +1,299 @@+//! Property definition endpoints.++use axum::{+ Json,+ extract::{Path, Query, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use entity_access::domain::ports::EntityAccessService;+use model::user::axum_extractor::MacroUserExtractor;+use models_properties::EntityType;+use models_properties::api::{CreatePropertyDefinitionRequest, CreatePropertyScope};+use models_properties::service::property_definition::PropertyDefinition;+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;+use serde::{Deserialize, Serialize};+use thiserror::Error;+use utoipa::ToSchema;+use uuid::Uuid;++use super::{PropertiesRouterState, PropertyTeamExtractor, caller_team_id, properties_err_status};+use crate::domain::error::PropertiesErr;+use crate::domain::model::PropertyDefinitionOwner;+use crate::domain::service::PropertiesService;++#[derive(Debug, Error)]+pub enum ListPropertiesErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for ListPropertiesErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ ListPropertiesErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "ListPropertiesErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Scope filter for property queries+#[derive(Debug, Deserialize, ToSchema, PartialEq)]+#[serde(rename_all = "snake_case")]+pub enum PropertyScope {+ /// User-scoped properties only+ User,+ /// The caller's team properties only+ Team,+ /// System properties only+ System,+ /// User, team, and system properties+ All,+}++/// Query parameters for listing properties+#[derive(Debug, Deserialize, ToSchema)]+pub struct ListPropertiesQuery {+ /// Scope filter for properties+ pub scope: PropertyScope,+ /// Whether to include property options in the response+ #[serde(default)]+ pub include_options: bool,+ /// Filter properties applicable to a specific entity type.+ /// When provided, excludes properties that cannot be attached to this entity type+ /// (e.g., Parent Task and Subtasks are excluded for non-task entities).+ pub for_entity_type: Option<EntityType>,+}++/// Response for property definition with optional property options+#[derive(Debug, Serialize, ToSchema)]+#[serde(untagged)]+pub enum PropertyDefinitionResponse {+ Simple(PropertyDefinition),+ WithOptions(PropertyDefinitionWithOptions),+}++/// List property definitions with flexible filtering+#[utoipa::path(+ get,+ path = "/properties/definitions",+ params(+ ("scope" = PropertyScope, Query, description = "Filter by scope: 'user', 'team', 'system', or 'all'"),+ ("include_options" = Option<bool>, Query, description = "Whether to include property options in the response"),+ ("for_entity_type" = Option<EntityType>, Query, description = "Filter properties applicable to a specific entity type")+ ),+ responses(+ (status = 200, description = "Properties retrieved successfully", body = Vec<PropertyDefinitionResponse>),+ (status = 400, description = "Invalid request"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Properties"+)]+#[tracing::instrument(skip(state, user, team), err)]+pub async fn list_properties<S: PropertiesService, A: EntityAccessService>(+ Query(query): Query<ListPropertiesQuery>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,+) -> Result<Json<Vec<PropertyDefinitionResponse>>, ListPropertiesErr> {+ let callers_team = caller_team_id(&team);++ // Determine query parameters based on scope. Team and user ids are derived from the+ // authenticated caller, never from the request.+ let (team_id, user_id_opt, include_system) = match query.scope {+ PropertyScope::User => (None, Some(&user), false),+ PropertyScope::Team => (callers_team, None, false),+ PropertyScope::System => (None, None, true),+ PropertyScope::All => (callers_team, Some(&user), true),+ };++ tracing::info!(+ team_id = ?team_id,+ scope = ?query.scope,+ include_system = include_system,+ for_entity_type = ?query.for_entity_type,+ user_id = %user,+ "listing properties"+ );++ let response = if query.include_options {+ state+ .properties_service+ .list_property_definitions_with_options(+ team_id,+ user_id_opt,+ include_system,+ query.for_entity_type,+ )+ .await?+ .into_iter()+ .map(PropertyDefinitionResponse::WithOptions)+ .collect::<Vec<_>>()+ } else {+ state+ .properties_service+ .list_property_definitions(team_id, user_id_opt, include_system, query.for_entity_type)+ .await?+ .into_iter()+ .map(PropertyDefinitionResponse::Simple)+ .collect::<Vec<_>>()+ };++ tracing::info!(+ properties_count = response.len(),+ team_id = ?team_id,+ scope = ?query.scope,+ user_id = %user,+ "successfully retrieved properties"+ );++ Ok(Json(response))+}++#[derive(Debug, Error)]+pub enum CreatePropertyDefinitionErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+ #[error("You must be on a team to create a team property")]+ TeamMembershipRequired,+}++impl IntoResponse for CreatePropertyDefinitionErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ CreatePropertyDefinitionErr::Properties(e) => properties_err_status(e),+ CreatePropertyDefinitionErr::TeamMembershipRequired => StatusCode::FORBIDDEN,+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "CreatePropertyDefinitionErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Create a new property definition+#[utoipa::path(+ post,+ path = "/properties/definitions",+ request_body = CreatePropertyDefinitionRequest,+ responses(+ (status = 201, description = "Property definition created successfully", body = PropertyDefinition),+ (status = 400, description = "Invalid request"),+ (status = 403, description = "Team membership required for team scope"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(state, user, team), err)]+pub async fn create_property_definition<S: PropertiesService, A: EntityAccessService>(+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,+ Json(request): Json<CreatePropertyDefinitionRequest>,+) -> Result<(StatusCode, Json<PropertyDefinition>), CreatePropertyDefinitionErr> {+ // Derive the owner from the authenticated caller - clients never supply owner ids.+ let owner = match request.scope {+ CreatePropertyScope::User => PropertyDefinitionOwner::User(&user),+ CreatePropertyScope::Team => {+ let team_id =+ caller_team_id(&team).ok_or(CreatePropertyDefinitionErr::TeamMembershipRequired)?;+ PropertyDefinitionOwner::Team(team_id)+ }+ };++ tracing::info!(+ owner = ?owner,+ scope = ?request.scope,+ "creating property definition"+ );++ let property = state+ .properties_service+ .create_property_definition(owner, &request)+ .await?;++ Ok((StatusCode::CREATED, Json(property)))+}++#[derive(Debug, Error)]+pub enum DeletePropertyDefinitionError {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for DeletePropertyDefinitionError {+ fn into_response(self) -> Response {+ let status_code = match &self {+ DeletePropertyDefinitionError::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "DeletePropertyDefinitionError",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Delete a property definition+#[utoipa::path(+ delete,+ path = "/properties/definitions/{definition_id}",+ params(+ ("definition_id" = Uuid, Path, description = "Property definition ID")+ ),+ responses(+ (status = 204, description = "Property definition deleted successfully"),+ (status = 400, description = "Invalid property ID"),+ (status = 403, description = "Cannot modify system properties"),+ (status = 404, description = "Property definition not found"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Properties"+)]+#[tracing::instrument(skip(state, user, team), err)]+pub async fn delete_property_definition<S: PropertiesService, A: EntityAccessService>(+ Path(property_uuid): Path<Uuid>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,+) -> Result<Response, DeletePropertyDefinitionError> {+ tracing::info!("deleting property definition");++ state+ .properties_service+ .delete_property_definition(property_uuid, &user, caller_team_id(&team))+ .await?;++ tracing::info!("successfully deleted property definition");++ Ok(StatusCode::NO_CONTENT.into_response())+}diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/entities.rs b/rust/cloud-storage/properties/src/inbound/axum_router/entities.rsnew file mode 100644index 0000000000..29d1499ee1--- /dev/null+++ b/rust/cloud-storage/properties/src/inbound/axum_router/entities.rs@@ -0,0 +1,753 @@+//! Entity property endpoints.++use std::collections::HashMap;++use axum::{+ Json,+ extract::{Path, Query, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use entity_access::domain::ports::EntityAccessService;+use macro_user_id::user_id::MacroUserIdStr;+use model::user::axum_extractor::{MacroUserExtractor, OptionalMacroUserExtractor};+use models_properties::api::SetPropertyValue;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::{DataType, EntityReference, EntityType, PropertyOwner};+use serde::{Deserialize, Serialize};+use thiserror::Error;+use utoipa::ToSchema;+use uuid::Uuid;++use super::{PropertiesRouterState, properties_err_status};+use crate::domain::error::PropertiesErr;+use crate::domain::service::PropertiesService;++// Re-export EntityQueryParams from models_properties for convenience+pub use models_properties::api::EntityQueryParams;++/// Response for document/entity properties endpoint.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct EntityPropertiesResponse {+ pub entity_id: String,+ pub properties: Vec<EntityPropertyWithDefinition>,+}++/// Type-safe request for setting entity property values.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SetEntityPropertyRequest {+ /// The value to set for the property. If None, the property is attached to the entity without a value.+ #[serde(default)]+ pub value: Option<SetPropertyValue>,+}++/// Request for getting properties for multiple entities in bulk+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct BulkEntityPropertiesRequest {+ /// Array of entity references (entity_id and entity_type pairs)+ pub entities: Vec<EntityReference>,+ /// Optional: only return properties with these definition IDs. If empty, returns all.+ #[serde(default)]+ pub property_ids: Vec<Uuid>,+}++/// Maximum number of entities allowed in a single bulk properties request.+const MAX_BULK_ENTITIES: usize = 200;+/// Maximum number of property IDs allowed in a single bulk properties request.+const MAX_BULK_PROPERTY_IDS: usize = 200;++/// Drops tag-typed properties the caller may not see. A user-owned tag set (personal labels)+/// is visible only to its owner, so personal tags stay private even on a shared entity.+/// Team- and system-owned tags are the shared vocabulary and are left in place. Non-tag+/// properties are unaffected.+pub fn retain_caller_visible_tags(+ properties: &mut Vec<EntityPropertyWithDefinition>,+ caller_user_id: Option<&MacroUserIdStr<'_>>,+) {+ properties.retain(|property| {+ if property.definition.data_type != DataType::Tag {+ return true;+ }+ match &property.definition.owner {+ PropertyOwner::User { user_id } => {+ caller_user_id.is_some_and(|caller| user_id == caller.as_ref())+ }+ PropertyOwner::Team { .. } | PropertyOwner::System => true,+ }+ });+}++#[derive(Debug, Error)]+pub enum GetEntityPropertiesErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),++ #[error("Entity not found")]+ MetadataNotFound,+}++impl IntoResponse for GetEntityPropertiesErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ GetEntityPropertiesErr::Properties(e) => properties_err_status(e),+ // Preserved behavior: a missing entity on the metadata path is a 500.+ GetEntityPropertiesErr::MetadataNotFound => StatusCode::INTERNAL_SERVER_ERROR,+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "GetEntityPropertiesErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Get all properties for an entity+#[utoipa::path(+ get,+ path = "/properties/entities/{entity_type}/{entity_id}",+ params(+ ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_id" = String, Path, description = "Entity ID"),+ ("include_metadata" = Option<bool>, Query, description = "Whether to include property metadata (default: false)")+ ),+ responses(+ (status = 200, description = "Entity properties retrieved successfully", body = EntityPropertiesResponse),+ (status = 400, description = "Invalid entity type"),+ (status = 403, description = "Forbidden - User does not have permission to view this entity"),+ (status = 404, description = "Entity not found"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Properties"+)]+#[tracing::instrument(skip(state, user), fields(entity_type = ?entity_type, include_metadata = query.include_metadata), err)]+pub async fn get_entity_properties<S: PropertiesService, A: EntityAccessService>(+ Path((entity_type, entity_id)): Path<(EntityType, String)>,+ Query(query): Query<EntityQueryParams>,+ State(state): State<PropertiesRouterState<S, A>>,+ // Optional: this route allows anonymous access for publicly shared entities.+ OptionalMacroUserExtractor {+ macro_user_id: user,+ ..+ }: OptionalMacroUserExtractor,+) -> Result<Json<EntityPropertiesResponse>, GetEntityPropertiesErr> {+ tracing::info!(+ entity_id = %entity_id,+ "retrieving entity properties"+ );++ // Note: This can fail if the entity is marked with "deletedAt"+ state+ .properties_service+ .check_entity_view_permission(user.as_ref(), &entity_id, entity_type)+ .await?;++ let (user_properties, metadata_properties) = if query.include_metadata {+ // Fetch user properties and metadata in parallel when metadata is requested+ let (user_properties_result, metadata_properties_result) = tokio::join!(+ state+ .properties_service+ .get_entity_properties_with_definitions(&entity_id, entity_type),+ state+ .properties_service+ .get_entity_metadata_properties(&entity_id, entity_type)+ );++ let user_properties = user_properties_result?;+ let metadata_properties =+ metadata_properties_result?.ok_or(GetEntityPropertiesErr::MetadataNotFound)?;++ (user_properties, metadata_properties)+ } else {+ // Only fetch user properties when metadata not requested - no parallel task needed+ tracing::debug!("skipping metadata properties due to include_metadata=false");+ let user_properties = state+ .properties_service+ .get_entity_properties_with_definitions(&entity_id, entity_type)+ .await?;++ (user_properties, vec![])+ };++ let mut all_properties = user_properties;+ all_properties.extend(metadata_properties);++ retain_caller_visible_tags(&mut all_properties, user.as_ref());++ let response = EntityPropertiesResponse {+ entity_id: entity_id.to_string(),+ properties: all_properties,+ };++ tracing::info!(+ entity_id = %entity_id,+ properties_count = response.properties.len(),+ "successfully retrieved entity properties"+ );++ Ok(Json(response))+}++#[derive(Debug, Error)]+pub enum GetBulkEntityPropertiesErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+ #[error("Entities array cannot be empty")]+ InvalidRequest,+ #[error("Cannot request more than {MAX_BULK_ENTITIES} entities at once")]+ TooManyEntities,+ #[error("Cannot request more than {MAX_BULK_PROPERTY_IDS} property IDs at once")]+ TooManyPropertyIds,+}++impl IntoResponse for GetBulkEntityPropertiesErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ GetBulkEntityPropertiesErr::Properties(e) => properties_err_status(e),+ GetBulkEntityPropertiesErr::InvalidRequest+ | GetBulkEntityPropertiesErr::TooManyEntities+ | GetBulkEntityPropertiesErr::TooManyPropertyIds => StatusCode::BAD_REQUEST,+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "GetBulkEntityPropertiesErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Rejects requests whose `entities` or `property_ids` arrays exceed the allowed maximums,+/// before any per-entity permission checks or DB calls are made.+fn validate_bulk_request_size(+ request: &BulkEntityPropertiesRequest,+) -> Result<(), GetBulkEntityPropertiesErr> {+ if request.entities.len() > MAX_BULK_ENTITIES {+ tracing::error!(+ entity_count = request.entities.len(),+ "too many entities in bulk request"+ );+ return Err(GetBulkEntityPropertiesErr::TooManyEntities);+ }+ if request.property_ids.len() > MAX_BULK_PROPERTY_IDS {+ tracing::error!(+ property_id_count = request.property_ids.len(),+ "too many property ids in bulk request"+ );+ return Err(GetBulkEntityPropertiesErr::TooManyPropertyIds);+ }+ Ok(())+}++/// Shared implementation for bulk entity properties retrieval+async fn get_bulk_entity_properties_impl<S: PropertiesService, A: EntityAccessService>(+ state: &PropertiesRouterState<S, A>,+ request: BulkEntityPropertiesRequest,+) -> Result<HashMap<String, EntityPropertiesResponse>, GetBulkEntityPropertiesErr> {+ if request.entities.is_empty() {+ tracing::error!("empty entities array in request");+ return Err(GetBulkEntityPropertiesErr::InvalidRequest);+ }+ validate_bulk_request_size(&request)?;++ tracing::info!("retrieving bulk entity properties");++ // An empty property_ids fetches all properties for the given entities.+ // Note: the public endpoint requires property_ids, but internal callers can+ // pass an empty vec to fetch all properties for the given entities.+ let bulk_properties = state+ .properties_service+ .get_bulk_entity_properties(request.entities, request.property_ids)+ .await?;++ let mut result: HashMap<String, EntityPropertiesResponse> = HashMap::new();++ for (key, properties_values) in bulk_properties {+ result.insert(+ key.entity_id.clone(),+ EntityPropertiesResponse {+ entity_id: key.entity_id,+ properties: properties_values,+ },+ );+ }++ tracing::info!(+ successful_entities = result.len(),+ "successfully retrieved bulk entity properties"+ );++ Ok(result)+}++/// Get properties for multiple entities in bulk (internal endpoint - service-to-service)+#[utoipa::path(+ post,+ path = "/internal/properties/entities/bulk",+ request_body = BulkEntityPropertiesRequest,+ responses(+ (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),+ (status = 400, description = "Invalid request body"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Internal"+)]+#[tracing::instrument(skip(state, request), fields(entity_count = request.entities.len()), err)]+pub async fn get_bulk_entity_properties_internal<S: PropertiesService, A: EntityAccessService>(+ State(state): State<PropertiesRouterState<S, A>>,+ Json(request): Json<BulkEntityPropertiesRequest>,+) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {+ get_bulk_entity_properties_impl(&state, request)+ .await+ .map(Json)+}++/// Get properties for multiple entities in bulk (public endpoint with user auth)+///+/// Only returns properties for entities the user has view permission for.+/// Entities without permission are silently omitted from the response.+#[utoipa::path(+ post,+ path = "/properties/entities/bulk",+ request_body = BulkEntityPropertiesRequest,+ responses(+ (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),+ (status = 400, description = "Invalid request body"),+ (status = 403, description = "Forbidden - User does not have permission"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Properties"+)]+#[tracing::instrument(skip(state, request, user), fields(entity_count = request.entities.len()), err)]+pub async fn get_bulk_entity_properties<S: PropertiesService, A: EntityAccessService>(+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ Json(request): Json<BulkEntityPropertiesRequest>,+) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {+ // Unlike the internal endpoint, the public endpoint requires explicit property IDs.+ // An empty property_ids means "no properties requested", so return early with empty result.+ if request.entities.is_empty() || request.property_ids.is_empty() {+ return Ok(Json(HashMap::new()));+ }+ validate_bulk_request_size(&request)?;++ // Filter to only entities the user has permission to view+ let mut permitted_entities = Vec::with_capacity(request.entities.len());+ for entity_ref in &request.entities {+ match state+ .properties_service+ .check_entity_view_permission(+ Some(&user),+ &entity_ref.entity_id,+ entity_ref.entity_type,+ )+ .await+ {+ Ok(()) => permitted_entities.push(entity_ref.clone()),+ Err(e) => {+ tracing::debug!(+ entity_id = %entity_ref.entity_id,+ entity_type = ?entity_ref.entity_type,+ error = ?e,+ "user lacks permission, skipping entity"+ );+ }+ }+ }++ tracing::info!(+ permitted = permitted_entities.len(),+ "filtered entities by permission"+ );++ if permitted_entities.is_empty() {+ return Ok(Json(HashMap::new()));+ }++ let filtered_request = BulkEntityPropertiesRequest {+ entities: permitted_entities,+ property_ids: request.property_ids.clone(),+ };++ let mut result = get_bulk_entity_properties_impl(&state, filtered_request).await?;+ for response in result.values_mut() {+ retain_caller_visible_tags(&mut response.properties, Some(&user));+ }+ Ok(Json(result))+}++#[derive(Debug, Error)]+pub enum SetEntityPropertyErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for SetEntityPropertyErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ SetEntityPropertyErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "SetEntityPropertyErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Set or update a property value for an entity, or attach a property without a value+#[utoipa::path(+ put,+ path = "/properties/entities/{entity_type}/{entity_id}/{property_id}",+ params(+ ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_id" = String, Path, description = "Entity ID"),+ ("property_id" = Uuid, Path, description = "Property ID")+ ),+ request_body = SetEntityPropertyRequest,+ responses(+ (status = 204, description = "Entity property set successfully (with or without value)"),+ (status = 400, description = "Invalid request or entity type"),+ (status = 404, description = "Entity or property not found"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(state, user, request), fields(entity_id = %entity_id, property_id = %property_uuid, entity_type = ?entity_type, has_value = request.value.is_some()), err)]+pub async fn set_entity_property<S: PropertiesService, A: EntityAccessService>(+ Path((entity_type, entity_id, property_uuid)): Path<(EntityType, String, Uuid)>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ Json(request): Json<SetEntityPropertyRequest>,+) -> Result<StatusCode, SetEntityPropertyErr> {+ tracing::info!("setting entity property");++ state+ .properties_service+ .set_entity_property(&user, &entity_id, entity_type, property_uuid, request.value)+ .await?;++ tracing::info!("successfully set entity property");++ Ok(StatusCode::NO_CONTENT)+}++#[derive(Debug, Error)]+pub enum EntityPropertyOptionErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for EntityPropertyOptionErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ EntityPropertyOptionErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "EntityPropertyOptionErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Add a single option to an entity's multi-select property value.+///+/// Atomic delta: the option is appended to the current stored value (deduped,+/// attaching the property if needed), so concurrent edits to the same value+/// merge rather than overwrite each other. Prefer this over the full-value PUT+/// when adding one option.+#[utoipa::path(+ post,+ path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",+ params(+ ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_id" = String, Path, description = "Entity ID"),+ ("property_id" = Uuid, Path, description = "Property ID"),+ ("option_id" = Uuid, Path, description = "Option ID to add")+ ),+ responses(+ (status = 204, description = "Option added successfully"),+ (status = 400, description = "Invalid request, property is not multi-select, or option does not belong to the property"),+ (status = 403, description = "No edit access to the entity"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(state, user), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type), err)]+pub async fn add_entity_property_option<S: PropertiesService, A: EntityAccessService>(+ Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(+ EntityType,+ String,+ Uuid,+ Uuid,+ )>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+) -> Result<StatusCode, EntityPropertyOptionErr> {+ tracing::info!("adding entity property option");++ state+ .properties_service+ .add_entity_property_option(&user, &entity_id, entity_type, property_uuid, option_uuid)+ .await?;++ Ok(StatusCode::NO_CONTENT)+}++/// Remove a single option from an entity's multi-select property value.+///+/// Atomic delta: the option is stripped from the current stored value (a no-op+/// if absent), so concurrent edits to the same value merge rather than overwrite+/// each other.+#[utoipa::path(+ delete,+ path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",+ params(+ ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_id" = String, Path, description = "Entity ID"),+ ("property_id" = Uuid, Path, description = "Property ID"),+ ("option_id" = Uuid, Path, description = "Option ID to remove")+ ),+ responses(+ (status = 204, description = "Option removed successfully"),+ (status = 403, description = "No edit access to the entity"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(state, user), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type), err)]+pub async fn remove_entity_property_option<S: PropertiesService, A: EntityAccessService>(+ Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(+ EntityType,+ String,+ Uuid,+ Uuid,+ )>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+) -> Result<StatusCode, EntityPropertyOptionErr> {+ tracing::info!("removing entity property option");++ state+ .properties_service+ .remove_entity_property_option(&user, &entity_id, entity_type, property_uuid, option_uuid)+ .await?;++ Ok(StatusCode::NO_CONTENT)+}++#[derive(Debug, Error)]+pub enum DeleteEntityErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for DeleteEntityErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ DeleteEntityErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "DeleteEntityErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Delete all properties for an entity+#[utoipa::path(+ delete,+ path = "/internal/properties/entities/{entity_type}/{entity_id}",+ params(+ ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),+ ("entity_id" = String, Path, description = "Entity ID")+ ),+ responses(+ (status = 204, description = "Entity properties deleted successfully"),+ (status = 404, description = "Entity not found"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Internal"+)]+#[tracing::instrument(skip(state), err)]+pub async fn delete_entity<S: PropertiesService, A: EntityAccessService>(+ Path((entity_type, entity_id)): Path<(EntityType, String)>,+ State(state): State<PropertiesRouterState<S, A>>,+) -> Result<StatusCode, DeleteEntityErr> {+ tracing::info!("deleting all properties for entity");++ let entity_reference = EntityReference::new(entity_id.clone(), entity_type);++ state+ .properties_service+ .delete_entity_properties(&entity_reference)+ .await?;++ tracing::info!("successfully deleted all properties for entity");++ Ok(StatusCode::NO_CONTENT)+}++#[derive(Debug, Error)]+pub enum DeleteEntityPropertyErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for DeleteEntityPropertyErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ DeleteEntityPropertyErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "DeleteEntityPropertyErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Remove a specific entity property by its ID+#[utoipa::path(+ delete,+ path = "/properties/entity_properties/{entity_property_id}",+ params(+ ("entity_property_id" = Uuid, Path, description = "Entity Property ID")+ ),+ responses(+ (status = 204, description = "Entity property removed successfully"),+ (status = 403, description = "Property is required and cannot be removed"),+ (status = 404, description = "Entity property not found"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Properties"+)]+#[tracing::instrument(skip(state, user), fields(entity_property_id = %entity_property_uuid), err)]+pub async fn delete_entity_property<S: PropertiesService, A: EntityAccessService>(+ Path(entity_property_uuid): Path<Uuid>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+) -> Result<StatusCode, DeleteEntityPropertyErr> {+ tracing::info!("removing entity property");++ state+ .properties_service+ .delete_entity_property(entity_property_uuid, &user)+ .await?;++ Ok(StatusCode::NO_CONTENT)+}++#[derive(Debug, Error)]+pub enum SetPropertyStatusCompleteErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for SetPropertyStatusCompleteErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ SetPropertyStatusCompleteErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "SetPropertyStatusCompleteErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Set an entity's status property to "Completed".+///+/// If the entity has a status property attached, it will be set to "Completed".+/// If the entity does not have a status property, this is a no-op and returns success.+#[utoipa::path(+ patch,+ path = "/properties/entities/{entity_type}/{entity_id}/status/complete",+ params(+ ("entity_type" = EntityType, Path, description = "Entity type (document, channel, project, thread, chat)"),+ ("entity_id" = String, Path, description = "Entity ID")+ ),+ responses(+ (status = 204, description = "Status set to complete"),+ (status = 403, description = "Access denied"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(state, user), fields(entity_id = %entity_id, entity_type = ?entity_type), err)]+pub async fn set_property_status_complete<S: PropertiesService, A: EntityAccessService>(+ Path((entity_type, entity_id)): Path<(EntityType, String)>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+) -> Result<StatusCode, SetPropertyStatusCompleteErr> {+ tracing::info!("setting entity status to complete");++ // Check edit permissions+ state+ .properties_service+ .check_entity_edit_permission(&user, &entity_id, entity_type)+ .await?;++ // Delegate to service layer for business logic+ state+ .properties_service+ .set_system_property_status_complete(&entity_id, entity_type)+ .await?;++ tracing::debug!("status complete handled");+ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/cloud-storage/properties/src/inbound/axum_router/options.rs b/rust/cloud-storage/properties/src/inbound/axum_router/options.rsnew file mode 100644index 0000000000..4386de44f2--- /dev/null+++ b/rust/cloud-storage/properties/src/inbound/axum_router/options.rs@@ -0,0 +1,275 @@+//! Property option endpoints.++use axum::{+ Json,+ extract::{Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use entity_access::domain::ports::EntityAccessService;+use model::user::axum_extractor::MacroUserExtractor;+use models_properties::api::{AddPropertyOptionRequest, UpdatePropertyOptionRequest};+use models_properties::service::property_option::PropertyOption;+use thiserror::Error;+use uuid::Uuid;++use super::{PropertiesRouterState, PropertyTeamExtractor, caller_team_id, properties_err_status};+use crate::domain::error::PropertiesErr;+use crate::domain::service::PropertiesService;++#[derive(Debug, Error)]+pub enum GetPropertyOptionsErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for GetPropertyOptionsErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ GetPropertyOptionsErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "GetPropertyOptionsErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Get all options for a property (for dropdowns)+#[utoipa::path(+ get,+ path = "/properties/definitions/{definition_id}/options",+ params(+ ("definition_id" = Uuid, Path, description = "Property definition ID")+ ),+ responses(+ (status = 200, description = "Property options retrieved successfully", body = Vec<PropertyOption>),+ (status = 404, description = "Property not found"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Properties"+)]+#[tracing::instrument(skip(state, user, team), fields(property_id = %property_uuid), err)]+pub async fn get_property_options<S: PropertiesService, A: EntityAccessService>(+ Path(property_uuid): Path<Uuid>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,+) -> Result<Json<Vec<PropertyOption>>, GetPropertyOptionsErr> {+ tracing::info!("retrieving property options");++ let options = state+ .properties_service+ .get_property_options(property_uuid, &user, caller_team_id(&team))+ .await?;++ tracing::info!(+ options_count = options.len(),+ "successfully retrieved property options"+ );++ Ok(Json(options))+}++#[derive(Debug, Error)]+pub enum AddPropertyOptionErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for AddPropertyOptionErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ AddPropertyOptionErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "AddPropertyOptionErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Add a new option to a property dropdown+#[utoipa::path(+ post,+ path = "/properties/definitions/{definition_id}/options",+ params(+ ("definition_id" = Uuid, Path, description = "Property definition ID")+ ),+ request_body = AddPropertyOptionRequest,+ responses(+ (status = 201, description = "Property option created successfully", body = PropertyOption),+ (status = 400, description = "Invalid request"),+ (status = 403, description = "Cannot modify system properties"),+ (status = 404, description = "Property not found"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(state, user, team), fields(property_id = %property_uuid, request = ?request), err)]+pub async fn add_property_option<S: PropertiesService, A: EntityAccessService>(+ Path(property_uuid): Path<Uuid>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,+ Json(request): Json<AddPropertyOptionRequest>,+) -> Result<(StatusCode, Json<PropertyOption>), AddPropertyOptionErr> {+ tracing::info!("adding property option");++ let option = state+ .properties_service+ .add_property_option(&user, caller_team_id(&team), property_uuid, &request)+ .await?;++ Ok((StatusCode::CREATED, Json(option)))+}++#[derive(Debug, Error)]+pub enum UpdatePropertyOptionErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for UpdatePropertyOptionErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ UpdatePropertyOptionErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "UpdatePropertyOptionErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Update a property option in place (rename / recolor / reorder).+///+/// The option id is preserved, so the change is reflected on every entity that references it.+#[utoipa::path(+ patch,+ path = "/properties/definitions/{definition_id}/options/{option_id}",+ params(+ ("definition_id" = Uuid, Path, description = "Property definition ID"),+ ("option_id" = Uuid, Path, description = "Property option ID")+ ),+ request_body = UpdatePropertyOptionRequest,+ responses(+ (status = 200, description = "Property option updated", body = PropertyOption),+ (status = 400, description = "Invalid request"),+ (status = 403, description = "Cannot modify system properties"),+ (status = 404, description = "Property or option not found"),+ (status = 409, description = "An option with that value already exists"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(state, user, team), fields(property_id = %def_uuid, option_id = %option_uuid, request = ?request), err)]+pub async fn update_property_option<S: PropertiesService, A: EntityAccessService>(+ Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,+ Json(request): Json<UpdatePropertyOptionRequest>,+) -> Result<(StatusCode, Json<PropertyOption>), UpdatePropertyOptionErr> {+ let updated = state+ .properties_service+ .update_property_option(+ &user,+ caller_team_id(&team),+ def_uuid,+ option_uuid,+ &request,+ )+ .await?;++ Ok((StatusCode::OK, Json(updated)))+}++#[derive(Debug, Error)]+pub enum DeletePropertyOptionErr {+ #[error(transparent)]+ Properties(#[from] PropertiesErr),+}++impl IntoResponse for DeletePropertyOptionErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ DeletePropertyOptionErr::Properties(e) => properties_err_status(e),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "DeletePropertyOptionErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Delete a property option+#[utoipa::path(+ delete,+ path = "/properties/definitions/{definition_id}/options/{option_id}",+ params(+ ("definition_id" = Uuid, Path, description = "Property definition ID"),+ ("option_id" = Uuid, Path, description = "Property option ID")+ ),+ responses(+ (status = 204, description = "Property option deleted successfully"),+ (status = 400, description = "Invalid option ID"),+ (status = 403, description = "Cannot modify system properties"),+ (status = 404, description = "Property option not found"),+ (status = 500, description = "Internal server error")+ ),+ tag = "Properties"+)]+#[tracing::instrument(skip(state, user, team), err)]+pub async fn delete_property_option<S: PropertiesService, A: EntityAccessService>(+ Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,+) -> Result<StatusCode, DeletePropertyOptionErr> {+ tracing::info!("deleting property option");++ state+ .properties_service+ .delete_property_option(&user, caller_team_id(&team), def_uuid, option_uuid)+ .await?;++ tracing::info!("successfully deleted property option");+ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/cloud-storage/properties_service/src/api/properties/tags.rs b/rust/cloud-storage/properties/src/inbound/axum_router/tags.rssimilarity index 50%rename from rust/cloud-storage/properties_service/src/api/properties/tags.rsrename to rust/cloud-storage/properties/src/inbound/axum_router/tags.rsindex 01629d3f3d..54d2931266 100644--- a/rust/cloud-storage/properties_service/src/api/properties/tags.rs+++ b/rust/cloud-storage/properties/src/inbound/axum_router/tags.rs@@ -1,25 +1,22 @@+//! Tag set endpoints.+use axum::{Json,- extract::{Extension, State},+ extract::State,http::StatusCode,response::{IntoResponse, Response},};+use entity_access::domain::ports::EntityAccessService;+use model::user::axum_extractor::MacroUserExtractor;+use models_properties::api::{PropertyDefinitionDetailResponse, PropertyOptionResponse};use serde::{Deserialize, Serialize};use thiserror::Error;use utoipa::ToSchema;-use crate::api::context::{PropertiesHandlerState, PropertyTeamExtractor, caller_team_id};-use model::user::UserContext;-use models_properties::api::{PropertyDefinitionDetailResponse, PropertyOptionResponse};-use models_properties::service::property_definition::PropertyDefinition;-use properties_db_client::{- error::PropertiesDatabaseError,- property_definitions::{- get as property_definitions_get,- insert::{self as property_definitions_insert, DefinitionOwner},- },- property_options::get as property_options_get,-};+use super::{PropertiesRouterState, PropertyTeamExtractor, caller_team_id, properties_err_status};+use crate::domain::error::PropertiesErr;+use crate::domain::model::{self as properties_model, PropertyDefinitionOwner};+use crate::domain::service::PropertiesService;/// Which owner a tag set belongs to.#[derive(Debug, Clone, Copy, Serialize, Deserialize, ToSchema, PartialEq)]@@ -31,6 +28,15 @@ pub enum TagScope {Team,}+impl From<properties_model::TagScope> for TagScope {+ fn from(scope: properties_model::TagScope) -> Self {+ match scope {+ properties_model::TagScope::User => TagScope::User,+ properties_model::TagScope::Team => TagScope::Team,+ }+ }+}+/// A tag set the caller can use. `definition` is absent until the set is provisioned/// (on first label create), in which case `options` is empty.#[derive(Debug, Serialize, ToSchema)]@@ -41,6 +47,16 @@ pub struct TagSetResponse {pub options: Vec<PropertyOptionResponse>,}+impl From<properties_model::TagSet> for TagSetResponse {+ fn from(set: properties_model::TagSet) -> Self {+ TagSetResponse {+ scope: set.scope.into(),+ definition: set.definition.map(Into::into),+ options: set.options.into_iter().map(Into::into).collect(),+ }+ }+}+/// Request to provision (get-or-create) the caller's tag set for a scope.#[derive(Debug, Deserialize, ToSchema)]pub struct EnsureTagSetRequest {@@ -49,10 +65,8 @@ pub struct EnsureTagSetRequest {#[derive(Debug, Error)]pub enum TagsError {- #[error("An internal error occurred")]- Internal(#[from] anyhow::Error),- #[error("An internal error occurred")]- Database(#[from] PropertiesDatabaseError),+ #[error(transparent)]+ Properties(#[from] PropertiesErr),#[error("You must be on a team to use team tags")]TeamMembershipRequired,}@@ -60,7 +74,7 @@ pub enum TagsError {impl IntoResponse for TagsError {fn into_response(self) -> Response {let status_code = match &self {- TagsError::Internal(_) | TagsError::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,+ TagsError::Properties(e) => properties_err_status(e),TagsError::TeamMembershipRequired => StatusCode::FORBIDDEN,};@@ -83,26 +97,21 @@ impl IntoResponse for TagsError {),tag = "Properties")]-#[tracing::instrument(skip(state, user_context, team), fields(user_id = %user_context.user_id), err)]-pub async fn list_tags(- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,+#[tracing::instrument(skip(state, user, team), err)]+pub async fn list_tags<S: PropertiesService, A: EntityAccessService>(+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,) -> Result<Json<Vec<TagSetResponse>>, TagsError> {- let mut sets = Vec::new();-- let user_definition =- property_definitions_get::get_tag_definition(&state.db, None, Some(&user_context.user_id))- .await?;- sets.push(build_tag_set(&state.db, TagScope::User, user_definition).await?);-- if let Some(team_id) = caller_team_id(&team) {- let team_definition =- property_definitions_get::get_tag_definition(&state.db, Some(team_id), None).await?;- sets.push(build_tag_set(&state.db, TagScope::Team, team_definition).await?);- }+ let sets = state+ .properties_service+ .list_tag_sets(&user, caller_team_id(&team))+ .await?;- Ok(Json(sets))+ Ok(Json(sets.into_iter().map(Into::into).collect()))}/// Provision (get-or-create) the caller's tag set for a scope and return it. Called when@@ -118,47 +127,25 @@ pub async fn list_tags(),tag = "Properties")]-#[tracing::instrument(skip(state, user_context, team), fields(user_id = %user_context.user_id, scope = ?request.scope), err)]-pub async fn ensure_tag_set(- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,+#[tracing::instrument(skip(state, user, team), fields(scope = ?request.scope), err)]+pub async fn ensure_tag_set<S: PropertiesService, A: EntityAccessService>(+ State(state): State<PropertiesRouterState<S, A>>,+ MacroUserExtractor {+ macro_user_id: user,+ ..+ }: MacroUserExtractor,+ team: PropertyTeamExtractor<A>,Json(request): Json<EnsureTagSetRequest>,) -> Result<Json<TagSetResponse>, TagsError> {let owner = match request.scope {- TagScope::User => DefinitionOwner::User(user_context.user_id.as_str()),+ TagScope::User => PropertyDefinitionOwner::User(&user),TagScope::Team => {let team_id = caller_team_id(&team).ok_or(TagsError::TeamMembershipRequired)?;- DefinitionOwner::Team(team_id)+ PropertyDefinitionOwner::Team(team_id)}};- let definition =- property_definitions_insert::get_or_create_tag_definition(&state.db, owner).await?;- let set = build_tag_set(&state.db, request.scope, Some(definition)).await?;+ let set = state.properties_service.ensure_tag_set(owner).await?;- Ok(Json(set))-}--/// Resolve a tag set's options into the response shape. A missing definition yields an empty set.-async fn build_tag_set(- db: &sqlx::PgPool,- scope: TagScope,- definition: Option<PropertyDefinition>,-) -> Result<TagSetResponse, PropertiesDatabaseError> {- match definition {- Some(definition) => {- let options = property_options_get::get_property_options(db, definition.id).await?;- Ok(TagSetResponse {- scope,- definition: Some(definition.into()),- options: options.into_iter().map(Into::into).collect(),- })- }- None => Ok(TagSetResponse {- scope,- definition: None,- options: Vec::new(),- }),- }+ Ok(Json(set.into()))}diff --git a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rsindex 8a15ef495a..7b2dafdf0b 100644--- a/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs+++ b/rust/cloud-storage/properties/src/inbound/toolset/set_entity_property.rs@@ -193,12 +193,11 @@ wherelet entity_type = EntityType::from(self.entity_type);let set_value = self.to_set_property_value();- let user_id: &str = request_context.user_id.0.as_ref();service_context.service.set_entity_property(- user_id,+ &request_context.user_id,&self.entity_id,entity_type,self.property_definition_id,diff --git a/rust/cloud-storage/properties/src/lib.rs b/rust/cloud-storage/properties/src/lib.rsindex f98a5da99b..915dfb90c2 100644--- a/rust/cloud-storage/properties/src/lib.rs+++ b/rust/cloud-storage/properties/src/lib.rs@@ -11,7 +11,9 @@//! - `outbound` - Outbound adapters (e.g., PostgreSQL implementation)pub mod domain;+#[cfg(any(feature = "ai_tools", feature = "inbound"))]pub mod inbound;+#[cfg(feature = "outbound")]pub mod outbound;pub use domain::error::PropertiesErr;@@ -21,6 +23,9 @@ pub use domain::ports::{};pub use domain::service::PropertiesService;pub use domain::service_impl::PropertiesServiceImpl;+#[cfg(feature = "outbound")]pub use outbound::notification_service::NotificationServiceImpl;+#[cfg(feature = "outbound")]pub use outbound::permission_service::PermissionServiceImpl;+#[cfg(feature = "outbound")]pub use outbound::properties_pg_repo::PropertiesPgRepo;diff --git a/rust/cloud-storage/properties/src/outbound.rs b/rust/cloud-storage/properties/src/outbound.rsindex ef738b536c..d53e085bb7 100644--- a/rust/cloud-storage/properties/src/outbound.rs+++ b/rust/cloud-storage/properties/src/outbound.rs@@ -1,9 +1,19 @@+#[cfg(test)]+mod definitions_test;+pub mod entity_info_queries;pub mod entity_properties_get_query;+#[cfg(test)]+mod entity_properties_values_test;pub mod entity_property_queries;+pub mod metadata_queries;pub mod notification_service;+#[cfg(test)]+mod options_test;+pub mod permission_queries;pub mod permission_service;pub mod properties_pg_repo;pub mod property_definition_queries;+pub mod property_option_queries;pub mod task_property_queries;#[cfg(test)]pub mod test;diff --git a/rust/cloud-storage/properties/src/outbound/definitions_test.rs b/rust/cloud-storage/properties/src/outbound/definitions_test.rsnew file mode 100644index 0000000000..b636d68588--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/definitions_test.rs@@ -0,0 +1,439 @@+//! Integration tests for property definition operations on PropertiesPgRepo.++use super::properties_pg_repo::PropertiesPgRepo;+use crate::domain::model::PropertyDefinitionOwner;+use crate::domain::ports::PropertiesRepo;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};+use models_properties::{DataType, EntityType};+use sqlx::{Pool, Postgres};+use uuid::Uuid;++fn user_1() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn user_2() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn user_3() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn team_1() -> Uuid {+ "0e000000-0000-0000-0000-000000000001".parse().unwrap()+}++fn team_2() -> Uuid {+ "0e000000-0000-0000-0000-000000000002".parse().unwrap()+}++fn new_option(display_order: i32, value: PropertyOptionValue) -> PropertyOption {+ PropertyOption {+ id: Uuid::nil(),+ property_definition_id: Uuid::nil(),+ display_order,+ value,+ color: None,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn list_property_definitions_by_team(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let properties = repo+ .list_property_definitions(Some(team_1()), None, false)+ .await?;++ assert_eq!(properties.len(), 10); // Team 1 has 10 properties++ // Verify they are sorted by display name (case-insensitive alphabetical)+ assert_eq!(properties[0].display_name, "Test Assigned To");+ assert_eq!(properties[1].display_name, "Test Budget");+ assert_eq!(properties[2].display_name, "Test Completed");+ assert_eq!(properties[3].display_name, "Test Department");+ assert_eq!(properties[4].display_name, "Test Description");+ assert_eq!(properties[5].display_name, "Test Due Date");+ assert_eq!(properties[6].display_name, "Test Priority");+ assert_eq!(properties[7].display_name, "Test Relevant Documents");+ assert_eq!(properties[8].display_name, "Test Score");+ assert_eq!(properties[9].display_name, "Test Website");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn list_property_definitions_by_user(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let properties = repo+ .list_property_definitions(None, Some(&user_1()), false)+ .await?;++ assert_eq!(properties.len(), 2); // User1 has 2 properties+ assert_eq!(properties[0].display_name, "Test Notes");+ assert_eq!(properties[1].display_name, "Test Personal Priority");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_property_definition_with_owner_checks_ownership(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let team_property_id = "11111111-1111-1111-1111-111111111111"+ .parse::<Uuid>()+ .unwrap();++ // The team owner can access the team property.+ let property = repo+ .get_property_definition_with_owner(team_property_id, &user_1(), Some(team_1()))+ .await?;+ assert!(property.is_some());++ // A different member of the same team can also access it.+ let property = repo+ .get_property_definition_with_owner(team_property_id, &user_3(), Some(team_1()))+ .await?;+ assert!(property.is_some());++ // A user on a different team cannot access it.+ let property = repo+ .get_property_definition_with_owner(team_property_id, &user_2(), Some(team_2()))+ .await?;+ assert!(property.is_none());++ // A user with no team cannot access it.+ let property = repo+ .get_property_definition_with_owner(team_property_id, &user_2(), None)+ .await?;+ assert!(property.is_none());++ // The owning user can access their own user property.+ let user_property_id = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"+ .parse::<Uuid>()+ .unwrap();+ let property = repo+ .get_property_definition_with_owner(user_property_id, &user_1(), Some(team_1()))+ .await?;+ assert!(property.is_some());++ // A different user cannot access someone else's user property.+ let property = repo+ .get_property_definition_with_owner(user_property_id, &user_3(), Some(team_1()))+ .await?;+ assert!(property.is_none());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn list_property_definitions_with_options(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let properties = repo+ .list_property_definitions_with_options(Some(team_1()), None, false)+ .await?;++ assert_eq!(properties.len(), 10);++ // Priority property should have 4 options, properly ordered.+ let priority_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Priority")+ .unwrap();++ assert_eq!(priority_prop.property_options.len(), 4);+ assert_eq!(priority_prop.property_options[0].display_order, 0);+ assert_eq!(+ priority_prop.property_options[0].value,+ PropertyOptionValue::String("Low".to_string())+ );++ // Non-select properties should have no options.+ let completed_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Completed")+ .unwrap();+ assert_eq!(completed_prop.definition.data_type, DataType::Boolean);+ assert_eq!(completed_prop.property_options.len(), 0);++ // Number select options.+ let score_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Score")+ .unwrap();+ assert_eq!(score_prop.property_options.len(), 5);+ assert_eq!(score_prop.definition.data_type, DataType::SelectNumber);+ assert_eq!(+ score_prop.property_options[0].value,+ PropertyOptionValue::Number(4.0)+ );++ // Multi-select string options.+ let dept_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Department")+ .unwrap();+ assert!(dept_prop.definition.is_multi_select);+ assert_eq!(dept_prop.definition.data_type, DataType::SelectString);+ assert_eq!(dept_prop.property_options.len(), 3);+ assert_eq!(+ dept_prop.property_options[0].value,+ PropertyOptionValue::String("Engineering".to_string())+ );+ assert_eq!(+ dept_prop.property_options[1].value,+ PropertyOptionValue::String("Human Resources".to_string())+ );+ assert_eq!(+ dept_prop.property_options[2].value,+ PropertyOptionValue::String("Marketing".to_string())+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_definition_simple(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let property = repo+ .create_property_definition(+ PropertyDefinitionOwner::Team(team_1()),+ "New Test Property",+ DataType::String,+ false,+ None,+ Vec::new(),+ )+ .await?;++ assert_eq!(property.display_name, "New Test Property");+ assert_eq!(property.data_type, DataType::String);+ assert!(!property.is_multi_select);+ assert!(property.specific_entity_type.is_none());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_definition_user_owned(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let property = repo+ .create_property_definition(+ PropertyDefinitionOwner::User(&user_1()),+ "My User Property",+ DataType::Number,+ false,+ None,+ Vec::new(),+ )+ .await?;++ assert_eq!(property.display_name, "My User Property");+ assert_eq!(property.data_type, DataType::Number);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_definition_duplicate_name_fails(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ // "Test Priority" already exists for team 1 in the fixture.+ let result = repo+ .create_property_definition(+ PropertyDefinitionOwner::Team(team_1()),+ "Test Priority",+ DataType::String,+ false,+ None,+ Vec::new(),+ )+ .await;++ assert!(result.is_err());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_definition_with_options(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool.clone());++ let options = vec![+ new_option(0, PropertyOptionValue::String("Alpha".to_string())),+ new_option(1, PropertyOptionValue::String("Beta".to_string())),+ ];++ let property = repo+ .create_property_definition(+ PropertyDefinitionOwner::Team(team_1()),+ "Select With Options",+ DataType::SelectString,+ false,+ None,+ options,+ )+ .await?;++ let option_count: i64 = sqlx::query_scalar!(+ r#"SELECT COUNT(*) as "count!" FROM property_options WHERE property_definition_id = $1"#,+ property.id+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(option_count, 2);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_definition_specific_entity(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let property = repo+ .create_property_definition(+ PropertyDefinitionOwner::Team(team_1()),+ "Document Only Property",+ DataType::String,+ false,+ Some(EntityType::Document),+ Vec::new(),+ )+ .await?;++ assert_eq!(property.specific_entity_type, Some(EntityType::Document));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_property_definition_removes_definition(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let property_id = "11111111-1111-1111-1111-111111111111"+ .parse::<Uuid>()+ .unwrap();++ // Verify it exists+ assert!(repo.get_property_definition(property_id).await?.is_some());++ // Delete it+ repo.delete_property_definition(property_id).await?;++ // Verify it's gone+ assert!(repo.get_property_definition(property_id).await?.is_none());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_property_definition_cascades(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool.clone());++ let property_id = "11111111-1111-1111-1111-111111111111"+ .parse::<Uuid>()+ .unwrap();++ // Verify options and entity properties exist for this definition.+ let options_before: i64 = sqlx::query_scalar!(+ r#"SELECT COUNT(*) as "count!" FROM property_options WHERE property_definition_id = $1"#,+ property_id+ )+ .fetch_one(&pool)+ .await?;+ assert!(options_before > 0);++ let entity_props_before: i64 = sqlx::query_scalar!(+ r#"SELECT COUNT(*) as "count!" FROM entity_properties WHERE property_definition_id = $1"#,+ property_id+ )+ .fetch_one(&pool)+ .await?;+ assert!(entity_props_before > 0);++ repo.delete_property_definition(property_id).await?;++ // Verify options and entity properties are also deleted (cascade).+ let options_after: i64 = sqlx::query_scalar!(+ r#"SELECT COUNT(*) as "count!" FROM property_options WHERE property_definition_id = $1"#,+ property_id+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(options_after, 0);++ let entity_props_after: i64 = sqlx::query_scalar!(+ r#"SELECT COUNT(*) as "count!" FROM entity_properties WHERE property_definition_id = $1"#,+ property_id+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(entity_props_after, 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_nonexistent_property_definition_is_noop(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let property_id = "00000000-0000-0000-0000-000000000000"+ .parse::<Uuid>()+ .unwrap();++ // Deleting non-existent property should succeed (no error)+ repo.delete_property_definition(property_id).await?;++ Ok(())+}diff --git a/rust/cloud-storage/properties/src/outbound/entity_info_queries.rs b/rust/cloud-storage/properties/src/outbound/entity_info_queries.rsnew file mode 100644index 0000000000..d8cbc5dad1--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/entity_info_queries.rs@@ -0,0 +1,51 @@+//! Cross-entity lookup query helpers (document names, user profile pictures).+//!+//! These queries read tables owned by other domains but are needed by the+//! properties domain (e.g. to render relation property values). They are+//! inlined here so this crate does not depend on the monolithic db client+//! crates.++use sqlx::{Pool, Postgres};++/// Get the name of a document by ID.+/// Returns `None` if the document doesn't exist.+/// Tasks are stored as documents, so this works for both documents and tasks.+pub async fn get_document_name(+ pool: &Pool<Postgres>,+ document_id: &str,+) -> anyhow::Result<Option<String>> {+ let name = sqlx::query_scalar!(+ r#"+ SELECT d.name+ FROM "Document" d+ WHERE d."id" = $1+ "#,+ document_id,+ )+ .fetch_optional(pool)+ .await?;++ Ok(name)+}++/// Get the profile picture URL for a user (by `"User"` profile id).+/// Returns `None` if the user doesn't exist or has no profile picture.+pub async fn get_user_profile_picture(+ pool: &Pool<Postgres>,+ user_id: &str,+) -> anyhow::Result<Option<String>> {+ let url = sqlx::query_scalar!(+ r#"+ SELECT mui.profile_picture as "profile_picture!"+ FROM "User" u+ JOIN macro_user mu ON mu.id = u.macro_user_id+ JOIN macro_user_info mui ON mui.macro_user_id = mu.id+ WHERE u.id = $1 AND mui.profile_picture IS NOT NULL+ "#,+ user_id,+ )+ .fetch_optional(pool)+ .await?;++ Ok(url)+}diff --git a/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rs b/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rsindex ea296ade0c..477b2ed417 100644--- a/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rs+++ b/rust/cloud-storage/properties/src/outbound/entity_properties_get_query.rs@@ -1,11 +1,17 @@-//! Query to get all properties attached to an entity.+//! Queries to read the properties attached to entities.+use std::collections::{HashMap, HashSet};++use models_properties::service::entity_property::EntityProperty;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;+use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_option::PropertyOptionValue;use models_properties::service::property_value::PropertyValue;-use models_properties::{DataType, EntityType};+use models_properties::{DataType, EntityPropertyReference, EntityReference, EntityType};use sqlx::{Pool, Postgres};use uuid::Uuid;+use super::property_option_queries;use crate::domain::model::{EntityPropertyInfo, PropertyOptionInfo};/// Database row from the joined query.@@ -144,3 +150,738 @@ pub async fn get_entity_properties(Ok(result)}++/// Database row data for entity property with definition+struct EntityPropertyRow {+ entity_property_id: Uuid,+ entity_id: String,+ entity_type: EntityType,+ property_definition_id: Uuid,+ entity_property_created_at: chrono::DateTime<chrono::Utc>,+ entity_property_updated_at: chrono::DateTime<chrono::Utc>,+ definition_team_id: Option<Uuid>,+ definition_user_id: Option<String>,+ display_name: String,+ data_type: DataType,+ is_multi_select: bool,+ specific_entity_type: Option<Option<EntityType>>,+ definition_created_at: chrono::DateTime<chrono::Utc>,+ definition_updated_at: chrono::DateTime<chrono::Utc>,+ definition_is_system: bool,+ values: Option<sqlx::types::JsonValue>,+}++/// Helper to convert a database row into EntityPropertyWithDefinition+fn row_to_entity_property_with_definition(+ row: EntityPropertyRow,+) -> anyhow::Result<EntityPropertyWithDefinition> {+ let owner = models_properties::PropertyOwner::from_optional_ids(+ row.definition_team_id,+ row.definition_user_id,+ row.definition_is_system,+ );++ let property_definition = PropertyDefinition {+ id: row.property_definition_id,+ owner,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type.flatten(),+ created_at: row.definition_created_at,+ updated_at: row.definition_updated_at,+ is_system: row.definition_is_system,+ is_metadata: false,+ };++ let property = EntityProperty {+ id: row.entity_property_id,+ entity_id: row.entity_id.clone(),+ entity_type: row.entity_type,+ property_definition_id: row.property_definition_id,+ created_at: row.entity_property_created_at,+ updated_at: row.entity_property_updated_at,+ };++ // Deserialize JSONB value (handle NULL)+ let value: Option<PropertyValue> = match row.values {+ None => None,+ Some(json_value) if json_value.is_null() => None,+ Some(json_value) => Some(serde_json::from_value(json_value).map_err(|e| {+ tracing::error!(+ error = ?e,+ entity_property_id = %row.entity_property_id,+ entity_id = %row.entity_id,+ "failed to deserialize property value from JSONB"+ );+ anyhow::Error::from(e).context("failed to deserialize property value from JSONB")+ })?),+ };++ Ok(EntityPropertyWithDefinition {+ property,+ definition: property_definition,+ value,+ options: None,+ })+}++/// Helper to sort properties by display name+fn sort_properties_by_display_name(properties: &mut [EntityPropertyWithDefinition]) {+ properties.sort_by(|a, b| {+ a.definition+ .display_name+ .to_lowercase()+ .cmp(&b.definition.display_name.to_lowercase())+ });+}++/// Validates and cleans select option values by deduplicating and filtering invalid IDs+fn validate_and_clean_select_option_value(+ property: &mut EntityPropertyWithDefinition,+ options: &[models_properties::service::property_option::PropertyOption],+) {+ let Some(PropertyValue::SelectOption(option_ids)) = &property.value else {+ return;+ };++ if option_ids.is_empty() {+ return;+ }++ // Handle case where property has option IDs but no valid options exist in DB+ if options.is_empty() {+ tracing::warn!(+ entity_property_id = %property.property.id,+ property_definition_id = %property.definition.id,+ option_ids_count = option_ids.len(),+ "select property has option IDs but no valid options exist in DB, clearing value"+ );+ property.value = Some(PropertyValue::SelectOption(vec![]));+ return;+ }++ // Deduplicate and validate option IDs+ let original_count = option_ids.len();+ let unique_ids: HashSet<Uuid> = option_ids.iter().copied().collect();+ let unique_count = unique_ids.len();++ let valid_ids_set: HashSet<Uuid> = options.iter().map(|opt| opt.id).collect();+ let valid_option_ids: Vec<Uuid> = unique_ids+ .into_iter()+ .filter(|id| valid_ids_set.contains(id))+ .collect();++ let has_invalid = valid_option_ids.len() != unique_count;+ let has_duplicates = unique_count != original_count;++ if has_invalid || has_duplicates {+ let invalid_count = unique_count - valid_option_ids.len();+ let duplicate_count = original_count - unique_count;++ tracing::warn!(+ entity_property_id = %property.property.id,+ property_definition_id = %property.definition.id,+ original_count = original_count,+ valid_count = valid_option_ids.len(),+ invalid_count = invalid_count,+ duplicate_count = duplicate_count,+ "filtered and deduplicated option IDs from entity property value"+ );++ property.value = Some(PropertyValue::SelectOption(valid_option_ids));+ }+}++/// Defensively clears stale select options/values from non-select properties+fn clear_stale_select_data(property: &mut EntityPropertyWithDefinition) {+ if property.options.is_some() {+ tracing::warn!(+ entity_property_id = %property.property.id,+ property_definition_id = %property.definition.id,+ data_type = ?property.definition.data_type,+ "non-select property has options attached, clearing"+ );+ property.options = None;+ }++ if matches!(property.value, Some(PropertyValue::SelectOption(_))) {+ tracing::warn!(+ entity_property_id = %property.property.id,+ property_definition_id = %property.definition.id,+ data_type = ?property.definition.data_type,+ "non-select property has SelectOption value, clearing"+ );+ property.value = None;+ }+}++/// Helper to fetch and attach property options to properties.+/// Also validates and deduplicates option IDs in property values.+/// Defensively clears stale options/values on non-select properties.+async fn attach_property_options(+ pool: &Pool<Postgres>,+ properties: &mut [EntityPropertyWithDefinition],+) -> anyhow::Result<()> {+ // Collect select-type property IDs for batch fetch+ let property_ids_needing_options: Vec<Uuid> = properties+ .iter()+ .filter(|p| {+ matches!(+ p.definition.data_type,+ DataType::SelectString | DataType::SelectNumber | DataType::Tag+ )+ })+ .map(|p| p.definition.id)+ .collect();++ // Fetch all options in one query (empty if no select properties)+ let options_map = if !property_ids_needing_options.is_empty() {+ property_option_queries::get_property_options_batch(pool, &property_ids_needing_options)+ .await?+ } else {+ HashMap::new()+ };++ // Process ALL properties+ for property in properties {+ let is_select_type = matches!(+ property.definition.data_type,+ DataType::SelectString | DataType::SelectNumber | DataType::Tag+ );++ if is_select_type {+ let options = options_map+ .get(&property.definition.id)+ .cloned()+ .unwrap_or_default();++ property.options = Some(options.clone());+ validate_and_clean_select_option_value(property, &options);+ } else {+ clear_stale_select_data(property);+ }+ }++ Ok(())+}++/// Fetch and attach property options to properties across multiple entities in ONE query.+/// Optimized for bulk operations - collects all unique select-type property IDs across all entities,+/// fetches options once, then distributes to each property.+async fn attach_property_options_bulk(+ pool: &Pool<Postgres>,+ entity_properties_map: &mut HashMap<String, Vec<EntityPropertyWithDefinition>>,+) -> anyhow::Result<()> {+ let property_ids_needing_options: HashSet<Uuid> = entity_properties_map+ .values()+ .flatten()+ .filter(|p| {+ matches!(+ p.definition.data_type,+ DataType::SelectString | DataType::SelectNumber | DataType::Tag+ )+ })+ .map(|p| p.definition.id)+ .collect();++ let options_map = if !property_ids_needing_options.is_empty() {+ let property_ids_vec: Vec<Uuid> = property_ids_needing_options.into_iter().collect();+ property_option_queries::get_property_options_batch(pool, &property_ids_vec).await?+ } else {+ HashMap::new()+ };++ for properties in entity_properties_map.values_mut() {+ for property in properties.iter_mut() {+ let is_select_type = matches!(+ property.definition.data_type,+ DataType::SelectString | DataType::SelectNumber | DataType::Tag+ );+ if is_select_type {+ let options = options_map+ .get(&property.definition.id)+ .cloned()+ .unwrap_or_default();+ validate_and_clean_select_option_value(property, &options);+ property.options = Some(options);+ } else {+ clear_stale_select_data(property);+ }+ }+ }++ Ok(())+}++/// Looks up an entity property by its ID.+/// Returns entity reference (for permissions) and definition ID (for required property check).+#[tracing::instrument(skip(pool))]+pub async fn lookup_entity_property(+ pool: &Pool<Postgres>,+ entity_property_id: Uuid,+) -> anyhow::Result<Option<EntityPropertyReference>> {+ let row = sqlx::query!(+ r#"+SELECT+ ep.entity_id,+ ep.entity_type as "entity_type: EntityType",+ ep.property_definition_id+FROM entity_properties ep+WHERE ep.id = $1+ "#,+ entity_property_id+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.map(|r| EntityPropertyReference {+ entity_id: r.entity_id,+ entity_type: r.entity_type,+ property_definition_id: r.property_definition_id,+ }))+}++/// Gets entity properties with their definitions and values.+/// Includes both custom and system properties.+#[tracing::instrument(skip(pool))]+pub async fn get_entity_properties_values(+ pool: &Pool<Postgres>,+ entity_id: &str,+ entity_type: EntityType,+) -> anyhow::Result<Vec<EntityPropertyWithDefinition>> {+ let rows = sqlx::query!(+ r#"+SELECT+ ep.id as entity_property_id,+ ep.entity_id,+ ep.entity_type as "entity_type: EntityType",+ ep.property_definition_id,+ ep.values as "values: sqlx::types::JsonValue",+ ep.created_at as entity_property_created_at,+ ep.updated_at as entity_property_updated_at,+ pd.team_id as definition_team_id,+ pd.user_id as definition_user_id,+ pd.display_name,+ pd.data_type as "data_type: DataType",+ pd.is_multi_select,+ pd.specific_entity_type as "specific_entity_type: Option<EntityType>",+ pd.created_at as definition_created_at,+ pd.updated_at as definition_updated_at,+ pd.is_system as definition_is_system+FROM entity_properties ep+INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id+WHERE ep.entity_id = $1 AND ep.entity_type = $2+ "#,+ entity_id,+ entity_type as EntityType+ )+ .fetch_all(pool)+ .await?;++ let mut result: Vec<EntityPropertyWithDefinition> = rows+ .into_iter()+ .map(|row| {+ row_to_entity_property_with_definition(EntityPropertyRow {+ entity_property_id: row.entity_property_id,+ entity_id: row.entity_id,+ entity_type: row.entity_type,+ property_definition_id: row.property_definition_id,+ entity_property_created_at: row.entity_property_created_at,+ entity_property_updated_at: row.entity_property_updated_at,+ definition_team_id: row.definition_team_id,+ definition_user_id: row.definition_user_id,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type,+ definition_created_at: row.definition_created_at,+ definition_updated_at: row.definition_updated_at,+ definition_is_system: row.definition_is_system,+ values: row.values,+ })+ })+ .collect::<anyhow::Result<Vec<_>>>()?;++ // Sort by display name+ sort_properties_by_display_name(&mut result);++ // Fetch and attach property options+ attach_property_options(pool, &mut result).await?;++ Ok(result)+}++/// Gets entity properties with their definitions and values for multiple entities.+/// Returns a HashMap where the key is the entity_id and the value is Vec<EntityPropertyWithDefinition>.+/// Includes both custom and system properties.+#[tracing::instrument(skip(pool))]+pub async fn get_bulk_entity_properties_values(+ pool: &Pool<Postgres>,+ entity_refs: &[EntityReference],+) -> anyhow::Result<HashMap<String, Vec<EntityPropertyWithDefinition>>> {+ if entity_refs.is_empty() {+ return Ok(HashMap::new());+ }++ // Use UNNEST to match entity_id and entity_type as pairs+ let entity_ids: Vec<String> = entity_refs.iter().map(|r| r.entity_id.clone()).collect();+ let entity_types: Vec<EntityType> = entity_refs.iter().map(|r| r.entity_type).collect();++ let rows = sqlx::query!(+ r#"+SELECT+ ep.id as entity_property_id,+ ep.entity_id,+ ep.entity_type as "entity_type: EntityType",+ ep.property_definition_id,+ ep.values as "values: sqlx::types::JsonValue",+ ep.created_at as entity_property_created_at,+ ep.updated_at as entity_property_updated_at,+ pd.team_id as definition_team_id,+ pd.user_id as definition_user_id,+ pd.display_name,+ pd.data_type as "data_type: DataType",+ pd.is_multi_select,+ pd.specific_entity_type as "specific_entity_type: Option<EntityType>",+ pd.created_at as definition_created_at,+ pd.updated_at as definition_updated_at,+ pd.is_system as definition_is_system+FROM entity_properties ep+INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id+WHERE (ep.entity_id, ep.entity_type) IN (+ SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])+)+"#,+ &entity_ids,+ &entity_types as &[EntityType]+ )+ .fetch_all(pool)+ .await?;++ // Group by entity_id+ let mut entity_properties_map: HashMap<String, Vec<EntityPropertyWithDefinition>> =+ HashMap::new();++ for row in rows {+ let entity_id = row.entity_id.clone();+ let property_with_definition = row_to_entity_property_with_definition(EntityPropertyRow {+ entity_property_id: row.entity_property_id,+ entity_id: row.entity_id,+ entity_type: row.entity_type,+ property_definition_id: row.property_definition_id,+ entity_property_created_at: row.entity_property_created_at,+ entity_property_updated_at: row.entity_property_updated_at,+ definition_team_id: row.definition_team_id,+ definition_user_id: row.definition_user_id,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type,+ definition_created_at: row.definition_created_at,+ definition_updated_at: row.definition_updated_at,+ definition_is_system: row.definition_is_system,+ values: row.values,+ })?;++ entity_properties_map+ .entry(entity_id)+ .or_default()+ .push(property_with_definition);+ }++ // Sort each entity's properties by display name+ for properties in entity_properties_map.values_mut() {+ sort_properties_by_display_name(properties);+ }++ attach_property_options_bulk(pool, &mut entity_properties_map).await?;++ // Ensure all requested entity_ids are present in the result, even if they have no properties+ for entity_ref in entity_refs {+ entity_properties_map+ .entry(entity_ref.entity_id.clone())+ .or_default();+ }++ Ok(entity_properties_map)+}++/// Gets entity properties with their definitions and values for multiple entities, filtered by property definition IDs.+/// Returns a HashMap where the key is the entity_id and the value is Vec<EntityPropertyWithDefinition>.+/// Only returns properties matching the specified property_ids. When `tag_viewer_user_id` is set,+/// also returns TAG properties whose definition is owned by that user or their team.+#[tracing::instrument(skip(pool))]+pub async fn get_bulk_entity_properties_values_filtered(+ pool: &Pool<Postgres>,+ entity_refs: &[EntityReference],+ property_ids: &[Uuid],+ tag_viewer_user_id: Option<¯o_user_id::user_id::MacroUserIdStr<'_>>,+) -> anyhow::Result<HashMap<String, Vec<EntityPropertyWithDefinition>>> {+ let tag_viewer_user_id: Option<&str> = tag_viewer_user_id.map(|u| u.as_ref());+ if entity_refs.is_empty() || (property_ids.is_empty() && tag_viewer_user_id.is_none()) {+ // If no property_ids specified, return empty map for each entity+ let mut result = HashMap::new();+ for entity_ref in entity_refs {+ result.insert(entity_ref.entity_id.clone(), Vec::new());+ }+ return Ok(result);+ }++ let entity_ids: Vec<String> = entity_refs.iter().map(|r| r.entity_id.clone()).collect();+ let entity_types: Vec<EntityType> = entity_refs.iter().map(|r| r.entity_type).collect();++ let rows = sqlx::query!(+ r#"+SELECT+ ep.id as entity_property_id,+ ep.entity_id,+ ep.entity_type as "entity_type: EntityType",+ ep.property_definition_id,+ ep.values as "values: sqlx::types::JsonValue",+ ep.created_at as entity_property_created_at,+ ep.updated_at as entity_property_updated_at,+ pd.team_id as definition_team_id,+ pd.user_id as definition_user_id,+ pd.display_name,+ pd.data_type as "data_type: DataType",+ pd.is_multi_select,+ pd.specific_entity_type as "specific_entity_type: Option<EntityType>",+ pd.created_at as definition_created_at,+ pd.updated_at as definition_updated_at,+ pd.is_system as definition_is_system+FROM entity_properties ep+INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id+WHERE (ep.entity_id, ep.entity_type) IN (+ SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])+)+AND (+ pd.id = ANY($3::UUID[])+ OR (+ $4::text IS NOT NULL+ AND pd.data_type = $5+ AND (+ pd.user_id = $4+ OR pd.team_id IN (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = $4)+ )+ )+)+ "#,+ &entity_ids,+ &entity_types as &[EntityType],+ &property_ids,+ tag_viewer_user_id,+ DataType::Tag as DataType+ )+ .fetch_all(pool)+ .await?;++ let mut entity_properties_map: HashMap<String, Vec<EntityPropertyWithDefinition>> =+ HashMap::new();++ for row in rows {+ let entity_id = row.entity_id.clone();+ let property_with_definition = row_to_entity_property_with_definition(EntityPropertyRow {+ entity_property_id: row.entity_property_id,+ entity_id: row.entity_id,+ entity_type: row.entity_type,+ property_definition_id: row.property_definition_id,+ entity_property_created_at: row.entity_property_created_at,+ entity_property_updated_at: row.entity_property_updated_at,+ definition_team_id: row.definition_team_id,+ definition_user_id: row.definition_user_id,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type,+ definition_created_at: row.definition_created_at,+ definition_updated_at: row.definition_updated_at,+ definition_is_system: row.definition_is_system,+ values: row.values,+ })?;++ entity_properties_map+ .entry(entity_id)+ .or_default()+ .push(property_with_definition);+ }++ for properties in entity_properties_map.values_mut() {+ sort_properties_by_display_name(properties);+ }++ attach_property_options_bulk(pool, &mut entity_properties_map).await?;++ for entity_ref in entity_refs {+ entity_properties_map+ .entry(entity_ref.entity_id.clone())+ .or_default();+ }++ Ok(entity_properties_map)+}++/// An entity property flattened into the shape the search index stores. Each+/// value lands under the field matching its type; the rest stay empty/None.+/// Covers every `PropertyValue` kind except multi-string.+#[derive(Default)]+pub struct IndexedEntityProperty {+ /// The property definition id this value belongs to.+ pub definition_id: String,+ /// Every equality-filterable value as a string: select-option UUIDs,+ /// entity-reference ids, links, text, bool as "true"/"false".+ pub values: Vec<String>,+ /// Numeric value (range + sort).+ pub number_value: Option<f64>,+ /// Date value as epoch milliseconds (range + sort).+ pub date_value: Option<i64>,+}++impl IndexedEntityProperty {+ fn is_empty(&self) -> bool {+ self.values.is_empty() && self.number_value.is_none() && self.date_value.is_none()+ }+}++/// Flatten one entity_properties row into the shape the search index stores.+/// Null and unparseable values yield None so one bad value can't fail the+/// whole index.+fn flatten_property_for_index(+ property_definition_id: Uuid,+ values: Option<serde_json::Value>,+) -> Option<IndexedEntityProperty> {+ let value = values?;+ if value.is_null() {+ return None;+ }+ let parsed = match serde_json::from_value::<PropertyValue>(value) {+ Ok(parsed) => parsed,+ Err(e) => {+ tracing::warn!(+ error = ?e,+ definition_id = %property_definition_id,+ "skipping unparseable property value for index"+ );+ return None;+ }+ };+ let mut property = IndexedEntityProperty {+ definition_id: property_definition_id.to_string(),+ ..Default::default()+ };+ match parsed {+ PropertyValue::SelectOption(ids) => {+ property.values = ids.into_iter().map(|id| id.to_string()).collect();+ }+ PropertyValue::EntityRef(refs) => {+ property.values = refs.into_iter().map(|r| r.entity_id).collect();+ }+ PropertyValue::Link(urls) => property.values = urls,+ PropertyValue::Str(s) => property.values = vec![s],+ PropertyValue::Bool(b) => property.values = vec![b.to_string()],+ PropertyValue::Num(n) => property.number_value = Some(n),+ PropertyValue::Date(d) => property.date_value = Some(d.timestamp_millis()),+ }+ if property.is_empty() {+ return None;+ }+ Some(property)+}++/// Fetch an entity's properties flattened for the search index. Each value+/// lands under the field matching its type (equality-filterable values as+/// strings, numbers, or epoch-millis dates); null and unparseable values are+/// skipped so one bad value can't fail the whole index.+#[tracing::instrument(skip(pool), err)]+pub async fn get_entity_properties_for_index(+ pool: &Pool<Postgres>,+ entity_id: &str,+ entity_type: EntityType,+) -> anyhow::Result<Vec<IndexedEntityProperty>> {+ let rows = sqlx::query!(+ r#"+ SELECT+ property_definition_id,+ values as "values: serde_json::Value"+ FROM entity_properties+ WHERE entity_id = $1+ AND entity_type = $2+ "#,+ entity_id,+ entity_type as EntityType,+ )+ .fetch_all(pool)+ .await?;++ Ok(rows+ .into_iter()+ .filter_map(|row| flatten_property_for_index(row.property_definition_id, row.values))+ .collect())+}++/// Page through the distinct entity ids that hold property rows of one+/// entity type, ordered by entity id so offset pagination is stable. Used by+/// the search properties backfill.+#[tracing::instrument(skip(pool), err)]+pub async fn get_entity_ids_with_properties(+ pool: &Pool<Postgres>,+ entity_type: EntityType,+ limit: i64,+ offset: i64,+) -> anyhow::Result<Vec<String>> {+ let rows = sqlx::query_scalar!(+ r#"+ SELECT DISTINCT entity_id+ FROM entity_properties+ WHERE entity_type = $1+ ORDER BY entity_id+ LIMIT $2 OFFSET $3+ "#,+ entity_type as EntityType,+ limit,+ offset,+ )+ .fetch_all(pool)+ .await?;+ Ok(rows)+}++/// Batch variant of [`get_entity_properties_for_index`]: fetch the flattened+/// properties of many entities of one type in a single query, keyed by+/// entity id. Entities without properties are absent from the map.+#[tracing::instrument(skip(pool, entity_ids), err)]+pub async fn get_entity_properties_for_index_batch(+ pool: &Pool<Postgres>,+ entity_ids: &[String],+ entity_type: EntityType,+) -> anyhow::Result<HashMap<String, Vec<IndexedEntityProperty>>> {+ if entity_ids.is_empty() {+ return Ok(HashMap::new());+ }+ let rows = sqlx::query!(+ r#"+ SELECT+ entity_id,+ property_definition_id,+ values as "values: serde_json::Value"+ FROM entity_properties+ WHERE entity_id = ANY($1)+ AND entity_type = $2+ "#,+ entity_ids,+ entity_type as EntityType,+ )+ .fetch_all(pool)+ .await?;++ let mut result: HashMap<String, Vec<IndexedEntityProperty>> = HashMap::new();+ for row in rows {+ let Some(property) = flatten_property_for_index(row.property_definition_id, row.values)+ else {+ continue;+ };+ result.entry(row.entity_id).or_default().push(property);+ }++ Ok(result)+}diff --git a/rust/cloud-storage/properties/src/outbound/entity_properties_values_test.rs b/rust/cloud-storage/properties/src/outbound/entity_properties_values_test.rsnew file mode 100644index 0000000000..b3fe963eca--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/entity_properties_values_test.rs@@ -0,0 +1,539 @@+//! Integration tests for entity property reads, deletes, and option batch queries.++use super::{entity_properties_get_query, entity_property_queries, property_option_queries};+use chrono::Datelike;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_properties::service::property_value::PropertyValue;+use models_properties::{DataType, EntityReference, EntityType};+use sqlx::{Pool, Postgres};+use uuid::Uuid;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_entity_properties_values_sorted(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc1",+ EntityType::Document,+ )+ .await?;++ assert_eq!(properties.len(), 6);++ // Verify they are sorted by display name (case-insensitive alphabetical)+ assert_eq!(properties[0].definition.display_name, "Test Assigned To");+ assert_eq!(properties[1].definition.display_name, "Test Completed");+ assert_eq!(properties[2].definition.display_name, "Test Department");+ assert_eq!(properties[3].definition.display_name, "Test Description");+ assert_eq!(properties[4].definition.display_name, "Test Due Date");+ assert_eq!(properties[5].definition.display_name, "Test Priority");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_entity_properties_values_value_kinds(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc1",+ EntityType::Document,+ )+ .await?;++ // Select property has its options attached.+ let priority_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Priority")+ .unwrap();+ assert_eq!(priority_prop.options.as_ref().unwrap().len(), 4);++ // Boolean value+ let completed_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Completed")+ .unwrap();+ assert_eq!(completed_prop.value, Some(PropertyValue::Bool(false)));++ // String value+ let desc_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Description")+ .unwrap();+ assert_eq!(+ desc_prop.value,+ Some(PropertyValue::Str(+ "Important document for testing".to_string()+ ))+ );++ // Date value+ let date_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Due Date")+ .unwrap();+ assert_eq!(date_prop.definition.data_type, DataType::Date);+ let Some(PropertyValue::Date(date)) = &date_prop.value else {+ panic!("Expected Date value");+ };+ assert_eq!((date.year(), date.month(), date.day()), (2025, 12, 31));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_entity_properties_values_null_values(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc3",+ EntityType::Document,+ )+ .await?;++ // doc3 has 3 properties with NULL values+ assert_eq!(properties.len(), 3);++ for prop in properties {+ assert!(prop.value.is_none());+ }++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_entity_properties_values_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "nonexistent",+ EntityType::Document,+ )+ .await?;++ assert_eq!(properties.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_entity_properties_entity_references(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // Single entity reference on doc1.+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc1",+ EntityType::Document,+ )+ .await?;+ let assigned_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Assigned To")+ .unwrap();+ assert_eq!(assigned_prop.definition.data_type, DataType::Entity);+ assert_eq!(+ assigned_prop.definition.specific_entity_type,+ Some(EntityType::User)+ );+ assert!(assigned_prop.definition.is_multi_select);+ let Some(PropertyValue::EntityRef(refs)) = &assigned_prop.value else {+ panic!("Expected EntityReference value");+ };+ assert_eq!(refs.len(), 1);+ assert_eq!(refs[0].entity_id, "macro|[email protected]");+ assert_eq!(refs[0].entity_type, EntityType::User);++ // Multiple entity references on doc2.+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc2",+ EntityType::Document,+ )+ .await?;+ let assigned_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Assigned To")+ .unwrap();+ let Some(PropertyValue::EntityRef(refs)) = &assigned_prop.value else {+ panic!("Expected EntityReference value with 2 users");+ };+ assert_eq!(refs.len(), 2);+ let user_ids: Vec<&str> = refs.iter().map(|r| r.entity_id.as_str()).collect();+ assert!(user_ids.contains(&"macro|[email protected]"));+ assert!(user_ids.contains(&"macro|[email protected]"));++ // Null entity reference on doc3.+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc3",+ EntityType::Document,+ )+ .await?;+ let assigned_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Assigned To")+ .unwrap();+ assert_eq!(assigned_prop.definition.data_type, DataType::Entity);+ assert!(assigned_prop.value.is_none());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_entity_properties_multi_select_string(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc2",+ EntityType::Document,+ )+ .await?;++ // Department property is a multi-select SELECT_STRING+ let dept_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Department")+ .unwrap();++ assert_eq!(dept_prop.definition.data_type, DataType::SelectString);+ assert!(dept_prop.definition.is_multi_select);++ let options = dept_prop.options.as_ref().unwrap();+ assert_eq!(options.len(), 3); // Engineering, Marketing, Human Resources++ let Some(PropertyValue::SelectOption(ids)) = &dept_prop.value else {+ panic!("Expected SelectOption value with 2 departments");+ };+ assert_eq!(ids.len(), 2);+ for id in ids {+ assert!(options.iter().any(|opt| opt.id == *id));+ }++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_entity_properties_link_and_number_values(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let properties = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "proj1",+ EntityType::Project,+ )+ .await?;++ let link_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Website")+ .unwrap();+ assert_eq!(link_prop.definition.data_type, DataType::Link);+ assert_eq!(+ link_prop.value,+ Some(PropertyValue::Link(vec!["https://example.com".to_string()]))+ );++ let budget_prop = properties+ .iter()+ .find(|p| p.definition.display_name == "Test Budget")+ .unwrap();+ assert_eq!(budget_prop.definition.data_type, DataType::Number);+ assert_eq!(budget_prop.value, Some(PropertyValue::Num(50000.50)));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_bulk_entity_properties(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let entity_refs = vec![+ EntityReference::new("doc1", EntityType::Document),+ EntityReference::new("doc2", EntityType::Document),+ EntityReference::new("proj1", EntityType::Project),+ ];+ let properties_map =+ entity_properties_get_query::get_bulk_entity_properties_values(&pool, &entity_refs).await?;++ assert_eq!(properties_map.len(), 3);+ assert_eq!(properties_map.get("doc1").unwrap().len(), 6);+ assert_eq!(properties_map.get("doc2").unwrap().len(), 4);+ assert_eq!(properties_map.get("proj1").unwrap().len(), 5);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_bulk_entity_properties_includes_empty_entities(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let entity_refs = vec![+ EntityReference::new("doc1", EntityType::Document),+ EntityReference::new("nonexistent", EntityType::Document),+ ];+ let properties_map =+ entity_properties_get_query::get_bulk_entity_properties_values(&pool, &entity_refs).await?;++ // Both entities should be in the map+ assert_eq!(properties_map.len(), 2);+ assert!(properties_map.contains_key("doc1"));+ assert!(properties_map.contains_key("nonexistent"));++ // nonexistent should have empty array+ assert_eq!(properties_map.get("nonexistent").unwrap().len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_bulk_entity_properties_empty_input(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let entity_refs: Vec<EntityReference> = vec![];+ let properties_map =+ entity_properties_get_query::get_bulk_entity_properties_values(&pool, &entity_refs).await?;++ assert_eq!(properties_map.len(), 0);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn lookup_entity_property(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let entity_property_id = "e0111111-1111-1111-1111-111111111111"+ .parse::<Uuid>()+ .unwrap();+ let info = entity_properties_get_query::lookup_entity_property(&pool, entity_property_id)+ .await?+ .expect("entity property should exist");++ assert_eq!(info.entity_id, "doc1");+ assert_eq!(info.entity_type, EntityType::Document);+ assert_eq!(+ info.property_definition_id,+ "11111111-1111-1111-1111-111111111111"+ .parse::<Uuid>()+ .unwrap()+ );++ // Nonexistent id yields None.+ let missing = entity_properties_get_query::lookup_entity_property(&pool, Uuid::nil()).await?;+ assert!(missing.is_none());++ Ok(())+}++/// Definition ids returned for tagdoc1 given a set of requested property+/// ids and an optional tag viewer.+async fn tagdoc_definition_ids(+ pool: &Pool<Postgres>,+ property_ids: &[Uuid],+ tag_viewer: Option<¯o_user_id::user_id::MacroUserIdStr<'_>>,+) -> anyhow::Result<Vec<Uuid>> {+ let entity_refs = vec![EntityReference {+ entity_id: "tagdoc1".to_string(),+ entity_type: EntityType::Document,+ specific_message_id: None,+ }];+ let map = entity_properties_get_query::get_bulk_entity_properties_values_filtered(+ pool,+ &entity_refs,+ property_ids,+ tag_viewer,+ )+ .await?;+ Ok(map["tagdoc1"]+ .iter()+ .map(|p| p.definition.id)+ .collect::<Vec<_>>())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties", "tags"))+)]+async fn get_bulk_filtered_includes_caller_visible_tags(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let priority = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let user1_tags = Uuid::parse_str("aa111111-1111-1111-1111-111111111111")?;+ let team1_tags = Uuid::parse_str("aa222222-2222-2222-2222-222222222222")?;+ let user2_tags = Uuid::parse_str("aa333333-3333-3333-3333-333333333333")?;++ // user1 sees the requested id plus their own and their team's tags,+ // never another user's personal tags.+ let user1 =+ macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let user3 =+ macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let ids = tagdoc_definition_ids(&pool, &[priority], Some(&user1)).await?;+ assert_eq!(ids.len(), 3);+ assert!(ids.contains(&priority));+ assert!(ids.contains(&user1_tags));+ assert!(ids.contains(&team1_tags));+ assert!(!ids.contains(&user2_tags));++ // A teammate without a personal set sees only the team tags.+ let ids = tagdoc_definition_ids(&pool, &[priority], Some(&user3)).await?;+ assert_eq!(ids.len(), 2);+ assert!(ids.contains(&priority));+ assert!(ids.contains(&team1_tags));++ // No viewer: only the explicitly requested ids.+ let ids = tagdoc_definition_ids(&pool, &[priority], None).await?;+ assert_eq!(ids, vec![priority]);++ // A viewer with no requested ids still gets their tags.+ let ids = tagdoc_definition_ids(&pool, &[], Some(&user1)).await?;+ assert_eq!(ids.len(), 2);+ assert!(ids.contains(&user1_tags));+ assert!(ids.contains(&team1_tags));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_entity_property_removes_property(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let entity_property_id = "e0111111-1111-1111-1111-111111111111"+ .parse::<Uuid>()+ .unwrap();++ let properties_before = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc1",+ EntityType::Document,+ )+ .await?;+ let initial_count = properties_before.len();+ assert!(initial_count > 0);++ entity_property_queries::delete_entity_property(&pool, entity_property_id).await?;++ let properties_after = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc1",+ EntityType::Document,+ )+ .await?;+ assert_eq!(properties_after.len(), initial_count - 1);++ // Deleting a non-existent entity property should succeed (no error).+ entity_property_queries::delete_entity_property(&pool, Uuid::nil()).await?;++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_entity_properties_only_deletes_specific_entity(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let entity_ref = EntityReference::new("doc1", EntityType::Document);++ let doc1_before = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc1",+ EntityType::Document,+ )+ .await?;+ assert!(!doc1_before.is_empty());+ let doc2_before = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc2",+ EntityType::Document,+ )+ .await?;+ let proj1_before = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "proj1",+ EntityType::Project,+ )+ .await?;+ assert!(!proj1_before.is_empty());++ entity_property_queries::delete_entity_properties(&pool, &entity_ref).await?;++ // doc1's properties are gone; doc2 and proj1 are unchanged.+ let doc1_after = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc1",+ EntityType::Document,+ )+ .await?;+ assert_eq!(doc1_after.len(), 0);+ let doc2_after = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "doc2",+ EntityType::Document,+ )+ .await?;+ assert_eq!(doc2_after.len(), doc2_before.len());+ let proj1_after = entity_properties_get_query::get_entity_properties_values(+ &pool,+ "proj1",+ EntityType::Project,+ )+ .await?;+ assert_eq!(proj1_after.len(), proj1_before.len());++ // Deleting a non-existent entity should succeed (no error).+ let nonexistent_ref = EntityReference::new("nonexistent", EntityType::Document);+ entity_property_queries::delete_entity_properties(&pool, &nonexistent_ref).await?;++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_property_options_batch(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let property_ids = vec![+ "11111111-1111-1111-1111-111111111111"+ .parse::<Uuid>()+ .unwrap(), // Priority: 4 options+ "44444444-4444-4444-4444-444444444444"+ .parse::<Uuid>()+ .unwrap(), // Score: 5 options+ ];++ let options_map =+ property_option_queries::get_property_options_batch(&pool, &property_ids).await?;++ assert_eq!(options_map.len(), 2);+ assert_eq!(options_map.get(&property_ids[0]).unwrap().len(), 4);+ assert_eq!(options_map.get(&property_ids[1]).unwrap().len(), 5);++ // Empty input yields an empty map.+ let empty = property_option_queries::get_property_options_batch(&pool, &[]).await?;+ assert_eq!(empty.len(), 0);++ Ok(())+}diff --git a/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rsindex 3f7ea58b2f..042bd5801f 100644--- a/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs+++ b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs@@ -1,7 +1,7 @@//! General entity property query helpers.-use models_properties::EntityType;use models_properties::service::property_value::PropertyValue;+use models_properties::{EntityReference, EntityType};use sqlx::{Pool, Postgres};use uuid::Uuid;@@ -209,3 +209,36 @@ pub async fn count_valid_property_options(Ok(count.0)}++/// Deletes an entity property by its ID.+#[tracing::instrument(skip(pool))]+pub async fn delete_entity_property(+ pool: &Pool<Postgres>,+ entity_property_id: Uuid,+) -> anyhow::Result<()> {+ sqlx::query!(+ "DELETE FROM entity_properties WHERE id = $1",+ entity_property_id+ )+ .execute(pool)+ .await?;++ Ok(())+}++/// Deletes all properties attached to an entity.+#[tracing::instrument(skip(pool))]+pub async fn delete_entity_properties(+ pool: &Pool<Postgres>,+ entity_reference: &EntityReference,+) -> anyhow::Result<()> {+ sqlx::query!(+ "DELETE FROM entity_properties WHERE entity_id = $1 AND entity_type = $2",+ entity_reference.entity_id,+ entity_reference.entity_type as _,+ )+ .execute(pool)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/properties/src/outbound/metadata_queries.rs b/rust/cloud-storage/properties/src/outbound/metadata_queries.rsnew file mode 100644index 0000000000..0c81bc286b--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/metadata_queries.rs@@ -0,0 +1,109 @@+//! Queries for entity metadata (documents, threads, projects) read from macrodb.+//!+//! These read tables owned by other domains; the properties domain surfaces+//! them as read-only metadata properties.++use models_properties::service::document_metadata::DocumentMetadata;+use models_properties::service::project_metadata::ProjectMetadata;+use models_properties::service::thread_metadata::ThreadMetadata;+use sqlx::{Pool, Postgres};+use uuid::Uuid;++/// Get document metadata by document ID from macrodb+#[tracing::instrument(skip(pool), err)]+pub async fn get_document_metadata(+ pool: &Pool<Postgres>,+ document_id: &str,+) -> anyhow::Result<Option<DocumentMetadata>> {+ let result = sqlx::query!(+ r#"+ SELECT+ d.id,+ d.name,+ d.owner,+ d."fileType" as "file_type",+ d."projectId" as "project_id",+ d."createdAt"::timestamptz as "created_at!",+ d."updatedAt"::timestamptz as "updated_at!"+ FROM+ "Document" d+ WHERE+ d.id = $1+ "#,+ document_id+ )+ .fetch_optional(pool)+ .await?;++ Ok(result.map(|row| DocumentMetadata {+ id: row.id,+ name: row.name,+ owner: row.owner,+ file_type: row.file_type,+ project_id: row.project_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ }))+}++/// Get thread metadata by thread ID from macrodb+#[tracing::instrument(skip(pool), err)]+pub async fn get_thread_metadata(+ pool: &Pool<Postgres>,+ thread_id: Uuid,+) -> anyhow::Result<Option<ThreadMetadata>> {+ Ok(sqlx::query_as!(+ ThreadMetadata,+ r#"+ SELECT+ t.id,+ t.latest_inbound_message_ts as last_received,+ t.latest_outbound_message_ts as last_sent,+ first_msg.internal_date_ts as thread_started,+ first_msg.subject,+ (SELECT COUNT(*)::bigint FROM email_messages WHERE thread_id = t.id) as "message_count!"+ FROM+ email_threads t+ -- LATERAL join to get subject and timestamp from the first message+ LEFT JOIN LATERAL (+ SELECT internal_date_ts, subject+ FROM email_messages+ WHERE thread_id = t.id+ ORDER BY internal_date_ts ASC NULLS LAST+ LIMIT 1+ ) first_msg ON true+ WHERE+ t.id = $1+ "#,+ thread_id+ )+ .fetch_optional(pool)+ .await?)+}++/// Get project metadata by project ID from macrodb+#[tracing::instrument(skip(pool), err)]+pub async fn get_project_metadata(+ pool: &Pool<Postgres>,+ project_id: &str,+) -> anyhow::Result<Option<ProjectMetadata>> {+ Ok(sqlx::query_as!(+ ProjectMetadata,+ r#"+ SELECT+ p.id,+ p.name,+ p."userId" as "owner",+ p."parentId" as "parent_id",+ p."createdAt"::timestamptz as "created_at!",+ p."updatedAt"::timestamptz as "updated_at!"+ FROM+ "Project" p+ WHERE+ p.id = $1 AND p."deletedAt" IS NULL+ "#,+ project_id+ )+ .fetch_optional(pool)+ .await?)+}diff --git a/rust/cloud-storage/properties/src/outbound/notification_service.rs b/rust/cloud-storage/properties/src/outbound/notification_service.rsindex 952b7f81e3..fbe7368074 100644--- a/rust/cloud-storage/properties/src/outbound/notification_service.rs+++ b/rust/cloud-storage/properties/src/outbound/notification_service.rs@@ -1,14 +1,24 @@//! Notification service implementation for properties.-use crate::domain::ports::NotificationService;-use model_notifications::TaskAssignedMetadata;-use notification::domain::models::SendNotificationRequest;+use std::collections::HashSet;++use futures::future::join_all;+use macro_user_id::cowlike::CowLike;+use notification::domain::models::SendNotificationRequestBuilder;use notification::domain::service::NotificationIngress;-use uuid::Uuid;+use sqlx::{Pool, Postgres};++use super::entity_info_queries;+use crate::domain::model::TaskAssignedNotification;+use crate::domain::ports::NotificationService;/// Notification service implementation using the new notification client.+///+/// Enriches domain-level notifications with display data (task name, sender+/// profile picture) and fans out one notification per recipient.pub struct NotificationServiceImpl<T> {notification_client: T,+ pool: Pool<Postgres>,}impl<T> NotificationServiceImpl<T>@@ -16,9 +26,10 @@ whereT: NotificationIngress,{/// Create a new notification service with the notification client.- pub fn new(notification_client: T) -> Self {+ pub fn new(notification_client: T, pool: Pool<Postgres>) -> Self {Self {notification_client,+ pool,}}}@@ -29,23 +40,77 @@ where{type Err = anyhow::Error;- #[tracing::instrument(skip(self, message), err)]- async fn send_notification(+ #[tracing::instrument(skip(self, notification), fields(task_id = %notification.task_id), err)]+ async fn send_task_assigned<'a>(&self,- message: SendNotificationRequest<- '_,- TaskAssignedMetadata,- notification::domain::models::apple::PushNotificationData,- >,- ) -> Result<Uuid, Self::Err> {- let result = self- .notification_client- .send_notification(message)- .await- .map_err(|e| anyhow::anyhow!("failed to send notification: {}", e))?;-- Ok(result- .map(|r| r.notification_id)- .unwrap_or_else(Uuid::now_v7))+ notification: TaskAssignedNotification<'a>,+ ) -> Result<(), Self::Err> {+ // Tasks are stored as documents, so the task name is the document name.+ let task_name =+ entity_info_queries::get_document_name(&self.pool, ¬ification.task_id.to_string())+ .await+ .ok()+ .flatten();++ let sender_profile_picture_url = entity_info_queries::get_user_profile_picture(+ &self.pool,+ notification.assigned_by.as_ref(),+ )+ .await+ .ok()+ .flatten();++ let assigned_by = notification.assigned_by.into_owned();+ let notification_entity =+ model_entity::EntityType::Document.with_entity_string(notification.task_id.to_string());++ let notification_futures: Vec<_> = notification+ .recipient_ids+ .iter()+ .map(|recipient_id| {+ let metadata = model_notifications::TaskAssignedMetadata {+ task_id: notification.task_id.to_string(),+ task_name: task_name.clone(),+ sub_type: Some(model_notifications::NotificationDocumentSubType::Task),+ assigned_by: assigned_by.clone(),+ sender_profile_picture_url: sender_profile_picture_url.clone(),+ };++ let request = SendNotificationRequestBuilder {+ notification_entity: notification_entity.clone(),+ secondary_notification_entity: None,+ notification: metadata,+ sender_id: Some(assigned_by.clone()),+ recipient_ids: HashSet::from([recipient_id.copied()]),+ }+ .into_request()+ .with_apns()+ .with_conn_gateway();++ async move {+ let send_result = self.notification_client.send_notification(request).await;+ match send_result {+ Ok(result) => {+ tracing::debug!(+ recipient_id = %recipient_id,+ notification_id = ?result.map(|r| r.notification_id),+ "sent task assignment notification"+ );+ }+ Err(e) => {+ tracing::error!(+ recipient_id = %recipient_id,+ error = ?e,+ "failed to send task assignment notification"+ );+ }+ }+ }+ })+ .collect();++ join_all(notification_futures).await;++ Ok(())}}diff --git a/rust/cloud-storage/properties/src/outbound/options_test.rs b/rust/cloud-storage/properties/src/outbound/options_test.rsnew file mode 100644index 0000000000..3e07f258ca--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/options_test.rs@@ -0,0 +1,407 @@+//! Integration tests for property option and tag operations on PropertiesPgRepo.++use super::properties_pg_repo::PropertiesPgRepo;+use crate::domain::model::{PropertyDefinitionOwner, UpdatePropertyOptionOutcome};+use crate::domain::ports::PropertiesRepo;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_properties::service::property_option::PropertyOptionValue;+use models_properties::service::property_value::PropertyValue;+use models_properties::{DataType, EntityType};+use sqlx::{Pool, Postgres};+use uuid::Uuid;++const PRIORITY_PROPERTY_ID: &str = "11111111-1111-1111-1111-111111111111";+const SCORE_PROPERTY_ID: &str = "44444444-4444-4444-4444-444444444444";+const PRIORITY_OPTION_LOW: &str = "10111111-1111-1111-1111-111111111111";+const PRIORITY_OPTION_MEDIUM: &str = "10111111-1111-1111-1111-111111111112";+const PRIORITY_OPTION_HIGH: &str = "10111111-1111-1111-1111-111111111113";+const PRIORITY_OPTION_URGENT: &str = "10111111-1111-1111-1111-111111111114";++fn team_1() -> Uuid {+ "0e000000-0000-0000-0000-000000000001".parse().unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_option_string(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();++ let options_before = repo.get_property_options(property_id).await?;+ assert_eq!(options_before.len(), 4);++ let option = repo+ .create_property_option(+ property_id,+ 4,+ PropertyOptionValue::String("Extra High".to_string()),+ None,+ )+ .await?;++ let options_after = repo.get_property_options(property_id).await?;+ assert_eq!(options_after.len(), 5);++ assert_eq!(option.display_order, 4);+ assert_eq!(option.property_definition_id, property_id);+ assert_eq!(+ option.value,+ PropertyOptionValue::String("Extra High".to_string())+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_option_number(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let property_id = SCORE_PROPERTY_ID.parse::<Uuid>().unwrap();++ let option = repo+ .create_property_option(property_id, 0, PropertyOptionValue::Number(3.5), None)+ .await?;++ assert_eq!(option.display_order, 0);+ assert_eq!(option.value, PropertyOptionValue::Number(3.5));++ // Options are ordered by display_order, so the new option sorts first.+ let options = repo.get_property_options(property_id).await?;+ assert_eq!(options[0].value, PropertyOptionValue::Number(3.5));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_option_duplicate_fails(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ // "Low" already exists on the priority property.+ let result = repo+ .create_property_option(+ PRIORITY_PROPERTY_ID.parse().unwrap(),+ 4,+ PropertyOptionValue::String("Low".to_string()),+ None,+ )+ .await;+ assert!(result.is_err());++ // 1.0 already exists on the score property.+ let result = repo+ .create_property_option(+ SCORE_PROPERTY_ID.parse().unwrap(),+ 5,+ PropertyOptionValue::Number(1.0),+ None,+ )+ .await;+ assert!(result.is_err());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn create_property_option_invalid_property_fails(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let result = repo+ .create_property_option(+ Uuid::nil(),+ 0,+ PropertyOptionValue::String("Test".to_string()),+ None,+ )+ .await;++ assert!(result.is_err()); // Foreign key constraint violation++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn update_property_option_renames_and_recolors(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();++ let outcome = repo+ .update_property_option(+ option_id,+ PropertyOptionValue::String("Lowest".to_string()),+ Some("#FF0000".to_string()),+ 3,+ )+ .await?;++ // Same id, so every entity referencing it resolves the new value/color (propagation by id).+ let UpdatePropertyOptionOutcome::Updated(updated) = outcome else {+ panic!("expected Updated outcome");+ };+ assert_eq!(updated.id, option_id);+ assert_eq!(updated.color.as_deref(), Some("#FF0000"));+ assert_eq!(updated.display_order, 3);+ assert_eq!(+ updated.value,+ PropertyOptionValue::String("Lowest".to_string())+ );++ let fetched = repo+ .get_property_option(option_id)+ .await?+ .expect("option should still exist");+ assert_eq!(fetched.color.as_deref(), Some("#FF0000"));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn update_property_option_missing_returns_not_found(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let outcome = repo+ .update_property_option(+ Uuid::nil(),+ PropertyOptionValue::String("x".to_string()),+ None,+ 0,+ )+ .await?;++ assert!(matches!(outcome, UpdatePropertyOptionOutcome::NotFound));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn update_property_option_duplicate_value(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();++ // "Medium" already exists on the same property.+ let outcome = repo+ .update_property_option(+ option_id,+ PropertyOptionValue::String("Medium".to_string()),+ None,+ 0,+ )+ .await?;++ assert!(matches!(+ outcome,+ UpdatePropertyOptionOutcome::DuplicateValue+ ));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_property_option_removes_option(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();+ let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();++ assert!(repo.get_property_option(option_id).await?.is_some());++ let deleted = repo.delete_property_option(property_id, option_id).await?;+ assert!(deleted);++ assert!(repo.get_property_option(option_id).await?.is_none());++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_nonexistent_property_option(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);++ let deleted = repo+ .delete_property_option(PRIORITY_PROPERTY_ID.parse().unwrap(), Uuid::nil())+ .await?;+ assert!(!deleted);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_property_option_reduces_count(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();+ let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();++ let count_before = repo.get_property_options(property_id).await?.len();++ repo.delete_property_option(property_id, option_id).await?;++ let count_after = repo.get_property_options(property_id).await?.len();+ assert_eq!(count_after, count_before - 1);++ Ok(())+}++/// Reproduces the dangling-option bug: an entity value referencing+/// [A, B, C, D] must drop D once option D is deleted, so a later set-value+/// echoing the surviving ids passes option validation.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn delete_property_option_strips_value_references(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool.clone());+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();+ let opt_a = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();+ let opt_b = PRIORITY_OPTION_MEDIUM.parse::<Uuid>().unwrap();+ let opt_c = PRIORITY_OPTION_HIGH.parse::<Uuid>().unwrap();+ let opt_d = PRIORITY_OPTION_URGENT.parse::<Uuid>().unwrap();++ // Entity selects all four options.+ repo.upsert_entity_property(+ "doc_cascade",+ EntityType::Document,+ property_id,+ Some(PropertyValue::SelectOption(vec![+ opt_a, opt_b, opt_c, opt_d,+ ])),+ )+ .await?;++ // A new option created after selection (the "new tag" in the repro).+ let opt_e = repo+ .create_property_option(+ property_id,+ 4,+ PropertyOptionValue::String("New".to_string()),+ None,+ )+ .await?+ .id;++ // Delete option D.+ let deleted = repo.delete_property_option(property_id, opt_d).await?;+ assert!(deleted);++ // Read the raw stored value (bypassing the read-path cleaner) to prove+ // the dangling id is gone from storage, not just filtered on read.+ let raw: serde_json::Value = sqlx::query_scalar!(+ r#"+ SELECT values as "values!: serde_json::Value"+ FROM entity_properties+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3+ "#,+ "doc_cascade",+ EntityType::Document as EntityType,+ property_id+ )+ .fetch_one(&pool)+ .await?;++ let stored: PropertyValue = serde_json::from_value(raw)?;+ let PropertyValue::SelectOption(ids) = stored else {+ panic!("expected SelectOption");+ };+ assert_eq!(ids, vec![opt_a, opt_b, opt_c]);++ // The surviving selection plus the new option all validate, so the+ // set-value that previously 400'd now succeeds.+ let valid = repo+ .count_valid_property_options(property_id, &[opt_a, opt_b, opt_c, opt_e])+ .await?;+ assert_eq!(valid, 4);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_or_create_tag_definition_is_idempotent(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let owner = PropertyDefinitionOwner::Team(team_1());++ let first = repo.get_or_create_tag_definition(owner).await?;+ assert_eq!(first.data_type, DataType::Tag);+ assert!(first.is_multi_select);++ // A second call returns the same definition rather than creating a duplicate.+ let second = repo.get_or_create_tag_definition(owner).await?;+ assert_eq!(first.id, second.id);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_tag_definition_none_then_some(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let owner = PropertyDefinitionOwner::Team(team_1());++ let before = repo.get_tag_definition(owner).await?;+ assert!(before.is_none());++ let created = repo.get_or_create_tag_definition(owner).await?;++ let after = repo.get_tag_definition(owner).await?;+ assert_eq!(after.map(|d| d.id), Some(created.id));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties"))+)]+async fn get_or_create_tag_definition_coexists_with_same_named_property(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool);+ let owner = PropertyDefinitionOwner::Team(team_1());++ // Owner already has a non-tag property literally named "Tags".+ repo.create_property_definition(owner, "Tags", DataType::String, false, None, Vec::new())+ .await?;++ // Provisioning the tag set still succeeds: tag definitions are exempt from the+ // display-name uniqueness that applies to user-created properties.+ let tag_def = repo.get_or_create_tag_definition(owner).await?;+ assert_eq!(tag_def.data_type, DataType::Tag);++ let again = repo.get_or_create_tag_definition(owner).await?;+ assert_eq!(tag_def.id, again.id);++ Ok(())+}diff --git a/rust/cloud-storage/properties/src/outbound/permission_queries.rs b/rust/cloud-storage/properties/src/outbound/permission_queries.rsnew file mode 100644index 0000000000..3566f65436--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/permission_queries.rs@@ -0,0 +1,72 @@+//! Permission-related query helpers.+//!+//! These queries read tables owned by other domains but are needed by the+//! permission outbound adapter. They are inlined here so this crate does not+//! depend on the monolithic db client crates.++use models_properties::EntityType;+use sqlx::{Pool, Postgres};+use uuid::Uuid;++/// Gets the entity's owner and whether it's deleted.+/// Errors if the entity doesn't exist or the entity type is unsupported.+pub async fn get_owner_and_deleted(+ pool: &Pool<Postgres>,+ entity_id: &str,+ entity_type: EntityType,+) -> anyhow::Result<(String, bool)> {+ let result = match entity_type {+ // The following entity types are either deleted immediately or simply unsupported+ EntityType::Channel | EntityType::Company | EntityType::User | EntityType::Thread => {+ anyhow::bail!("unsupported entity type")+ }+ EntityType::Document | EntityType::Task => {+ sqlx::query!(+ r#"SELECT owner, "deletedAt" as deleted_at FROM "Document" WHERE id=$1"#,+ entity_id+ )+ .map(|r| (r.owner, r.deleted_at.is_some()))+ .fetch_one(pool)+ .await?+ }+ EntityType::Chat => {+ sqlx::query!(+ r#"SELECT "userId" as user_id, "deletedAt" as deleted_at FROM "Chat" WHERE id=$1"#,+ entity_id+ )+ .map(|r| (r.user_id, r.deleted_at.is_some()))+ .fetch_one(pool)+ .await?+ }+ EntityType::Project => sqlx::query!(+ r#"SELECT "userId" as user_id, "deletedAt" as deleted_at FROM "Project" WHERE id=$1"#,+ entity_id+ )+ .map(|r| (r.user_id, r.deleted_at.is_some()))+ .fetch_one(pool)+ .await?,+ };++ Ok(result)+}++/// Gets the macro user id of the owner of an email thread via its link.+/// Returns `None` if the thread doesn't exist.+pub async fn get_macro_id_from_thread_id(+ pool: &Pool<Postgres>,+ thread_id: Uuid,+) -> anyhow::Result<Option<String>> {+ let macro_id = sqlx::query_scalar!(+ r#"+ SELECT l.macro_id+ FROM email_threads t+ JOIN email_links l ON t.link_id = l.id+ WHERE t.id = $1+ "#,+ thread_id+ )+ .fetch_optional(pool)+ .await?;++ Ok(macro_id)+}diff --git a/rust/cloud-storage/properties/src/outbound/permission_service.rs b/rust/cloud-storage/properties/src/outbound/permission_service.rsindex 9350aa099d..4094f2d54a 100644--- a/rust/cloud-storage/properties/src/outbound/permission_service.rs+++ b/rust/cloud-storage/properties/src/outbound/permission_service.rs@@ -11,8 +11,8 @@ use models_properties::EntityType;use sqlx::{Pool, Postgres};use uuid::Uuid;+use super::permission_queries;use crate::domain::ports::PermissionService;-use email_db_client::threads::get::get_macro_id_from_thread_id;/// Permission service implementation using database.pub struct PermissionServiceImpl<Svc> {@@ -27,34 +27,16 @@ impl<Svc: EntityAccessService> PermissionServiceImpl<Svc> {entity_access_service,}}-}--/// Map `models_properties::EntityType` to `model_entity::EntityType`.-fn map_entity_type(entity_type: EntityType) -> Option<ModelEntityType> {- match entity_type {- EntityType::Document => Some(ModelEntityType::Document),- EntityType::Chat => Some(ModelEntityType::Chat),- EntityType::Project => Some(ModelEntityType::Project),- EntityType::Thread => Some(ModelEntityType::EmailThread),- EntityType::Channel => Some(ModelEntityType::Channel),- EntityType::Task => Some(ModelEntityType::Document), // tasks use document permissions- // CRM company access is resolved from the owning team's membership- // (member → View, admin → Edit, owner → Owner).- EntityType::Company => Some(ModelEntityType::CrmCompany),- EntityType::User => None,- }-}-impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc> {- type Err = anyhow::Error;-- #[tracing::instrument(skip(self), fields(user_id = %user_id, entity_id = %entity_id, entity_type = ?entity_type), err)]- async fn check_entity_edit_permission(+ /// Gets the user's access level for an entity, including the thread+ /// ownership fallback for owned threads where permission records were+ /// never created.+ async fn get_access_level(&self,- user_id: &str,+ user_id: Option<&MacroUserIdStr<'_>>,entity_id: &str,entity_type: EntityType,- ) -> Result<(), Self::Err> {+ ) -> anyhow::Result<Option<AccessLevel>> {let model_entity_type = match map_entity_type(entity_type) {Some(t) => t,None => {@@ -63,8 +45,7 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>}};- let parsed_user_id = MacroUserIdStr::parse_from_str(user_id);- let user_id_ref = parsed_user_id.as_ref().ok().map(std::ops::Deref::deref);+ let user_id_ref = user_id.map(std::ops::Deref::deref);let access_level = self.entity_access_service@@ -72,7 +53,7 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>.await.map_err(|e: AccessError| {tracing::error!(- error = %e,+ error = ?e,"failed to get user access level");anyhow::anyhow!("Failed to get user access level: {}", e)@@ -82,20 +63,101 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>// This handles owned threads where EmailThreadPermission/UserItemAccess were never created.if access_level.is_none()&& entity_type == EntityType::Thread+ && let Some(user_id) = user_id&& let Ok(thread_id) = Uuid::parse_str(entity_id)- && let Ok(Some(owner_id)) = get_macro_id_from_thread_id(&self.db, thread_id).await- && owner_id == user_id{- tracing::debug!("user owns thread via link_id, granting owner access");- return Ok(());+ match permission_queries::get_macro_id_from_thread_id(&self.db, thread_id).await {+ Ok(Some(owner_id)) if owner_id == user_id.as_ref() => {+ tracing::debug!("user owns thread via link_id, granting owner access");+ return Ok(Some(AccessLevel::Owner));+ }+ Ok(_) => {}+ Err(e) => {+ tracing::error!(+ error = ?e,+ thread_id = %thread_id,+ "failed to look up thread owner for permission fallback"+ );+ }+ }}- match access_level {+ Ok(access_level)+ }+}++/// Map `models_properties::EntityType` to `model_entity::EntityType`.+fn map_entity_type(entity_type: EntityType) -> Option<ModelEntityType> {+ match entity_type {+ EntityType::Document => Some(ModelEntityType::Document),+ EntityType::Chat => Some(ModelEntityType::Chat),+ EntityType::Project => Some(ModelEntityType::Project),+ EntityType::Thread => Some(ModelEntityType::EmailThread),+ EntityType::Channel => Some(ModelEntityType::Channel),+ EntityType::Task => Some(ModelEntityType::Document), // tasks use document permissions+ // CRM company access is resolved from the owning team's membership+ // (member → View, admin → Edit, owner → Owner).+ EntityType::Company => Some(ModelEntityType::CrmCompany),+ EntityType::User => None,+ }+}++impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc> {+ type Err = anyhow::Error;++ #[tracing::instrument(skip(self), fields(user_id = %user_id, entity_id = %entity_id, entity_type = ?entity_type), err)]+ async fn check_entity_edit_permission(+ &self,+ user_id: &MacroUserIdStr<'_>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<(), Self::Err> {+ match self+ .get_access_level(Some(user_id), entity_id, entity_type)+ .await?+ {Some(AccessLevel::Edit) | Some(AccessLevel::Owner) => Ok(()),Some(_) | None => anyhow::bail!("Access denied"),}}+ #[tracing::instrument(skip(self), fields(user_id = ?user_id, entity_id = %entity_id, entity_type = ?entity_type), err)]+ async fn check_entity_view_permission(+ &self,+ user_id: Option<&MacroUserIdStr<'_>>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<(), Self::Err> {+ // Check if entity is deleted: the owner always has access, and deleted+ // entities are only visible to their owner.+ match entity_type {+ EntityType::Channel | EntityType::Company | EntityType::User | EntityType::Thread => {}+ _ => {+ let (owner, deleted) =+ permission_queries::get_owner_and_deleted(&self.db, entity_id, entity_type)+ .await?;++ // If you are the owner fast return+ if user_id.is_some_and(|u| owner == u.as_ref()) {+ return Ok(());+ }++ // If the item is deleted and you aren't the owner you are unauthorized+ if deleted {+ anyhow::bail!("Access denied");+ }+ }+ }++ match self+ .get_access_level(user_id, entity_id, entity_type)+ .await?+ {+ Some(_) => Ok(()), // Any access level is sufficient for viewing+ None => anyhow::bail!("Access denied"),+ }+ }+#[tracing::instrument(skip(self), fields(task_id = %task_id, user_count = user_ids.len()), err)]async fn grant_permissions_to_task(&self,@@ -125,17 +187,6 @@ impl<Svc: EntityAccessService> PermissionService for PermissionServiceImpl<Svc>entity_id: &str,entity_type: EntityType,) -> Result<(String, bool), Self::Err> {- let item_type = match entity_type {- // The following entity types are either deleted immediately or simply unsupported- EntityType::Channel | EntityType::Company | EntityType::User | EntityType::Thread => {- anyhow::bail!("unsupported entity type")- }- EntityType::Chat => "chat",- EntityType::Document | EntityType::Task => "document",- EntityType::Project => "project",- };-- macro_db_client::item_access::get::get_owner_and_deleted(&self.db, entity_id, item_type)- .await+ permission_queries::get_owner_and_deleted(&self.db, entity_id, entity_type).await}}diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rsindex 046a9e869c..d642982024 100644--- a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs@@ -1,5 +1,6 @@//! PostgreSQL implementation for properties repository.+use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_value::PropertyValue;use models_properties::{EntityReference, EntityType};@@ -8,12 +9,21 @@ use std::collections::HashMap;use uuid::Uuid;use super::{- entity_properties_get_query, entity_property_queries, property_definition_queries,- task_property_queries,+ entity_properties_get_query, entity_property_queries, metadata_queries,+ property_definition_queries, property_option_queries, task_property_queries,+};+use crate::domain::model::{+ EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, UpdatePropertyOptionOutcome,};-use crate::domain::model::{EntityPropertiesKey, EntityPropertyInfo};use crate::domain::ports::PropertiesRepo;+use models_properties::DataType;+use models_properties::EntityPropertyReference;+use models_properties::service::document_metadata::DocumentMetadata;+use models_properties::service::project_metadata::ProjectMetadata;use models_properties::service::property_definition::PropertyDefinition;+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};+use models_properties::service::thread_metadata::ThreadMetadata;/// PostgreSQL implementation of PropertiesRepo.#[derive(Debug, Clone)]@@ -28,6 +38,26 @@ impl PropertiesPgRepo {}}+fn regroup_entity_properties(+ entity_refs: &[EntityReference],+ properties_by_entity_id: HashMap<String, Vec<EntityPropertyWithDefinition>>,+) -> HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>> {+ let mut result = entity_refs+ .iter()+ .map(|entity_ref| (EntityPropertiesKey::from(entity_ref), Vec::new()))+ .collect::<HashMap<_, _>>();++ for property in properties_by_entity_id.into_values().flatten() {+ let key = EntityPropertiesKey {+ entity_id: property.property.entity_id.clone(),+ entity_type: property.property.entity_type,+ };+ result.entry(key).or_default().push(property);+ }++ result+}+impl PropertiesRepo for PropertiesPgRepo {type Err = anyhow::Error;@@ -40,6 +70,167 @@ impl PropertiesRepo for PropertiesPgRepo {.await}+ #[tracing::instrument(skip(self))]+ async fn get_property_definition_with_owner(+ &self,+ property_definition_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+ ) -> Result<Option<PropertyDefinition>, Self::Err> {+ property_definition_queries::get_property_definition_with_owner(+ &self.pool,+ property_definition_id,+ user_id,+ team_id,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn list_property_definitions(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+ ) -> Result<Vec<PropertyDefinition>, Self::Err> {+ property_definition_queries::list_property_definitions(+ &self.pool,+ team_id,+ user_id,+ include_system,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn list_property_definitions_with_options(+ &self,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+ ) -> Result<Vec<PropertyDefinitionWithOptions>, Self::Err> {+ property_definition_queries::list_property_definitions_with_options(+ &self.pool,+ team_id,+ user_id,+ include_system,+ )+ .await+ }++ #[tracing::instrument(skip(self, options), err)]+ async fn create_property_definition(+ &self,+ owner: PropertyDefinitionOwner<'_>,+ display_name: &str,+ data_type: DataType,+ is_multi_select: bool,+ specific_entity_type: Option<EntityType>,+ options: Vec<PropertyOption>,+ ) -> Result<PropertyDefinition, Self::Err> {+ property_definition_queries::create_property_definition(+ &self.pool,+ owner,+ display_name,+ data_type,+ is_multi_select,+ specific_entity_type,+ options,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_property_definition(+ &self,+ property_definition_id: Uuid,+ ) -> Result<(), Self::Err> {+ property_definition_queries::delete_property_definition(&self.pool, property_definition_id)+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_property_option(+ &self,+ option_id: Uuid,+ ) -> Result<Option<PropertyOption>, Self::Err> {+ property_option_queries::get_property_option(&self.pool, option_id).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_property_options(+ &self,+ property_definition_id: Uuid,+ ) -> Result<Vec<PropertyOption>, Self::Err> {+ property_option_queries::get_property_options(&self.pool, property_definition_id).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn create_property_option(+ &self,+ property_definition_id: Uuid,+ display_order: i32,+ value: PropertyOptionValue,+ color: Option<String>,+ ) -> Result<PropertyOption, Self::Err> {+ property_option_queries::create_property_option(+ &self.pool,+ property_definition_id,+ display_order,+ value,+ color,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn update_property_option(+ &self,+ option_id: Uuid,+ value: PropertyOptionValue,+ color: Option<String>,+ display_order: i32,+ ) -> Result<UpdatePropertyOptionOutcome, Self::Err> {+ property_option_queries::update_property_option(+ &self.pool,+ option_id,+ value,+ color,+ display_order,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_property_option(+ &self,+ property_definition_id: Uuid,+ option_id: Uuid,+ ) -> Result<bool, Self::Err> {+ property_option_queries::delete_property_option(+ &self.pool,+ property_definition_id,+ option_id,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_tag_definition(+ &self,+ owner: PropertyDefinitionOwner<'_>,+ ) -> Result<Option<PropertyDefinition>, Self::Err> {+ property_definition_queries::get_tag_definition(&self.pool, owner).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_or_create_tag_definition(+ &self,+ owner: PropertyDefinitionOwner<'_>,+ ) -> Result<PropertyDefinition, Self::Err> {+ property_definition_queries::get_or_create_tag_definition(&self.pool, owner).await+ }+#[tracing::instrument(skip(self))]async fn count_valid_property_options(&self,@@ -154,27 +345,98 @@ impl PropertiesRepo for PropertiesPgRepo {&self,entity_refs: Vec<EntityReference>,) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, Self::Err> {- let mut result = entity_refs- .iter()- .map(|entity_ref| (EntityPropertiesKey::from(entity_ref), Vec::new()))- .collect::<HashMap<_, _>>();+ let properties_by_entity_id =+ entity_properties_get_query::get_bulk_entity_properties_values(+ &self.pool,+ &entity_refs,+ )+ .await?;+ Ok(regroup_entity_properties(+ &entity_refs,+ properties_by_entity_id,+ ))+ }++ #[tracing::instrument(skip(self, entity_refs, property_ids), err)]+ async fn get_entity_properties_batch_filtered(+ &self,+ entity_refs: Vec<EntityReference>,+ property_ids: Vec<Uuid>,+ tag_viewer_user_id: Option<&MacroUserIdStr<'_>>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, Self::Err> {let properties_by_entity_id =- properties_db_client::entity_properties::get::get_bulk_entity_properties_values(+ entity_properties_get_query::get_bulk_entity_properties_values_filtered(&self.pool,&entity_refs,+ &property_ids,+ tag_viewer_user_id,).await?;- for property in properties_by_entity_id.into_values().flatten() {- let key = EntityPropertiesKey {- entity_id: property.property.entity_id.clone(),- entity_type: property.property.entity_type,- };- result.entry(key).or_default().push(property);- }+ Ok(regroup_entity_properties(+ &entity_refs,+ properties_by_entity_id,+ ))+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_entity_properties_with_definitions(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Vec<EntityPropertyWithDefinition>, Self::Err> {+ entity_properties_get_query::get_entity_properties_values(+ &self.pool,+ entity_id,+ entity_type,+ )+ .await+ }++ #[tracing::instrument(skip(self), err)]+ async fn lookup_entity_property(+ &self,+ entity_property_id: Uuid,+ ) -> Result<Option<EntityPropertyReference>, Self::Err> {+ entity_properties_get_query::lookup_entity_property(&self.pool, entity_property_id).await+ }- Ok(result)+ #[tracing::instrument(skip(self), err)]+ async fn delete_entity_property(&self, entity_property_id: Uuid) -> Result<(), Self::Err> {+ entity_property_queries::delete_entity_property(&self.pool, entity_property_id).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_entity_properties(+ &self,+ entity_reference: &EntityReference,+ ) -> Result<(), Self::Err> {+ entity_property_queries::delete_entity_properties(&self.pool, entity_reference).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_document_metadata(+ &self,+ document_id: &str,+ ) -> Result<Option<DocumentMetadata>, Self::Err> {+ metadata_queries::get_document_metadata(&self.pool, document_id).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_thread_metadata(+ &self,+ thread_id: Uuid,+ ) -> Result<Option<ThreadMetadata>, Self::Err> {+ metadata_queries::get_thread_metadata(&self.pool, thread_id).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn get_project_metadata(+ &self,+ project_id: &str,+ ) -> Result<Option<ProjectMetadata>, Self::Err> {+ metadata_queries::get_project_metadata(&self.pool, project_id).await}#[tracing::instrument(skip(self))]@@ -211,31 +473,4 @@ impl PropertiesRepo for PropertiesPgRepo {},}}-- #[tracing::instrument(skip(self))]- async fn get_document_name(&self, id: &str) -> Result<Option<String>, Self::Err> {- // Tasks are stored as documents, so this works for both documents and tasks- match macro_db_client::document::get_document_name(&self.pool, id).await {- Ok(name) => Ok(Some(name)),- Err(e) => {- // If document doesn't exist, return None instead of error- if let Some(db_err) = e.downcast_ref::<sqlx::Error>()- && matches!(db_err, sqlx::Error::RowNotFound)- {- return Ok(None);- }- Err(e)- }- }- }-- #[tracing::instrument(skip(self))]- async fn get_user_profile_picture(&self, user_id: &str) -> Result<Option<String>, Self::Err> {- let pics = macro_db_client::user::update_profile_picture::get_profile_pictures(- &self.pool,- &vec![user_id.to_string()],- )- .await?;- Ok(pics.pictures.into_iter().next().map(|p| p.url))- }}diff --git a/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs b/rust/cloud-storage/properties/src/outbound/property_definition_queries.rsindex 28012226c0..f33affb42d 100644--- a/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs+++ b/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs@@ -1,10 +1,17 @@//! Property definition query helpers.+use std::collections::HashMap;++use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::property_definition::PropertyDefinition;+use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::{DataType, EntityType, db};use sqlx::{Pool, Postgres};use uuid::Uuid;+use crate::domain::model::PropertyDefinitionOwner;+/// Gets a single property definition by ID (includes system properties).pub async fn get_property_definition(pool: &Pool<Postgres>,@@ -49,3 +56,469 @@ pub async fn get_property_definition(Ok(result)}++/// Gets a single property definition by ID with ownership validation.+/// Returns None if the property doesn't exist, if the caller doesn't own it, or if it's a system property.+/// The caller owns it when it is their user property, or a property of the team they belong to.+/// System properties don't have owners and should be fetched via `get_property_definition`.+#[tracing::instrument(skip(pool))]+pub async fn get_property_definition_with_owner(+ pool: &Pool<Postgres>,+ property_id: Uuid,+ user_id: &MacroUserIdStr<'_>,+ team_id: Option<Uuid>,+) -> anyhow::Result<Option<PropertyDefinition>> {+ let user_id: &str = user_id.as_ref();+ let row = sqlx::query!(+ r#"+ SELECT+ id,+ team_id,+ user_id,+ display_name,+ data_type as "data_type: DataType",+ is_multi_select,+ specific_entity_type as "specific_entity_type: Option<EntityType>",+ created_at,+ updated_at,+ is_system+ FROM property_definitions+ WHERE id = $1+ AND is_system = FALSE+ AND (+ user_id = $2+ OR ($3::uuid IS NOT NULL AND team_id = $3)+ )+ "#,+ property_id,+ user_id,+ team_id+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.map(|row| {+ PropertyDefinition::from(db::PropertyDefinition {+ id: row.id,+ team_id: row.team_id,+ user_id: row.user_id,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type.flatten(),+ created_at: row.created_at,+ updated_at: row.updated_at,+ is_system: row.is_system,+ })+ }))+}++/// Gets property definitions based on optional team and optional user access.+/// Set `include_system` to true to also include system properties.+#[tracing::instrument(skip(pool))]+pub async fn list_property_definitions(+ pool: &Pool<Postgres>,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+) -> anyhow::Result<Vec<PropertyDefinition>> {+ let user_id: Option<&str> = user_id.map(|u| u.as_ref());+ let rows = sqlx::query!(+ r#"+ SELECT+ id,+ team_id,+ user_id,+ display_name,+ data_type as "data_type: DataType",+ is_multi_select,+ specific_entity_type as "specific_entity_type: Option<EntityType>",+ created_at,+ updated_at,+ is_system+ FROM property_definitions+ WHERE+ ($3 AND is_system)+ OR (+ ($1::uuid IS NOT NULL AND team_id = $1)+ OR ($2::text IS NOT NULL AND user_id = $2)+ )+ ORDER BY LOWER(display_name) ASC+ "#,+ team_id,+ user_id,+ include_system+ )+ .fetch_all(pool)+ .await?;++ let result = rows+ .into_iter()+ .map(|row| {+ PropertyDefinition::from(db::PropertyDefinition {+ id: row.id,+ team_id: row.team_id,+ user_id: row.user_id,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type.flatten(),+ created_at: row.created_at,+ updated_at: row.updated_at,+ is_system: row.is_system,+ })+ })+ .collect();++ Ok(result)+}++/// Gets property definitions with options based on team and optional user access.+/// Set `include_system` to true to also include system properties.+#[tracing::instrument(skip(pool))]+pub async fn list_property_definitions_with_options(+ pool: &Pool<Postgres>,+ team_id: Option<Uuid>,+ user_id: Option<&MacroUserIdStr<'_>>,+ include_system: bool,+) -> anyhow::Result<Vec<PropertyDefinitionWithOptions>> {+ let user_id: Option<&str> = user_id.map(|u| u.as_ref());+ let rows = sqlx::query!(+ r#"+ SELECT+ pd.id,+ pd.team_id,+ pd.user_id,+ pd.display_name,+ pd.data_type as "data_type: DataType",+ pd.is_multi_select,+ pd.specific_entity_type as "specific_entity_type: Option<EntityType>",+ pd.created_at,+ pd.updated_at,+ pd.is_system,+ po.id as "option_id?",+ po.display_order as "option_display_order?",+ po.number_value as option_number_value,+ po.string_value as option_string_value,+ po.color as option_color,+ po.created_at as "option_created_at?",+ po.updated_at as "option_updated_at?"+ FROM property_definitions pd+ LEFT JOIN property_options po ON pd.id = po.property_definition_id+ WHERE+ ($3 AND pd.is_system)+ OR (+ ($1::uuid IS NOT NULL AND pd.team_id = $1)+ OR ($2::text IS NOT NULL AND pd.user_id = $2)+ )+ ORDER BY LOWER(pd.display_name), po.display_order, po.number_value, LOWER(po.string_value)+ "#,+ team_id,+ user_id,+ include_system+ )+ .fetch_all(pool)+ .await?;++ let mut property_map: HashMap<Uuid, PropertyDefinitionWithOptions> = HashMap::new();++ for row in rows {+ let owner = models_properties::PropertyOwner::from_optional_ids(+ row.team_id,+ row.user_id.clone(),+ row.is_system,+ );++ let property_def = PropertyDefinition {+ id: row.id,+ owner,+ display_name: row.display_name.clone(),+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type.flatten(),+ created_at: row.created_at,+ updated_at: row.updated_at,+ is_system: row.is_system,+ is_metadata: false,+ };++ let entry = property_map+ .entry(row.id)+ .or_insert_with(|| PropertyDefinitionWithOptions {+ definition: property_def,+ property_options: Vec::new(),+ });++ // Only process options if option_id is present (from LEFT JOIN)+ if let Some(option_id) = row.option_id+ && (row.data_type == DataType::SelectNumber+ || row.data_type == DataType::SelectString+ || row.data_type == DataType::Tag)+ {+ let value = match (row.option_number_value, &row.option_string_value) {+ (Some(num), None) => PropertyOptionValue::Number(num),+ (None, Some(str)) => PropertyOptionValue::String(str.clone()),+ (Some(_), Some(_)) => {+ return Err(+ models_properties::db::DbConversionError::PropertyOptionBothValuesSet {+ id: option_id,+ }+ .into(),+ );+ }+ (None, None) => {+ return Err(+ models_properties::db::DbConversionError::PropertyOptionNoValueSet {+ id: option_id,+ }+ .into(),+ );+ }+ };++ let option = PropertyOption {+ id: option_id,+ property_definition_id: row.id,+ display_order: row.option_display_order.unwrap_or(0),+ value,+ color: row.option_color,+ created_at: row.option_created_at.unwrap_or(row.created_at),+ updated_at: row.option_updated_at.unwrap_or(row.updated_at),+ };+ entry.property_options.push(option);+ }+ }++ let mut results: Vec<PropertyDefinitionWithOptions> = property_map.into_values().collect();++ results.sort_by(|a, b| {+ a.definition+ .display_name+ .to_lowercase()+ .cmp(&b.definition.display_name.to_lowercase())+ });++ Ok(results)+}++/// Creates a new property definition, atomically creating any select options+/// alongside it.+#[tracing::instrument(skip(pool, options))]+pub async fn create_property_definition(+ pool: &Pool<Postgres>,+ owner: PropertyDefinitionOwner<'_>,+ display_name: &str,+ data_type: DataType,+ is_multi_select: bool,+ specific_entity_type: Option<EntityType>,+ options: Vec<PropertyOption>,+) -> anyhow::Result<PropertyDefinition> {+ let (team_id, user_id) = owner.into_ids();+ let user_id: Option<&str> = user_id.map(|u| u.as_ref());++ let id = macro_uuid::generate_uuid_v7();++ let mut tx = pool.begin().await?;++ let row = sqlx::query!(+ r#"+ INSERT INTO property_definitions (+ id,+ team_id,+ user_id,+ display_name,+ data_type,+ is_multi_select,+ specific_entity_type+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ RETURNING+ id,+ team_id,+ user_id,+ display_name,+ data_type as "data_type: DataType",+ is_multi_select,+ specific_entity_type as "specific_entity_type: Option<EntityType>",+ created_at,+ updated_at+ "#,+ id,+ team_id,+ user_id,+ display_name,+ data_type as DataType,+ is_multi_select,+ specific_entity_type as Option<EntityType>+ )+ .fetch_one(&mut *tx)+ .await?;++ let db_property_def = db::PropertyDefinition {+ id: row.id,+ team_id: row.team_id,+ user_id: row.user_id,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type.flatten(),+ created_at: row.created_at,+ updated_at: row.updated_at,+ is_system: false, // User-created properties are never system properties+ };++ for option in options {+ create_property_option_tx(+ &mut tx,+ db_property_def.id,+ option.display_order,+ option.value,+ option.color,+ )+ .await?;+ }++ tx.commit().await?;++ Ok(db_property_def.into())+}++/// Inserts a property option within an existing transaction.+pub(super) async fn create_property_option_tx(+ tx: &mut sqlx::Transaction<'_, Postgres>,+ property_definition_id: Uuid,+ display_order: i32,+ value: PropertyOptionValue,+ color: Option<String>,+) -> anyhow::Result<()> {+ let id = macro_uuid::generate_uuid_v7();+ let (number_value, string_value) = value.to_db_values();++ sqlx::query!(+ r#"+ INSERT INTO property_options (+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color+ )+ VALUES ($1, $2, $3, $4, $5, $6)+ "#,+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color+ )+ .execute(&mut **tx)+ .await?;++ Ok(())+}++/// Display name used for the auto-provisioned tag definition.+pub const TAG_DEFINITION_DISPLAY_NAME: &str = "Tags";++/// Gets the single tag definition owned by the given owner, if it exists.+#[tracing::instrument(skip(pool), err)]+pub async fn get_tag_definition(+ pool: &Pool<Postgres>,+ owner: PropertyDefinitionOwner<'_>,+) -> anyhow::Result<Option<PropertyDefinition>> {+ let (team_id, user_id) = owner.into_ids();+ let user_id: Option<&str> = user_id.map(|u| u.as_ref());++ let row = sqlx::query!(+ r#"+ SELECT+ id,+ team_id,+ user_id,+ display_name,+ data_type as "data_type: DataType",+ is_multi_select,+ specific_entity_type as "specific_entity_type: Option<EntityType>",+ created_at,+ updated_at,+ is_system+ FROM property_definitions+ WHERE data_type = $3+ AND (+ ($1::uuid IS NOT NULL AND team_id = $1)+ OR ($2::text IS NOT NULL AND user_id = $2)+ )+ LIMIT 1+ "#,+ team_id,+ user_id,+ DataType::Tag as DataType+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.map(|row| {+ PropertyDefinition::from(db::PropertyDefinition {+ id: row.id,+ team_id: row.team_id,+ user_id: row.user_id,+ display_name: row.display_name,+ data_type: row.data_type,+ is_multi_select: row.is_multi_select,+ specific_entity_type: row.specific_entity_type.flatten(),+ created_at: row.created_at,+ updated_at: row.updated_at,+ is_system: row.is_system,+ })+ }))+}++/// Returns the owner's tag definition, creating it on first use.+///+/// Tag definitions are TAG-typed, multi-select, and unique per owner (enforced by a partial+/// unique index). A lost create race re-fetches the definition the winner just created.+#[tracing::instrument(skip(pool), err)]+pub async fn get_or_create_tag_definition(+ pool: &Pool<Postgres>,+ owner: PropertyDefinitionOwner<'_>,+) -> anyhow::Result<PropertyDefinition> {+ if let Some(existing) = get_tag_definition(pool, owner).await? {+ return Ok(existing);+ }++ match create_property_definition(+ pool,+ owner,+ TAG_DEFINITION_DISPLAY_NAME,+ DataType::Tag,+ true,+ None,+ Vec::new(),+ )+ .await+ {+ Ok(def) => Ok(def),+ Err(create_err) => match get_tag_definition(pool, owner).await? {+ Some(existing) => Ok(existing),+ None => Err(create_err),+ },+ }+}++/// Deletes a property definition and all associated data (cascades).+#[tracing::instrument(skip(pool))]+pub async fn delete_property_definition(+ pool: &Pool<Postgres>,+ property_definition_id: Uuid,+) -> anyhow::Result<()> {+ sqlx::query!(+ "DELETE FROM property_definitions WHERE id = $1",+ property_definition_id+ )+ .execute(pool)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/properties/src/outbound/property_option_queries.rs b/rust/cloud-storage/properties/src/outbound/property_option_queries.rsnew file mode 100644index 0000000000..ef7c5555dc--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/property_option_queries.rs@@ -0,0 +1,266 @@+//! Property option query helpers.++use std::collections::HashMap;++use models_properties::db;+use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};+use sqlx::{Pool, Postgres};+use uuid::Uuid;++use crate::domain::model::UpdatePropertyOptionOutcome;++/// Gets a single property option by ID.+#[tracing::instrument(skip(pool))]+pub async fn get_property_option(+ pool: &Pool<Postgres>,+ option_id: Uuid,+) -> anyhow::Result<Option<PropertyOption>> {+ let row = sqlx::query_as!(+ db::PropertyOption,+ r#"+ SELECT+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color,+ created_at,+ updated_at+ FROM property_options+ WHERE id = $1+ "#,+ option_id+ )+ .fetch_optional(pool)+ .await?;++ Ok(row.map(TryInto::try_into).transpose()?)+}++/// Gets all property options for a property definition, ordered for display.+#[tracing::instrument(skip(pool))]+pub async fn get_property_options(+ pool: &Pool<Postgres>,+ property_definition_id: Uuid,+) -> anyhow::Result<Vec<PropertyOption>> {+ let rows = sqlx::query_as!(+ db::PropertyOption,+ r#"+ SELECT+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color,+ created_at,+ updated_at+ FROM property_options+ WHERE property_definition_id = $1+ ORDER BY display_order, number_value, LOWER(string_value)+ "#,+ property_definition_id+ )+ .fetch_all(pool)+ .await?;++ rows.into_iter()+ .map(|row| row.try_into().map_err(anyhow::Error::from))+ .collect()+}++/// Gets property options for multiple properties in a single query.+/// Returns a HashMap where the key is property_definition_id and value is the list of options.+#[tracing::instrument(skip(pool))]+pub async fn get_property_options_batch(+ pool: &Pool<Postgres>,+ property_definition_ids: &[Uuid],+) -> anyhow::Result<HashMap<Uuid, Vec<PropertyOption>>> {+ if property_definition_ids.is_empty() {+ return Ok(HashMap::new());+ }++ let rows = sqlx::query_as!(+ db::PropertyOption,+ r#"+ SELECT+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color,+ created_at,+ updated_at+ FROM property_options+ WHERE property_definition_id = ANY($1)+ ORDER BY property_definition_id, display_order, number_value, LOWER(string_value)+ "#,+ property_definition_ids+ )+ .fetch_all(pool)+ .await?;++ // Group options by property_definition_id+ let mut result: HashMap<Uuid, Vec<PropertyOption>> = HashMap::new();+ for row in rows {+ let option: PropertyOption = row.try_into()?;+ result+ .entry(option.property_definition_id)+ .or_default()+ .push(option);+ }++ Ok(result)+}++/// Creates a new property option.+#[tracing::instrument(skip(pool))]+pub async fn create_property_option(+ pool: &Pool<Postgres>,+ property_definition_id: Uuid,+ display_order: i32,+ value: PropertyOptionValue,+ color: Option<String>,+) -> anyhow::Result<PropertyOption> {+ let id = macro_uuid::generate_uuid_v7();+ let (number_value, string_value) = value.to_db_values();++ let row = sqlx::query!(+ r#"+ INSERT INTO property_options (+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color+ )+ VALUES ($1, $2, $3, $4, $5, $6)+ RETURNING id, created_at, updated_at+ "#,+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color.clone()+ )+ .fetch_one(pool)+ .await?;++ Ok(PropertyOption {+ id: row.id,+ property_definition_id,+ display_order,+ value,+ color,+ created_at: row.created_at,+ updated_at: row.updated_at,+ })+}++/// Updates a property option's value, color, and display order in place.+///+/// The option id is preserved, so every entity referencing this option by id in its+/// `entity_properties.values` reflects the new value and color with no per-entity rewrite.+#[tracing::instrument(skip(pool), err)]+pub async fn update_property_option(+ pool: &Pool<Postgres>,+ option_id: Uuid,+ value: PropertyOptionValue,+ color: Option<String>,+ display_order: i32,+) -> anyhow::Result<UpdatePropertyOptionOutcome> {+ let (number_value, string_value) = value.to_db_values();++ let result = sqlx::query_as!(+ db::PropertyOption,+ r#"+ UPDATE property_options+ SET number_value = $2,+ string_value = $3,+ color = $4,+ display_order = $5,+ updated_at = NOW()+ WHERE id = $1+ RETURNING+ id,+ property_definition_id,+ display_order,+ number_value,+ string_value,+ color,+ created_at,+ updated_at+ "#,+ option_id,+ number_value,+ string_value,+ color,+ display_order+ )+ .fetch_optional(pool)+ .await;++ match result {+ Ok(Some(row)) => Ok(UpdatePropertyOptionOutcome::Updated(row.try_into()?)),+ Ok(None) => Ok(UpdatePropertyOptionOutcome::NotFound),+ Err(sqlx::Error::Database(db_err)) if db_err.is_unique_violation() => {+ Ok(UpdatePropertyOptionOutcome::DuplicateValue)+ }+ Err(e) => Err(e.into()),+ }+}++/// Deletes a property option and strips its id from every entity value that+/// references it, atomically. Without the cleanup a stored value keeps the+/// dead id and a later set-value that echoes the full id list fails option+/// validation.+/// Returns Ok(true) if the option was deleted, Ok(false) if it didn't exist.+#[tracing::instrument(skip(pool))]+pub async fn delete_property_option(+ pool: &Pool<Postgres>,+ property_definition_id: Uuid,+ property_option_id: Uuid,+) -> anyhow::Result<bool> {+ let mut tx = pool.begin().await?;++ sqlx::query!(+ r#"+ UPDATE entity_properties+ SET+ values = jsonb_set(+ values,+ '{value}',+ COALESCE(+ (+ SELECT jsonb_agg(elem)+ FROM jsonb_array_elements(values -> 'value') AS elem+ WHERE elem <> to_jsonb($2::text)+ ),+ '[]'::jsonb+ )+ ),+ updated_at = NOW()+ WHERE property_definition_id = $1+ AND values @> jsonb_build_object('value', jsonb_build_array($2::text))+ "#,+ property_definition_id,+ property_option_id.to_string(),+ )+ .execute(&mut *tx)+ .await?;++ let result = sqlx::query!(+ "DELETE FROM property_options WHERE id = $1",+ property_option_id+ )+ .execute(&mut *tx)+ .await?;++ tx.commit().await?;++ Ok(result.rows_affected() > 0)+}diff --git a/rust/cloud-storage/properties_db_client/.gitignore b/rust/cloud-storage/properties_db_client/.gitignoredeleted file mode 100644index e69de29bb2..0000000000diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-0893292d05dc339bc516ddc4e2e27ee0f730dd38e1d82bd2a049d38cb7abb275.json b/rust/cloud-storage/properties_db_client/.sqlx/query-0893292d05dc339bc516ddc4e2e27ee0f730dd38e1d82bd2a049d38cb7abb275.jsondeleted file mode 100644index 34779cb42e..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-0893292d05dc339bc516ddc4e2e27ee0f730dd38e1d82bd2a049d38cb7abb275.json+++ /dev/null@@ -1,58 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n d.id,\n d.name,\n d.owner,\n d.\"fileType\" as \"file_type\",\n d.\"projectId\" as \"project_id\",\n d.\"createdAt\"::timestamptz as \"created_at!\",\n d.\"updatedAt\"::timestamptz as \"updated_at!\"\n FROM\n \"Document\" d\n WHERE\n d.id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "file_type",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "project_id",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "created_at!",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "updated_at!",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- false,- true,- true,- null,- null- ]- },- "hash": "0893292d05dc339bc516ddc4e2e27ee0f730dd38e1d82bd2a049d38cb7abb275"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39.json b/rust/cloud-storage/properties_db_client/.sqlx/query-301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39.jsondeleted file mode 100644index 3b5b423da4..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39.json+++ /dev/null@@ -1,185 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nSELECT\n ep.id as entity_property_id,\n ep.entity_id,\n ep.entity_type as \"entity_type: EntityType\",\n ep.property_definition_id,\n ep.values as \"values: sqlx::types::JsonValue\",\n ep.created_at as entity_property_created_at,\n ep.updated_at as entity_property_updated_at,\n pd.team_id as definition_team_id,\n pd.user_id as definition_user_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n pd.created_at as definition_created_at,\n pd.updated_at as definition_updated_at,\n pd.is_system as definition_is_system\nFROM entity_properties ep\nINNER JOIN property_definitions pd ON ep.property_definition_id = pd.id\nWHERE (ep.entity_id, ep.entity_type) IN (\n SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])\n)\n",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_property_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "entity_type: EntityType",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 3,- "name": "property_definition_id",- "type_info": "Uuid"- },- {- "ordinal": 4,- "name": "values: sqlx::types::JsonValue",- "type_info": "Jsonb"- },- {- "ordinal": 5,- "name": "entity_property_created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "entity_property_updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "definition_team_id",- "type_info": "Uuid"- },- {- "ordinal": 8,- "name": "definition_user_id",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 11,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 13,- "name": "definition_created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 14,- "name": "definition_updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 15,- "name": "definition_is_system",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "TextArray",- {- "Custom": {- "name": "property_entity_type[]",- "kind": {- "Array": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- }- }- }- ]- },- "nullable": [- false,- false,- false,- false,- true,- false,- false,- true,- true,- false,- false,- false,- true,- false,- false,- false- ]- },- "hash": "301f5b3142a30e271df62607b5743ff019bff1a5b0142fc260ff772837db3f39"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-3361ff2e8d90c65b188ef614379cdbf977e4f89f8c22603071fc169fdfa038e2.json b/rust/cloud-storage/properties_db_client/.sqlx/query-3361ff2e8d90c65b188ef614379cdbf977e4f89f8c22603071fc169fdfa038e2.jsondeleted file mode 100644index d592cf7ba7..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-3361ff2e8d90c65b188ef614379cdbf977e4f89f8c22603071fc169fdfa038e2.json+++ /dev/null@@ -1,39 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO property_options (\n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id, created_at, updated_at\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 2,- "name": "updated_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Int4",- "Float8",- "Text",- "Text"- ]- },- "nullable": [- false,- false,- false- ]- },- "hash": "3361ff2e8d90c65b188ef614379cdbf977e4f89f8c22603071fc169fdfa038e2"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-3e259ea5cbdcfae4334cb0125de6423fa95a0c127fbeba0a59d7096b0177c072.json b/rust/cloud-storage/properties_db_client/.sqlx/query-3e259ea5cbdcfae4334cb0125de6423fa95a0c127fbeba0a59d7096b0177c072.jsondeleted file mode 100644index 8ee9d7919b..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-3e259ea5cbdcfae4334cb0125de6423fa95a0c127fbeba0a59d7096b0177c072.json+++ /dev/null@@ -1,52 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n p.id,\n p.name,\n p.\"userId\" as \"owner\",\n p.\"parentId\" as \"parent_id\",\n p.\"createdAt\"::timestamptz as \"created_at!\",\n p.\"updatedAt\"::timestamptz as \"updated_at!\"\n FROM\n \"Project\" p\n WHERE\n p.id = $1 AND p.\"deletedAt\" IS NULL\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "parent_id",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "created_at!",- "type_info": "Timestamptz"- },- {- "ordinal": 5,- "name": "updated_at!",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- false,- false,- true,- null,- null- ]- },- "hash": "3e259ea5cbdcfae4334cb0125de6423fa95a0c127fbeba0a59d7096b0177c072"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8.json b/rust/cloud-storage/properties_db_client/.sqlx/query-3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8.jsondeleted file mode 100644index 5c152ecd5e..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8.json+++ /dev/null@@ -1,50 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nSELECT\n ep.entity_id,\n ep.entity_type as \"entity_type: EntityType\",\n ep.property_definition_id\nFROM entity_properties ep\nWHERE ep.id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "entity_type: EntityType",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 2,- "name": "property_definition_id",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- false,- false- ]- },- "hash": "3f3b5a5d8734e3748d4e29d64cfa89baff99dae621e7cbd7a10017beec9485c8"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8.json b/rust/cloud-storage/properties_db_client/.sqlx/query-462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8.jsondeleted file mode 100644index 2dbdd8559c..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8.json+++ /dev/null@@ -1,111 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n team_id,\n user_id,\n display_name,\n data_type as \"data_type: DataType\",\n is_multi_select,\n specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n created_at,\n updated_at,\n is_system\n FROM property_definitions\n WHERE id = $1\n AND is_system = FALSE\n AND (\n user_id = $2\n OR ($3::uuid IS NOT NULL AND team_id = $3)\n )\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 5,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 7,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "is_system",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- "Uuid"- ]- },- "nullable": [- false,- true,- true,- false,- false,- false,- true,- false,- false,- false- ]- },- "hash": "462655d9cce541e4b25cb2d85e9d2e8ce3c84e28b4f459e4ea4ef62881278ae8"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495.json b/rust/cloud-storage/properties_db_client/.sqlx/query-4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495.jsondeleted file mode 100644index 067614a699..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495.json+++ /dev/null@@ -1,205 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nSELECT\n ep.id as entity_property_id,\n ep.entity_id,\n ep.entity_type as \"entity_type: EntityType\",\n ep.property_definition_id,\n ep.values as \"values: sqlx::types::JsonValue\",\n ep.created_at as entity_property_created_at,\n ep.updated_at as entity_property_updated_at,\n pd.team_id as definition_team_id,\n pd.user_id as definition_user_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n pd.created_at as definition_created_at,\n pd.updated_at as definition_updated_at,\n pd.is_system as definition_is_system\nFROM entity_properties ep\nINNER JOIN property_definitions pd ON ep.property_definition_id = pd.id\nWHERE (ep.entity_id, ep.entity_type) IN (\n SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])\n)\nAND (\n pd.id = ANY($3::UUID[])\n OR (\n $4::text IS NOT NULL\n AND pd.data_type = $5\n AND (\n pd.user_id = $4\n OR pd.team_id IN (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = $4)\n )\n )\n)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_property_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "entity_type: EntityType",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 3,- "name": "property_definition_id",- "type_info": "Uuid"- },- {- "ordinal": 4,- "name": "values: sqlx::types::JsonValue",- "type_info": "Jsonb"- },- {- "ordinal": 5,- "name": "entity_property_created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "entity_property_updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "definition_team_id",- "type_info": "Uuid"- },- {- "ordinal": 8,- "name": "definition_user_id",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 11,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 13,- "name": "definition_created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 14,- "name": "definition_updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 15,- "name": "definition_is_system",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "TextArray",- {- "Custom": {- "name": "property_entity_type[]",- "kind": {- "Array": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- }- }- },- "UuidArray",- "Text",- {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- ]- },- "nullable": [- false,- false,- false,- false,- true,- false,- false,- true,- true,- false,- false,- false,- true,- false,- false,- false- ]- },- "hash": "4d75ecd9c8d6f98881d44d88d10ebc20de426c8aad90b680cc8ae351118e5495"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7.json b/rust/cloud-storage/properties_db_client/.sqlx/query-4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7.jsondeleted file mode 100644index b54de1a07a..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7.json+++ /dev/null@@ -1,128 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n team_id,\n user_id,\n display_name,\n data_type as \"data_type: DataType\",\n is_multi_select,\n specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n created_at,\n updated_at,\n is_system\n FROM property_definitions\n WHERE data_type = $3\n AND (\n ($1::uuid IS NOT NULL AND team_id = $1)\n OR ($2::text IS NOT NULL AND user_id = $2)\n )\n LIMIT 1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 5,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 7,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "is_system",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- ]- },- "nullable": [- false,- true,- true,- false,- false,- false,- true,- false,- false,- false- ]- },- "hash": "4e7dff37296c4976495ee40673ee20a6729b6ce030222e1776a0fd22d93bafb7"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03.json b/rust/cloud-storage/properties_db_client/.sqlx/query-6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03.jsondeleted file mode 100644index 354995e8a1..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03.json+++ /dev/null@@ -1,142 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO property_definitions (\n id,\n team_id,\n user_id,\n display_name,\n data_type,\n is_multi_select,\n specific_entity_type\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING\n id,\n team_id,\n user_id,\n display_name,\n data_type as \"data_type: DataType\",\n is_multi_select,\n specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n created_at,\n updated_at\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 5,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 7,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Text",- "Text",- {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- },- "Bool",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- ]- },- "nullable": [- false,- true,- true,- false,- false,- false,- true,- false,- false- ]- },- "hash": "6fd87794b687b1687b8c4f0bc0390ffcc91811ae9909ce333273e6bf77013b03"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.json b/rust/cloud-storage/properties_db_client/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.jsondeleted file mode 100644index a33e79f60e..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.json+++ /dev/null@@ -1,34 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (entity_id, entity_type, property_definition_id) \n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- },- "Uuid",- "Jsonb"- ]- },- "nullable": []- },- "hash": "7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf.json b/rust/cloud-storage/properties_db_client/.sqlx/query-9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf.jsondeleted file mode 100644index 785d0addfd..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE entity_properties\n SET\n values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($2::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE property_definition_id = $1\n AND values @> jsonb_build_object('value', jsonb_build_array($2::text))\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": []- },- "hash": "9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1.json b/rust/cloud-storage/properties_db_client/.sqlx/query-a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1.jsondeleted file mode 100644index ae7e70b085..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1.json+++ /dev/null@@ -1,109 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n team_id,\n user_id,\n display_name,\n data_type as \"data_type: DataType\",\n is_multi_select,\n specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n created_at,\n updated_at,\n is_system\n FROM property_definitions\n WHERE id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 5,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 7,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "is_system",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- true,- true,- false,- false,- false,- true,- false,- false,- false- ]- },- "hash": "a63c0f9e0b3c58438d46cff265e3f412890402e3627b85d5dfb74a08d72787e1"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-b370ac2ac7ace6911ff13454d24ff42b906dcc72b2fb4bcd783b8cb7c06ceab4.json b/rust/cloud-storage/properties_db_client/.sqlx/query-b370ac2ac7ace6911ff13454d24ff42b906dcc72b2fb4bcd783b8cb7c06ceab4.jsondeleted file mode 100644index 4ab9cd0461..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-b370ac2ac7ace6911ff13454d24ff42b906dcc72b2fb4bcd783b8cb7c06ceab4.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "DELETE FROM entity_properties WHERE id = $1",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "b370ac2ac7ace6911ff13454d24ff42b906dcc72b2fb4bcd783b8cb7c06ceab4"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f.json b/rust/cloud-storage/properties_db_client/.sqlx/query-b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f.jsondeleted file mode 100644index c2d448113f..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f.json+++ /dev/null@@ -1,111 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n id,\n team_id,\n user_id,\n display_name,\n data_type as \"data_type: DataType\",\n is_multi_select,\n specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n created_at,\n updated_at,\n is_system\n FROM property_definitions\n WHERE\n ($3 AND is_system)\n OR (\n ($1::uuid IS NOT NULL AND team_id = $1)\n OR ($2::text IS NOT NULL AND user_id = $2)\n )\n ORDER BY LOWER(display_name) ASC\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 5,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 7,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "is_system",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- "Bool"- ]- },- "nullable": [- false,- true,- true,- false,- false,- false,- true,- false,- false,- false- ]- },- "hash": "b6a900ce4ef05b399b15c5df9df622228577a112642245990b64442fb691305f"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea.json b/rust/cloud-storage/properties_db_client/.sqlx/query-be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea.jsondeleted file mode 100644index ab32428f61..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea.json+++ /dev/null@@ -1,153 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n pd.id,\n pd.team_id,\n pd.user_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n pd.created_at,\n pd.updated_at,\n pd.is_system,\n po.id as \"option_id?\",\n po.display_order as \"option_display_order?\",\n po.number_value as option_number_value,\n po.string_value as option_string_value,\n po.color as option_color,\n po.created_at as \"option_created_at?\",\n po.updated_at as \"option_updated_at?\"\n FROM property_definitions pd\n LEFT JOIN property_options po ON pd.id = po.property_definition_id\n WHERE\n ($3 AND pd.is_system)\n OR (\n ($1::uuid IS NOT NULL AND pd.team_id = $1)\n OR ($2::text IS NOT NULL AND pd.user_id = $2)\n )\n ORDER BY LOWER(pd.display_name), po.display_order, po.number_value, LOWER(po.string_value)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "team_id",- "type_info": "Uuid"- },- {- "ordinal": 2,- "name": "user_id",- "type_info": "Text"- },- {- "ordinal": 3,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 5,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 6,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 7,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 8,- "name": "updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 9,- "name": "is_system",- "type_info": "Bool"- },- {- "ordinal": 10,- "name": "option_id?",- "type_info": "Uuid"- },- {- "ordinal": 11,- "name": "option_display_order?",- "type_info": "Int4"- },- {- "ordinal": 12,- "name": "option_number_value",- "type_info": "Float8"- },- {- "ordinal": 13,- "name": "option_string_value",- "type_info": "Text"- },- {- "ordinal": 14,- "name": "option_color",- "type_info": "Text"- },- {- "ordinal": 15,- "name": "option_created_at?",- "type_info": "Timestamptz"- },- {- "ordinal": 16,- "name": "option_updated_at?",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- "Bool"- ]- },- "nullable": [- false,- true,- true,- false,- false,- false,- true,- false,- false,- false,- false,- false,- true,- true,- true,- false,- false- ]- },- "hash": "be9196900ae5aa5d1bf5bdee0a4e8bb94fa15e24fe46ee1fd0cbeb9b644c80ea"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2.json b/rust/cloud-storage/properties_db_client/.sqlx/query-c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2.jsondeleted file mode 100644index e2aa061544..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2.json+++ /dev/null@@ -1,31 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "DELETE FROM entity_properties WHERE entity_id = $1 AND entity_type = $2",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- ]- },- "nullable": []- },- "hash": "c12b511f8fbe853ce8e5489db2468ee8a07030cb234bc0a10bc014c493b8e9c2"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-c6f8bb6a2a9cda820cf54efb5e4ff8b048d735cfcc23716612f2ee66a8c7151c.json b/rust/cloud-storage/properties_db_client/.sqlx/query-c6f8bb6a2a9cda820cf54efb5e4ff8b048d735cfcc23716612f2ee66a8c7151c.jsondeleted file mode 100644index c6b12842de..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-c6f8bb6a2a9cda820cf54efb5e4ff8b048d735cfcc23716612f2ee66a8c7151c.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "DELETE FROM property_options WHERE id = $1",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "c6f8bb6a2a9cda820cf54efb5e4ff8b048d735cfcc23716612f2ee66a8c7151c"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f.json b/rust/cloud-storage/properties_db_client/.sqlx/query-d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f.jsondeleted file mode 100644index 2a3dbfedef..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f.json+++ /dev/null@@ -1,178 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\nSELECT\n ep.id as entity_property_id,\n ep.entity_id,\n ep.entity_type as \"entity_type: EntityType\",\n ep.property_definition_id,\n ep.values as \"values: sqlx::types::JsonValue\",\n ep.created_at as entity_property_created_at,\n ep.updated_at as entity_property_updated_at,\n pd.team_id as definition_team_id,\n pd.user_id as definition_user_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n pd.created_at as definition_created_at,\n pd.updated_at as definition_updated_at,\n pd.is_system as definition_is_system\nFROM entity_properties ep\nINNER JOIN property_definitions pd ON ep.property_definition_id = pd.id\nWHERE ep.entity_id = $1 AND ep.entity_type = $2\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_property_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "entity_type: EntityType",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 3,- "name": "property_definition_id",- "type_info": "Uuid"- },- {- "ordinal": 4,- "name": "values: sqlx::types::JsonValue",- "type_info": "Jsonb"- },- {- "ordinal": 5,- "name": "entity_property_created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 6,- "name": "entity_property_updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 7,- "name": "definition_team_id",- "type_info": "Uuid"- },- {- "ordinal": 8,- "name": "definition_user_id",- "type_info": "Text"- },- {- "ordinal": 9,- "name": "display_name",- "type_info": "Text"- },- {- "ordinal": 10,- "name": "data_type: DataType",- "type_info": {- "Custom": {- "name": "property_data_type",- "kind": {- "Enum": [- "BOOLEAN",- "DATE",- "NUMBER",- "STRING",- "SELECT_NUMBER",- "SELECT_STRING",- "ENTITY",- "LINK",- "TAG"- ]- }- }- }- },- {- "ordinal": 11,- "name": "is_multi_select",- "type_info": "Bool"- },- {- "ordinal": 12,- "name": "specific_entity_type: Option<EntityType>",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- },- {- "ordinal": 13,- "name": "definition_created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 14,- "name": "definition_updated_at",- "type_info": "Timestamptz"- },- {- "ordinal": 15,- "name": "definition_is_system",- "type_info": "Bool"- }- ],- "parameters": {- "Left": [- "Text",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- ]- },- "nullable": [- false,- false,- false,- false,- true,- false,- false,- true,- true,- false,- false,- false,- true,- false,- false,- false- ]- },- "hash": "d09a22b5d0a049677c6fc96d0aef74260d592ae30752c12a50512ebf95592e5f"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-d9521e04db4b5f1603cf5daf48a5e7216c9eee8a4c99f254b1b9471a918b884c.json b/rust/cloud-storage/properties_db_client/.sqlx/query-d9521e04db4b5f1603cf5daf48a5e7216c9eee8a4c99f254b1b9471a918b884c.jsondeleted file mode 100644index 0f3b8edba3..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-d9521e04db4b5f1603cf5daf48a5e7216c9eee8a4c99f254b1b9471a918b884c.json+++ /dev/null@@ -1,19 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO property_options (\n id,\n property_definition_id,\n display_order,\n number_value,\n string_value,\n color\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid",- "Int4",- "Float8",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "d9521e04db4b5f1603cf5daf48a5e7216c9eee8a4c99f254b1b9471a918b884c"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-dc836e7dd12a3df4a05ba072af32cb1aca7d6b8c20e636adff6fb3977577e62a.json b/rust/cloud-storage/properties_db_client/.sqlx/query-dc836e7dd12a3df4a05ba072af32cb1aca7d6b8c20e636adff6fb3977577e62a.jsondeleted file mode 100644index 2ce75f867a..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-dc836e7dd12a3df4a05ba072af32cb1aca7d6b8c20e636adff6fb3977577e62a.json+++ /dev/null@@ -1,52 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n t.id,\n t.latest_inbound_message_ts as last_received,\n t.latest_outbound_message_ts as last_sent,\n first_msg.internal_date_ts as thread_started,\n first_msg.subject,\n (SELECT COUNT(*)::bigint FROM email_messages WHERE thread_id = t.id) as \"message_count!\"\n FROM\n email_threads t\n -- LATERAL join to get subject and timestamp from the first message\n LEFT JOIN LATERAL (\n SELECT internal_date_ts, subject\n FROM email_messages\n WHERE thread_id = t.id\n ORDER BY internal_date_ts ASC NULLS LAST\n LIMIT 1\n ) first_msg ON true\n WHERE\n t.id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "last_received",- "type_info": "Timestamptz"- },- {- "ordinal": 2,- "name": "last_sent",- "type_info": "Timestamptz"- },- {- "ordinal": 3,- "name": "thread_started",- "type_info": "Timestamptz"- },- {- "ordinal": 4,- "name": "subject",- "type_info": "Text"- },- {- "ordinal": 5,- "name": "message_count!",- "type_info": "Int8"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false,- true,- true,- true,- true,- null- ]- },- "hash": "dc836e7dd12a3df4a05ba072af32cb1aca7d6b8c20e636adff6fb3977577e62a"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-e3502d4611d734fa9d27c17c3adb0785d06317da255894345de287a654f24fc3.json b/rust/cloud-storage/properties_db_client/.sqlx/query-e3502d4611d734fa9d27c17c3adb0785d06317da255894345de287a654f24fc3.jsondeleted file mode 100644index 1bb390dc5d..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-e3502d4611d734fa9d27c17c3adb0785d06317da255894345de287a654f24fc3.json+++ /dev/null@@ -1,14 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "DELETE FROM property_definitions WHERE id = $1",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": []- },- "hash": "e3502d4611d734fa9d27c17c3adb0785d06317da255894345de287a654f24fc3"-}diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json b/rust/cloud-storage/properties_db_client/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.jsondeleted file mode 100644index 1b9f06c60a..0000000000--- a/rust/cloud-storage/properties_db_client/.sqlx/query-eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71.json+++ /dev/null@@ -1,45 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n property_definition_id,\n values as \"values: serde_json::Value\"\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = $2\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "property_definition_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "values: serde_json::Value",- "type_info": "Jsonb"- }- ],- "parameters": {- "Left": [- "Text",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- }- ]- },- "nullable": [- false,- true- ]- },- "hash": "eaf32ba063527b6af6e09f701039d2bf0fd4316d9e1280175eca27a0470c2a71"-}diff --git a/rust/cloud-storage/properties_db_client/Cargo.toml b/rust/cloud-storage/properties_db_client/Cargo.tomldeleted file mode 100644index 806c5d4b16..0000000000--- a/rust/cloud-storage/properties_db_client/Cargo.toml+++ /dev/null@@ -1,21 +0,0 @@-[package]-edition = "2024"-name = "properties_db_client"-publish = false-version = "0.1.0"--[dependencies]-anyhow = { workspace = true }-chrono = { workspace = true }-macro_uuid = { path = "../macro_uuid" }-models_properties = { path = "../models_properties" }-serde = { workspace = true }-serde_json = { workspace = true }-sqlx = { workspace = true }-thiserror = { workspace = true }-tracing = { workspace = true }-uuid = { workspace = true }-workspace-hack = { version = "0.1", path = "../workspace-hack" }--[dev-dependencies]-macro_db_migrator = { path = "../macro_db_migrator" }diff --git a/rust/cloud-storage/properties_db_client/README.md b/rust/cloud-storage/properties_db_client/README.mddeleted file mode 100644index e6b2510c97..0000000000--- a/rust/cloud-storage/properties_db_client/README.md+++ /dev/null@@ -1,7 +0,0 @@-# Properties Service Database Client--Database client for accessing properties tables in macrodb.--The properties tables (property_definitions, property_options, entity_properties) are stored in the main macrodb database.--The service entrypoint is the `properties_service` crate.diff --git a/rust/cloud-storage/properties_db_client/justfile b/rust/cloud-storage/properties_db_client/justfiledeleted file mode 100644index 424cd9005c..0000000000--- a/rust/cloud-storage/properties_db_client/justfile+++ /dev/null@@ -1,7 +0,0 @@-import '../database.just'--mod sqlx '../sqlx.just'--prepare_db:- just sqlx::prepare_db {{ DATABASE_URL }}-diff --git a/rust/cloud-storage/properties_db_client/src/document_metadata/get.rs b/rust/cloud-storage/properties_db_client/src/document_metadata/get.rsdeleted file mode 100644index beb7b1b9bd..0000000000--- a/rust/cloud-storage/properties_db_client/src/document_metadata/get.rs+++ /dev/null@@ -1,52 +0,0 @@-//! Get document metadata from macrodb.--use crate::error::PropertiesDatabaseError;-use models_properties::service::document_metadata::DocumentMetadata;-use sqlx::{Pool, Postgres};--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Get document metadata by document ID from macrodb-#[tracing::instrument(skip(db))]-pub async fn get_document_metadata(- db: &Pool<Postgres>,- document_id: &str,-) -> Result<Option<DocumentMetadata>> {- let result = sqlx::query!(- r#"- SELECT- d.id,- d.name,- d.owner,- d."fileType" as "file_type",- d."projectId" as "project_id",- d."createdAt"::timestamptz as "created_at!",- d."updatedAt"::timestamptz as "updated_at!"- FROM- "Document" d- WHERE- d.id = $1- "#,- document_id- )- .fetch_optional(db)- .await- .map_err(|e| {- tracing::error!(- error = ?e,- document_id = %document_id,- "failed to fetch document metadata"- );- PropertiesDatabaseError::Query(e)- })?;-- Ok(result.map(|row| DocumentMetadata {- id: row.id,- name: row.name,- owner: row.owner,- file_type: row.file_type,- project_id: row.project_id,- created_at: row.created_at,- updated_at: row.updated_at,- }))-}diff --git a/rust/cloud-storage/properties_db_client/src/document_metadata/mod.rs b/rust/cloud-storage/properties_db_client/src/document_metadata/mod.rsdeleted file mode 100644index edac2baddb..0000000000--- a/rust/cloud-storage/properties_db_client/src/document_metadata/mod.rs+++ /dev/null@@ -1,3 +0,0 @@-//! Document metadata operations for property queries.--pub mod get;diff --git a/rust/cloud-storage/properties_db_client/src/entity_properties/delete.rs b/rust/cloud-storage/properties_db_client/src/entity_properties/delete.rsdeleted file mode 100644index 0a6e0eb45c..0000000000--- a/rust/cloud-storage/properties_db_client/src/entity_properties/delete.rs+++ /dev/null@@ -1,247 +0,0 @@-//! Entity property delete operations.--use crate::error::PropertiesDatabaseError;-use models_properties::EntityReference;-use sqlx::{Pool, Postgres};-use uuid::Uuid;--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Deletes an entity property by its ID.-#[tracing::instrument(skip(db))]-pub async fn delete_entity_property(db: &Pool<Postgres>, entity_property_id: Uuid) -> Result<()> {- sqlx::query!(- "DELETE FROM entity_properties WHERE id = $1",- entity_property_id- )- .execute(db)- .await?;-- Ok(())-}--/// Deletes an entity.-#[tracing::instrument(skip(db))]-pub async fn delete_entity(db: &Pool<Postgres>, entity_reference: &EntityReference) -> Result<()> {- sqlx::query!(- "DELETE FROM entity_properties WHERE entity_id = $1 AND entity_type = $2",- entity_reference.entity_id,- entity_reference.entity_type as _,- )- .execute(db)- .await?;-- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use models_properties::EntityType;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_entity_property(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_property_id = "e0111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();-- // Verify entity has properties before deletion- let properties_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- let initial_count = properties_before.len();- assert!(initial_count > 0);-- // Delete the entity property- delete_entity_property(&pool, entity_property_id).await?;-- // Verify it was deleted- let properties_after = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- assert_eq!(properties_after.len(), initial_count - 1);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_nonexistent_entity_property(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_property_id = "00000000-0000-0000-0000-000000000000"- .parse::<Uuid>()- .unwrap();-- // Deleting non-existent entity property should succeed (no error)- let result = delete_entity_property(&pool, entity_property_id).await;- assert!(result.is_ok());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_entity(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_ref = EntityReference::new("doc1", EntityType::Document);-- // Verify entity has properties before deletion- let properties_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- assert!(properties_before.len() > 0);-- // Delete all properties for the entity- delete_entity(&pool, &entity_ref).await?;-- // Verify all properties were deleted- let properties_after = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- assert_eq!(properties_after.len(), 0);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_entity_only_deletes_specific_entity(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_ref = EntityReference::new("doc1", EntityType::Document);-- // Get properties for doc2 before deletion- let doc2_properties_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- let doc2_count_before = doc2_properties_before.len();-- // Delete doc1- delete_entity(&pool, &entity_ref).await?;-- // Verify doc2 properties are unchanged- let doc2_properties_after = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- assert_eq!(doc2_properties_after.len(), doc2_count_before);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_nonexistent_entity(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_ref = EntityReference::new("nonexistent", EntityType::Document);-- // Deleting non-existent entity should succeed (no error)- let result = delete_entity(&pool, &entity_ref).await;- assert!(result.is_ok());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_entity_by_entity_type(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- // Delete all document entities- let doc1_ref = EntityReference::new("doc1", EntityType::Document);- let doc2_ref = EntityReference::new("doc2", EntityType::Document);-- // Verify documents have no properties- let doc1_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- let doc2_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- assert!(doc1_before.len() > 0);- assert!(doc2_before.len() > 0);-- let proj1_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "proj1",- EntityType::Project,- )- .await?;- assert!(proj1_before.len() > 0);-- delete_entity(&pool, &doc1_ref).await?;- delete_entity(&pool, &doc2_ref).await?;-- // Verify documents have no properties- let doc1_after = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- let doc2_after = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- assert_eq!(doc1_after.len(), 0);- assert_eq!(doc2_after.len(), 0);-- // Verify project properties still exist- let proj1_after = crate::entity_properties::get::get_entity_properties_values(- &pool,- "proj1",- EntityType::Project,- )- .await?;- assert_eq!(proj1_after.len(), proj1_before.len());-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs b/rust/cloud-storage/properties_db_client/src/entity_properties/get.rsdeleted file mode 100644index 3884b18d44..0000000000--- a/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs+++ /dev/null@@ -1,1296 +0,0 @@-//! Entity property get operations.--use crate::error::PropertiesDatabaseError;-use sqlx::{Pool, Postgres};-use std::collections::{HashMap, HashSet};-use uuid::Uuid;--use models_properties::service::entity_property::EntityProperty;-use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;-use models_properties::service::property_definition::PropertyDefinition;-use models_properties::service::property_value::PropertyValue;-use models_properties::{DataType, EntityPropertyReference, EntityReference, EntityType};--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Database row data for entity property with definition-struct EntityPropertyRow {- entity_property_id: Uuid,- entity_id: String,- entity_type: EntityType,- property_definition_id: Uuid,- entity_property_created_at: chrono::DateTime<chrono::Utc>,- entity_property_updated_at: chrono::DateTime<chrono::Utc>,- definition_team_id: Option<Uuid>,- definition_user_id: Option<String>,- display_name: String,- data_type: DataType,- is_multi_select: bool,- specific_entity_type: Option<Option<EntityType>>,- definition_created_at: chrono::DateTime<chrono::Utc>,- definition_updated_at: chrono::DateTime<chrono::Utc>,- definition_is_system: bool,- values: Option<sqlx::types::JsonValue>,-}--/// Helper to convert a database row into EntityPropertyWithDefinition-fn row_to_entity_property_with_definition(- row: EntityPropertyRow,-) -> Result<EntityPropertyWithDefinition> {- let owner = models_properties::PropertyOwner::from_optional_ids(- row.definition_team_id,- row.definition_user_id,- row.definition_is_system,- );-- let property_definition = PropertyDefinition {- id: row.property_definition_id,- owner,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.definition_created_at,- updated_at: row.definition_updated_at,- is_system: row.definition_is_system,- is_metadata: false,- };-- let property = EntityProperty {- id: row.entity_property_id,- entity_id: row.entity_id.clone(),- entity_type: row.entity_type,- property_definition_id: row.property_definition_id,- created_at: row.entity_property_created_at,- updated_at: row.entity_property_updated_at,- };-- // Deserialize JSONB value (handle NULL)- let value: Option<PropertyValue> = match row.values {- None => None,- Some(json_value) if json_value.is_null() => None,- Some(json_value) => Some(serde_json::from_value(json_value).map_err(|e| {- tracing::error!(- error = ?e,- entity_property_id = %row.entity_property_id,- entity_id = %row.entity_id,- "failed to deserialize property value from JSONB"- );- PropertiesDatabaseError::DeserializationError(e)- })?),- };-- Ok(EntityPropertyWithDefinition {- property,- definition: property_definition,- value,- options: None,- })-}--/// Helper to sort properties by display name-fn sort_properties_by_display_name(properties: &mut [EntityPropertyWithDefinition]) {- properties.sort_by(|a, b| {- a.definition- .display_name- .to_lowercase()- .cmp(&b.definition.display_name.to_lowercase())- });-}--/// Validates and cleans select option values by deduplicating and filtering invalid IDs-fn validate_and_clean_select_option_value(- property: &mut EntityPropertyWithDefinition,- options: &[models_properties::service::property_option::PropertyOption],-) {- let Some(PropertyValue::SelectOption(option_ids)) = &property.value else {- return;- };-- if option_ids.is_empty() {- return;- }-- // Handle case where property has option IDs but no valid options exist in DB- if options.is_empty() {- tracing::warn!(- entity_property_id = %property.property.id,- property_definition_id = %property.definition.id,- option_ids_count = option_ids.len(),- "select property has option IDs but no valid options exist in DB, clearing value"- );- property.value = Some(PropertyValue::SelectOption(vec![]));- return;- }-- // Deduplicate and validate option IDs- let original_count = option_ids.len();- let unique_ids: HashSet<Uuid> = option_ids.iter().copied().collect();- let unique_count = unique_ids.len();-- let valid_ids_set: HashSet<Uuid> = options.iter().map(|opt| opt.id).collect();- let valid_option_ids: Vec<Uuid> = unique_ids- .into_iter()- .filter(|id| valid_ids_set.contains(id))- .collect();-- let has_invalid = valid_option_ids.len() != unique_count;- let has_duplicates = unique_count != original_count;-- if has_invalid || has_duplicates {- let invalid_count = unique_count - valid_option_ids.len();- let duplicate_count = original_count - unique_count;-- tracing::warn!(- entity_property_id = %property.property.id,- property_definition_id = %property.definition.id,- original_count = original_count,- valid_count = valid_option_ids.len(),- invalid_count = invalid_count,- duplicate_count = duplicate_count,- "filtered and deduplicated option IDs from entity property value"- );-- property.value = Some(PropertyValue::SelectOption(valid_option_ids));- }-}--/// Defensively clears stale select options/values from non-select properties-fn clear_stale_select_data(property: &mut EntityPropertyWithDefinition) {- if property.options.is_some() {- tracing::warn!(- entity_property_id = %property.property.id,- property_definition_id = %property.definition.id,- data_type = ?property.definition.data_type,- "non-select property has options attached, clearing"- );- property.options = None;- }-- if matches!(property.value, Some(PropertyValue::SelectOption(_))) {- tracing::warn!(- entity_property_id = %property.property.id,- property_definition_id = %property.definition.id,- data_type = ?property.definition.data_type,- "non-select property has SelectOption value, clearing"- );- property.value = None;- }-}--/// Helper to fetch and attach property options to properties.-/// Also validates and deduplicates option IDs in property values.-/// Defensively clears stale options/values on non-select properties.-async fn attach_property_options(- db: &Pool<Postgres>,- properties: &mut [EntityPropertyWithDefinition],-) -> Result<()> {- // Collect select-type property IDs for batch fetch- let property_ids_needing_options: Vec<Uuid> = properties- .iter()- .filter(|p| {- matches!(- p.definition.data_type,- DataType::SelectString | DataType::SelectNumber | DataType::Tag- )- })- .map(|p| p.definition.id)- .collect();-- // Fetch all options in one query (empty if no select properties)- let options_map = if !property_ids_needing_options.is_empty() {- crate::property_options::get::get_property_options_batch(db, &property_ids_needing_options)- .await?- } else {- HashMap::new()- };-- // Process ALL properties- for property in properties {- let is_select_type = matches!(- property.definition.data_type,- DataType::SelectString | DataType::SelectNumber | DataType::Tag- );-- if is_select_type {- let options = options_map- .get(&property.definition.id)- .cloned()- .unwrap_or_default();-- property.options = Some(options.clone());- validate_and_clean_select_option_value(property, &options);- } else {- clear_stale_select_data(property);- }- }-- Ok(())-}--/// Fetch and attach property options to properties across multiple entities in ONE query.-/// Optimized for bulk operations - collects all unique select-type property IDs across all entities,-/// fetches options once, then distributes to each property.-async fn attach_property_options_bulk(- db: &Pool<Postgres>,- entity_properties_map: &mut HashMap<String, Vec<EntityPropertyWithDefinition>>,-) -> Result<()> {- let property_ids_needing_options: HashSet<Uuid> = entity_properties_map- .values()- .flatten()- .filter(|p| {- matches!(- p.definition.data_type,- DataType::SelectString | DataType::SelectNumber | DataType::Tag- )- })- .map(|p| p.definition.id)- .collect();-- let options_map = if !property_ids_needing_options.is_empty() {- let property_ids_vec: Vec<Uuid> = property_ids_needing_options.into_iter().collect();- crate::property_options::get::get_property_options_batch(db, &property_ids_vec).await?- } else {- HashMap::new()- };-- for properties in entity_properties_map.values_mut() {- for property in properties.iter_mut() {- let is_select_type = matches!(- property.definition.data_type,- DataType::SelectString | DataType::SelectNumber | DataType::Tag- );- if is_select_type {- let options = options_map- .get(&property.definition.id)- .cloned()- .unwrap_or_default();- validate_and_clean_select_option_value(property, &options);- property.options = Some(options);- } else {- clear_stale_select_data(property);- }- }- }-- Ok(())-}--/// Looks up an entity property by its ID.-/// Returns entity reference (for permissions) and definition ID (for required property check).-#[tracing::instrument(skip(db))]-pub async fn lookup_entity_property(- db: &Pool<Postgres>,- entity_property_id: Uuid,-) -> Result<Option<EntityPropertyReference>> {- let row = sqlx::query!(- r#"-SELECT- ep.entity_id,- ep.entity_type as "entity_type: EntityType",- ep.property_definition_id-FROM entity_properties ep-WHERE ep.id = $1- "#,- entity_property_id- )- .fetch_optional(db)- .await?;-- Ok(row.map(|r| EntityPropertyReference {- entity_id: r.entity_id,- entity_type: r.entity_type,- property_definition_id: r.property_definition_id,- }))-}--/// Gets entity properties with their definitions and values.-/// Includes both custom and system properties.-#[tracing::instrument(skip(db))]-pub async fn get_entity_properties_values(- db: &Pool<Postgres>,- entity_id: &str,- entity_type: EntityType,-) -> Result<Vec<EntityPropertyWithDefinition>> {- let rows = sqlx::query!(- r#"-SELECT- ep.id as entity_property_id,- ep.entity_id,- ep.entity_type as "entity_type: EntityType",- ep.property_definition_id,- ep.values as "values: sqlx::types::JsonValue",- ep.created_at as entity_property_created_at,- ep.updated_at as entity_property_updated_at,- pd.team_id as definition_team_id,- pd.user_id as definition_user_id,- pd.display_name,- pd.data_type as "data_type: DataType",- pd.is_multi_select,- pd.specific_entity_type as "specific_entity_type: Option<EntityType>",- pd.created_at as definition_created_at,- pd.updated_at as definition_updated_at,- pd.is_system as definition_is_system-FROM entity_properties ep-INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id-WHERE ep.entity_id = $1 AND ep.entity_type = $2- "#,- entity_id,- entity_type as EntityType- )- .fetch_all(db)- .await?;-- let mut result: Vec<EntityPropertyWithDefinition> = rows- .into_iter()- .map(|row| {- row_to_entity_property_with_definition(EntityPropertyRow {- entity_property_id: row.entity_property_id,- entity_id: row.entity_id,- entity_type: row.entity_type,- property_definition_id: row.property_definition_id,- entity_property_created_at: row.entity_property_created_at,- entity_property_updated_at: row.entity_property_updated_at,- definition_team_id: row.definition_team_id,- definition_user_id: row.definition_user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type,- definition_created_at: row.definition_created_at,- definition_updated_at: row.definition_updated_at,- definition_is_system: row.definition_is_system,- values: row.values,- })- })- .collect::<Result<Vec<_>>>()?;-- // Sort by display name- sort_properties_by_display_name(&mut result);-- // Fetch and attach property options- attach_property_options(db, &mut result).await?;-- Ok(result)-}--/// Gets entity properties with their definitions and values for multiple entities.-/// Returns a HashMap where the key is the entity_id and the value is Vec<EntityPropertyWithDefinition>.-/// Includes both custom and system properties.-#[tracing::instrument(skip(db))]-pub async fn get_bulk_entity_properties_values(- db: &Pool<Postgres>,- entity_refs: &[EntityReference],-) -> Result<HashMap<String, Vec<EntityPropertyWithDefinition>>> {- if entity_refs.is_empty() {- return Ok(HashMap::new());- }-- // Use UNNEST to match entity_id and entity_type as pairs- let entity_ids: Vec<String> = entity_refs.iter().map(|r| r.entity_id.clone()).collect();- let entity_types: Vec<EntityType> = entity_refs.iter().map(|r| r.entity_type).collect();-- let rows = sqlx::query!(- r#"-SELECT- ep.id as entity_property_id,- ep.entity_id,- ep.entity_type as "entity_type: EntityType",- ep.property_definition_id,- ep.values as "values: sqlx::types::JsonValue",- ep.created_at as entity_property_created_at,- ep.updated_at as entity_property_updated_at,- pd.team_id as definition_team_id,- pd.user_id as definition_user_id,- pd.display_name,- pd.data_type as "data_type: DataType",- pd.is_multi_select,- pd.specific_entity_type as "specific_entity_type: Option<EntityType>",- pd.created_at as definition_created_at,- pd.updated_at as definition_updated_at,- pd.is_system as definition_is_system-FROM entity_properties ep-INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id-WHERE (ep.entity_id, ep.entity_type) IN (- SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])-)-"#,- &entity_ids,- &entity_types as &[EntityType]- )- .fetch_all(db)- .await?;-- // Group by entity_id- let mut entity_properties_map: HashMap<String, Vec<EntityPropertyWithDefinition>> =- HashMap::new();-- for row in rows {- let entity_id = row.entity_id.clone();- let property_with_definition = row_to_entity_property_with_definition(EntityPropertyRow {- entity_property_id: row.entity_property_id,- entity_id: row.entity_id,- entity_type: row.entity_type,- property_definition_id: row.property_definition_id,- entity_property_created_at: row.entity_property_created_at,- entity_property_updated_at: row.entity_property_updated_at,- definition_team_id: row.definition_team_id,- definition_user_id: row.definition_user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type,- definition_created_at: row.definition_created_at,- definition_updated_at: row.definition_updated_at,- definition_is_system: row.definition_is_system,- values: row.values,- })?;-- entity_properties_map- .entry(entity_id)- .or_default()- .push(property_with_definition);- }-- // Sort each entity's properties by display name- for properties in entity_properties_map.values_mut() {- sort_properties_by_display_name(properties);- }-- attach_property_options_bulk(db, &mut entity_properties_map).await?;-- // Ensure all requested entity_ids are present in the result, even if they have no properties- for entity_ref in entity_refs {- entity_properties_map- .entry(entity_ref.entity_id.clone())- .or_default();- }-- Ok(entity_properties_map)-}--/// Gets entity properties with their definitions and values for multiple entities, filtered by property definition IDs.-/// Returns a HashMap where the key is the entity_id and the value is Vec<EntityPropertyWithDefinition>.-/// Only returns properties matching the specified property_ids. When `tag_viewer_user_id` is set,-/// also returns TAG properties whose definition is owned by that user or their team.-#[tracing::instrument(skip(db))]-pub async fn get_bulk_entity_properties_values_filtered(- db: &Pool<Postgres>,- entity_refs: &[EntityReference],- property_ids: &[Uuid],- tag_viewer_user_id: Option<&str>,-) -> Result<HashMap<String, Vec<EntityPropertyWithDefinition>>> {- if entity_refs.is_empty() || (property_ids.is_empty() && tag_viewer_user_id.is_none()) {- // If no property_ids specified, return empty map for each entity- let mut result = HashMap::new();- for entity_ref in entity_refs {- result.insert(entity_ref.entity_id.clone(), Vec::new());- }- return Ok(result);- }-- let entity_ids: Vec<String> = entity_refs.iter().map(|r| r.entity_id.clone()).collect();- let entity_types: Vec<EntityType> = entity_refs.iter().map(|r| r.entity_type).collect();-- let rows = sqlx::query!(- r#"-SELECT- ep.id as entity_property_id,- ep.entity_id,- ep.entity_type as "entity_type: EntityType",- ep.property_definition_id,- ep.values as "values: sqlx::types::JsonValue",- ep.created_at as entity_property_created_at,- ep.updated_at as entity_property_updated_at,- pd.team_id as definition_team_id,- pd.user_id as definition_user_id,- pd.display_name,- pd.data_type as "data_type: DataType",- pd.is_multi_select,- pd.specific_entity_type as "specific_entity_type: Option<EntityType>",- pd.created_at as definition_created_at,- pd.updated_at as definition_updated_at,- pd.is_system as definition_is_system-FROM entity_properties ep-INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id-WHERE (ep.entity_id, ep.entity_type) IN (- SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])-)-AND (- pd.id = ANY($3::UUID[])- OR (- $4::text IS NOT NULL- AND pd.data_type = $5- AND (- pd.user_id = $4- OR pd.team_id IN (SELECT tu.team_id FROM team_user tu WHERE tu.user_id = $4)- )- )-)- "#,- &entity_ids,- &entity_types as &[EntityType],- &property_ids,- tag_viewer_user_id,- DataType::Tag as DataType- )- .fetch_all(db)- .await?;-- let mut entity_properties_map: HashMap<String, Vec<EntityPropertyWithDefinition>> =- HashMap::new();-- for row in rows {- let entity_id = row.entity_id.clone();- let property_with_definition = row_to_entity_property_with_definition(EntityPropertyRow {- entity_property_id: row.entity_property_id,- entity_id: row.entity_id,- entity_type: row.entity_type,- property_definition_id: row.property_definition_id,- entity_property_created_at: row.entity_property_created_at,- entity_property_updated_at: row.entity_property_updated_at,- definition_team_id: row.definition_team_id,- definition_user_id: row.definition_user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type,- definition_created_at: row.definition_created_at,- definition_updated_at: row.definition_updated_at,- definition_is_system: row.definition_is_system,- values: row.values,- })?;-- entity_properties_map- .entry(entity_id)- .or_default()- .push(property_with_definition);- }-- for properties in entity_properties_map.values_mut() {- sort_properties_by_display_name(properties);- }-- attach_property_options_bulk(db, &mut entity_properties_map).await?;-- for entity_ref in entity_refs {- entity_properties_map- .entry(entity_ref.entity_id.clone())- .or_default();- }-- Ok(entity_properties_map)-}--/// An entity property flattened into the shape the search index stores. Each-/// value lands under the field matching its type; the rest stay empty/None.-/// Covers every `PropertyValue` kind except multi-string.-#[derive(Default)]-pub struct IndexedEntityProperty {- /// The property definition id this value belongs to.- pub definition_id: String,- /// Every equality-filterable value as a string: select-option UUIDs,- /// entity-reference ids, links, text, bool as "true"/"false".- pub values: Vec<String>,- /// Numeric value (range + sort).- pub number_value: Option<f64>,- /// Date value as epoch milliseconds (range + sort).- pub date_value: Option<i64>,-}--impl IndexedEntityProperty {- fn is_empty(&self) -> bool {- self.values.is_empty() && self.number_value.is_none() && self.date_value.is_none()- }-}--/// Flatten one entity_properties row into the shape the search index stores.-/// Null and unparseable values yield None so one bad value can't fail the-/// whole index.-fn flatten_property_for_index(- property_definition_id: Uuid,- values: Option<serde_json::Value>,-) -> Option<IndexedEntityProperty> {- let value = values?;- if value.is_null() {- return None;- }- let parsed = match serde_json::from_value::<PropertyValue>(value) {- Ok(parsed) => parsed,- Err(e) => {- tracing::warn!(- error = ?e,- definition_id = %property_definition_id,- "skipping unparseable property value for index"- );- return None;- }- };- let mut property = IndexedEntityProperty {- definition_id: property_definition_id.to_string(),- ..Default::default()- };- match parsed {- PropertyValue::SelectOption(ids) => {- property.values = ids.into_iter().map(|id| id.to_string()).collect();- }- PropertyValue::EntityRef(refs) => {- property.values = refs.into_iter().map(|r| r.entity_id).collect();- }- PropertyValue::Link(urls) => property.values = urls,- PropertyValue::Str(s) => property.values = vec![s],- PropertyValue::Bool(b) => property.values = vec![b.to_string()],- PropertyValue::Num(n) => property.number_value = Some(n),- PropertyValue::Date(d) => property.date_value = Some(d.timestamp_millis()),- }- if property.is_empty() {- return None;- }- Some(property)-}--/// Fetch an entity's properties flattened for the search index. Each value-/// lands under the field matching its type (equality-filterable values as-/// strings, numbers, or epoch-millis dates); null and unparseable values are-/// skipped so one bad value can't fail the whole index.-#[tracing::instrument(skip(db), err)]-pub async fn get_entity_properties_for_index(- db: &Pool<Postgres>,- entity_id: &str,- entity_type: EntityType,-) -> Result<Vec<IndexedEntityProperty>> {- let rows = sqlx::query!(- r#"- SELECT- property_definition_id,- values as "values: serde_json::Value"- FROM entity_properties- WHERE entity_id = $1- AND entity_type = $2- "#,- entity_id,- entity_type as EntityType,- )- .fetch_all(db)- .await?;-- Ok(rows- .into_iter()- .filter_map(|row| flatten_property_for_index(row.property_definition_id, row.values))- .collect())-}--/// Page through the distinct entity ids that hold property rows of one-/// entity type, ordered by entity id so offset pagination is stable. Used by-/// the search properties backfill.-#[tracing::instrument(skip(db), err)]-pub async fn get_entity_ids_with_properties(- db: &Pool<Postgres>,- entity_type: EntityType,- limit: i64,- offset: i64,-) -> Result<Vec<String>> {- let rows = sqlx::query_scalar!(- r#"- SELECT DISTINCT entity_id- FROM entity_properties- WHERE entity_type = $1- ORDER BY entity_id- LIMIT $2 OFFSET $3- "#,- entity_type as EntityType,- limit,- offset,- )- .fetch_all(db)- .await?;- Ok(rows)-}--/// Batch variant of [`get_entity_properties_for_index`]: fetch the flattened-/// properties of many entities of one type in a single query, keyed by-/// entity id. Entities without properties are absent from the map.-#[tracing::instrument(skip(db, entity_ids), err)]-pub async fn get_entity_properties_for_index_batch(- db: &Pool<Postgres>,- entity_ids: &[String],- entity_type: EntityType,-) -> Result<HashMap<String, Vec<IndexedEntityProperty>>> {- if entity_ids.is_empty() {- return Ok(HashMap::new());- }- let rows = sqlx::query!(- r#"- SELECT- entity_id,- property_definition_id,- values as "values: serde_json::Value"- FROM entity_properties- WHERE entity_id = ANY($1)- AND entity_type = $2- "#,- entity_ids,- entity_type as EntityType,- )- .fetch_all(db)- .await?;-- let mut result: HashMap<String, Vec<IndexedEntityProperty>> = HashMap::new();- for row in rows {- let Some(property) = flatten_property_for_index(row.property_definition_id, row.values)- else {- continue;- };- result.entry(row.entity_id).or_default().push(property);- }-- Ok(result)-}--#[cfg(test)]-mod tests {- use super::*;- use chrono::Datelike;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_values(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc1", EntityType::Document).await?;-- // doc1 has 7 properties in fixtures- assert_eq!(properties.len(), 6);-- // Verify they are sorted by display name (case-insensitive alphabetical)- assert_eq!(properties[0].definition.display_name, "Test Assigned To");- assert_eq!(properties[1].definition.display_name, "Test Completed");- assert_eq!(properties[2].definition.display_name, "Test Department");- assert_eq!(properties[3].definition.display_name, "Test Description");- assert_eq!(properties[4].definition.display_name, "Test Due Date");- assert_eq!(properties[5].definition.display_name, "Test Priority");-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_values_with_select_options(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc1", EntityType::Document).await?;-- // Find Priority property- let priority_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Priority")- .unwrap();-- // Verify it has options attached- assert!(priority_prop.options.is_some());- let options = priority_prop.options.as_ref().unwrap();- assert_eq!(options.len(), 4);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_values_boolean_value(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc1", EntityType::Document).await?;-- // Find Completed property (boolean)- let completed_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Completed")- .unwrap();-- // Verify boolean value- if let Some(PropertyValue::Bool(val)) = completed_prop.value {- assert!(!val); // doc1 has false- } else {- panic!("Expected boolean value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_values_string_value(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc1", EntityType::Document).await?;-- // Find Description property (string)- let desc_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Description")- .unwrap();-- // Verify string value- if let Some(PropertyValue::Str(val)) = &desc_prop.value {- assert_eq!(val, "Important document for testing");- } else {- panic!("Expected string value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_values_null_values(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc3", EntityType::Document).await?;-- // doc3 has 3 properties with NULL values- assert_eq!(properties.len(), 3);-- for prop in properties {- assert!(prop.value.is_none());- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_values_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties =- get_entity_properties_values(&pool, "nonexistent", EntityType::Document).await?;-- assert_eq!(properties.len(), 0);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_bulk_entity_properties_values(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_refs = vec![- EntityReference::new("doc1", EntityType::Document),- EntityReference::new("doc2", EntityType::Document),- EntityReference::new("proj1", EntityType::Project),- ];- let properties_map = get_bulk_entity_properties_values(&pool, &entity_refs).await?;-- assert_eq!(properties_map.len(), 3);- assert_eq!(properties_map.get("doc1").unwrap().len(), 6);- assert_eq!(properties_map.get("doc2").unwrap().len(), 4);- assert_eq!(properties_map.get("proj1").unwrap().len(), 5);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_bulk_entity_properties_values_includes_empty_entities(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_refs = vec![- EntityReference::new("doc1", EntityType::Document),- EntityReference::new("nonexistent", EntityType::Document),- ];- let properties_map = get_bulk_entity_properties_values(&pool, &entity_refs).await?;-- // Both entities should be in the map- assert_eq!(properties_map.len(), 2);- assert!(properties_map.contains_key("doc1"));- assert!(properties_map.contains_key("nonexistent"));-- // nonexistent should have empty array- assert_eq!(properties_map.get("nonexistent").unwrap().len(), 0);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_bulk_entity_properties_values_empty_input(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_refs: Vec<EntityReference> = vec![];- let properties_map = get_bulk_entity_properties_values(&pool, &entity_refs).await?;-- assert_eq!(properties_map.len(), 0);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_lookup_entity_property(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_property_id = "e0111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let info = lookup_entity_property(&pool, entity_property_id).await?;-- assert!(info.is_some());- let info = info.unwrap();- assert_eq!(info.entity_id, "doc1");- assert_eq!(info.entity_type, EntityType::Document);- assert_eq!(- info.property_definition_id,- "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap()- );-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_lookup_entity_property_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let entity_property_id = "00000000-0000-0000-0000-000000000000"- .parse::<Uuid>()- .unwrap();- let info = lookup_entity_property(&pool, entity_property_id).await?;-- assert!(info.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_entity_reference_single(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc1", EntityType::Document).await?;-- // Find Assigned To property (ENTITY type with 1 user)- let assigned_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Assigned To")- .unwrap();-- // Verify it's an ENTITY type property- assert_eq!(assigned_prop.definition.data_type, DataType::Entity);- assert_eq!(- assigned_prop.definition.specific_entity_type,- Some(EntityType::User)- );- assert!(assigned_prop.definition.is_multi_select); // Multi-select enabled-- // Verify it has 1 user reference- if let Some(PropertyValue::EntityRef(refs)) = &assigned_prop.value {- assert_eq!(refs.len(), 1);- assert_eq!(refs[0].entity_id, "user1");- assert_eq!(refs[0].entity_type, EntityType::User);- } else {- panic!("Expected EntityReference value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_entity_reference_multiple(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc2", EntityType::Document).await?;-- // Find Assigned To property (ENTITY type with 2 users)- let assigned_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Assigned To")- .unwrap();-- // Verify it has 2 user references- if let Some(PropertyValue::EntityRef(refs)) = &assigned_prop.value {- assert_eq!(refs.len(), 2);-- // Verify both users are present- let user_ids: Vec<&str> = refs.iter().map(|r| r.entity_id.as_str()).collect();- assert!(user_ids.contains(&"user1"));- assert!(user_ids.contains(&"user2"));-- // All should be USER entity type- for ref_val in refs {- assert_eq!(ref_val.entity_type, EntityType::User);- }- } else {- panic!("Expected EntityReference value with 2 users");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_entity_reference_null(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc3", EntityType::Document).await?;-- // Find Assigned To property (NULL value)- let assigned_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Assigned To")- .unwrap();-- // Verify the property exists but value is NULL- assert_eq!(assigned_prop.definition.data_type, DataType::Entity);- assert!(assigned_prop.value.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_multi_select_string(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc2", EntityType::Document).await?;-- // Find Department property (multi-select SELECT_STRING)- let dept_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Department")- .unwrap();-- // Verify it's multi-select- assert_eq!(dept_prop.definition.data_type, DataType::SelectString);- assert!(dept_prop.definition.is_multi_select);-- // Verify it has options attached- assert!(dept_prop.options.is_some());- let options = dept_prop.options.as_ref().unwrap();- assert_eq!(options.len(), 3); // Engineering, Marketing, Human Resources-- // Verify it has 2 selected values- if let Some(PropertyValue::SelectOption(ids)) = &dept_prop.value {- assert_eq!(ids.len(), 2);-- // Verify the selected options are valid- for id in ids {- assert!(options.iter().any(|opt| opt.id == *id));- }- } else {- panic!("Expected SelectOption value with 2 departments");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_date_value(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "doc1", EntityType::Document).await?;-- // Find Due Date property (DATE type)- let date_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Due Date")- .unwrap();-- // Verify it's a DATE type- assert_eq!(date_prop.definition.data_type, DataType::Date);-- // Verify it has a date value- if let Some(PropertyValue::Date(date)) = &date_prop.value {- // Verify the date is 2025-12-31- assert_eq!(date.year(), 2025);- assert_eq!(date.month(), 12);- assert_eq!(date.day(), 31);- } else {- panic!("Expected Date value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_link_value(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "proj1", EntityType::Project).await?;-- // Find Website property (LINK type)- let link_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Website")- .unwrap();-- // Verify it's a LINK type- assert_eq!(link_prop.definition.data_type, DataType::Link);-- // Verify it has a link value- if let Some(PropertyValue::Link(links)) = &link_prop.value {- assert_eq!(links.len(), 1);- assert_eq!(links[0], "https://example.com");- } else {- panic!("Expected Link value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_entity_properties_number_value(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_entity_properties_values(&pool, "proj1", EntityType::Project).await?;-- // Find Budget property (NUMBER type)- let budget_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Budget")- .unwrap();-- // Verify it's a NUMBER type- assert_eq!(budget_prop.definition.data_type, DataType::Number);-- // Verify it has the correct number value- if let Some(PropertyValue::Num(val)) = budget_prop.value {- assert_eq!(val, 50000.50);- } else {- panic!("Expected Number value");- }-- Ok(())- }-- /// Definition ids returned for tagdoc1 given a set of requested property- /// ids and an optional tag viewer.- async fn tagdoc_definition_ids(- pool: &Pool<Postgres>,- property_ids: &[Uuid],- tag_viewer: Option<&str>,- ) -> anyhow::Result<Vec<Uuid>> {- let entity_refs = vec![EntityReference {- entity_id: "tagdoc1".to_string(),- entity_type: EntityType::Document,- specific_message_id: None,- }];- let map = get_bulk_entity_properties_values_filtered(- pool,- &entity_refs,- property_ids,- tag_viewer,- )- .await?;- Ok(map["tagdoc1"]- .iter()- .map(|p| p.definition.id)- .collect::<Vec<_>>())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties", "tags"))- )]- async fn test_get_bulk_filtered_includes_caller_visible_tags(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let priority = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;- let user1_tags = Uuid::parse_str("aa111111-1111-1111-1111-111111111111")?;- let team1_tags = Uuid::parse_str("aa222222-2222-2222-2222-222222222222")?;- let user2_tags = Uuid::parse_str("aa333333-3333-3333-3333-333333333333")?;-- // user1 sees the requested id plus their own and their team's tags,- // never another user's personal tags.- let ids = tagdoc_definition_ids(&pool, &[priority], Some("user1")).await?;- assert_eq!(ids.len(), 3);- assert!(ids.contains(&priority));- assert!(ids.contains(&user1_tags));- assert!(ids.contains(&team1_tags));- assert!(!ids.contains(&user2_tags));-- // A teammate without a personal set sees only the team tags.- let ids = tagdoc_definition_ids(&pool, &[priority], Some("user3")).await?;- assert_eq!(ids.len(), 2);- assert!(ids.contains(&priority));- assert!(ids.contains(&team1_tags));-- // No viewer: only the explicitly requested ids.- let ids = tagdoc_definition_ids(&pool, &[priority], None).await?;- assert_eq!(ids, vec![priority]);-- // A viewer with no requested ids still gets their tags.- let ids = tagdoc_definition_ids(&pool, &[], Some("user1")).await?;- assert_eq!(ids.len(), 2);- assert!(ids.contains(&user1_tags));- assert!(ids.contains(&team1_tags));-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/entity_properties/mod.rs b/rust/cloud-storage/properties_db_client/src/entity_properties/mod.rsdeleted file mode 100644index a740553787..0000000000--- a/rust/cloud-storage/properties_db_client/src/entity_properties/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-//! Entity property database operations.--pub mod delete;-pub mod get;-pub mod upsert;diff --git a/rust/cloud-storage/properties_db_client/src/entity_properties/upsert.rs b/rust/cloud-storage/properties_db_client/src/entity_properties/upsert.rsdeleted file mode 100644index e0d66ed2f6..0000000000--- a/rust/cloud-storage/properties_db_client/src/entity_properties/upsert.rs+++ /dev/null@@ -1,583 +0,0 @@-//! Entity property upsert operations.--use crate::error::PropertiesDatabaseError;-use models_properties::EntityType;-use models_properties::service::property_value::PropertyValue;-use sqlx::{Pool, Postgres};-use uuid::Uuid;--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Upserts entity property values for a given entity and property definition.-/// Values are stored as JSONB with tagged union structure.-/// If value is None, the property is set to NULL (clearing the value).-#[tracing::instrument(skip(db, value))]-pub async fn upsert_entity_property_values(- db: &Pool<Postgres>,- entity_id: &str,- entity_type: EntityType,- property_definition_id: Uuid,- value: Option<PropertyValue>,-) -> Result<()> {- let id = macro_uuid::generate_uuid_v7();-- // Serialize PropertyValue to JSONB (or NULL if None)- let value_json = match value {- Some(v) => serde_json::to_value(&v).map_err(|e| {- tracing::error!(- error = ?e,- entity_id = %entity_id,- property_definition_id = %property_definition_id,- "failed to serialize property value to JSON"- );- PropertiesDatabaseError::SerializationError(e)- })?,- None => serde_json::Value::Null,- };-- tracing::debug!(- entity_id = %entity_id,- property_definition_id = %property_definition_id,- value_json = ?value_json,- has_value = !value_json.is_null(),- "upserting entity property with JSONB value"- );-- // Single UPSERT operation - handles both INSERT and UPDATE cases- // When value is None, JSONB will be NULL, effectively clearing the value while keeping the property attached- sqlx::query!(- r#"- INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)- VALUES ($1, $2, $3, $4, $5)- ON CONFLICT (entity_id, entity_type, property_definition_id)- DO UPDATE SET- values = EXCLUDED.values,- updated_at = NOW()- "#,- id,- entity_id,- entity_type as EntityType,- property_definition_id,- value_json- )- .execute(db)- .await- .map_err(|e| {- tracing::error!(- error = ?e,- entity_id = %entity_id,- property_definition_id = %property_definition_id,- "failed to upsert entity property"- );- PropertiesDatabaseError::Query(e)- })?;-- tracing::info!(- entity_id = %entity_id,- property_definition_id = %property_definition_id,- has_value = !value_json.is_null(),- "successfully upserted entity property"- );-- Ok(())-}--/// Validates property options by checking if they exist for the property definition.-/// This should be called at the service layer before upserting.-pub async fn validate_property_options(- db: &Pool<Postgres>,- property_definition_id: Uuid,- option_ids: &[Uuid],-) -> Result<()> {- if option_ids.is_empty() {- return Ok(());- }-- tracing::debug!(- property_definition_id = %property_definition_id,- option_ids = ?option_ids,- "validating property options"- );-- // Count how many of the provided option IDs actually exist for this property- let valid_count = crate::property_options::get::count_property_options_by_ids(- db,- property_definition_id,- option_ids,- )- .await?;-- if valid_count != option_ids.len() as i64 {- tracing::warn!(- property_definition_id = %property_definition_id,- provided_count = option_ids.len(),- valid_count = valid_count,- "property option validation failed"- );- return Err(PropertiesDatabaseError::InvalidPropertyOptions {- provided: option_ids.len(),- valid: valid_count,- property_id: property_definition_id,- });- }-- tracing::debug!(- property_definition_id = %property_definition_id,- option_count = option_ids.len(),- "property options validated successfully"- );-- Ok(())-}--/// Extracts all option IDs from PropertyValue for validation-pub fn extract_option_ids(value: &Option<PropertyValue>) -> Vec<Uuid> {- match value {- Some(PropertyValue::SelectOption(ids)) => ids.clone(),- _ => Vec::new(),- }-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use models_properties::EntityReference;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_upsert_entity_property_values_insert(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- let desc_prop_before = properties_before- .iter()- .find(|p| p.definition.display_name == "Test Description");- assert!(desc_prop_before.is_none());-- let property_id = "88888888-8888-8888-8888-888888888888"- .parse::<Uuid>()- .unwrap();- let value = PropertyValue::Str("New description".to_string());-- upsert_entity_property_values(- &pool,- "doc2",- EntityType::Document,- property_id,- Some(value),- )- .await?;-- // Verify it was inserted- let properties = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- let desc_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Description");-- assert!(desc_prop.is_some());- let desc_prop = desc_prop.unwrap();-- if let Some(PropertyValue::Str(val)) = &desc_prop.value {- assert_eq!(val, "New description");- } else {- panic!("Expected string value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_upsert_entity_property_values_update(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "88888888-8888-8888-8888-888888888888"- .parse::<Uuid>()- .unwrap();- let new_value = PropertyValue::Str("Updated description".to_string());-- // Update existing property- upsert_entity_property_values(- &pool,- "doc1",- EntityType::Document,- property_id,- Some(new_value),- )- .await?;-- // Verify it was updated- let properties = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- let desc_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Description")- .unwrap();-- if let Some(PropertyValue::Str(val)) = &desc_prop.value {- assert_eq!(val, "Updated description");- } else {- panic!("Expected string value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_upsert_entity_property_values_clear_value(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "88888888-8888-8888-8888-888888888888"- .parse::<Uuid>()- .unwrap();-- // Clear the value by passing None- upsert_entity_property_values(&pool, "doc1", EntityType::Document, property_id, None)- .await?;-- // Verify value is now NULL- let properties = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- EntityType::Document,- )- .await?;- let desc_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Description")- .unwrap();-- assert!(desc_prop.value.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_upsert_entity_property_values_boolean(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "55555555-5555-5555-5555-555555555555"- .parse::<Uuid>()- .unwrap();- let value = PropertyValue::Bool(true);-- upsert_entity_property_values(- &pool,- "proj1",- EntityType::Project,- property_id,- Some(value),- )- .await?;-- // Verify it was set- let properties = crate::entity_properties::get::get_entity_properties_values(- &pool,- "proj1",- EntityType::Project,- )- .await?;- let completed_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Completed");-- assert!(completed_prop.is_some());- if let Some(PropertyValue::Bool(val)) = completed_prop.unwrap().value {- assert!(val);- } else {- panic!("Expected boolean value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_upsert_entity_property_values_number(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "77777777-7777-7777-7777-777777777777"- .parse::<Uuid>()- .unwrap();- let value = PropertyValue::Num(75000.99);-- upsert_entity_property_values(- &pool,- "proj1",- EntityType::Project,- property_id,- Some(value),- )- .await?;-- // Verify it was updated- let properties = crate::entity_properties::get::get_entity_properties_values(- &pool,- "proj1",- EntityType::Project,- )- .await?;- let budget_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Budget")- .unwrap();-- if let Some(PropertyValue::Num(val)) = budget_prop.value {- assert_eq!(val, 75000.99);- } else {- panic!("Expected number value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_upsert_entity_property_values_select_option(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- let priority_prop_before = properties_before- .iter()- .find(|p| p.definition.display_name == "Test Priority")- .unwrap();- if let Some(PropertyValue::SelectOption(ids)) = &priority_prop_before.value {- assert_eq!(ids.len(), 1);- assert_eq!(- ids[0],- "10111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap()- );- } else {- panic!("Expected select option value");- }-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let option_id = "10111111-1111-1111-1111-111111111112"- .parse::<Uuid>()- .unwrap();- let value = PropertyValue::SelectOption(vec![option_id]);-- upsert_entity_property_values(- &pool,- "doc2",- EntityType::Document,- property_id,- Some(value),- )- .await?;-- // Verify it was updated- let properties = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc2",- EntityType::Document,- )- .await?;- let priority_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Priority")- .unwrap();-- if let Some(PropertyValue::SelectOption(ids)) = &priority_prop.value {- assert_eq!(ids.len(), 1);- assert_eq!(ids[0], option_id);- } else {- panic!("Expected select option value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_upsert_entity_property_values_entity_reference(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- // Verify it was updated- let properties_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "proj1",- EntityType::Project,- )- .await?;- let assigned_prop_before = properties_before- .iter()- .find(|p| p.definition.display_name == "Test Assigned To")- .unwrap();-- if let Some(PropertyValue::EntityRef(refs)) = &assigned_prop_before.value {- assert_eq!(refs.len(), 1);- assert_eq!(refs[0].entity_id, "user1");- assert_eq!(refs[0].entity_type, EntityType::User);- } else {- panic!("Expected entity reference value");- }-- let property_id = "33333333-3333-3333-3333-333333333333"- .parse::<Uuid>()- .unwrap();- let entity_ref_1 = EntityReference::new("user1", EntityType::User);- let entity_ref_2 = EntityReference::new("user2", EntityType::User);- let value = PropertyValue::EntityRef(vec![entity_ref_1, entity_ref_2]);-- upsert_entity_property_values(- &pool,- "proj1",- EntityType::Project,- property_id,- Some(value),- )- .await?;-- // Verify it was updated- let properties = crate::entity_properties::get::get_entity_properties_values(- &pool,- "proj1",- EntityType::Project,- )- .await?;- let assigned_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Assigned To")- .unwrap();-- if let Some(PropertyValue::EntityRef(refs)) = &assigned_prop.value {- assert_eq!(refs.len(), 2);- assert_eq!(refs[0].entity_id, "user1");- assert_eq!(refs[0].entity_type, EntityType::User);- assert_eq!(refs[1].entity_id, "user2");- assert_eq!(refs[1].entity_type, EntityType::User);- } else {- panic!("Expected entity reference value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_validate_property_options_valid(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let option_ids = vec![- "10111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap(),- "10111111-1111-1111-1111-111111111112"- .parse::<Uuid>()- .unwrap(),- ];-- let result = validate_property_options(&pool, property_id, &option_ids).await;- assert!(result.is_ok());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_validate_property_options_invalid(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let option_ids = vec![- "10111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap(),- "00000000-0000-0000-0000-000000000000"- .parse::<Uuid>()- .unwrap(), // Invalid- ];-- let result = validate_property_options(&pool, property_id, &option_ids).await;- assert!(result.is_err());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_extract_option_ids(_pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let option_ids = vec![- "10111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap(),- "10111111-1111-1111-1111-111111111112"- .parse::<Uuid>()- .unwrap(),- ];- let value = Some(PropertyValue::SelectOption(option_ids.clone()));-- let extracted = extract_option_ids(&value);- assert_eq!(extracted, option_ids);-- // Test with non-select option- let value2 = Some(PropertyValue::Str("test".to_string()));- let extracted2 = extract_option_ids(&value2);- assert_eq!(extracted2.len(), 0);-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/error.rs b/rust/cloud-storage/properties_db_client/src/error.rsdeleted file mode 100644index 3d0b919d24..0000000000--- a/rust/cloud-storage/properties_db_client/src/error.rs+++ /dev/null@@ -1,29 +0,0 @@-//! Database errors for properties operations--use thiserror::Error;-use uuid::Uuid;--/// Errors that can occur during database operations-#[derive(Debug, Error)]-pub enum PropertiesDatabaseError {- #[error(- "Invalid property options: {provided} provided, only {valid} belong to property {property_id}"- )]- InvalidPropertyOptions {- provided: usize,- valid: i64,- property_id: Uuid,- },-- #[error("Failed to serialize property value to JSON: {0}")]- SerializationError(#[source] serde_json::Error),-- #[error("Failed to deserialize property value from JSONB: {0}")]- DeserializationError(#[source] serde_json::Error),-- #[error("Database conversion error: {0}")]- Conversion(#[from] models_properties::db::DbConversionError),-- #[error("Query error: {0}")]- Query(#[from] sqlx::Error),-}diff --git a/rust/cloud-storage/properties_db_client/src/lib.rs b/rust/cloud-storage/properties_db_client/src/lib.rsdeleted file mode 100644index 425ab61e0b..0000000000--- a/rust/cloud-storage/properties_db_client/src/lib.rs+++ /dev/null@@ -1,12 +0,0 @@-//! Properties Database Client-//!-//! This crate provides database access functions for the properties service, handling-//! property definitions, property options, and entity property assignments.--pub mod document_metadata;-pub mod entity_properties;-pub mod error;-pub mod project_metadata;-pub mod property_definitions;-pub mod property_options;-pub mod thread_metadata;diff --git a/rust/cloud-storage/properties_db_client/src/project_metadata/get.rs b/rust/cloud-storage/properties_db_client/src/project_metadata/get.rsdeleted file mode 100644index 471b6db615..0000000000--- a/rust/cloud-storage/properties_db_client/src/project_metadata/get.rs+++ /dev/null@@ -1,35 +0,0 @@-//! Get project metadata from macrodb.--use crate::error::PropertiesDatabaseError;-use models_properties::service::project_metadata::ProjectMetadata;-use sqlx::{Pool, Postgres};--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Get project metadata by project ID from macrodb-#[tracing::instrument(skip(db), err)]-pub async fn get_project_metadata(- db: &Pool<Postgres>,- project_id: &str,-) -> Result<Option<ProjectMetadata>> {- sqlx::query_as!(- ProjectMetadata,- r#"- SELECT- p.id,- p.name,- p."userId" as "owner",- p."parentId" as "parent_id",- p."createdAt"::timestamptz as "created_at!",- p."updatedAt"::timestamptz as "updated_at!"- FROM- "Project" p- WHERE- p.id = $1 AND p."deletedAt" IS NULL- "#,- project_id- )- .fetch_optional(db)- .await- .map_err(PropertiesDatabaseError::Query)-}diff --git a/rust/cloud-storage/properties_db_client/src/project_metadata/mod.rs b/rust/cloud-storage/properties_db_client/src/project_metadata/mod.rsdeleted file mode 100644index 3432b80980..0000000000--- a/rust/cloud-storage/properties_db_client/src/project_metadata/mod.rs+++ /dev/null@@ -1,3 +0,0 @@-//! Project metadata queries for properties service--pub mod get;diff --git a/rust/cloud-storage/properties_db_client/src/property_definitions/delete.rs b/rust/cloud-storage/properties_db_client/src/property_definitions/delete.rsdeleted file mode 100644index 7b0c637c70..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_definitions/delete.rs+++ /dev/null@@ -1,148 +0,0 @@-//! Property definitions delete operations.--use crate::error::PropertiesDatabaseError;-use sqlx::{Pool, Postgres};--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Deletes a property definition and all associated data (cascades).-#[tracing::instrument(skip(db))]-pub async fn delete_property_definition(- db: &Pool<Postgres>,- property_definition_id: uuid::Uuid,-) -> Result<()> {- sqlx::query!(- "DELETE FROM property_definitions WHERE id = $1",- property_definition_id- )- .execute(db)- .await?;-- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_property_definition(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<uuid::Uuid>()- .unwrap();-- // Verify it exists- let property_before =- crate::property_definitions::get::get_property_definition(&pool, property_id).await?;- assert!(property_before.is_some());-- // Delete it- delete_property_definition(&pool, property_id).await?;-- // Verify it's gone- let property_after =- crate::property_definitions::get::get_property_definition(&pool, property_id).await?;- assert!(property_after.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_property_definition_cascades_options(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<uuid::Uuid>()- .unwrap();-- // Verify options exist- let options_before =- crate::property_options::get::get_property_options(&pool, property_id).await?;- assert!(!options_before.is_empty());-- // Delete property definition- delete_property_definition(&pool, property_id).await?;-- // Verify options are also deleted (cascade)- let options_after =- crate::property_options::get::get_property_options(&pool, property_id).await?;- assert!(options_after.is_empty());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_property_definition_cascades_entity_properties(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<uuid::Uuid>()- .unwrap();-- // Verify entity properties exist for this definition- let entity_props_before = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- models_properties::EntityType::Document,- )- .await?;- let has_property_before = entity_props_before- .iter()- .any(|ep| ep.definition.id == property_id);- assert!(has_property_before);-- // Delete property definition- delete_property_definition(&pool, property_id).await?;-- // Verify entity properties are also deleted (cascade)- let entity_props_after = crate::entity_properties::get::get_entity_properties_values(- &pool,- "doc1",- models_properties::EntityType::Document,- )- .await?;- let has_property_after = entity_props_after- .iter()- .any(|ep| ep.definition.id == property_id);- assert!(!has_property_after);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_nonexistent_property_definition(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "00000000-0000-0000-0000-000000000000"- .parse::<uuid::Uuid>()- .unwrap();-- // Deleting non-existent property should succeed (no error)- let result = delete_property_definition(&pool, property_id).await;- assert!(result.is_ok());-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/property_definitions/get.rs b/rust/cloud-storage/properties_db_client/src/property_definitions/get.rsdeleted file mode 100644index 73423430b5..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_definitions/get.rs+++ /dev/null@@ -1,640 +0,0 @@-//! Property definitions get operations.--use crate::error::PropertiesDatabaseError;-use models_properties::service::property_definition::PropertyDefinition;-use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;-use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};-use models_properties::{DataType, EntityType, db};-use sqlx::{Pool, Postgres};-use std::collections::HashMap;-use uuid::Uuid;--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Gets property definitions based on optional team and optional user access.-/// Set `include_system` to true to also include system properties.-#[tracing::instrument(skip(db))]-pub async fn get_properties(- db: &Pool<Postgres>,- team_id: Option<Uuid>,- user_id: Option<&str>,- include_system: bool,-) -> Result<Vec<PropertyDefinition>> {- let rows = sqlx::query!(- r#"- SELECT- id,- team_id,- user_id,- display_name,- data_type as "data_type: DataType",- is_multi_select,- specific_entity_type as "specific_entity_type: Option<EntityType>",- created_at,- updated_at,- is_system- FROM property_definitions- WHERE- ($3 AND is_system)- OR (- ($1::uuid IS NOT NULL AND team_id = $1)- OR ($2::text IS NOT NULL AND user_id = $2)- )- ORDER BY LOWER(display_name) ASC- "#,- team_id,- user_id,- include_system- )- .fetch_all(db)- .await?;-- let result = rows- .into_iter()- .map(|row| {- let db_def = db::PropertyDefinition {- id: row.id,- team_id: row.team_id,- user_id: row.user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.created_at,- updated_at: row.updated_at,- is_system: row.is_system,- };- PropertyDefinition::from(db_def)- })- .collect();-- Ok(result)-}--/// Gets a single property definition by ID (includes system properties).-#[tracing::instrument(skip(db))]-pub async fn get_property_definition(- db: &Pool<Postgres>,- property_id: uuid::Uuid,-) -> Result<Option<PropertyDefinition>> {- let row = sqlx::query!(- r#"- SELECT- id,- team_id,- user_id,- display_name,- data_type as "data_type: DataType",- is_multi_select,- specific_entity_type as "specific_entity_type: Option<EntityType>",- created_at,- updated_at,- is_system- FROM property_definitions- WHERE id = $1- "#,- property_id- )- .fetch_optional(db)- .await?;-- let result = row.map(|row| {- let db_prop = db::PropertyDefinition {- id: row.id,- team_id: row.team_id,- user_id: row.user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.created_at,- updated_at: row.updated_at,- is_system: row.is_system,- };- PropertyDefinition::from(db_prop)- });-- Ok(result)-}--/// Gets a single property definition by ID with ownership validation.-/// Returns None if the property doesn't exist, if the caller doesn't own it, or if it's a system property.-/// The caller owns it when it is their user property, or a property of the team they belong to.-/// System properties don't have owners and should be fetched via `get_property_definition`.-#[tracing::instrument(skip(db))]-pub async fn get_property_definition_with_owner(- db: &Pool<Postgres>,- property_id: uuid::Uuid,- user_id: &str,- team_id: Option<Uuid>,-) -> Result<Option<PropertyDefinition>> {- let row = sqlx::query!(- r#"- SELECT- id,- team_id,- user_id,- display_name,- data_type as "data_type: DataType",- is_multi_select,- specific_entity_type as "specific_entity_type: Option<EntityType>",- created_at,- updated_at,- is_system- FROM property_definitions- WHERE id = $1- AND is_system = FALSE- AND (- user_id = $2- OR ($3::uuid IS NOT NULL AND team_id = $3)- )- "#,- property_id,- user_id,- team_id- )- .fetch_optional(db)- .await?;-- let result = row.map(|row| {- let db_prop = db::PropertyDefinition {- id: row.id,- team_id: row.team_id,- user_id: row.user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.created_at,- updated_at: row.updated_at,- is_system: row.is_system,- };- PropertyDefinition::from(db_prop)- });-- Ok(result)-}--/// Display name used for the auto-provisioned tag definition.-pub const TAG_DEFINITION_DISPLAY_NAME: &str = "Tags";--/// Gets the single tag definition owned by the given team or user, if it exists.-/// Exactly one of `team_id` / `user_id` is expected to be set.-#[tracing::instrument(skip(db), err)]-pub async fn get_tag_definition(- db: &Pool<Postgres>,- team_id: Option<Uuid>,- user_id: Option<&str>,-) -> Result<Option<PropertyDefinition>> {- let row = sqlx::query!(- r#"- SELECT- id,- team_id,- user_id,- display_name,- data_type as "data_type: DataType",- is_multi_select,- specific_entity_type as "specific_entity_type: Option<EntityType>",- created_at,- updated_at,- is_system- FROM property_definitions- WHERE data_type = $3- AND (- ($1::uuid IS NOT NULL AND team_id = $1)- OR ($2::text IS NOT NULL AND user_id = $2)- )- LIMIT 1- "#,- team_id,- user_id,- DataType::Tag as DataType- )- .fetch_optional(db)- .await?;-- Ok(row.map(|row| {- PropertyDefinition::from(db::PropertyDefinition {- id: row.id,- team_id: row.team_id,- user_id: row.user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.created_at,- updated_at: row.updated_at,- is_system: row.is_system,- })- }))-}--/// Gets property definitions with options based on team and optional user access.-/// Set `include_system` to true to also include system properties.-#[tracing::instrument(skip(db))]-pub async fn get_properties_with_options(- db: &Pool<Postgres>,- team_id: Option<Uuid>,- user_id: Option<&str>,- include_system: bool,-) -> Result<Vec<PropertyDefinitionWithOptions>> {- let rows = sqlx::query!(- r#"- SELECT- pd.id,- pd.team_id,- pd.user_id,- pd.display_name,- pd.data_type as "data_type: DataType",- pd.is_multi_select,- pd.specific_entity_type as "specific_entity_type: Option<EntityType>",- pd.created_at,- pd.updated_at,- pd.is_system,- po.id as "option_id?",- po.display_order as "option_display_order?",- po.number_value as option_number_value,- po.string_value as option_string_value,- po.color as option_color,- po.created_at as "option_created_at?",- po.updated_at as "option_updated_at?"- FROM property_definitions pd- LEFT JOIN property_options po ON pd.id = po.property_definition_id- WHERE- ($3 AND pd.is_system)- OR (- ($1::uuid IS NOT NULL AND pd.team_id = $1)- OR ($2::text IS NOT NULL AND pd.user_id = $2)- )- ORDER BY LOWER(pd.display_name), po.display_order, po.number_value, LOWER(po.string_value)- "#,- team_id,- user_id,- include_system- )- .fetch_all(db)- .await?;-- let mut property_map: HashMap<Uuid, PropertyDefinitionWithOptions> = HashMap::new();-- for row in rows {- let owner = models_properties::PropertyOwner::from_optional_ids(- row.team_id,- row.user_id.clone(),- row.is_system,- );-- let property_def = PropertyDefinition {- id: row.id,- owner,- display_name: row.display_name.clone(),- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.created_at,- updated_at: row.updated_at,- is_system: row.is_system,- is_metadata: false,- };-- let entry = property_map- .entry(row.id)- .or_insert_with(|| PropertyDefinitionWithOptions {- definition: property_def,- property_options: Vec::new(),- });-- // Only process options if option_id is present (from LEFT JOIN)- if let Some(option_id) = row.option_id- && (row.option_number_value.is_some() || row.option_string_value.is_some())- && (row.data_type == DataType::SelectNumber- || row.data_type == DataType::SelectString- || row.data_type == DataType::Tag)- {- let value = match (row.option_number_value, &row.option_string_value) {- (Some(num), None) => PropertyOptionValue::Number(num),- (None, Some(str)) => PropertyOptionValue::String(str.clone()),- (Some(_), Some(_)) => {- return Err(- models_properties::db::DbConversionError::PropertyOptionBothValuesSet {- id: option_id,- }- .into(),- );- }- (None, None) => {- return Err(- models_properties::db::DbConversionError::PropertyOptionNoValueSet {- id: option_id,- }- .into(),- );- }- };-- let option = PropertyOption {- id: option_id,- property_definition_id: row.id,- display_order: row.option_display_order.unwrap_or(0),- value,- color: row.option_color,- created_at: row.option_created_at.unwrap_or(row.created_at),- updated_at: row.option_updated_at.unwrap_or(row.updated_at),- };- entry.property_options.push(option);- }- }-- let mut results: Vec<PropertyDefinitionWithOptions> = property_map.into_values().collect();-- results.sort_by(|a, b| {- a.definition- .display_name- .to_lowercase()- .cmp(&b.definition.display_name.to_lowercase())- });-- Ok(results)-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- fn team_1() -> Uuid {- "0e000000-0000-0000-0000-000000000001".parse().unwrap()- }-- fn team_2() -> Uuid {- "0e000000-0000-0000-0000-000000000002".parse().unwrap()- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_properties_by_team(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE-- let properties = get_properties(&pool, Some(team_1()), None, false).await?;-- assert_eq!(properties.len(), 10); // Team 1 has 10 properties-- // Verify they are sorted by display name (case-insensitive alphabetical)- assert_eq!(properties[0].display_name, "Test Assigned To");- assert_eq!(properties[1].display_name, "Test Budget");- assert_eq!(properties[2].display_name, "Test Completed");- assert_eq!(properties[3].display_name, "Test Department");- assert_eq!(properties[4].display_name, "Test Description");- assert_eq!(properties[5].display_name, "Test Due Date");- assert_eq!(properties[6].display_name, "Test Priority");- assert_eq!(properties[7].display_name, "Test Relevant Documents");- assert_eq!(properties[8].display_name, "Test Score");- assert_eq!(properties[9].display_name, "Test Website");-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_properties_by_user(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_properties(&pool, None, Some("user1"), false).await?;-- assert_eq!(properties.len(), 2); // User1 has 2 properties- assert_eq!(properties[0].display_name, "Test Notes");- assert_eq!(properties[1].display_name, "Test Personal Priority");-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_definition_by_id(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let property = get_property_definition(&pool, property_id).await?;-- assert!(property.is_some());- let property = property.unwrap();- assert_eq!(property.display_name, "Test Priority");- assert_eq!(property.data_type, DataType::SelectString);- assert!(!property.is_multi_select);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_definition_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "00000000-0000-0000-0000-000000000000"- .parse::<Uuid>()- .unwrap();- let property = get_property_definition(&pool, property_id).await?;-- assert!(property.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_definition_with_owner(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let team_property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();-- // The team owner can access the team property.- let property =- get_property_definition_with_owner(&pool, team_property_id, "user1", Some(team_1()))- .await?;- assert!(property.is_some());-- // A different member of the same team can also access it.- let property =- get_property_definition_with_owner(&pool, team_property_id, "user3", Some(team_1()))- .await?;- assert!(property.is_some());-- // A user on a different team cannot access it.- let property =- get_property_definition_with_owner(&pool, team_property_id, "user2", Some(team_2()))- .await?;- assert!(property.is_none());-- // A user with no team cannot access it.- let property =- get_property_definition_with_owner(&pool, team_property_id, "user2", None).await?;- assert!(property.is_none());-- // The owning user can access their own user property.- let user_property_id = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"- .parse::<Uuid>()- .unwrap();- let property =- get_property_definition_with_owner(&pool, user_property_id, "user1", Some(team_1()))- .await?;- assert!(property.is_some());-- // A different user cannot access someone else's user property.- let property =- get_property_definition_with_owner(&pool, user_property_id, "user3", Some(team_1()))- .await?;- assert!(property.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_properties_with_options(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_properties_with_options(&pool, Some(team_1()), None, false).await?;-- assert_eq!(properties.len(), 10);-- // Find Priority property which should have 4 options- let priority_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Priority")- .unwrap();-- assert_eq!(priority_prop.property_options.len(), 4);- assert_eq!(priority_prop.property_options[0].display_order, 0);-- // Verify the options are properly ordered and have correct values- if let models_properties::service::property_option::PropertyOptionValue::String(val) =- &priority_prop.property_options[0].value- {- assert_eq!(val, "Low");- } else {- panic!("Expected string value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_properties_with_options_includes_non_select(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_properties_with_options(&pool, Some(team_1()), None, false).await?;-- // Find non-select properties (should have 0 options)- let completed_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Completed")- .unwrap();-- assert_eq!(completed_prop.definition.data_type, DataType::Boolean);- assert_eq!(completed_prop.property_options.len(), 0);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_properties_with_number_options(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_properties_with_options(&pool, Some(team_1()), None, false).await?;-- // Find Score property which has number options- let score_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Score")- .unwrap();-- assert_eq!(score_prop.property_options.len(), 5);- assert_eq!(score_prop.definition.data_type, DataType::SelectNumber);-- // Check first option is number 1.0- if let models_properties::service::property_option::PropertyOptionValue::Number(val) =- score_prop.property_options[0].value- {- assert_eq!(val, 4.0);- } else {- panic!("Expected number value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_properties_with_options_multi_select(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let properties = get_properties_with_options(&pool, Some(team_1()), None, false).await?;-- // Find Department property which is multi-select- let dept_prop = properties- .iter()- .find(|p| p.definition.display_name == "Test Department")- .unwrap();-- assert!(dept_prop.definition.is_multi_select);- assert_eq!(dept_prop.definition.data_type, DataType::SelectString);- assert_eq!(dept_prop.property_options.len(), 3);-- // Verify the options are properly ordered and have correct values- if let models_properties::service::property_option::PropertyOptionValue::String(val) =- &dept_prop.property_options[0].value- {- assert_eq!(val, "Engineering");- } else {- panic!("Expected string value");- }-- if let models_properties::service::property_option::PropertyOptionValue::String(val) =- &dept_prop.property_options[1].value- {- assert_eq!(val, "Human Resources");- } else {- panic!("Expected string value");- }-- if let models_properties::service::property_option::PropertyOptionValue::String(val) =- &dept_prop.property_options[2].value- {- assert_eq!(val, "Marketing");- } else {- panic!("Expected string value");- }-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/property_definitions/insert.rs b/rust/cloud-storage/properties_db_client/src/property_definitions/insert.rsdeleted file mode 100644index 43884fe591..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_definitions/insert.rs+++ /dev/null@@ -1,517 +0,0 @@-//! Property definitions insert operations.--use crate::error::PropertiesDatabaseError;-use models_properties::service::property_definition::PropertyDefinition;-use models_properties::service::property_option::PropertyOption;-use models_properties::{DataType, EntityType, db};-use sqlx::{Pool, Postgres};-use uuid::Uuid;--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// The owner of a user- or team-created property definition. Encodes the-/// "exactly one of user / team" invariant in the type, so neither a both-owners-/// nor a no-owner row is representable. System properties are not created here.-#[derive(Debug, Clone, Copy)]-pub enum DefinitionOwner<'a> {- /// Owned by a single user.- User(&'a str),- /// Owned by a team.- Team(Uuid),-}--impl<'a> DefinitionOwner<'a> {- /// Split into the nullable (team_id, user_id) columns the row stores.- fn into_ids(self) -> (Option<Uuid>, Option<&'a str>) {- match self {- DefinitionOwner::User(user_id) => (None, Some(user_id)),- DefinitionOwner::Team(team_id) => (Some(team_id), None),- }- }-}--/// Creates a new property definition.-#[tracing::instrument(skip(db))]-pub async fn create_property_definition(- db: &Pool<Postgres>,- owner: DefinitionOwner<'_>,- display_name: &str,- data_type: DataType,- is_multi_select: bool,- specific_entity_type: Option<EntityType>,-) -> Result<PropertyDefinition> {- let (team_id, user_id) = owner.into_ids();-- let id = macro_uuid::generate_uuid_v7();-- let row = sqlx::query!(- r#"- INSERT INTO property_definitions (- id,- team_id,- user_id,- display_name,- data_type,- is_multi_select,- specific_entity_type- )- VALUES ($1, $2, $3, $4, $5, $6, $7)- RETURNING- id,- team_id,- user_id,- display_name,- data_type as "data_type: DataType",- is_multi_select,- specific_entity_type as "specific_entity_type: Option<EntityType>",- created_at,- updated_at- "#,- id,- team_id,- user_id,- display_name,- data_type as DataType,- is_multi_select,- specific_entity_type as Option<EntityType>- )- .fetch_one(db)- .await?;-- let db_result = db::PropertyDefinition {- id: row.id,- team_id: row.team_id,- user_id: row.user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.created_at,- updated_at: row.updated_at,- is_system: false, // User-created properties are never system properties- };-- Ok(PropertyDefinition::from(db_result))-}--/// Creates a property definition with options in a single transaction.-#[tracing::instrument(skip(db, options))]-pub async fn create_property_definition_with_options(- db: &Pool<Postgres>,- owner: DefinitionOwner<'_>,- display_name: &str,- data_type: DataType,- is_multi_select: bool,- specific_entity_type: Option<EntityType>,- options: Vec<PropertyOption>,-) -> Result<PropertyDefinition> {- let (team_id, user_id) = owner.into_ids();-- let mut tx = db.begin().await?;-- let id = macro_uuid::generate_uuid_v7();-- let row = match sqlx::query!(- r#"- INSERT INTO property_definitions (- id,- team_id,- user_id,- display_name,- data_type,- is_multi_select,- specific_entity_type- )- VALUES ($1, $2, $3, $4, $5, $6, $7)- RETURNING- id,- team_id,- user_id,- display_name,- data_type as "data_type: DataType",- is_multi_select,- specific_entity_type as "specific_entity_type: Option<EntityType>",- created_at,- updated_at- "#,- id,- team_id,- user_id,- display_name,- data_type as DataType,- is_multi_select,- specific_entity_type as Option<EntityType>- )- .fetch_one(&mut *tx)- .await- {- Ok(row) => row,- Err(e) => {- tracing::error!(- error = ?e,- display_name = %display_name,- "property definition insert failed, rolling back transaction"- );- if let Err(rollback_err) = tx.rollback().await {- tracing::error!(- error = ?rollback_err,- "failed to rollback transaction after property definition insert error"- );- }- return Err(e.into());- }- };-- let db_property_def = db::PropertyDefinition {- id: row.id,- team_id: row.team_id,- user_id: row.user_id,- display_name: row.display_name,- data_type: row.data_type,- is_multi_select: row.is_multi_select,- specific_entity_type: row.specific_entity_type.flatten(),- created_at: row.created_at,- updated_at: row.updated_at,- is_system: false, // User-created properties are never system properties- };-- for option in options {- if let Err(e) = crate::property_options::insert::create_property_option_tx(- &mut tx,- db_property_def.id,- option.display_order,- option.value,- option.color,- )- .await- {- tracing::error!(- error = ?e,- property_definition_id = %db_property_def.id,- "property option creation failed, rolling back transaction"- );- if let Err(rollback_err) = tx.rollback().await {- tracing::error!(- error = ?rollback_err,- "failed to rollback transaction after property option insert error"- );- }- return Err(e);- }- }-- match tx.commit().await {- Ok(_) => Ok(db_property_def.into()),- Err(e) => {- tracing::error!(- error = ?e,- "failed to commit transaction for property definition with options"- );- Err(e.into())- }- }-}--/// Returns the owner's tag definition, creating it on first use.-///-/// Tag definitions are TAG-typed, multi-select, and unique per owner (enforced by a partial-/// unique index). A lost create race re-fetches the definition the winner just created.-#[tracing::instrument(skip(db), err)]-pub async fn get_or_create_tag_definition(- db: &Pool<Postgres>,- owner: DefinitionOwner<'_>,-) -> Result<PropertyDefinition> {- let (team_id, user_id) = owner.into_ids();-- if let Some(existing) =- crate::property_definitions::get::get_tag_definition(db, team_id, user_id).await?- {- return Ok(existing);- }-- match create_property_definition(- db,- owner,- crate::property_definitions::get::TAG_DEFINITION_DISPLAY_NAME,- DataType::Tag,- true,- None,- )- .await- {- Ok(def) => Ok(def),- Err(create_err) => {- match crate::property_definitions::get::get_tag_definition(db, team_id, user_id).await?- {- Some(existing) => Ok(existing),- None => Err(create_err),- }- }- }-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use models_properties::service::property_option::PropertyOptionValue;- use sqlx::{Pool, Postgres};-- fn team_1() -> Uuid {- "0e000000-0000-0000-0000-000000000001".parse().unwrap()- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_definition(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property = create_property_definition(- &pool,- DefinitionOwner::Team(team_1()),- "New Test Property",- DataType::String,- false,- None,- )- .await?;-- assert_eq!(property.display_name, "New Test Property");- assert_eq!(property.data_type, DataType::String);- assert!(!property.is_multi_select);- assert!(property.specific_entity_type.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_definition_user_owned(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property = create_property_definition(- &pool,- DefinitionOwner::User("user1"),- "User Property",- DataType::Number,- false,- None,- )- .await?;-- assert_eq!(property.display_name, "User Property");- assert_eq!(property.data_type, DataType::Number);- assert!(property.specific_entity_type.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_definition_duplicate_name_fails(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- // Try to create a property with the same name as an existing one in team 1- let result = create_property_definition(- &pool,- DefinitionOwner::Team(team_1()),- "Test Priority", // Already exists in fixtures- DataType::String,- false,- None,- )- .await;-- assert!(result.is_err());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_definition_with_options(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let options = vec![- PropertyOption {- id: macro_uuid::generate_uuid_v7(),- property_definition_id: uuid::Uuid::nil(), // Will be set by the function- display_order: 0,- value: PropertyOptionValue::String("Option 1".to_string()),- color: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- },- PropertyOption {- id: macro_uuid::generate_uuid_v7(),- property_definition_id: uuid::Uuid::nil(),- display_order: 1,- value: PropertyOptionValue::String("Option 2".to_string()),- color: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- },- ];-- let property = create_property_definition_with_options(- &pool,- DefinitionOwner::Team(team_1()),- "Property With Options",- DataType::SelectString,- false,- None,- options,- )- .await?;-- assert_eq!(property.display_name, "Property With Options");- assert_eq!(property.data_type, DataType::SelectString);-- // Verify options were created- let created_options =- crate::property_options::get::get_property_options(&pool, property.id).await?;-- assert_eq!(created_options.len(), 2);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_definition_multi_select(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property = create_property_definition(- &pool,- DefinitionOwner::Team(team_1()),- "Multi Select Property",- DataType::SelectString,- true, // multi-select- None,- )- .await?;-- assert_eq!(property.display_name, "Multi Select Property");- assert!(property.is_multi_select);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_definition_specific_entity(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property = create_property_definition(- &pool,- DefinitionOwner::Team(team_1()),- "Multi Select Documents",- DataType::Entity,- true,- Some(EntityType::User),- )- .await?;-- assert_eq!(property.display_name, "Multi Select Documents");- assert!(property.is_multi_select);- assert_eq!(property.specific_entity_type, Some(EntityType::User));-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_or_create_tag_definition_is_idempotent(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let owner = DefinitionOwner::Team(team_1());- let first = get_or_create_tag_definition(&pool, owner).await?;- assert_eq!(first.data_type, DataType::Tag);- assert!(first.is_multi_select);-- // A second call returns the same definition rather than creating a duplicate.- let second = get_or_create_tag_definition(&pool, owner).await?;- assert_eq!(first.id, second.id);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_tag_definition_none_then_some(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let before =- crate::property_definitions::get::get_tag_definition(&pool, Some(team_1()), None)- .await?;- assert!(before.is_none());-- let created = get_or_create_tag_definition(&pool, DefinitionOwner::Team(team_1())).await?;-- let after =- crate::property_definitions::get::get_tag_definition(&pool, Some(team_1()), None)- .await?;- assert_eq!(after.map(|d| d.id), Some(created.id));-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_or_create_tag_definition_coexists_with_same_named_property(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- // Owner already has a non-tag property literally named "Tags".- create_property_definition(- &pool,- DefinitionOwner::Team(team_1()),- "Tags",- DataType::String,- false,- None,- )- .await?;-- // Provisioning the tag set still succeeds: tag definitions are exempt from the- // display-name uniqueness that applies to user-created properties.- let tag_def = get_or_create_tag_definition(&pool, DefinitionOwner::Team(team_1())).await?;- assert_eq!(tag_def.data_type, DataType::Tag);-- let again = get_or_create_tag_definition(&pool, DefinitionOwner::Team(team_1())).await?;- assert_eq!(tag_def.id, again.id);-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/property_definitions/mod.rs b/rust/cloud-storage/properties_db_client/src/property_definitions/mod.rsdeleted file mode 100644index 81b4ad3384..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_definitions/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-//! Property definitions database operations.--pub mod delete;-pub mod get;-pub mod insert;diff --git a/rust/cloud-storage/properties_db_client/src/property_options/delete.rs b/rust/cloud-storage/properties_db_client/src/property_options/delete.rsdeleted file mode 100644index 81e732b734..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_options/delete.rs+++ /dev/null@@ -1,227 +0,0 @@-//! Property options delete operations.--use crate::error::PropertiesDatabaseError;-use sqlx::{Pool, Postgres};--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Deletes a property option and strips its id from every entity value that-/// references it, atomically. Without the cleanup a stored value keeps the-/// dead id and a later set-value that echoes the full id list fails option-/// validation.-/// Returns Ok(true) if the option was deleted, Ok(false) if it didn't exist.-#[tracing::instrument(skip(db))]-pub async fn delete_property_option(- db: &Pool<Postgres>,- property_definition_id: uuid::Uuid,- property_option_id: uuid::Uuid,-) -> Result<bool> {- let mut tx = db.begin().await?;-- sqlx::query!(- r#"- UPDATE entity_properties- SET- values = jsonb_set(- values,- '{value}',- COALESCE(- (- SELECT jsonb_agg(elem)- FROM jsonb_array_elements(values -> 'value') AS elem- WHERE elem <> to_jsonb($2::text)- ),- '[]'::jsonb- )- ),- updated_at = NOW()- WHERE property_definition_id = $1- AND values @> jsonb_build_object('value', jsonb_build_array($2::text))- "#,- property_definition_id,- property_option_id.to_string(),- )- .execute(&mut *tx)- .await?;-- let result = sqlx::query!(- "DELETE FROM property_options WHERE id = $1",- property_option_id- )- .execute(&mut *tx)- .await?;-- tx.commit().await?;-- Ok(result.rows_affected() > 0)-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use models_properties::EntityType;- use models_properties::service::property_option::PropertyOptionValue;- use models_properties::service::property_value::PropertyValue;- use sqlx::{Pool, Postgres};- use uuid::Uuid;-- const PRIORITY_PROPERTY_ID: &str = "11111111-1111-1111-1111-111111111111";- const PRIORITY_OPTION_LOW: &str = "10111111-1111-1111-1111-111111111111";- const PRIORITY_OPTION_MEDIUM: &str = "10111111-1111-1111-1111-111111111112";- const PRIORITY_OPTION_HIGH: &str = "10111111-1111-1111-1111-111111111113";- const PRIORITY_OPTION_URGENT: &str = "10111111-1111-1111-1111-111111111114";-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_property_option(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();- let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();-- // Verify it exists- let option_before =- crate::property_options::get::get_property_option_by_id(&pool, option_id).await?;- assert!(option_before.is_some());-- // Delete it- let deleted = delete_property_option(&pool, property_id, option_id).await?;- assert!(deleted);-- // Verify it's gone- let option_after =- crate::property_options::get::get_property_option_by_id(&pool, option_id).await?;- assert!(option_after.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_nonexistent_property_option(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();- let option_id = "00000000-0000-0000-0000-000000000000"- .parse::<Uuid>()- .unwrap();-- // Deleting non-existent option should return false- let deleted = delete_property_option(&pool, property_id, option_id).await?;- assert!(!deleted);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_property_option_reduces_count(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();- let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();-- // Get initial count- let options_before =- crate::property_options::get::get_property_options(&pool, property_id).await?;- let count_before = options_before.len();-- // Delete one option- delete_property_option(&pool, property_id, option_id).await?;-- // Verify count decreased- let options_after =- crate::property_options::get::get_property_options(&pool, property_id).await?;- let count_after = options_after.len();-- assert_eq!(count_after, count_before - 1);-- Ok(())- }-- /// Reproduces the dangling-option bug: an entity value referencing- /// [A, B, C, D] must drop D once option D is deleted, so a later set-value- /// echoing the surviving ids passes option validation.- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_delete_property_option_strips_value_references(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();- let opt_a = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();- let opt_b = PRIORITY_OPTION_MEDIUM.parse::<Uuid>().unwrap();- let opt_c = PRIORITY_OPTION_HIGH.parse::<Uuid>().unwrap();- let opt_d = PRIORITY_OPTION_URGENT.parse::<Uuid>().unwrap();-- // Entity selects all four options.- crate::entity_properties::upsert::upsert_entity_property_values(- &pool,- "doc_cascade",- EntityType::Document,- property_id,- Some(PropertyValue::SelectOption(vec![- opt_a, opt_b, opt_c, opt_d,- ])),- )- .await?;-- // A new option created after selection (the "new tag" in the repro).- let opt_e = crate::property_options::insert::create_property_option(- &pool,- property_id,- 4,- PropertyOptionValue::String("New".to_string()),- None,- )- .await?- .id;-- // Delete option D.- let deleted = delete_property_option(&pool, property_id, opt_d).await?;- assert!(deleted);-- // Read the raw stored value (bypassing the read-path cleaner) to prove- // the dangling id is gone from storage, not just filtered on read.- let raw: Option<serde_json::Value> = sqlx::query_scalar!(- r#"- SELECT values as "values: serde_json::Value"- FROM entity_properties- WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3- "#,- "doc_cascade",- EntityType::Document as EntityType,- property_id,- )- .fetch_one(&pool)- .await?;-- let stored: PropertyValue = serde_json::from_value(raw.expect("value present"))?;- let PropertyValue::SelectOption(ids) = stored else {- panic!("expected SelectOption");- };- assert_eq!(ids, vec![opt_a, opt_b, opt_c]);-- // The surviving selection plus the new option all validate, so the- // set-value that previously 400'd now succeeds.- let valid = crate::property_options::get::count_property_options_by_ids(- &pool,- property_id,- &[opt_a, opt_b, opt_c, opt_e],- )- .await?;- assert_eq!(valid, 4);-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/property_options/get.rs b/rust/cloud-storage/properties_db_client/src/property_options/get.rsdeleted file mode 100644index b3ebb4b01d..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_options/get.rs+++ /dev/null@@ -1,389 +0,0 @@-//! Property options get operations.--use crate::error::PropertiesDatabaseError;-use models_properties::db;-use models_properties::service::property_option::PropertyOption;-use sqlx::{Pool, Postgres};-use std::collections::HashMap;-use uuid::Uuid;--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Gets a single property option by ID.-#[tracing::instrument(skip(db))]-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]-pub async fn get_property_option_by_id(- db: &Pool<Postgres>,- option_id: uuid::Uuid,-) -> Result<Option<PropertyOption>> {- let row = sqlx::query_as::<_, db::PropertyOption>(- r#"- SELECT- id,- property_definition_id,- display_order,- number_value,- string_value,- color,- created_at,- updated_at- FROM property_options- WHERE id = $1- "#,- )- .bind(option_id)- .fetch_optional(db)- .await?;-- Ok(row.map(TryInto::try_into).transpose()?)-}--/// Gets all property options for a property definition.-#[tracing::instrument(skip(db))]-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]-pub async fn get_property_options(- db: &Pool<Postgres>,- property_definition_id: uuid::Uuid,-) -> Result<Vec<PropertyOption>> {- let rows = sqlx::query_as::<_, db::PropertyOption>(- r#"- SELECT- id,- property_definition_id,- display_order,- number_value,- string_value,- color,- created_at,- updated_at- FROM property_options- WHERE property_definition_id = $1- ORDER BY display_order, number_value, LOWER(string_value)- "#,- )- .bind(property_definition_id)- .fetch_all(db)- .await?;-- rows.into_iter()- .map(|row| row.try_into().map_err(PropertiesDatabaseError::from))- .collect()-}--/// Counts property options by their IDs.-#[tracing::instrument(skip(db))]-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]-pub async fn count_property_options_by_ids(- db: &Pool<Postgres>,- property_definition_id: uuid::Uuid,- property_option_ids: &[uuid::Uuid],-) -> Result<i64> {- let count: (i64,) = sqlx::query_as(- r#"- SELECT COUNT(*)- FROM property_options- WHERE property_definition_id = $1- AND id = ANY($2)- "#,- )- .bind(property_definition_id)- .bind(property_option_ids)- .fetch_one(db)- .await?;-- Ok(count.0)-}--/// Gets property options for multiple properties in a single query.-/// Returns a HashMap where the key is property_definition_id and value is the list of options.-#[tracing::instrument(skip(db))]-#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]-pub async fn get_property_options_batch(- db: &Pool<Postgres>,- property_definition_ids: &[Uuid],-) -> Result<HashMap<Uuid, Vec<PropertyOption>>> {- if property_definition_ids.is_empty() {- return Ok(HashMap::new());- }-- let rows = sqlx::query_as::<_, db::PropertyOption>(- r#"- SELECT- id,- property_definition_id,- display_order,- number_value,- string_value,- color,- created_at,- updated_at- FROM property_options- WHERE property_definition_id = ANY($1)- ORDER BY property_definition_id, display_order, number_value, LOWER(string_value)- "#,- )- .bind(property_definition_ids)- .fetch_all(db)- .await?;-- // Group options by property_definition_id- let mut result: HashMap<Uuid, Vec<PropertyOption>> = HashMap::new();-- for row in rows {- let property_id = row.property_definition_id;- let service_option: PropertyOption = row.try_into()?;-- result.entry(property_id).or_default().push(service_option);- }-- Ok(result)-}--#[cfg(test)]-mod tests {- use super::*;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_option_by_id(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let option_id = "10111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let option = get_property_option_by_id(&pool, option_id).await?;-- assert!(option.is_some());- let option = option.unwrap();- assert_eq!(option.display_order, 0);- if let models_properties::service::property_option::PropertyOptionValue::String(val) =- &option.value- {- assert_eq!(val, "Low");- } else {- panic!("Expected string value");- }- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_option_by_id_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let option_id = "00000000-0000-0000-0000-000000000000"- .parse::<Uuid>()- .unwrap();- let option = get_property_option_by_id(&pool, option_id).await?;-- assert!(option.is_none());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_options(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let options = get_property_options(&pool, property_id).await?;-- assert_eq!(options.len(), 4); // Priority has 4 options-- // Verify they are ordered by display_order- assert_eq!(options[0].display_order, 0);- assert_eq!(options[1].display_order, 1);- assert_eq!(options[2].display_order, 2);- assert_eq!(options[3].display_order, 3);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_options_string_values(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let options = get_property_options(&pool, property_id).await?;-- // Verify string values- if let models_properties::service::property_option::PropertyOptionValue::String(val) =- &options[0].value- {- assert_eq!(val, "Low");- } else {- panic!("Expected string value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_options_number_values(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "44444444-4444-4444-4444-444444444444"- .parse::<Uuid>()- .unwrap(); // Score property- let options = get_property_options(&pool, property_id).await?;-- assert_eq!(options.len(), 5);-- // Verify number values- if let models_properties::service::property_option::PropertyOptionValue::Number(val) =- options[0].value- {- assert_eq!(val, 4.0);- } else {- panic!("Expected number value");- }-- if let models_properties::service::property_option::PropertyOptionValue::Number(val) =- options[1].value- {- assert_eq!(val, 5.0);- } else {- panic!("Expected number value");- }-- if let models_properties::service::property_option::PropertyOptionValue::Number(val) =- options[2].value- {- assert_eq!(val, 3.0);- } else {- panic!("Expected number value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_options_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "55555555-5555-5555-5555-555555555555"- .parse::<Uuid>()- .unwrap(); // Boolean property- let options = get_property_options(&pool, property_id).await?;-- assert_eq!(options.len(), 0); // Boolean properties don't have options-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_count_property_options_by_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let option_ids = vec![- "10111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap(),- "10111111-1111-1111-1111-111111111112"- .parse::<Uuid>()- .unwrap(),- ];-- let count = count_property_options_by_ids(&pool, property_id, &option_ids).await?;-- assert_eq!(count, 2);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_count_property_options_by_ids_invalid(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap();- let option_ids = vec![- "10111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap(),- "00000000-0000-0000-0000-000000000000"- .parse::<Uuid>()- .unwrap(), // Invalid ID- ];-- let count = count_property_options_by_ids(&pool, property_id, &option_ids).await?;-- assert_eq!(count, 1); // Only 1 valid option-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_options_batch(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_ids = vec![- "11111111-1111-1111-1111-111111111111"- .parse::<Uuid>()- .unwrap(), // Priority: 4 options- "44444444-4444-4444-4444-444444444444"- .parse::<Uuid>()- .unwrap(), // Score: 5 options- ];-- let options_map = get_property_options_batch(&pool, &property_ids).await?;-- assert_eq!(options_map.len(), 2);- assert_eq!(options_map.get(&property_ids[0]).unwrap().len(), 4);- assert_eq!(options_map.get(&property_ids[1]).unwrap().len(), 5);-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_get_property_options_batch_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_ids: Vec<Uuid> = vec![];- let options_map = get_property_options_batch(&pool, &property_ids).await?;-- assert_eq!(options_map.len(), 0);-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/property_options/insert.rs b/rust/cloud-storage/properties_db_client/src/property_options/insert.rsdeleted file mode 100644index b60be42215..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_options/insert.rs+++ /dev/null@@ -1,282 +0,0 @@-//! Property options insert operations.--use crate::error::PropertiesDatabaseError;-use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};-use sqlx::{Pool, Postgres};--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Creates a new property option.-#[tracing::instrument(skip(db))]-pub async fn create_property_option(- db: &Pool<Postgres>,- property_definition_id: uuid::Uuid,- display_order: i32,- value: PropertyOptionValue,- color: Option<String>,-) -> Result<PropertyOption> {- let id = macro_uuid::generate_uuid_v7();- let (number_value, string_value) = value.to_db_values();-- let row = sqlx::query!(- r#"- INSERT INTO property_options (- id,- property_definition_id,- display_order,- number_value,- string_value,- color- )- VALUES ($1, $2, $3, $4, $5, $6)- RETURNING id, created_at, updated_at- "#,- id,- property_definition_id,- display_order,- number_value,- string_value,- color.clone()- )- .fetch_one(db)- .await?;-- Ok(PropertyOption {- id: row.id,- property_definition_id,- display_order,- value,- color,- created_at: row.created_at,- updated_at: row.updated_at,- })-}--/// Creates a property option within a transaction.-#[tracing::instrument(skip(tx))]-pub async fn create_property_option_tx(- tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,- property_definition_id: uuid::Uuid,- display_order: i32,- value: PropertyOptionValue,- color: Option<String>,-) -> Result<()> {- let id = macro_uuid::generate_uuid_v7();- let (number_value, string_value) = value.to_db_values();-- sqlx::query!(- r#"- INSERT INTO property_options (- id,- property_definition_id,- display_order,- number_value,- string_value,- color- )- VALUES ($1, $2, $3, $4, $5, $6)- "#,- id,- property_definition_id,- display_order,- number_value,- string_value,- color- )- .execute(&mut **tx)- .await?;-- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;- use crate::property_options::get::get_property_options;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_option_string(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<uuid::Uuid>()- .unwrap();- let value = PropertyOptionValue::String("Extra High".to_string());-- let options_before = get_property_options(&pool, property_id).await?;- assert_eq!(options_before.len(), 4);-- let option = create_property_option(&pool, property_id, 4, value, None).await?;-- let options_after = get_property_options(&pool, property_id).await?;- assert_eq!(options_after.len(), 5);-- assert_eq!(option.display_order, 4);- assert_eq!(option.property_definition_id, property_id);-- if let PropertyOptionValue::String(val) = &option.value {- assert_eq!(val, "Extra High");- } else {- panic!("Expected string value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_option_number(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "44444444-4444-4444-4444-444444444444"- .parse::<uuid::Uuid>()- .unwrap();- let value = PropertyOptionValue::Number(10.5);-- let option = create_property_option(&pool, property_id, 99, value, None).await?;-- assert_eq!(option.display_order, 99);-- if let PropertyOptionValue::Number(val) = option.value {- assert_eq!(val, 10.5);- } else {- panic!("Expected number value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_option_number_2(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "44444444-4444-4444-4444-444444444444"- .parse::<uuid::Uuid>()- .unwrap();- let value = PropertyOptionValue::Number(3.5);-- let option = create_property_option(&pool, property_id, 0, value, None).await?;-- assert_eq!(option.display_order, 0);-- if let PropertyOptionValue::Number(val) = option.value {- assert_eq!(val, 3.5);- } else {- panic!("Expected number value");- }-- let options = get_property_options(&pool, property_id).await?;- if let models_properties::service::property_option::PropertyOptionValue::Number(val) =- options[0].value- {- assert_eq!(val, 3.5);- } else {- panic!("Expected number value");- }-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_option_duplicate_string_fails(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<uuid::Uuid>()- .unwrap();- let value = PropertyOptionValue::String("Low".to_string()); // Already exists-- let result = create_property_option(&pool, property_id, 4, value, None).await;-- assert!(result.is_err());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_option_duplicate_number_fails(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "44444444-4444-4444-4444-444444444444"- .parse::<uuid::Uuid>()- .unwrap();- let value = PropertyOptionValue::Number(1.0); // Already exists-- let result = create_property_option(&pool, property_id, 5, value, None).await;-- assert!(result.is_err());-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_option_invalid_property_fails(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "00000000-0000-0000-0000-000000000000"- .parse::<uuid::Uuid>()- .unwrap();- let value = PropertyOptionValue::String("Test".to_string());-- let result = create_property_option(&pool, property_id, 0, value, None).await;-- assert!(result.is_err()); // Foreign key constraint violation-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_create_property_option_tx(pool: Pool<Postgres>) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let property_id = "11111111-1111-1111-1111-111111111111"- .parse::<uuid::Uuid>()- .unwrap();- let value = PropertyOptionValue::String("Test Option".to_string());-- let mut tx = pool.begin().await?;- create_property_option_tx(&mut tx, property_id, 10, value, None).await?;- tx.commit().await?;-- // Verify it was created- let options =- crate::property_options::get::get_property_options(&pool, property_id).await?;- assert!(options.iter().any(|opt| {- if let PropertyOptionValue::String(val) = &opt.value {- val == "Test Option"- } else {- false- }- }));-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/property_options/mod.rs b/rust/cloud-storage/properties_db_client/src/property_options/mod.rsdeleted file mode 100644index b467dea63e..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_options/mod.rs+++ /dev/null@@ -1,6 +0,0 @@-//! Property options database operations.--pub mod delete;-pub mod get;-pub mod insert;-pub mod update;diff --git a/rust/cloud-storage/properties_db_client/src/property_options/update.rs b/rust/cloud-storage/properties_db_client/src/property_options/update.rsdeleted file mode 100644index f019117961..0000000000--- a/rust/cloud-storage/properties_db_client/src/property_options/update.rs+++ /dev/null@@ -1,132 +0,0 @@-//! Property options update operations.--use crate::error::PropertiesDatabaseError;-use models_properties::db;-use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};-use sqlx::{Pool, Postgres};--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Updates a property option's value, color, and display order in place.-///-/// The option id is preserved, so every entity referencing this option by id in its-/// `entity_properties.values` reflects the new value and color with no per-entity rewrite.-/// Returns `None` if no option with the given id exists.-#[tracing::instrument(skip(db), err)]-#[allow(- clippy::disallowed_methods,- reason = "runtime query mirrors property_options::get"-)]-pub async fn update_property_option(- db: &Pool<Postgres>,- option_id: uuid::Uuid,- value: PropertyOptionValue,- color: Option<String>,- display_order: i32,-) -> Result<Option<PropertyOption>> {- let (number_value, string_value) = value.to_db_values();-- let row = sqlx::query_as::<_, db::PropertyOption>(- r#"- UPDATE property_options- SET number_value = $2,- string_value = $3,- color = $4,- display_order = $5,- updated_at = NOW()- WHERE id = $1- RETURNING- id,- property_definition_id,- display_order,- number_value,- string_value,- color,- created_at,- updated_at- "#,- )- .bind(option_id)- .bind(number_value)- .bind(string_value)- .bind(color)- .bind(display_order)- .fetch_optional(db)- .await?;-- Ok(row.map(TryInto::try_into).transpose()?)-}--#[cfg(test)]-mod tests {- use super::*;- use crate::property_options::get::get_property_option_by_id;- use macro_db_migrator::MACRO_DB_MIGRATIONS;- use sqlx::{Pool, Postgres};-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_update_property_option_renames_and_recolors(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let option_id = "10111111-1111-1111-1111-111111111111"- .parse::<uuid::Uuid>()- .unwrap();-- let updated = update_property_option(- &pool,- option_id,- PropertyOptionValue::String("Lowest".to_string()),- Some("#FF0000".to_string()),- 3,- )- .await?- .expect("option should exist");-- // Same id, so every entity referencing it resolves the new value/color (propagation by id).- assert_eq!(updated.id, option_id);- assert_eq!(updated.color.as_deref(), Some("#FF0000"));- assert_eq!(updated.display_order, 3);- match &updated.value {- PropertyOptionValue::String(s) => assert_eq!(s, "Lowest"),- _ => panic!("expected string value"),- }-- let fetched = get_property_option_by_id(&pool, option_id)- .await?- .expect("option should still exist");- assert_eq!(fetched.color.as_deref(), Some("#FF0000"));-- Ok(())- }-- #[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties"))- )]- async fn test_update_property_option_missing_returns_none(- pool: Pool<Postgres>,- ) -> anyhow::Result<()> {- const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;-- let missing = "00000000-0000-0000-0000-000000000000"- .parse::<uuid::Uuid>()- .unwrap();-- let result = update_property_option(- &pool,- missing,- PropertyOptionValue::String("x".to_string()),- None,- 0,- )- .await?;- assert!(result.is_none());-- Ok(())- }-}diff --git a/rust/cloud-storage/properties_db_client/src/thread_metadata/get.rs b/rust/cloud-storage/properties_db_client/src/thread_metadata/get.rsdeleted file mode 100644index efffc9c7d5..0000000000--- a/rust/cloud-storage/properties_db_client/src/thread_metadata/get.rs+++ /dev/null@@ -1,44 +0,0 @@-//! Get thread metadata from macrodb.--use crate::error::PropertiesDatabaseError;-use models_properties::service::thread_metadata::ThreadMetadata;-use sqlx::{Pool, Postgres};-use uuid::Uuid;--type Result<T> = std::result::Result<T, PropertiesDatabaseError>;--/// Get thread metadata by thread ID from macrodb-#[tracing::instrument(skip(db), err)]-pub async fn get_thread_metadata(- db: &Pool<Postgres>,- thread_id: Uuid,-) -> Result<Option<ThreadMetadata>> {- sqlx::query_as!(- ThreadMetadata,- r#"- SELECT- t.id,- t.latest_inbound_message_ts as last_received,- t.latest_outbound_message_ts as last_sent,- first_msg.internal_date_ts as thread_started,- first_msg.subject,- (SELECT COUNT(*)::bigint FROM email_messages WHERE thread_id = t.id) as "message_count!"- FROM- email_threads t- -- LATERAL join to get subject and timestamp from the first message- LEFT JOIN LATERAL (- SELECT internal_date_ts, subject- FROM email_messages- WHERE thread_id = t.id- ORDER BY internal_date_ts ASC NULLS LAST- LIMIT 1- ) first_msg ON true- WHERE- t.id = $1- "#,- thread_id- )- .fetch_optional(db)- .await- .map_err(PropertiesDatabaseError::Query)-}diff --git a/rust/cloud-storage/properties_db_client/src/thread_metadata/mod.rs b/rust/cloud-storage/properties_db_client/src/thread_metadata/mod.rsdeleted file mode 100644index 0d38bf20ea..0000000000--- a/rust/cloud-storage/properties_db_client/src/thread_metadata/mod.rs+++ /dev/null@@ -1,3 +0,0 @@-//! Thread metadata operations for property queries.--pub mod get;diff --git a/rust/cloud-storage/properties_service/Cargo.toml b/rust/cloud-storage/properties_service/Cargo.tomlindex 0ce6f72444..01e81bb417 100644--- a/rust/cloud-storage/properties_service/Cargo.toml+++ b/rust/cloud-storage/properties_service/Cargo.toml@@ -13,40 +13,15 @@ name = "properties_service_openapi"path = "src/openapi.rs"[dependencies]-anyhow = { workspace = true }-async-trait = { workspace = true }axum = { workspace = true, features = ["tower-log", "ws"] }-chrono = { workspace = true }-email_db_client = { path = "../email_db_client" }entity_access = { path = "../entity_access" }-http-body-util = { workspace = true }-macro_user_id = { path = "../macro_user_id" }-model-entity = { path = "../model-entity" }-macro_auth = { path = "../macro_auth" }-macro_env = { path = "../macro_env" }macro_middleware = { path = "../macro_middleware", default-features = false, features = ["auth","cloud_storage",] }-last_online_tracker = { path = "../last_online_tracker" }-notification = { path = "../notification" }-aws-sdk-sqs = { workspace = true }-macro_uuid = { path = "../macro_uuid" }-model = { path = "../model" }-models_permissions = { path = "../models_permissions" }models_properties = { path = "../models_properties" }-properties_db_client = { path = "../properties_db_client" }+notification = { path = "../notification" }properties = { path = "../properties" }-system_properties = { path = "../system_properties" }-serde = { workspace = true }serde_json = { workspace = true }-serde_with = { workspace = true }-sqlx = { workspace = true }-thiserror = { workspace = true }-tokio = { workspace = true }-tower = { workspace = true }-tower-http = { workspace = true }-tracing = { workspace = true }utoipa = { workspace = true }-uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/rust/cloud-storage/properties_service/src/api/context.rs b/rust/cloud-storage/properties_service/src/api/context.rsindex d9006836f1..4b4c46d6e6 100644--- a/rust/cloud-storage/properties_service/src/api/context.rs+++ b/rust/cloud-storage/properties_service/src/api/context.rs@@ -1,14 +1,9 @@-use axum::extract::FromRef;-use entity_access::domain::models::MemberTeamRole;-use entity_access::inbound::axum_extractors::OptionalMacroUserTeamExtractor;use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use notification::domain::service::SqsNotificationIngress;use notification::outbound::queue::SqsQueue;-use sqlx::PgPool;-use std::sync::Arc;-use uuid::Uuid;use properties::PropertiesServiceImpl;+use properties::inbound::axum_router::PropertiesRouterState;/// The concrete notification ingress service type.type NotificationIngressType = SqsNotificationIngress<SqsQueue>;@@ -16,20 +11,6 @@ type NotificationIngressType = SqsNotificationIngress<SqsQueue>;/// Type alias for the entity access service.pub type EntityAccessServiceType = EntityAccessServiceImpl<PgAccessRepository>;-/// Team extractor used by property definition endpoints. Resolves the caller's team-/// membership without failing when they have no team. Member role is required, matching-/// the model where anyone on a team can manage that team's properties.-pub type PropertyTeamExtractor =- OptionalMacroUserTeamExtractor<MemberTeamRole, EntityAccessServiceType>;--/// The team the caller belongs to, if any. A `None` team scopes the caller to their own-/// user properties.-pub fn caller_team_id(team: &PropertyTeamExtractor) -> Option<Uuid> {- team.entity_access_receipt- .as_ref()- .and_then(|receipt| Uuid::parse_str(&receipt.entity().entity_id).ok())-}-/// Type alias for the properties service implementation used throughout the service.pub type PropertiesService = PropertiesServiceImpl<properties::PropertiesPgRepo,@@ -38,13 +19,4 @@ pub type PropertiesService = PropertiesServiceImpl<>;/// Minimal state required by properties handlers.-/// This can be extracted from any state that implements `FromRef<PropertiesHandlerState>`.-#[derive(Clone, FromRef)]-pub struct PropertiesHandlerState {- /// Macrodb database connection (contains properties tables and permission tables)- pub db: PgPool,- /// The properties service implementation- pub properties_service: Arc<PropertiesService>,- /// The entity access service for permission checks- pub entity_access_service: Arc<EntityAccessServiceType>,-}+pub type PropertiesHandlerState = PropertiesRouterState<PropertiesService, EntityAccessServiceType>;diff --git a/rust/cloud-storage/properties_service/src/api/mod.rs b/rust/cloud-storage/properties_service/src/api/mod.rsindex 79092e4926..55e5108816 100644--- a/rust/cloud-storage/properties_service/src/api/mod.rs+++ b/rust/cloud-storage/properties_service/src/api/mod.rs@@ -1,4 +1,14 @@pub mod context;-pub mod permissions;-pub mod properties;pub mod swagger;++use axum::Router;++use crate::api::context::PropertiesHandlerState;++/// Creates the properties router with the service's authentication middleware+/// applied to every route that requires an authenticated user.+pub fn router() -> Router<PropertiesHandlerState> {+ properties::inbound::axum_router::router(axum::middleware::from_fn(+ macro_middleware::auth::ensure_user_exists::handler,+ ))+}diff --git a/rust/cloud-storage/properties_service/src/api/permissions.rs b/rust/cloud-storage/properties_service/src/api/permissions.rsdeleted file mode 100644index 33322be6dc..0000000000--- a/rust/cloud-storage/properties_service/src/api/permissions.rs+++ /dev/null@@ -1,153 +0,0 @@-use axum::http::StatusCode;-use entity_access::domain::ports::EntityAccessService;-use macro_user_id::user_id::MacroUserIdStr;-use model_entity::EntityType as ModelEntityType;-use models_permissions::share_permission::access_level::AccessLevel;-use models_properties::{EntityReference, EntityType};-use properties::PropertiesService;-use thiserror::Error;--use crate::api::context::PropertiesHandlerState;--#[derive(Debug, Error)]-pub enum PermissionError {- #[error("Unsupported entity type")]- UnsupportedEntityType,-- #[error("Access denied")]- Unauthorized,-- #[error("An internal error occurred")]- InternalError(String),-}--impl PermissionError {- pub fn status_code(&self) -> StatusCode {- match self {- PermissionError::UnsupportedEntityType => StatusCode::FORBIDDEN,- PermissionError::Unauthorized => StatusCode::FORBIDDEN,- PermissionError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,- }- }-}--/// Checks if a user has view access to an entity (View, Comment, Edit, or Owner level).-/// Supports: Document, Chat, Project, Thread, Channel, Macro.-/// For anonymous users (empty user_id), only allows access to publicly shared entities.-#[tracing::instrument(skip(context), fields(user_id = %user_id, entity_id = %entity_ref.entity_id, entity_type = ?entity_ref.entity_type), err)]-pub async fn check_entity_view_permission(- context: &PropertiesHandlerState,- user_id: &str,- entity_ref: &EntityReference,-) -> Result<(), PermissionError> {- // Check if entity is deleted- match entity_ref.entity_type {- EntityType::Channel | EntityType::Company | EntityType::User | EntityType::Thread => (),- _ => {- let (owner, deleted) = context- .properties_service- .get_owner_and_deleted(&entity_ref.entity_id, entity_ref.entity_type)- .await- .map_err(|e| PermissionError::InternalError(e.to_string()))?;-- // If you are the owner fast return- if owner.eq(user_id) {- return Ok(());- }-- // If the item is deleted and you aren't the owner you are unauthorized- if deleted {- return Err(PermissionError::Unauthorized);- }- }- }-- // If entity is deleted, if user is not owner return 401.- let access_level = get_access_level(context, user_id, entity_ref).await?;-- match access_level {- Some(_) => Ok(()), // Any access level is sufficient for viewing- None => Err(PermissionError::Unauthorized),- }-}--/// Checks if a user has edit access to an entity (Edit or Owner level).-/// Supports: Document, Chat, Project, Thread, Channel, Macro.-#[tracing::instrument(skip(context), fields(user_id = %user_id, entity_id = %entity_ref.entity_id, entity_type = ?entity_ref.entity_type), err)]-pub async fn check_entity_edit_permission(- context: &PropertiesHandlerState,- user_id: &str,- entity_ref: &EntityReference,-) -> Result<(), PermissionError> {- let access_level = get_access_level(context, user_id, entity_ref).await?;-- match access_level {- Some(AccessLevel::Edit) | Some(AccessLevel::Owner) => Ok(()),- Some(_) | None => Err(PermissionError::Unauthorized),- }-}--/// Map `models_properties::EntityType` to `model_entity::EntityType`.-fn map_entity_type(entity_type: EntityType) -> Option<ModelEntityType> {- match entity_type {- EntityType::Document => Some(ModelEntityType::Document),- EntityType::Chat => Some(ModelEntityType::Chat),- EntityType::Project => Some(ModelEntityType::Project),- EntityType::Thread => Some(ModelEntityType::EmailThread),- EntityType::Channel => Some(ModelEntityType::Channel),- EntityType::Task => Some(ModelEntityType::Document), // tasks use document permissions- // CRM company access is resolved from the owning team's membership- // (member → View, admin → Edit, owner → Owner).- EntityType::Company => Some(ModelEntityType::CrmCompany),- EntityType::User => None,- }-}--/// Internal: Gets the user's access level for an entity.-///-/// NOTE: Makes a separate DB query (+ HTTP call for channels). Not worth inlining into-/// properties query due to complex recursive CTEs and entity-specific permission logic.-#[tracing::instrument(skip(context), fields(user_id = %user_id, entity_id = %entity_ref.entity_id, entity_type = ?entity_ref.entity_type), err)]-async fn get_access_level(- context: &PropertiesHandlerState,- user_id: &str,- entity_ref: &EntityReference,-) -> Result<Option<AccessLevel>, PermissionError> {- let model_entity_type = match map_entity_type(entity_ref.entity_type) {- Some(t) => t,- None => {- tracing::warn!("property operations not supported for this entity type");- return Err(PermissionError::UnsupportedEntityType);- }- };-- let parsed_user_id = MacroUserIdStr::parse_from_str(user_id);- let user_id_ref = parsed_user_id.as_ref().ok().map(std::ops::Deref::deref);-- let access_level = context- .entity_access_service- .get_access_level(user_id_ref, &entity_ref.entity_id, model_entity_type)- .await- .map_err(|e| {- tracing::error!(- error = %e,- "failed to get user access level"- );- PermissionError::InternalError(e.to_string())- })?;-- // Fallback for threads: check ownership via link_id if no permission records exist.- // This handles owned threads where EmailThreadPermission/UserItemAccess were never created.- if access_level.is_none()- && entity_ref.entity_type == EntityType::Thread- && let Ok(thread_id) = uuid::Uuid::parse_str(&entity_ref.entity_id)- && let Ok(Some(owner_id)) =- email_db_client::threads::get::get_macro_id_from_thread_id(&context.db, thread_id).await- && owner_id == user_id- {- tracing::debug!("user owns thread via link_id, granting owner access");- return Ok(Some(AccessLevel::Owner));- }-- Ok(access_level)-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/definitions/create.rs b/rust/cloud-storage/properties_service/src/api/properties/definitions/create.rsdeleted file mode 100644index f52e78e56c..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/definitions/create.rs+++ /dev/null@@ -1,185 +0,0 @@-use axum::{- Json,- extract::{Extension, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;-use uuid::Uuid;--use crate::api::context::{PropertiesHandlerState, PropertyTeamExtractor, caller_team_id};-use model::user::UserContext;-use models_properties::api::{- CreatePropertyDefinitionRequest, CreatePropertyScope, PropertyDataType,-};-use models_properties::service::property_definition::PropertyDefinition;-use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};-use properties_db_client::{- error::PropertiesDatabaseError,- property_definitions::insert::{self as property_definitions_insert, DefinitionOwner},-};--#[derive(Debug, Error)]-pub enum CreatePropertyDefinitionErr {- #[error("An internal error occurred")]- InternalError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),- #[error("{0}")]- InvalidRequest(String),- #[error("You must be on a team to create a team property")]- TeamMembershipRequired,-}--impl IntoResponse for CreatePropertyDefinitionErr {- fn into_response(self) -> Response {- let status_code = match &self {- CreatePropertyDefinitionErr::InternalError(_)- | CreatePropertyDefinitionErr::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,- CreatePropertyDefinitionErr::InvalidRequest(_) => StatusCode::BAD_REQUEST,- CreatePropertyDefinitionErr::TeamMembershipRequired => StatusCode::FORBIDDEN,- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "CreatePropertyDefinitionErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Create a new property definition-#[utoipa::path(- post,- path = "/properties/definitions",- request_body = CreatePropertyDefinitionRequest,- responses(- (status = 201, description = "Property definition created successfully", body = PropertyDefinition),- (status = 400, description = "Invalid request"),- (status = 403, description = "Team membership required for team scope"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, user_context, team), fields(user_id = %user_context.user_id), err)]-pub async fn create_property_definition(- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,- Json(request): Json<CreatePropertyDefinitionRequest>,-) -> Result<(StatusCode, Json<PropertyDefinition>), CreatePropertyDefinitionErr> {- if let Err(err) = request.validate() {- tracing::error!(- error = %err,- "property definition validation failed"- );- return Err(CreatePropertyDefinitionErr::InvalidRequest(err.to_string()));- }-- // Derive the owner from the authenticated caller - clients never supply owner ids.- let owner = match request.scope {- CreatePropertyScope::User => DefinitionOwner::User(user_context.user_id.as_str()),- CreatePropertyScope::Team => {- let team_id =- caller_team_id(&team).ok_or(CreatePropertyDefinitionErr::TeamMembershipRequired)?;- DefinitionOwner::Team(team_id)- }- };-- tracing::info!(- owner = ?owner,- scope = ?request.scope,- "creating property definition"- );-- let (base_data_type, property_options) = match &request.data_type {- PropertyDataType::SelectString { options, .. } => {- let property_options: Vec<PropertyOption> = options- .iter()- .map(|opt| PropertyOption {- id: Uuid::nil(), // Temporary ID, will be replaced by DB- property_definition_id: Uuid::nil(), // Temporary ID, will be replaced by DB- display_order: opt.display_order,- value: PropertyOptionValue::String(opt.value.clone()),- color: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- })- .collect();- (request.data_type.to_data_type(), property_options)- }- PropertyDataType::SelectNumber { options, .. } => {- let property_options: Vec<PropertyOption> = options- .iter()- .map(|opt| PropertyOption {- id: Uuid::nil(), // Temporary ID, will be replaced by DB- property_definition_id: Uuid::nil(), // Temporary ID, will be replaced by DB- display_order: opt.display_order,- value: PropertyOptionValue::Number(opt.value),- color: None,- created_at: chrono::Utc::now(),- updated_at: chrono::Utc::now(),- })- .collect();- (request.data_type.to_data_type(), property_options)- }- _ => (request.data_type.to_data_type(), Vec::new()),- };-- let property = if property_options.is_empty() {- tracing::debug!("no options provided, using simple creation");-- property_definitions_insert::create_property_definition(- &state.db,- owner,- &request.display_name,- base_data_type,- request.data_type.is_multi_select(),- request.data_type.specific_entity_type(),- )- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- display_name = %request.display_name,- "failed to create property definition in database"- );- })?- } else {- tracing::debug!(- options_count = property_options.len(),- "options provided, using transactional creation"- );-- property_definitions_insert::create_property_definition_with_options(- &state.db,- owner,- &request.display_name,- base_data_type,- request.data_type.is_multi_select(),- request.data_type.specific_entity_type(),- property_options,- )- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- display_name = %request.display_name,- "failed to create property definition with options in database"- );- })?- };-- tracing::info!(- property_id = %property.id,- display_name = %property.display_name,- data_type = ?property.data_type,- "successfully created property definition"- );-- Ok((StatusCode::CREATED, Json(property)))-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/definitions/delete.rs b/rust/cloud-storage/properties_service/src/api/properties/definitions/delete.rsdeleted file mode 100644index bb95cdcef8..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/definitions/delete.rs+++ /dev/null@@ -1,101 +0,0 @@-use axum::{- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use system_properties::SystemPropertyKey;-use thiserror::Error;-use uuid::Uuid;--use crate::api::context::{PropertiesHandlerState, PropertyTeamExtractor, caller_team_id};-use model::user::UserContext;-use properties_db_client::{- error::PropertiesDatabaseError,- property_definitions::{- delete as property_definitions_delete, get as property_definitions_get,- },-};--#[derive(Debug, Error)]-pub enum DeletePropertyDefinitionError {- #[error("Property definition not found")]- NotFound,- #[error("Cannot modify system properties")]- SystemPropertyNotModifiable,- #[error("An internal error occurred")]- InternalServerError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),-}--impl IntoResponse for DeletePropertyDefinitionError {- fn into_response(self) -> Response {- let status_code = match &self {- DeletePropertyDefinitionError::NotFound => StatusCode::NOT_FOUND,- DeletePropertyDefinitionError::SystemPropertyNotModifiable => StatusCode::FORBIDDEN,- DeletePropertyDefinitionError::InternalServerError(_)- | DeletePropertyDefinitionError::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "DeletePropertyDefinitionError",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Delete a property definition-#[utoipa::path(- delete,- path = "/properties/definitions/{definition_id}",- params(- ("definition_id" = Uuid, Path, description = "Property definition ID")- ),- responses(- (status = 204, description = "Property definition deleted successfully"),- (status = 400, description = "Invalid property ID"),- (status = 403, description = "Cannot modify system properties"),- (status = 404, description = "Property definition not found"),- (status = 500, description = "Internal server error")- ),- tag = "Properties"-)]-#[tracing::instrument(skip(state, user_context, team), err)]-pub async fn delete_property_definition(- Path(property_uuid): Path<Uuid>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,-) -> Result<Response, DeletePropertyDefinitionError> {- tracing::info!("deleting property definition");-- // First check if property exists and if it's a system property- let property = property_definitions_get::get_property_definition(&state.db, property_uuid)- .await?- .ok_or(DeletePropertyDefinitionError::NotFound)?;-- if property.is_system || SystemPropertyKey::is_system_uuid(property_uuid) {- return Err(DeletePropertyDefinitionError::SystemPropertyNotModifiable);- }-- // Then verify ownership- let _property = property_definitions_get::get_property_definition_with_owner(- &state.db,- property_uuid,- &user_context.user_id,- caller_team_id(&team),- )- .await?- .ok_or(DeletePropertyDefinitionError::NotFound)?;-- property_definitions_delete::delete_property_definition(&state.db, property_uuid).await?;-- tracing::info!("successfully deleted property definition");-- Ok(StatusCode::NO_CONTENT.into_response())-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/definitions/list.rs b/rust/cloud-storage/properties_service/src/api/properties/definitions/list.rsdeleted file mode 100644index 11b3ef871a..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/definitions/list.rs+++ /dev/null@@ -1,217 +0,0 @@-use axum::{- Json,- extract::{Extension, Query, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use serde::{Deserialize, Serialize};-use thiserror::Error;-use utoipa::ToSchema;--use crate::api::context::{PropertiesHandlerState, PropertyTeamExtractor, caller_team_id};-use model::user::UserContext;-use models_properties::EntityType;-use models_properties::service::property_definition::PropertyDefinition;-use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;-use properties_db_client::{- error::PropertiesDatabaseError, property_definitions::get as property_definitions_get,-};-use system_properties::SystemPropertyKey;--#[derive(Debug, Error)]-pub enum ListPropertiesErr {- #[error("An internal error occurred")]- InternalError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),-}--impl IntoResponse for ListPropertiesErr {- fn into_response(self) -> Response {- let status_code = match &self {- ListPropertiesErr::InternalError(_) | ListPropertiesErr::DatabaseError(_) => {- StatusCode::INTERNAL_SERVER_ERROR- }- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "ListPropertiesErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Scope filter for property queries-#[derive(Debug, Deserialize, ToSchema, PartialEq)]-#[serde(rename_all = "snake_case")]-pub enum PropertyScope {- /// User-scoped properties only- User,- /// The caller's team properties only- Team,- /// System properties only- System,- /// User, team, and system properties- All,-}--/// Query parameters for listing properties-#[derive(Debug, Deserialize, ToSchema)]-pub struct ListPropertiesQuery {- /// Scope filter for properties- pub scope: PropertyScope,- /// Whether to include property options in the response- #[serde(default)]- pub include_options: bool,- /// Filter properties applicable to a specific entity type.- /// When provided, excludes properties that cannot be attached to this entity type- /// (e.g., Parent Task and Subtasks are excluded for non-task entities).- pub for_entity_type: Option<EntityType>,-}--/// Response for property definition with optional property options-#[derive(Debug, Serialize, ToSchema)]-#[serde(untagged)]-pub enum PropertyDefinitionResponse {- Simple(PropertyDefinition),- WithOptions(PropertyDefinitionWithOptions),-}--/// List property definitions with flexible filtering-#[utoipa::path(- get,- path = "/properties/definitions",- params(- ("scope" = PropertyScope, Query, description = "Filter by scope: 'user', 'team', 'system', or 'all'"),- ("include_options" = Option<bool>, Query, description = "Whether to include property options in the response"),- ("for_entity_type" = Option<EntityType>, Query, description = "Filter properties applicable to a specific entity type")- ),- responses(- (status = 200, description = "Properties retrieved successfully", body = Vec<PropertyDefinitionResponse>),- (status = 400, description = "Invalid request"),- (status = 500, description = "Internal server error")- ),- tag = "Properties"-)]-#[tracing::instrument(skip(state, user_context, team), err)]-pub async fn list_properties(- Query(query): Query<ListPropertiesQuery>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,-) -> Result<Json<Vec<PropertyDefinitionResponse>>, ListPropertiesErr> {- let callers_team = caller_team_id(&team);-- // Determine query parameters based on scope. Team and user ids are derived from the- // authenticated caller, never from the request.- let (team_id, user_id_opt, include_system) = match query.scope {- PropertyScope::User => (None, Some(user_context.user_id.as_str()), false),- PropertyScope::Team => (callers_team, None, false),- PropertyScope::System => (None, None, true),- PropertyScope::All => (callers_team, Some(user_context.user_id.as_str()), true),- };-- tracing::info!(- team_id = ?team_id,- scope = ?query.scope,- include_system = include_system,- for_entity_type = ?query.for_entity_type,- user_id = %user_context.user_id,- "listing properties"- );-- let filter_entity_type = query.for_entity_type;-- let response = if query.include_options {- let properties_with_options = property_definitions_get::get_properties_with_options(- &state.db,- team_id,- user_id_opt,- include_system,- )- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- team_id = ?team_id,- scope = ?query.scope,- user_id = %user_context.user_id,- "failed to retrieve properties with options"- );- })?;-- let response: Vec<PropertyDefinitionResponse> = properties_with_options- .into_iter()- .filter(|p| {- filter_entity_type- .map(|et| is_property_applicable_to(p.definition.id, et))- .unwrap_or(true)- })- .map(PropertyDefinitionResponse::WithOptions)- .collect();-- tracing::info!(- properties_count = response.len(),- team_id = ?team_id,- scope = ?query.scope,- user_id = %user_context.user_id,- "successfully retrieved properties with options"- );- response- } else {- let properties = property_definitions_get::get_properties(- &state.db,- team_id,- user_id_opt,- include_system,- )- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- team_id = ?team_id,- scope = ?query.scope,- user_id = %user_context.user_id,- "failed to retrieve properties"- );- })?;-- let response: Vec<PropertyDefinitionResponse> = properties- .into_iter()- .filter(|p| {- filter_entity_type- .map(|et| is_property_applicable_to(p.id, et))- .unwrap_or(true)- })- .map(PropertyDefinitionResponse::Simple)- .collect();-- tracing::info!(- properties_count = response.len(),- team_id = ?team_id,- scope = ?query.scope,- user_id = %user_context.user_id,- "successfully retrieved properties"- );- response- };-- Ok(Json(response))-}--/// Check if a property can be attached to the given entity type.-pub fn is_property_applicable_to(property_id: uuid::Uuid, entity_type: EntityType) -> bool {- // Task-only properties: Parent Task and Subtasks- if property_id == SystemPropertyKey::PARENT_TASK_UUID- || property_id == SystemPropertyKey::SUBTASKS_UUID- {- return entity_type == EntityType::Task;- }-- true-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/definitions/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/definitions/mod.rsdeleted file mode 100644index 882e206ea3..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/definitions/mod.rs+++ /dev/null@@ -1,6 +0,0 @@-pub mod create;-pub mod delete;-pub mod list;--// Re-export commonly used types from the list module-pub use list::{ListPropertiesQuery, PropertyDefinitionResponse};diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/delete_entity.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/delete_entity.rsdeleted file mode 100644index d7d57ff527..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/delete_entity.rs+++ /dev/null@@ -1,79 +0,0 @@-use axum::{- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;--use crate::api::context::PropertiesHandlerState;-use models_properties::{EntityReference, EntityType};-use properties_db_client::{- entity_properties::delete as entity_properties_delete, error::PropertiesDatabaseError,-};--#[allow(dead_code)]-#[derive(Debug, Error)]-pub enum DeleteEntityErr {- #[error("An internal error occurred")]- Internal(#[from] anyhow::Error),- #[error("An internal error occurred")]- Database(#[from] PropertiesDatabaseError),-}--impl IntoResponse for DeleteEntityErr {- fn into_response(self) -> Response {- let status_code = match &self {- DeleteEntityErr::Internal(_) | DeleteEntityErr::Database(_) => {- StatusCode::INTERNAL_SERVER_ERROR- }- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "DeleteEntityErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Delete all properties for an entity-#[utoipa::path(- delete,- path = "/internal/properties/entities/{entity_type}/{entity_id}",- params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),- ("entity_id" = String, Path, description = "Entity ID")- ),- responses(- (status = 204, description = "Entity properties deleted successfully"),- (status = 404, description = "Entity not found"),- (status = 500, description = "Internal server error")- ),- tag = "Internal"-)]-#[tracing::instrument(skip(state), err)]-pub async fn delete_entity(- Path((entity_type, entity_id)): Path<(EntityType, String)>,- State(state): State<PropertiesHandlerState>,-) -> Result<StatusCode, DeleteEntityErr> {- tracing::info!("deleting all properties for entity");-- let entity_reference = EntityReference::new(entity_id.clone(), entity_type);-- entity_properties_delete::delete_entity(&state.db, &entity_reference)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to delete entity properties"- );- })?;-- tracing::info!("successfully deleted all properties for entity");-- Ok(StatusCode::NO_CONTENT)-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/delete_property.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/delete_property.rsdeleted file mode 100644index aad9ea2735..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/delete_property.rs+++ /dev/null@@ -1,129 +0,0 @@-use axum::{- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use models_properties::EntityReference;-use system_properties::SystemPropertyKey;-use thiserror::Error;-use uuid::Uuid;--use crate::api::context::PropertiesHandlerState;-use model::user::UserContext;-use properties_db_client::{- entity_properties::{delete as entity_properties_delete, get::lookup_entity_property},- error::PropertiesDatabaseError,-};--#[derive(Debug, Error)]-pub enum DeleteEntityPropertyErr {- #[error("An internal error occurred")]- InternalError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),- #[error("{0}")]- Permission(#[from] crate::api::permissions::PermissionError),- #[error("Entity property not found")]- NotFound,- #[error("This property is required and cannot be removed from this entity")]- RequiredProperty,-}--impl IntoResponse for DeleteEntityPropertyErr {- fn into_response(self) -> Response {- let status_code = match &self {- DeleteEntityPropertyErr::InternalError(_)- | DeleteEntityPropertyErr::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,- DeleteEntityPropertyErr::Permission(e) => e.status_code(),- DeleteEntityPropertyErr::NotFound => StatusCode::NOT_FOUND,- DeleteEntityPropertyErr::RequiredProperty => StatusCode::FORBIDDEN,- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "DeleteEntityPropertyErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Remove a specific entity property by its ID-#[utoipa::path(- delete,- path = "/properties/entity_properties/{entity_property_id}",- params(- ("entity_property_id" = Uuid, Path, description = "Entity Property ID")- ),- responses(- (status = 204, description = "Entity property removed successfully"),- (status = 403, description = "Property is required and cannot be removed"),- (status = 404, description = "Entity property not found"),- (status = 500, description = "Internal server error")- ),- tag = "Properties"-)]-#[tracing::instrument(skip(state, user_context), fields(entity_property_id = %entity_property_uuid, user_id = %user_context.user_id), err)]-pub async fn delete_entity_property(- Path(entity_property_uuid): Path<Uuid>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,-) -> Result<StatusCode, DeleteEntityPropertyErr> {- tracing::info!("removing entity property");-- // Lookup entity property- let property_info = lookup_entity_property(&state.db, entity_property_uuid)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to get entity property metadata"- );- })?- .ok_or(DeleteEntityPropertyErr::NotFound)?;-- tracing::debug!(- entity_id = %property_info.entity_id,- entity_type = ?property_info.entity_type,- property_definition_id = %property_info.property_definition_id,- "fetched entity property info"- );-- // Check if this property is required for the entity type (e.g., Task properties)- if SystemPropertyKey::is_required_for_entity(- property_info.property_definition_id,- property_info.entity_type,- ) {- tracing::warn!(- entity_type = ?property_info.entity_type,- property_definition_id = %property_info.property_definition_id,- "attempted to remove required property"- );- return Err(DeleteEntityPropertyErr::RequiredProperty);- }-- let entity_ref = EntityReference::new(property_info.entity_id, property_info.entity_type);-- crate::api::permissions::check_entity_edit_permission(- &state,- &user_context.user_id,- &entity_ref,- )- .await?;-- entity_properties_delete::delete_entity_property(&state.db, entity_property_uuid)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to remove entity property"- );- })?;-- tracing::info!("successfully removed entity property");-- Ok(StatusCode::NO_CONTENT)-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/get.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/get.rsdeleted file mode 100644index b3a7974e43..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/get.rs+++ /dev/null@@ -1,188 +0,0 @@-use axum::{- Json,- extract::{Extension, Path, Query, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;--use crate::api::{- context::PropertiesHandlerState,- properties::entities::types::{- EntityPropertiesResponse, EntityQueryParams, retain_caller_visible_tags,- },-};-use model::user::UserContext;-use models_properties::EntityType;-use properties_db_client::{- entity_properties::get as entity_properties_get, error::PropertiesDatabaseError,-};--#[derive(Debug, Error)]-pub enum GetEntityPropertiesErr {- #[error("An internal error occurred")]- Internal(#[from] anyhow::Error),- #[error("An internal error occurred")]- Database(#[from] PropertiesDatabaseError),-- #[error("{0}")]- Metadata(#[from] crate::api::properties::metadata::MetadataError),-- #[error("{0}")]- Permission(#[from] crate::api::permissions::PermissionError),-}--impl IntoResponse for GetEntityPropertiesErr {- fn into_response(self) -> Response {- let status_code = match &self {- GetEntityPropertiesErr::Internal(_)- | GetEntityPropertiesErr::Database(_)- | GetEntityPropertiesErr::Metadata(_) => StatusCode::INTERNAL_SERVER_ERROR,- GetEntityPropertiesErr::Permission(e) => e.status_code(),- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "GetEntityPropertiesErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Get all properties for an entity-#[utoipa::path(- get,- path = "/properties/entities/{entity_type}/{entity_id}",- params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),- ("entity_id" = String, Path, description = "Entity ID"),- ("include_metadata" = Option<bool>, Query, description = "Whether to include property metadata (default: false)")- ),- responses(- (status = 200, description = "Entity properties retrieved successfully", body = EntityPropertiesResponse),- (status = 400, description = "Invalid entity type"),- (status = 403, description = "Forbidden - User does not have permission to view this entity"),- (status = 404, description = "Entity not found"),- (status = 500, description = "Internal server error")- ),- tag = "Properties"-)]-#[tracing::instrument(skip(state, user_context), fields(user_id = %user_context.user_id, entity_type = ?entity_type, include_metadata = query.include_metadata), err)]-pub async fn get_entity_properties(- Path((entity_type, entity_id)): Path<(EntityType, String)>,- Query(query): Query<EntityQueryParams>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,-) -> Result<Json<EntityPropertiesResponse>, GetEntityPropertiesErr> {- tracing::info!(- entity_id = %entity_id,- "retrieving entity properties"- );-- let entity_ref = models_properties::EntityReference::new(entity_id.clone(), entity_type);-- // Note: This can fail if the entity is marked with "deletedAt"- crate::api::permissions::check_entity_view_permission(- &state,- &user_context.user_id,- &entity_ref,- )- .await?;-- let (user_properties, metadata_properties) = if query.include_metadata {- // Fetch user properties and metadata in parallel when metadata is requested- let (user_properties_result, metadata_properties_result) = tokio::join!(- entity_properties_get::get_entity_properties_values(&state.db, &entity_id, entity_type),- async {- match entity_type {- EntityType::Document | EntityType::Task => {- crate::api::properties::metadata::get_document_metadata_properties(- &state.db,- &entity_id,- entity_type,- )- .await- }- EntityType::Thread => {- let thread_id = uuid::Uuid::parse_str(&entity_id).map_err(|e| {- tracing::error!(error = ?e, entity_id = %entity_id, "invalid thread UUID");- crate::api::properties::metadata::MetadataError::NotFound- })?;- crate::api::properties::metadata::get_thread_metadata_properties(- &state.db, thread_id,- )- .await- }- EntityType::Project => {- super::super::metadata::get_project_metadata_properties(- &state.db, &entity_id,- )- .await- }- _ => {- tracing::debug!(- entity_type = ?entity_type,- "no system properties available for this entity type"- );- Ok(vec![])- }- }- }- );-- let user_properties = user_properties_result.inspect_err(|e| {- tracing::error!(- error = ?e,- entity_id = %entity_id,- "failed to retrieve entity properties from database"- );- })?;-- let metadata_properties = metadata_properties_result.inspect_err(|e| {- tracing::error!(- error = ?e,- entity_id = %entity_id,- "failed to get metadata properties"- );- })?;-- (user_properties, metadata_properties)- } else {- // Only fetch user properties when metadata not requested - no parallel task needed- tracing::debug!("skipping metadata properties due to include_metadata=false");- let user_properties =- entity_properties_get::get_entity_properties_values(&state.db, &entity_id, entity_type)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- entity_id = %entity_id,- "failed to retrieve entity properties from database"- );- })?;-- (user_properties, vec![])- };-- let mut all_properties = user_properties;- all_properties.extend(metadata_properties);-- retain_caller_visible_tags(&mut all_properties, &user_context.user_id);-- let response = EntityPropertiesResponse {- entity_id: entity_id.to_string(),- properties: all_properties,- };-- tracing::info!(- entity_id = %entity_id,- properties_count = response.properties.len(),- "successfully retrieved entity properties"- );-- Ok(Json(response))-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/get_bulk.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/get_bulk.rsdeleted file mode 100644index b4dc3bec27..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/get_bulk.rs+++ /dev/null@@ -1,198 +0,0 @@-use axum::{- Extension, Json,- extract::State,- http::StatusCode,- response::{IntoResponse, Response},-};-use std::collections::HashMap;-use thiserror::Error;--use crate::api::{- context::PropertiesHandlerState,- properties::entities::types::{BulkEntityPropertiesRequest, EntityPropertiesResponse},-};-use model::user::UserContext;-use properties_db_client::{- entity_properties::get as entity_properties_get, error::PropertiesDatabaseError,-};--#[derive(Debug, Error)]-pub enum GetBulkEntityPropertiesErr {- #[error("An internal error occurred")]- InternalError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),- #[error("Entities array cannot be empty")]- InvalidRequest,- #[error("Access denied")]- Permission(#[from] crate::api::permissions::PermissionError),-}--impl IntoResponse for GetBulkEntityPropertiesErr {- fn into_response(self) -> Response {- let status_code = match &self {- GetBulkEntityPropertiesErr::InternalError(_)- | GetBulkEntityPropertiesErr::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,- GetBulkEntityPropertiesErr::InvalidRequest => StatusCode::BAD_REQUEST,- GetBulkEntityPropertiesErr::Permission(e) => e.status_code(),- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "GetBulkEntityPropertiesErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Shared implementation for bulk entity properties retrieval-async fn get_bulk_entity_properties_impl(- state: &PropertiesHandlerState,- request: BulkEntityPropertiesRequest,-) -> Result<HashMap<String, EntityPropertiesResponse>, GetBulkEntityPropertiesErr> {- if request.entities.is_empty() {- tracing::error!("empty entities array in request");- return Err(GetBulkEntityPropertiesErr::InvalidRequest);- }-- tracing::info!("retrieving bulk entity properties");-- // Use filtered query if property_ids specified, otherwise fetch all.- // Note: the public endpoint requires property_ids, but internal callers can- // pass an empty vec to fetch all properties for the given entities.- let bulk_properties = if request.property_ids.is_empty() {- entity_properties_get::get_bulk_entity_properties_values(&state.db, &request.entities).await- } else {- entity_properties_get::get_bulk_entity_properties_values_filtered(- &state.db,- &request.entities,- &request.property_ids,- None,- )- .await- }- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to retrieve bulk entity properties"- );- })?;-- let mut result = HashMap::new();-- for (entity_id, properties_values) in bulk_properties {- let response = EntityPropertiesResponse {- entity_id: entity_id.clone(),- properties: properties_values,- };-- result.insert(entity_id, response);- }-- tracing::info!(- successful_entities = result.len(),- "successfully retrieved bulk entity properties"- );-- Ok(result)-}--/// Get properties for multiple entities in bulk (internal endpoint - service-to-service)-#[utoipa::path(- post,- path = "/internal/properties/entities/bulk",- request_body = BulkEntityPropertiesRequest,- responses(- (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),- (status = 400, description = "Invalid request body"),- (status = 500, description = "Internal server error")- ),- tag = "Internal"-)]-#[tracing::instrument(skip(state, request), fields(entity_count = request.entities.len()), err)]-pub async fn get_bulk_entity_properties_internal(- State(state): State<PropertiesHandlerState>,- Json(request): Json<BulkEntityPropertiesRequest>,-) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {- get_bulk_entity_properties_impl(&state, request)- .await- .map(Json)-}--/// Get properties for multiple entities in bulk (public endpoint with user auth)-///-/// Only returns properties for entities the user has view permission for.-/// Entities without permission are silently omitted from the response.-#[utoipa::path(- post,- path = "/properties/entities/bulk",- request_body = BulkEntityPropertiesRequest,- responses(- (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),- (status = 400, description = "Invalid request body"),- (status = 403, description = "Forbidden - User does not have permission"),- (status = 500, description = "Internal server error")- ),- tag = "Properties"-)]-#[tracing::instrument(skip(state, request, user_context), fields(user_id = %user_context.user_id, entity_count = request.entities.len()), err)]-pub async fn get_bulk_entity_properties(- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- Json(request): Json<BulkEntityPropertiesRequest>,-) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {- // Unlike the internal endpoint, the public endpoint requires explicit property IDs.- // An empty property_ids means "no properties requested", so return early with empty result.- if request.entities.is_empty() || request.property_ids.is_empty() {- return Ok(Json(HashMap::new()));- }-- // Filter to only entities the user has permission to view- let mut permitted_entities = Vec::with_capacity(request.entities.len());- for entity_ref in &request.entities {- match crate::api::permissions::check_entity_view_permission(- &state,- &user_context.user_id,- entity_ref,- )- .await- {- Ok(()) => permitted_entities.push(entity_ref.clone()),- Err(e) => {- tracing::debug!(- entity_id = %entity_ref.entity_id,- entity_type = ?entity_ref.entity_type,- error = ?e,- "user lacks permission, skipping entity"- );- }- }- }-- tracing::info!(- permitted = permitted_entities.len(),- "filtered entities by permission"- );-- if permitted_entities.is_empty() {- return Ok(Json(HashMap::new()));- }-- let filtered_request = BulkEntityPropertiesRequest {- entities: permitted_entities,- property_ids: request.property_ids.clone(),- };-- let mut result = get_bulk_entity_properties_impl(&state, filtered_request).await?;- for response in result.values_mut() {- crate::api::properties::entities::types::retain_caller_visible_tags(- &mut response.properties,- &user_context.user_id,- );- }- Ok(Json(result))-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rsdeleted file mode 100644index c86598b6eb..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rs+++ /dev/null@@ -1,11 +0,0 @@-pub mod delete_entity;-pub mod delete_property;-pub mod get;-pub mod get_bulk;-pub mod option;-pub mod set;-pub mod set_property_status_complete;-pub mod types;--// Re-export commonly used types-pub use types::{EntityPropertiesResponse, EntityQueryParams, SetEntityPropertyRequest};diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/option.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/option.rsdeleted file mode 100644index 9cd78e96a6..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/option.rs+++ /dev/null@@ -1,140 +0,0 @@-use axum::{- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;-use uuid::Uuid;--use crate::api::context::PropertiesHandlerState;-use model::user::UserContext;-use models_properties::EntityType;-use properties::{PropertiesErr, PropertiesService};--#[derive(Debug, Error)]-pub enum EntityPropertyOptionErr {- #[error(transparent)]- Properties(#[from] PropertiesErr),-}--impl IntoResponse for EntityPropertyOptionErr {- fn into_response(self) -> Response {- let status_code = match &self {- EntityPropertyOptionErr::Properties(e) => match e {- PropertiesErr::Validation(_) => StatusCode::BAD_REQUEST,- PropertiesErr::PermissionDenied => StatusCode::FORBIDDEN,- PropertiesErr::Repo(_) | PropertiesErr::PermissionServiceNotConfigured => {- StatusCode::INTERNAL_SERVER_ERROR- }- },- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "EntityPropertyOptionErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Add a single option to an entity's multi-select property value.-///-/// Atomic delta: the option is appended to the current stored value (deduped,-/// attaching the property if needed), so concurrent edits to the same value-/// merge rather than overwrite each other. Prefer this over the full-value PUT-/// when adding one option.-#[utoipa::path(- post,- path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",- params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),- ("entity_id" = String, Path, description = "Entity ID"),- ("property_id" = Uuid, Path, description = "Property ID"),- ("option_id" = Uuid, Path, description = "Option ID to add")- ),- responses(- (status = 204, description = "Option added successfully"),- (status = 400, description = "Invalid request, property is not multi-select, or option does not belong to the property"),- (status = 403, description = "No edit access to the entity"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, user_context), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type, user_id = %user_context.user_id), err)]-pub async fn add_entity_property_option(- Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(- EntityType,- String,- Uuid,- Uuid,- )>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,-) -> Result<StatusCode, EntityPropertyOptionErr> {- tracing::info!("adding entity property option");-- state- .properties_service- .add_entity_property_option(- &user_context.user_id,- &entity_id,- entity_type,- property_uuid,- option_uuid,- )- .await?;-- Ok(StatusCode::NO_CONTENT)-}--/// Remove a single option from an entity's multi-select property value.-///-/// Atomic delta: the option is stripped from the current stored value (a no-op-/// if absent), so concurrent edits to the same value merge rather than overwrite-/// each other.-#[utoipa::path(- delete,- path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",- params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),- ("entity_id" = String, Path, description = "Entity ID"),- ("property_id" = Uuid, Path, description = "Property ID"),- ("option_id" = Uuid, Path, description = "Option ID to remove")- ),- responses(- (status = 204, description = "Option removed successfully"),- (status = 403, description = "No edit access to the entity"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, user_context), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type, user_id = %user_context.user_id), err)]-pub async fn remove_entity_property_option(- Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(- EntityType,- String,- Uuid,- Uuid,- )>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,-) -> Result<StatusCode, EntityPropertyOptionErr> {- tracing::info!("removing entity property option");-- state- .properties_service- .remove_entity_property_option(- &user_context.user_id,- &entity_id,- entity_type,- property_uuid,- option_uuid,- )- .await?;-- Ok(StatusCode::NO_CONTENT)-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/set.rsdeleted file mode 100644index 7e96ce3e93..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs+++ /dev/null@@ -1,313 +0,0 @@-use axum::{- Json,- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;-use uuid::Uuid;--use crate::api::{- context::PropertiesHandlerState, properties::entities::types::SetEntityPropertyRequest,-};-use model::user::UserContext;-use models_properties::EntityType;-use properties::{PropertiesErr, PropertiesService};--#[derive(Debug, Error)]-pub enum SetEntityPropertyErr {- #[error(transparent)]- Properties(#[from] PropertiesErr),-}--impl IntoResponse for SetEntityPropertyErr {- fn into_response(self) -> Response {- let status_code = match &self {- SetEntityPropertyErr::Properties(e) => match e {- PropertiesErr::Validation(_) => StatusCode::BAD_REQUEST,- PropertiesErr::PermissionDenied => StatusCode::FORBIDDEN,- PropertiesErr::Repo(_) | PropertiesErr::PermissionServiceNotConfigured => {- StatusCode::INTERNAL_SERVER_ERROR- }- },- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "SetEntityPropertyErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Set or update a property value for an entity, or attach a property without a value-#[utoipa::path(- put,- path = "/properties/entities/{entity_type}/{entity_id}/{property_id}",- params(- ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),- ("entity_id" = String, Path, description = "Entity ID"),- ("property_id" = Uuid, Path, description = "Property ID")- ),- request_body = SetEntityPropertyRequest,- responses(- (status = 204, description = "Entity property set successfully (with or without value)"),- (status = 400, description = "Invalid request or entity type"),- (status = 404, description = "Entity or property not found"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, user_context), fields(entity_id = %entity_id, property_id = %property_uuid, entity_type = ?entity_type, user_id = %user_context.user_id, request = ?request), err)]-pub async fn set_entity_property(- Path((entity_type, entity_id, property_uuid)): Path<(EntityType, String, Uuid)>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- Json(request): Json<SetEntityPropertyRequest>,-) -> Result<StatusCode, SetEntityPropertyErr> {- tracing::info!("setting entity property");-- state- .properties_service- .set_entity_property(- &user_context.user_id,- &entity_id,- entity_type,- property_uuid,- request.value,- )- .await?;-- tracing::info!("successfully set entity property");-- Ok(StatusCode::NO_CONTENT)-}-#[cfg(test)]-mod tests {- use super::*;- use chrono::Utc;- use models_properties::api::SetPropertyValue;- use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};- use models_properties::service::property_value::PropertyValue;- use std::collections::HashSet;- use uuid::Uuid;-- /// Helper function to create a test property option- fn create_test_property_option(- property_id: Uuid,- string_value: Option<String>,- number_value: Option<f64>,- ) -> PropertyOption {- let value = match (number_value, string_value) {- (Some(num), None) => PropertyOptionValue::Number(num),- (None, Some(str)) => PropertyOptionValue::String(str),- _ => PropertyOptionValue::String("default".to_string()),- };-- PropertyOption {- id: macro_uuid::generate_uuid_v7(),- property_definition_id: property_id,- display_order: 1,- value,- color: None,- created_at: Utc::now(),- updated_at: Utc::now(),- }- }-- #[test]- fn test_property_option_ownership_validation() {- // Test that we can identify which option IDs belong to which properties- let property_id_1 = macro_uuid::generate_uuid_v7();- let property_id_2 = macro_uuid::generate_uuid_v7();-- let option_1 =- create_test_property_option(property_id_1, Some("Option 1".to_string()), None);- let option_2 =- create_test_property_option(property_id_1, Some("Option 2".to_string()), None);- let option_3 =- create_test_property_option(property_id_2, Some("Option 3".to_string()), None);-- let property_1_options = vec![option_1.clone(), option_2.clone()];- let valid_option_ids: HashSet<Uuid> = property_1_options.iter().map(|opt| opt.id).collect();-- // Option 1 and 2 should be valid for property 1- assert!(valid_option_ids.contains(&option_1.id));- assert!(valid_option_ids.contains(&option_2.id));-- // Option 3 should not be valid for property 1 (belongs to property 2)- assert!(!valid_option_ids.contains(&option_3.id));- }-- #[test]- fn test_option_id_extraction() {- let option_id_1 = macro_uuid::generate_uuid_v7();- let option_id_2 = macro_uuid::generate_uuid_v7();-- // Test single option extraction- let single_option = SetPropertyValue::SelectOption {- option_id: option_id_1,- };- let extracted_single = match single_option {- SetPropertyValue::SelectOption { option_id } => vec![option_id],- SetPropertyValue::MultiSelectOption { option_ids } => option_ids,- _ => vec![],- };- assert_eq!(extracted_single, vec![option_id_1]);-- // Test multi option extraction- let multi_option = SetPropertyValue::MultiSelectOption {- option_ids: vec![option_id_1, option_id_2],- };- let extracted_multi = match multi_option {- SetPropertyValue::SelectOption { option_id } => vec![option_id],- SetPropertyValue::MultiSelectOption { option_ids } => option_ids,- _ => vec![],- };- assert_eq!(extracted_multi, vec![option_id_1, option_id_2]);-- // Test non-option value- let string_value = SetPropertyValue::String {- value: "test".to_string(),- };- let extracted_none = match string_value {- SetPropertyValue::SelectOption { option_id } => vec![option_id],- SetPropertyValue::MultiSelectOption { option_ids } => option_ids,- _ => vec![],- };- assert!(extracted_none.is_empty());- }-- #[test]- fn test_multi_select_option_deduplication() {- let option_id_1 = macro_uuid::generate_uuid_v7();- let option_id_2 = macro_uuid::generate_uuid_v7();- let option_id_3 = macro_uuid::generate_uuid_v7();-- // Test with duplicate option IDs- let multi_option_with_dupes = SetPropertyValue::MultiSelectOption {- option_ids: vec![- option_id_1,- option_id_2,- option_id_1, // Duplicate- option_id_3,- option_id_2, // Duplicate- ],- };-- let result = Some(- models_properties::convert_set_property_value_to_property_value(- &multi_option_with_dupes,- ),- );-- // Should have only 3 unique values- let Some(PropertyValue::SelectOption(option_ids)) = result else {- panic!("Expected SelectOption variant");- };- assert_eq!(option_ids.len(), 3);-- // Verify all unique IDs are present- let result_option_ids: HashSet<Uuid> = option_ids.iter().copied().collect();- assert!(result_option_ids.contains(&option_id_1));- assert!(result_option_ids.contains(&option_id_2));- assert!(result_option_ids.contains(&option_id_3));- assert_eq!(result_option_ids.len(), 3);- }-- #[test]- fn test_multi_select_option_no_duplicates() {- let option_id_1 = macro_uuid::generate_uuid_v7();- let option_id_2 = macro_uuid::generate_uuid_v7();-- // Test with no duplicates- let multi_option = SetPropertyValue::MultiSelectOption {- option_ids: vec![option_id_1, option_id_2],- };-- let result =- Some(models_properties::convert_set_property_value_to_property_value(&multi_option));-- // Should have 2 values- let Some(PropertyValue::SelectOption(option_ids)) = result else {- panic!("Expected SelectOption variant");- };- assert_eq!(option_ids.len(), 2);-- let result_option_ids: HashSet<Uuid> = option_ids.iter().copied().collect();- assert!(result_option_ids.contains(&option_id_1));- assert!(result_option_ids.contains(&option_id_2));- }-- #[test]- fn test_multi_entity_reference_deduplication() {- use models_properties::EntityReference;-- let entity_ref_1 = EntityReference::new("doc-1", EntityType::Document);- let entity_ref_2 = EntityReference::new("user-1", EntityType::User);- let entity_ref_1_dup = EntityReference::new("doc-1", EntityType::Document); // Same as entity_ref_1-- // Test with duplicate entity references- let multi_entity_ref_with_dupes = SetPropertyValue::MultiEntityReference {- references: vec![- entity_ref_1.clone(),- entity_ref_2.clone(),- entity_ref_1_dup, // Duplicate- ],- };-- let result = Some(- models_properties::convert_set_property_value_to_property_value(- &multi_entity_ref_with_dupes,- ),- );-- // Should have only 2 unique values (duplicates removed)- let Some(PropertyValue::EntityRef(entity_refs)) = result else {- panic!("Expected EntityRef variant");- };- assert_eq!(entity_refs.len(), 2);-- // Verify the unique combinations are present- let has_doc_1 = entity_refs- .iter()- .any(|r| r.entity_type == EntityType::Document && r.entity_id == "doc-1");- let has_user_1 = entity_refs- .iter()- .any(|r| r.entity_type == EntityType::User && r.entity_id == "user-1");-- assert!(has_doc_1);- assert!(has_user_1);- }-- #[test]- fn test_multi_entity_reference_different_types_same_id() {- use models_properties::EntityReference;-- // Test that same ID with different entity types ARE considered duplicates- // (deduplicating by entity_id only, keeping first occurrence)- let entity_ref_1 = EntityReference::new("123", EntityType::Document);- let entity_ref_2 = EntityReference::new("123", EntityType::User); // Same ID but different type-- let multi_entity_ref = SetPropertyValue::MultiEntityReference {- references: vec![entity_ref_1, entity_ref_2],- };-- let result = Some(- models_properties::convert_set_property_value_to_property_value(&multi_entity_ref),- );-- // Should have 1 value (considered duplicates, keeps first occurrence)- let Some(PropertyValue::EntityRef(entity_refs)) = result else {- panic!("Expected EntityRef variant");- };- assert_eq!(entity_refs.len(), 1);- // Should keep the Document type (first occurrence)- assert_eq!(entity_refs[0].entity_type, EntityType::Document);- assert_eq!(entity_refs[0].entity_id, "123");- }-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/set_property_status_complete.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/set_property_status_complete.rsdeleted file mode 100644index a33675e90c..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/set_property_status_complete.rs+++ /dev/null@@ -1,85 +0,0 @@-//! Set entity status to complete endpoint.-//!-//! If the entity has the system status property attached, set it to "Completed".-//! If not attached, this is a no-op (still returns 204).--use axum::{- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;--use crate::api::context::PropertiesHandlerState;-use crate::api::permissions::{PermissionError, check_entity_edit_permission};-use model::user::UserContext;-use models_properties::{EntityReference, EntityType};-use properties::PropertiesService;--#[derive(Debug, Error)]-pub enum SetPropertyStatusCompleteErr {- #[error("An internal error occurred")]- InternalError(String),- #[error("{0}")]- Permission(#[from] PermissionError),-}--impl IntoResponse for SetPropertyStatusCompleteErr {- fn into_response(self) -> Response {- let status_code = match &self {- SetPropertyStatusCompleteErr::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,- SetPropertyStatusCompleteErr::Permission(e) => e.status_code(),- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "SetPropertyStatusCompleteErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Set an entity's status property to "Completed".-///-/// If the entity has a status property attached, it will be set to "Completed".-/// If the entity does not have a status property, this is a no-op and returns success.-#[utoipa::path(- patch,- path = "/properties/entities/{entity_type}/{entity_id}/status/complete",- params(- ("entity_type" = EntityType, Path, description = "Entity type (document, channel, project, thread, chat)"),- ("entity_id" = String, Path, description = "Entity ID")- ),- responses(- (status = 204, description = "Status set to complete"),- (status = 403, description = "Access denied"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, user_context), fields(entity_id = %entity_id, entity_type = ?entity_type, user_id = %user_context.user_id), err)]-pub async fn set_property_status_complete(- Path((entity_type, entity_id)): Path<(EntityType, String)>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,-) -> Result<StatusCode, SetPropertyStatusCompleteErr> {- tracing::info!("setting entity status to complete");-- // Check edit permissions- let entity_ref = EntityReference::new(entity_id.clone(), entity_type);- check_entity_edit_permission(&state, &user_context.user_id, &entity_ref).await?;-- // Delegate to service layer for business logic- state- .properties_service- .set_system_property_status_complete(&entity_id, entity_type)- .await- .map_err(|e| SetPropertyStatusCompleteErr::InternalError(e.to_string()))?;-- tracing::debug!("status complete handled");- Ok(StatusCode::NO_CONTENT)-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/types.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/types.rsdeleted file mode 100644index 30959e24cf..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/entities/types.rs+++ /dev/null@@ -1,55 +0,0 @@-use serde::{Deserialize, Serialize};-use utoipa::ToSchema;-use uuid::Uuid;--use models_properties::EntityReference;-use models_properties::api::SetPropertyValue;-use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;-use models_properties::{DataType, PropertyOwner};--// Re-export EntityQueryParams from models_properties for convenience-pub use models_properties::api::EntityQueryParams;--/// Response for document/entity properties endpoint.-#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct EntityPropertiesResponse {- pub entity_id: String,- pub properties: Vec<EntityPropertyWithDefinition>,-}--/// Type-safe request for setting entity property values.-#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct SetEntityPropertyRequest {- /// The value to set for the property. If None, the property is attached to the entity without a value.- #[serde(default)]- pub value: Option<SetPropertyValue>,-}--/// Request for getting properties for multiple entities in bulk-#[derive(Debug, Serialize, Deserialize, ToSchema)]-pub struct BulkEntityPropertiesRequest {- /// Array of entity references (entity_id and entity_type pairs)- pub entities: Vec<EntityReference>,- /// Optional: only return properties with these definition IDs. If empty, returns all.- #[serde(default)]- pub property_ids: Vec<Uuid>,-}--/// Drops tag-typed properties the caller may not see. A user-owned tag set (personal labels)-/// is visible only to its owner, so personal tags stay private even on a shared entity.-/// Team- and system-owned tags are the shared vocabulary and are left in place. Non-tag-/// properties are unaffected.-pub fn retain_caller_visible_tags(- properties: &mut Vec<EntityPropertyWithDefinition>,- caller_user_id: &str,-) {- properties.retain(|property| {- if property.definition.data_type != DataType::Tag {- return true;- }- match &property.definition.owner {- PropertyOwner::User { user_id } => user_id == caller_user_id,- PropertyOwner::Team { .. } | PropertyOwner::System => true,- }- });-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/mod.rsdeleted file mode 100644index 17143f9224..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/mod.rs+++ /dev/null@@ -1,84 +0,0 @@-use crate::api::context::PropertiesHandlerState;-use axum::{- Router,- routing::{delete, get, patch, post, put},-};--pub mod definitions;-pub mod entities;-pub mod metadata;-pub mod options;-pub mod tags;--/// Creates the properties router. Works with any state type that implements `FromRef<PropertiesHandlerState>`.-pub fn router() -> Router<PropertiesHandlerState> {- let ensure_user_exists =- axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler);-- Router::new()- // Property Definition Management - requires authentication- .route(- "/definitions",- get(definitions::list::list_properties)- .post(definitions::create::create_property_definition)- .layer(ensure_user_exists.clone()),- )- .route(- "/definitions/{definition_id}",- delete(definitions::delete::delete_property_definition)- .layer(ensure_user_exists.clone()),- )- // Property Options Management - requires authentication- .route(- "/definitions/{definition_id}/options",- get(options::get::get_property_options)- .post(options::create::add_property_option)- .layer(ensure_user_exists.clone()),- )- .route(- "/definitions/{definition_id}/options/{option_id}",- delete(options::delete::delete_property_option)- .patch(options::update::update_property_option)- .layer(ensure_user_exists.clone()),- )- .route(- "/tags",- get(tags::list_tags)- .post(tags::ensure_tag_set)- .layer(ensure_user_exists.clone()),- )- // Entity Property Operations- // GET allows anonymous access for public entities- .route(- "/entities/{entity_type}/{entity_id}",- get(entities::get::get_entity_properties),- )- // Bulk entity properties - requires authentication- .route(- "/entities/bulk",- post(entities::get_bulk::get_bulk_entity_properties).layer(ensure_user_exists.clone()),- )- // PUT/DELETE require authentication- .route(- "/entities/{entity_type}/{entity_id}/{property_id}",- put(entities::set::set_entity_property).layer(ensure_user_exists.clone()),- )- // Atomic single-option delta on a multi-select value (merges concurrent edits)- .route(- "/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",- post(entities::option::add_entity_property_option)- .delete(entities::option::remove_entity_property_option)- .layer(ensure_user_exists.clone()),- )- .route(- "/entity_properties/{entity_property_id}",- delete(entities::delete_property::delete_entity_property)- .layer(ensure_user_exists.clone()),- )- // Status shortcut - requires authentication- .route(- "/entities/{entity_type}/{entity_id}/status/complete",- patch(entities::set_property_status_complete::set_property_status_complete)- .layer(ensure_user_exists),- )-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/options/create.rs b/rust/cloud-storage/properties_service/src/api/properties/options/create.rsdeleted file mode 100644index 3b27843612..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/options/create.rs+++ /dev/null@@ -1,185 +0,0 @@-use axum::{- Json,- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;-use uuid::Uuid;--use crate::api::context::{PropertiesHandlerState, PropertyTeamExtractor, caller_team_id};-use model::user::UserContext;-use models_properties::api::AddPropertyOptionRequest;-use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};-use properties_db_client::{- error::PropertiesDatabaseError, property_definitions::get as property_definitions_get,- property_options::insert as property_options_insert,-};--#[derive(Debug, Error)]-pub enum AddPropertyOptionErr {- #[error("An internal error occurred")]- InternalError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),- #[error("Property definition not found")]- PropertyNotFound,- #[error("Cannot modify system properties")]- SystemPropertyNotModifiable,- #[error("{0}")]- InvalidRequest(String),-}--impl IntoResponse for AddPropertyOptionErr {- fn into_response(self) -> Response {- let status_code = match &self {- AddPropertyOptionErr::InternalError(_) | AddPropertyOptionErr::DatabaseError(_) => {- StatusCode::INTERNAL_SERVER_ERROR- }- AddPropertyOptionErr::PropertyNotFound => StatusCode::NOT_FOUND,- AddPropertyOptionErr::SystemPropertyNotModifiable => StatusCode::FORBIDDEN,- AddPropertyOptionErr::InvalidRequest(_) => StatusCode::BAD_REQUEST,- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "AddPropertyOptionErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Add a new option to a property dropdown-#[utoipa::path(- post,- path = "/properties/definitions/{definition_id}/options",- params(- ("definition_id" = Uuid, Path, description = "Property definition ID")- ),- request_body = AddPropertyOptionRequest,- responses(- (status = 201, description = "Property option created successfully", body = PropertyOption),- (status = 400, description = "Invalid request"),- (status = 403, description = "Cannot modify system properties"),- (status = 404, description = "Property not found"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, user_context, team), fields(property_id = %property_uuid, request = ?request), err)]-pub async fn add_property_option(- Path(property_uuid): Path<Uuid>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,- Json(request): Json<AddPropertyOptionRequest>,-) -> Result<(StatusCode, Json<PropertyOption>), AddPropertyOptionErr> {- tracing::info!("adding property option");-- // First check if property exists and if it's a system property- let property = property_definitions_get::get_property_definition(&state.db, property_uuid)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to fetch property definition"- );- })?- .ok_or(AddPropertyOptionErr::PropertyNotFound)?;-- if property.is_system {- return Err(AddPropertyOptionErr::SystemPropertyNotModifiable);- }-- // Then verify ownership- let property_definition = property_definitions_get::get_property_definition_with_owner(- &state.db,- property_uuid,- &user_context.user_id,- caller_team_id(&team),- )- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to fetch property definition with owner"- );- })?- .ok_or(AddPropertyOptionErr::PropertyNotFound)?;-- if let Err(err) = request.validate() {- tracing::error!(- error = %err,- "option value validation failed"- );- return Err(AddPropertyOptionErr::InvalidRequest(err.to_string()));- }-- if let Err(err) = request.validate_compatibility(&property_definition.data_type) {- tracing::error!(- data_type = ?property_definition.data_type,- request_type = ?request,- error = %err,- "request type doesn't match property data type"- );- return Err(AddPropertyOptionErr::InvalidRequest(err.to_string()));- }-- let (display_order, option_value, color) = match &request {- AddPropertyOptionRequest::SelectString { option } => (- option.display_order,- PropertyOptionValue::String(option.value.clone()),- option.color.clone(),- ),- AddPropertyOptionRequest::SelectNumber { option } => (- option.display_order,- PropertyOptionValue::Number(option.value),- None,- ),- };-- if color.is_some() && property_definition.data_type != models_properties::DataType::Tag {- return Err(AddPropertyOptionErr::InvalidRequest(- "color is only supported on tag options".to_string(),- ));- }- if let Some(color) = &color- && !models_properties::api::is_valid_hex_color(color)- {- return Err(AddPropertyOptionErr::InvalidRequest(- "color must be a hex string like #RRGGBB".to_string(),- ));- }- if property_definition.data_type == models_properties::DataType::Tag && color.is_none() {- return Err(AddPropertyOptionErr::InvalidRequest(- "tag options require a color".to_string(),- ));- }-- let option = property_options_insert::create_property_option(- &state.db,- property_uuid,- display_order,- option_value,- color,- )- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to add property option"- );- })?;-- tracing::info!(- option_id = %option.id,- display_order = option.display_order,- "successfully added property option"- );-- Ok((StatusCode::CREATED, Json(option)))-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/options/delete.rs b/rust/cloud-storage/properties_service/src/api/properties/options/delete.rsdeleted file mode 100644index 5aba54d7f1..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/options/delete.rs+++ /dev/null@@ -1,140 +0,0 @@-use axum::{- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;-use uuid::Uuid;--use crate::api::context::{PropertiesHandlerState, PropertyTeamExtractor, caller_team_id};-use model::user::UserContext;-use properties_db_client::{- error::PropertiesDatabaseError,- property_definitions::get as property_definitions_get,- property_options::{delete as property_options_delete, get as property_options_get},-};--#[derive(Debug, Error)]-pub enum DeletePropertyOptionErr {- #[error("An internal error occurred")]- InternalError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),- #[error("Property definition not found")]- PropertyNotFound,- #[error("Cannot modify system properties")]- SystemPropertyNotModifiable,- #[error("Property option not found")]- OptionNotFound,-}--impl IntoResponse for DeletePropertyOptionErr {- fn into_response(self) -> Response {- let status_code = match &self {- DeletePropertyOptionErr::InternalError(_)- | DeletePropertyOptionErr::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,- DeletePropertyOptionErr::PropertyNotFound | DeletePropertyOptionErr::OptionNotFound => {- StatusCode::NOT_FOUND- }- DeletePropertyOptionErr::SystemPropertyNotModifiable => StatusCode::FORBIDDEN,- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "DeletePropertyOptionErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Delete a property option-#[utoipa::path(- delete,- path = "/properties/definitions/{definition_id}/options/{option_id}",- params(- ("definition_id" = Uuid, Path, description = "Property definition ID"),- ("option_id" = Uuid, Path, description = "Property option ID")- ),- responses(- (status = 204, description = "Property option deleted successfully"),- (status = 400, description = "Invalid option ID"),- (status = 403, description = "Cannot modify system properties"),- (status = 404, description = "Property option not found"),- (status = 500, description = "Internal server error")- ),- tag = "Properties"-)]-#[tracing::instrument(skip(state, user_context, team), err)]-pub async fn delete_property_option(- Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,-) -> Result<StatusCode, DeletePropertyOptionErr> {- tracing::info!("deleting property option");-- // First check if property exists and if it's a system property- let property = property_definitions_get::get_property_definition(&state.db, def_uuid)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to fetch property definition"- );- })?- .ok_or(DeletePropertyOptionErr::PropertyNotFound)?;-- if property.is_system {- return Err(DeletePropertyOptionErr::SystemPropertyNotModifiable);- }-- // Then verify ownership- let _property_definition = property_definitions_get::get_property_definition_with_owner(- &state.db,- def_uuid,- &user_context.user_id,- caller_team_id(&team),- )- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to fetch property definition with owner"- );- })?- .ok_or(DeletePropertyOptionErr::PropertyNotFound)?;-- let option = property_options_get::get_property_option_by_id(&state.db, option_uuid)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to fetch property option"- );- })?- .ok_or(DeletePropertyOptionErr::OptionNotFound)?;-- if option.property_definition_id != def_uuid {- return Err(DeletePropertyOptionErr::OptionNotFound);- }-- let deleted = property_options_delete::delete_property_option(&state.db, def_uuid, option_uuid)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to delete property option"- );- })?;-- if deleted {- tracing::info!("successfully deleted property option");- Ok(StatusCode::NO_CONTENT)- } else {- Err(DeletePropertyOptionErr::OptionNotFound)- }-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/options/get.rs b/rust/cloud-storage/properties_service/src/api/properties/options/get.rsdeleted file mode 100644index a7dc25a517..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/options/get.rs+++ /dev/null@@ -1,82 +0,0 @@-use axum::{- Json,- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;-use uuid::Uuid;--use model::user::UserContext;-use models_properties::service::property_option::PropertyOption;-use properties_db_client::{- error::PropertiesDatabaseError, property_options::get as property_options_get,-};-use sqlx::PgPool;--#[derive(Debug, Error)]-pub enum GetPropertyOptionsErr {- #[error("An internal error occurred")]- Internal(#[from] anyhow::Error),- #[error("An internal error occurred")]- Database(#[from] PropertiesDatabaseError),-}--impl IntoResponse for GetPropertyOptionsErr {- fn into_response(self) -> Response {- let status_code = match &self {- GetPropertyOptionsErr::Internal(_) | GetPropertyOptionsErr::Database(_) => {- StatusCode::INTERNAL_SERVER_ERROR- }- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "GetPropertyOptionsErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Get all options for a property (for dropdowns)-#[utoipa::path(- get,- path = "/properties/definitions/{definition_id}/options",- params(- ("definition_id" = Uuid, Path, description = "Property definition ID")- ),- responses(- (status = 200, description = "Property options retrieved successfully", body = Vec<PropertyOption>),- (status = 404, description = "Property not found"),- (status = 500, description = "Internal server error")- ),- tag = "Properties"-)]-#[tracing::instrument(skip(db, _user_context), err)]-pub async fn get_property_options(- Path(property_uuid): Path<Uuid>,- State(db): State<PgPool>,- Extension(_user_context): Extension<UserContext>,-) -> Result<Json<Vec<PropertyOption>>, GetPropertyOptionsErr> {- tracing::info!("retrieving property options");-- let options = property_options_get::get_property_options(&db, property_uuid)- .await- .inspect_err(|e| {- tracing::error!(- error = ?e,- "failed to retrieve property options"- );- })?;-- tracing::info!(- options_count = options.len(),- "successfully retrieved property options"- );-- Ok(Json(options))-}diff --git a/rust/cloud-storage/properties_service/src/api/properties/options/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/options/mod.rsdeleted file mode 100644index f4b0d33ab6..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/options/mod.rs+++ /dev/null@@ -1,4 +0,0 @@-pub mod create;-pub mod delete;-pub mod get;-pub mod update;diff --git a/rust/cloud-storage/properties_service/src/api/properties/options/update.rs b/rust/cloud-storage/properties_service/src/api/properties/options/update.rsdeleted file mode 100644index a104c73773..0000000000--- a/rust/cloud-storage/properties_service/src/api/properties/options/update.rs+++ /dev/null@@ -1,177 +0,0 @@-use axum::{- Json,- extract::{Extension, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use thiserror::Error;-use uuid::Uuid;--use crate::api::context::{PropertiesHandlerState, PropertyTeamExtractor, caller_team_id};-use model::user::UserContext;-use models_properties::DataType;-use models_properties::api::{UpdatePropertyOptionRequest, is_valid_hex_color};-use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};-use properties_db_client::{- error::PropertiesDatabaseError, property_definitions::get as property_definitions_get,- property_options::get as property_options_get,- property_options::update as property_options_update,-};--#[derive(Debug, Error)]-pub enum UpdatePropertyOptionErr {- #[error("An internal error occurred")]- InternalError(#[from] anyhow::Error),- #[error("An internal error occurred")]- DatabaseError(#[from] PropertiesDatabaseError),- #[error("Property definition not found")]- PropertyNotFound,- #[error("Cannot modify system properties")]- SystemPropertyNotModifiable,- #[error("Property option not found")]- OptionNotFound,- #[error("{0}")]- InvalidRequest(String),- #[error("An option with that value already exists")]- Conflict,-}--impl IntoResponse for UpdatePropertyOptionErr {- fn into_response(self) -> Response {- let status_code = match &self {- UpdatePropertyOptionErr::InternalError(_)- | UpdatePropertyOptionErr::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,- UpdatePropertyOptionErr::PropertyNotFound | UpdatePropertyOptionErr::OptionNotFound => {- StatusCode::NOT_FOUND- }- UpdatePropertyOptionErr::SystemPropertyNotModifiable => StatusCode::FORBIDDEN,- UpdatePropertyOptionErr::InvalidRequest(_) => StatusCode::BAD_REQUEST,- UpdatePropertyOptionErr::Conflict => StatusCode::CONFLICT,- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "UpdatePropertyOptionErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Update a property option in place (rename / recolor / reorder).-///-/// The option id is preserved, so the change is reflected on every entity that references it.-#[utoipa::path(- patch,- path = "/properties/definitions/{definition_id}/options/{option_id}",- params(- ("definition_id" = Uuid, Path, description = "Property definition ID"),- ("option_id" = Uuid, Path, description = "Property option ID")- ),- request_body = UpdatePropertyOptionRequest,- responses(- (status = 200, description = "Property option updated", body = PropertyOption),- (status = 400, description = "Invalid request"),- (status = 403, description = "Cannot modify system properties"),- (status = 404, description = "Property or option not found"),- (status = 409, description = "An option with that value already exists"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, user_context, team), fields(property_id = %def_uuid, option_id = %option_uuid, request = ?request), err)]-pub async fn update_property_option(- Path((def_uuid, option_uuid)): Path<(Uuid, Uuid)>,- State(state): State<PropertiesHandlerState>,- Extension(user_context): Extension<UserContext>,- team: PropertyTeamExtractor,- Json(request): Json<UpdatePropertyOptionRequest>,-) -> Result<(StatusCode, Json<PropertyOption>), UpdatePropertyOptionErr> {- let property = property_definitions_get::get_property_definition(&state.db, def_uuid)- .await?- .ok_or(UpdatePropertyOptionErr::PropertyNotFound)?;-- if property.is_system {- return Err(UpdatePropertyOptionErr::SystemPropertyNotModifiable);- }-- let definition = property_definitions_get::get_property_definition_with_owner(- &state.db,- def_uuid,- &user_context.user_id,- caller_team_id(&team),- )- .await?- .ok_or(UpdatePropertyOptionErr::PropertyNotFound)?;-- let option = property_options_get::get_property_option_by_id(&state.db, option_uuid)- .await?- .ok_or(UpdatePropertyOptionErr::OptionNotFound)?;-- if option.property_definition_id != def_uuid {- return Err(UpdatePropertyOptionErr::OptionNotFound);- }-- let new_value = match &request.value {- Some(value) => match definition.data_type {- DataType::SelectString | DataType::Tag => {- if value.trim().is_empty() {- return Err(UpdatePropertyOptionErr::InvalidRequest(- "value cannot be empty".to_string(),- ));- }- PropertyOptionValue::String(value.clone())- }- _ => {- return Err(UpdatePropertyOptionErr::InvalidRequest(- "value updates are only supported for string and tag options".to_string(),- ));- }- },- None => option.value.clone(),- };-- if request.color.is_some() && definition.data_type != DataType::Tag {- return Err(UpdatePropertyOptionErr::InvalidRequest(- "color is only supported on tag options".to_string(),- ));- }-- if let Some(color) = &request.color- && !is_valid_hex_color(color)- {- return Err(UpdatePropertyOptionErr::InvalidRequest(- "color must be a hex string like #RRGGBB".to_string(),- ));- }- let new_color = request.color.clone().or_else(|| option.color.clone());- if definition.data_type == DataType::Tag && new_color.is_none() {- return Err(UpdatePropertyOptionErr::InvalidRequest(- "tag options require a color".to_string(),- ));- }-- let new_display_order = request.display_order.unwrap_or(option.display_order);-- match property_options_update::update_property_option(- &state.db,- option_uuid,- new_value,- new_color,- new_display_order,- )- .await- {- Ok(Some(updated)) => Ok((StatusCode::OK, Json(updated))),- Ok(None) => Err(UpdatePropertyOptionErr::OptionNotFound),- Err(PropertiesDatabaseError::Query(sqlx::Error::Database(db_err)))- if db_err.is_unique_violation() =>- {- Err(UpdatePropertyOptionErr::Conflict)- }- Err(e) => Err(e.into()),- }-}diff --git a/rust/cloud-storage/properties_service/src/api/swagger.rs b/rust/cloud-storage/properties_service/src/api/swagger.rsindex 4b223ba141..8704e12683 100644--- a/rust/cloud-storage/properties_service/src/api/swagger.rs+++ b/rust/cloud-storage/properties_service/src/api/swagger.rs@@ -1,12 +1,12 @@-use crate::api::properties::{+use models_properties::api;+use properties::inbound::axum_router::{definitions::{ListPropertiesQuery, PropertyDefinitionResponse},entities::{- EntityPropertiesResponse, EntityQueryParams, SetEntityPropertyRequest,- types::BulkEntityPropertiesRequest,+ BulkEntityPropertiesRequest, EntityPropertiesResponse, EntityQueryParams,+ SetEntityPropertyRequest,},tags::{EnsureTagSetRequest, TagScope, TagSetResponse},};-use models_properties::api;use utoipa::OpenApi;#[derive(OpenApi)]@@ -16,23 +16,23 @@ use utoipa::OpenApi;),paths(// Property definitions- crate::api::properties::definitions::list::list_properties,- crate::api::properties::definitions::create::create_property_definition,- crate::api::properties::definitions::delete::delete_property_definition,+ properties::inbound::axum_router::definitions::list_properties,+ properties::inbound::axum_router::definitions::create_property_definition,+ properties::inbound::axum_router::definitions::delete_property_definition,// Property options- crate::api::properties::options::get::get_property_options,- crate::api::properties::options::create::add_property_option,- crate::api::properties::options::update::update_property_option,- crate::api::properties::options::delete::delete_property_option,- crate::api::properties::tags::list_tags,- crate::api::properties::tags::ensure_tag_set,+ properties::inbound::axum_router::options::get_property_options,+ properties::inbound::axum_router::options::add_property_option,+ properties::inbound::axum_router::options::update_property_option,+ properties::inbound::axum_router::options::delete_property_option,+ properties::inbound::axum_router::tags::list_tags,+ properties::inbound::axum_router::tags::ensure_tag_set,// Entity properties- crate::api::properties::entities::get::get_entity_properties,- crate::api::properties::entities::get_bulk::get_bulk_entity_properties,- crate::api::properties::entities::set::set_entity_property,- crate::api::properties::entities::option::add_entity_property_option,- crate::api::properties::entities::option::remove_entity_property_option,- crate::api::properties::entities::delete_property::delete_entity_property,+ properties::inbound::axum_router::entities::get_entity_properties,+ properties::inbound::axum_router::entities::get_bulk_entity_properties,+ properties::inbound::axum_router::entities::set_entity_property,+ properties::inbound::axum_router::entities::add_entity_property_option,+ properties::inbound::axum_router::entities::remove_entity_property_option,+ properties::inbound::axum_router::entities::delete_entity_property,),components(schemas(diff --git a/rust/cloud-storage/properties_service/src/constants.rs b/rust/cloud-storage/properties_service/src/constants.rsdeleted file mode 100644index bce44313d0..0000000000--- a/rust/cloud-storage/properties_service/src/constants.rs+++ /dev/null@@ -1,28 +0,0 @@-use uuid::Uuid;--/// Metadata property display names-pub mod metadata {- // Common (shared across entity types)- pub const OWNER: &str = "Owner";- pub const CREATED_AT: &str = "Created At";- pub const LAST_UPDATED: &str = "Last Updated";-- // Document metadata- pub const DOCUMENT_NAME: &str = "Document Name";- pub const DOCUMENT_PROJECT: &str = "Project";-- // Thread metadata- pub const THREAD_SUBJECT: &str = "Subject";- pub const THREAD_STARTED: &str = "Thread Started";- pub const THREAD_LAST_RECEIVED: &str = "Last Received";- pub const THREAD_LAST_SENT: &str = "Last Sent";- pub const THREAD_MESSAGES: &str = "Messages";-- // Project metadata- pub const PROJECT_NAME: &str = "Project Name";- pub const PROJECT_PARENT: &str = "Parent Project";-}--/// Special UUID used for system-generated metadata properties.-/// This distinguishes metadata properties from user-created properties.-pub const METADATA_PROPERTY_ID: Uuid = Uuid::from_u128(0xFFFFFFFF_FFFF_FFFF_FFFF_FFFFFFFFFFFF);diff --git a/rust/cloud-storage/properties_service/src/lib.rs b/rust/cloud-storage/properties_service/src/lib.rsindex a982b6b4a4..0314d3162e 100644--- a/rust/cloud-storage/properties_service/src/lib.rs+++ b/rust/cloud-storage/properties_service/src/lib.rs@@ -1,11 +1,14 @@//! Properties Service Library - exposes API routes for integration into other services+//!+//! The routes themselves live in `properties::inbound::axum_router`; this crate+//! is the composition shim binding them to the concrete service types and the+//! service's authentication middleware.pub mod api;-pub mod constants;// Re-exports for consumerspub use api::context::EntityAccessServiceType;pub use api::context::PropertiesHandlerState;pub use api::context::PropertiesService;-pub use api::properties::router as properties_router;+pub use api::router as properties_router;pub use api::swagger::ApiDoc as PropertiesApiDoc;diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.tomlindex 034f81198f..ac41e203db 100644--- a/rust/cloud-storage/search_processing_service/Cargo.toml+++ b/rust/cloud-storage/search_processing_service/Cargo.toml@@ -8,7 +8,7 @@ version = "0.1.0"[features]default = ["processing", "service", "pdf"]processing = []-service = ["macro_db_client", "models_properties", "properties_db_client"]+service = ["macro_db_client", "models_properties", "properties"]pdf = ["dep:pdfium-render"][[bin]]@@ -60,7 +60,9 @@ nom = { workspace = true }opensearch_client = { path = "../opensearch_client" }ensure_exists = { path = "../ensure_exists", features = ["dynamodb"] }pdfium-render = { workspace = true, optional = true }-properties_db_client = { path = "../properties_db_client", optional = true }+properties = { path = "../properties", default-features = false, features = [+ "outbound",+], optional = true }rust-embed = "8.6.0"s3_client = { path = "../s3_client" }secretsmanager_client = { path = "../secretsmanager_client" }diff --git a/rust/cloud-storage/search_processing_service/src/outbound/source.rs b/rust/cloud-storage/search_processing_service/src/outbound/source.rsindex 981d3b43dc..50d960ef91 100644--- a/rust/cloud-storage/search_processing_service/src/outbound/source.rs+++ b/rust/cloud-storage/search_processing_service/src/outbound/source.rs@@ -344,14 +344,14 @@ impl BackfillSource for PgBackfillSource {.map_err(|e| BackfillError::Source(anyhow::Error::new(e)))?;let entity_ids =- properties_db_client::entity_properties::get::get_entity_ids_with_properties(+ properties::outbound::entity_properties_get_query::get_entity_ids_with_properties(&self.db,entity_type,PROPERTIES_PAGE_SIZE as i64,offset as i64,).await- .map_err(|e| BackfillError::Source(e.into()))?;+ .map_err(BackfillError::Source)?;let rows_consumed = entity_ids.len();let messages: Vec<SearchQueueMessage> = entity_idsdiff --git a/rust/cloud-storage/search_processing_service/src/process/chat.rs b/rust/cloud-storage/search_processing_service/src/process/chat.rsindex 797d5c26c8..5edaeaafbf 100644--- a/rust/cloud-storage/search_processing_service/src/process/chat.rs+++ b/rust/cloud-storage/search_processing_service/src/process/chat.rs@@ -3,7 +3,7 @@ use models_properties::EntityType;use opensearch_client::{OpensearchClient, date_format::EpochSeconds, upsert::chat_message::UpsertChatMessageArgs,};-use properties_db_client::entity_properties::get::get_entity_properties_for_index;+use properties::outbound::entity_properties_get_query::get_entity_properties_for_index;use sqs_client::search::chat::{ChatMessage, RemoveChatMessage};use crate::process::properties::to_indexed_properties;diff --git a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rsindex a84f3abc2c..dff92b3b6f 100644--- a/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs+++ b/rust/cloud-storage/search_processing_service/src/process/document/raw_document.rs@@ -10,7 +10,7 @@ use models_search::unified::is_searchable_association;use opensearch_client::{OpensearchClient, date_format::EpochSeconds, upsert::document::UpsertDocumentArgs,};-use properties_db_client::entity_properties::get::get_entity_properties_for_index;+use properties::outbound::entity_properties_get_query::get_entity_properties_for_index;use s3_key::{CONVERTED_DOCUMENT_FILE_NAME, build_cloud_storage_bucket_document_key,build_docx_to_pdf_converted_document_key,diff --git a/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs b/rust/cloud-storage/search_processing_service/src/process/email/upsert.rsindex 816fe820f1..bb5b19cb9c 100644--- a/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs+++ b/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs@@ -5,7 +5,7 @@ use models_properties::EntityType;use opensearch_client::{OpensearchClient, date_format::EpochSeconds, upsert::email::UpsertEmailArgs,};-use properties_db_client::entity_properties::get::{+use properties::outbound::entity_properties_get_query::{get_entity_properties_for_index, get_entity_properties_for_index_batch,};use sqlx::PgPool;diff --git a/rust/cloud-storage/search_processing_service/src/process/project.rs b/rust/cloud-storage/search_processing_service/src/process/project.rsindex 708a919caf..07b3aba966 100644--- a/rust/cloud-storage/search_processing_service/src/process/project.rs+++ b/rust/cloud-storage/search_processing_service/src/process/project.rs@@ -5,7 +5,7 @@ use opensearch_client::{date_format::EpochSeconds,upsert::{project::UpsertProjectArgs, properties::IndexedProperty},};-use properties_db_client::entity_properties::get::get_entity_properties_for_index;+use properties::outbound::entity_properties_get_query::get_entity_properties_for_index;use sqs_client::search::project::{RemoveProject, UpsertProject};/// Fetch the project's indexed properties, flattened for the search index.diff --git a/rust/cloud-storage/search_processing_service/src/process/properties.rs b/rust/cloud-storage/search_processing_service/src/process/properties.rsindex 424baf16e0..a49c0d4c34 100644--- a/rust/cloud-storage/search_processing_service/src/process/properties.rs+++ b/rust/cloud-storage/search_processing_service/src/process/properties.rs@@ -3,7 +3,7 @@ use std::str::FromStr;use anyhow::Context;use models_properties::EntityType;use opensearch_client::{OpensearchClient, upsert::properties::IndexedProperty};-use properties_db_client::entity_properties::get::{+use properties::outbound::entity_properties_get_query::{IndexedEntityProperty, get_entity_properties_for_index,};use sqs_client::search::document::DocumentPropertiesUpdate;diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.tomlindex be01c51c2b..7104855a03 100644--- a/rust/cloud-storage/search_service/Cargo.toml+++ b/rust/cloud-storage/search_service/Cargo.toml@@ -34,7 +34,9 @@ macro_auth = { path = "../macro_auth" }macro_db_client = { path = "../macro_db_client" }models_properties = { path = "../models_properties" }models_soup = { path = "../models_soup" }-properties_db_client = { path = "../properties_db_client" }+properties = { path = "../properties", default-features = false, features = [+ "outbound",+] }readonly_pool = { path = "../readonly_pool" }macro_env = { path = "../macro_env" }macro_env_var = { path = "../macro_env_var" }diff --git a/rust/cloud-storage/search_service/src/api/search/chat.rs b/rust/cloud-storage/search_service/src/api/search/chat.rsindex 995edf1028..8be01015a2 100644--- a/rust/cloud-storage/search_service/src/api/search/chat.rs+++ b/rust/cloud-storage/search_service/src/api/search/chat.rs@@ -41,7 +41,7 @@ pub(in crate::api::search) async fn enrich_chats(.map(|id| EntityReference::new(id.to_string(), EntityType::Chat)).collect();let properties_map: HashMap<String, Vec<SoupProperty>> =- properties_db_client::entity_properties::get::get_bulk_entity_properties_values(+ properties::outbound::entity_properties_get_query::get_bulk_entity_properties_values(&ctx.db,&chat_entity_refs,)diff --git a/rust/cloud-storage/search_service/src/api/search/document.rs b/rust/cloud-storage/search_service/src/api/search/document.rsindex afa0706ba7..a2e7483dc2 100644--- a/rust/cloud-storage/search_service/src/api/search/document.rs+++ b/rust/cloud-storage/search_service/src/api/search/document.rs@@ -55,7 +55,7 @@ pub(in crate::api::search) async fn enrich_documents(.collect();let properties_map = if !entity_refs.is_empty() {- properties_db_client::entity_properties::get::get_bulk_entity_properties_values(+ properties::outbound::entity_properties_get_query::get_bulk_entity_properties_values(&ctx.db,&entity_refs,)diff --git a/rust/cloud-storage/search_service/src/api/search/email.rs b/rust/cloud-storage/search_service/src/api/search/email.rsindex 9dfc225bbd..6e29b4f25c 100644--- a/rust/cloud-storage/search_service/src/api/search/email.rs+++ b/rust/cloud-storage/search_service/src/api/search/email.rs@@ -80,7 +80,7 @@ pub(in crate::api::search) async fn enrich_emails(.map(|id| EntityReference::new(id.to_string(), EntityType::Thread)).collect();let properties_map: HashMap<String, Vec<SoupProperty>> =- properties_db_client::entity_properties::get::get_bulk_entity_properties_values(+ properties::outbound::entity_properties_get_query::get_bulk_entity_properties_values(&ctx.db,&thread_entity_refs,)diff --git a/rust/cloud-storage/search_service/src/api/search/project.rs b/rust/cloud-storage/search_service/src/api/search/project.rsindex 0a8ecdb752..7783ebbeca 100644--- a/rust/cloud-storage/search_service/src/api/search/project.rs+++ b/rust/cloud-storage/search_service/src/api/search/project.rs@@ -45,7 +45,7 @@ pub(in crate::api::search) async fn enrich_projects(.map(|id| EntityReference::new(id.to_string(), EntityType::Project)).collect();let properties_map: HashMap<String, Vec<SoupProperty>> =- properties_db_client::entity_properties::get::get_bulk_entity_properties_values(+ properties::outbound::entity_properties_get_query::get_bulk_entity_properties_values(&ctx.db,&project_entity_refs,)diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex 31fbca4da8..47754af32c 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -32,7 +32,14 @@ axum = ["models_soup/schema",]inbound = ["email/inbound", "entity_access/inbound", "ports"]-outbound = ["crm/outbound", "dep:readonly_pool", "dep:sqlx", "ports"]+outbound = [+ "crm/outbound",+ "dep:properties",+ "dep:readonly_pool",+ "dep:sqlx",+ "ports",+ "properties/outbound",+]ports = ["crm/ports", "dep:tokio", "frecency/ports"]@@ -65,7 +72,7 @@ models_pagination = { path = "../models_pagination" }models_properties = { path = "../models_properties" }models_soup = { path = "../models_soup" }non_empty = { path = "../non_empty" }-properties_db_client = { path = "../properties_db_client/" }+properties = { path = "../properties", default-features = false, optional = true }readonly_pool = { path = "../readonly_pool", optional = true }recursion = { workspace = true }rootcause = { workspace = true }diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rsindex 000d73cc00..7de486e43b 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs@@ -188,14 +188,14 @@ pub(crate) async fn populate_properties(let property_ids = SystemPropertyKey::all_system_property_keys();let properties_map =- properties_db_client::entity_properties::get::get_bulk_entity_properties_values_filtered(+ properties::outbound::entity_properties_get_query::get_bulk_entity_properties_values_filtered(db,&entity_refs,property_ids,- Some(user_id.as_ref()),+ Some(&user_id),).await- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?;+ .map_err(|e| sqlx::Error::Decode(e.into()))?;// `items` may repeat an id (one row per group it belongs to), so use// `.get()` not `.remove()` — every occurrence needs the props.