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
add [properties-be] - properties crate set_entity_property (#749)
Daniel Kweon45850f27ef57
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 01885686d8..b1dd7f3fb0 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -5615,6 +5615,7 @@ dependencies = ["sqlx","strum","thiserror 2.0.17",+ "tracing","utoipa","uuid",]@@ -6589,13 +6590,18 @@ name = "properties"version = "0.1.0"dependencies = ["anyhow",+ "comms_service_client",+ "email_db_client","macro_db_migrator",+ "macro_middleware","macro_uuid","mockall",+ "models_permissions","models_properties","serde_json","sqlx","system_properties",+ "thiserror 2.0.17","tokio","tracing","uuid",diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 537582d216..88e241f200 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -8,7 +8,7 @@ use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::Fuse macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_env_var::env_var;use macro_redis_cluster_client::Redis;-use properties::{PropertiesPgRepo, PropertiesServiceImpl};+use properties::{PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl};use soup::{domain::service::SoupImpl, inbound::axum_router::SoupRouterState,outbound::pg_soup_repo::PgSoupRepo,@@ -33,7 +33,7 @@ type DssSoupState = SoupRouterState<>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;-type PropertiesService = PropertiesServiceImpl<PropertiesPgRepo>;+type PropertiesService = PropertiesServiceImpl<PropertiesPgRepo, PermissionServiceImpl>;#[derive(Clone, FromRef)]pub(crate) struct ApiContext {diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex d5efec44a7..c36d0eff40 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -16,7 +16,7 @@ use macro_entrypoint::MacroEntrypoint;use macro_env_var::env_var;use macro_middleware::auth::internal_access::InternalApiSecretKey;use macro_redis_cluster_client::Redis;-use properties::{PropertiesPgRepo, PropertiesServiceImpl};+use properties::{PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl};use secretsmanager_client::SecretManager;use soup::{domain::service::SoupImpl, inbound::axum_router::SoupRouterState,@@ -188,7 +188,15 @@ async fn main() -> anyhow::Result<()> {EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());let system_properties_service =SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));- let properties_service = PropertiesServiceImpl::new(PropertiesPgRepo::new(db.clone()));+ let permission_checker = PermissionServiceImpl::new(+ db.clone(),+ CommsServiceClient::new(+ dss_auth_key.as_ref().to_string(),+ config.vars.comms_service_url.as_ref().to_string(),+ ),+ );+ let properties_service =+ PropertiesServiceImpl::new(PropertiesPgRepo::new(db.clone()), Some(permission_checker));let api_context = ApiContext {soup_router_state: SoupRouterState::new(SoupImpl::new(diff --git a/rust/cloud-storage/models_properties/Cargo.toml b/rust/cloud-storage/models_properties/Cargo.tomlindex badbcec1e5..ca8e62716d 100644--- a/rust/cloud-storage/models_properties/Cargo.toml+++ b/rust/cloud-storage/models_properties/Cargo.toml@@ -13,5 +13,6 @@ serde_with = { workspace = true }sqlx = { workspace = true }strum = { workspace = true }thiserror = { workspace = true }+tracing = { workspace = true }utoipa = { workspace = true }uuid = { workspace = true }diff --git a/rust/cloud-storage/models_properties/src/lib.rs b/rust/cloud-storage/models_properties/src/lib.rsindex 312ed744b2..87c52df62c 100644--- a/rust/cloud-storage/models_properties/src/lib.rs+++ b/rust/cloud-storage/models_properties/src/lib.rs@@ -14,3 +14,6 @@ pub mod shared;// Re-export commonly used shared types for conveniencepub use shared::{DataType, EntityPropertyReference, EntityReference, EntityType, PropertyOwner};++// Re-export conversion function+pub use service::property_value::convert_set_property_value_to_property_value;diff --git a/rust/cloud-storage/models_properties/src/service/property_value.rs b/rust/cloud-storage/models_properties/src/service/property_value.rsindex 5b53c95a47..70125a17ae 100644--- a/rust/cloud-storage/models_properties/src/service/property_value.rs+++ b/rust/cloud-storage/models_properties/src/service/property_value.rs@@ -1,9 +1,13 @@//! Service layer property value model.+use std::collections::HashSet;+use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};+use tracing;use uuid::Uuid;+use crate::api::requests::SetPropertyValue;use crate::shared::EntityReference;/// Property value (service representation).@@ -72,3 +76,93 @@ impl From<crate::api::PropertyValue> for PropertyValue {}}}++/// Convert SetPropertyValue (API request format) to PropertyValue (storage format).+///+/// This function handles the conversion from the API's single/multi variants+/// to the storage format's array-based representation, including deduplication+/// for multi-value types.+pub fn convert_set_property_value_to_property_value(value: &SetPropertyValue) -> PropertyValue {+ match value {+ // Single primitive values+ SetPropertyValue::Boolean { value } => PropertyValue::Bool(*value),+ SetPropertyValue::Date { value } => PropertyValue::Date(*value),+ SetPropertyValue::Number { value } => PropertyValue::Num(*value),+ SetPropertyValue::String { value } => PropertyValue::Str(value.clone()),++ // Single select option+ SetPropertyValue::SelectOption { option_id } => {+ PropertyValue::SelectOption(vec![*option_id])+ }++ // Multi-select options+ SetPropertyValue::MultiSelectOption { option_ids } => {+ let original_count = option_ids.len();+ let unique_ids: HashSet<Uuid> = option_ids.iter().copied().collect();++ if unique_ids.len() < original_count {+ tracing::warn!(+ original_count = original_count,+ unique_count = unique_ids.len(),+ "Duplicate option IDs detected in MultiSelectOption, deduplicating"+ );+ }++ PropertyValue::SelectOption(unique_ids.into_iter().collect())+ }++ // Single entity reference+ SetPropertyValue::EntityReference { reference } => {+ PropertyValue::EntityRef(vec![EntityReference {+ entity_type: reference.entity_type,+ entity_id: reference.entity_id.clone(),+ specific_message_id: reference.specific_message_id,+ }])+ }++ // Multi-entity references+ SetPropertyValue::MultiEntityReference { references } => {+ let original_count = references.len();++ let mut seen_ids: HashSet<String> = HashSet::new();+ let unique_refs: Vec<EntityReference> = references+ .iter()+ .filter(|ref_| seen_ids.insert(ref_.entity_id.clone()))+ .map(|ref_| EntityReference {+ entity_type: ref_.entity_type,+ entity_id: ref_.entity_id.clone(),+ specific_message_id: ref_.specific_message_id,+ })+ .collect();++ if unique_refs.len() < original_count {+ tracing::warn!(+ original_count = original_count,+ unique_count = unique_refs.len(),+ "Duplicate entity references detected in MultiEntityReference, deduplicating by entity_id"+ );+ }++ PropertyValue::EntityRef(unique_refs)+ }++ // Single link+ SetPropertyValue::Link { url } => PropertyValue::Link(vec![url.clone()]),++ // Multi-link+ SetPropertyValue::MultiLink { urls } => {+ let original_count = urls.len();+ let unique_urls: HashSet<String> = urls.iter().cloned().collect();++ if unique_urls.len() < original_count {+ tracing::warn!(+ original_count = original_count,+ unique_count = unique_urls.len(),+ "Duplicate URLs detected in MultiLink, deduplicating"+ );+ }++ PropertyValue::Link(unique_urls.into_iter().collect())+ }+ }+}diff --git a/rust/cloud-storage/properties/.sqlx/query-732141210551d42218ce027266c6dfa3dd1f0ddb2c37493ed1235fe488073d89.json b/rust/cloud-storage/properties/.sqlx/query-732141210551d42218ce027266c6dfa3dd1f0ddb2c37493ed1235fe488073d89.jsonnew file mode 100644index 0000000000..ea49b9c1cd--- /dev/null+++ b/rust/cloud-storage/properties/.sqlx/query-732141210551d42218ce027266c6dfa3dd1f0ddb2c37493ed1235fe488073d89.json@@ -0,0 +1,108 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \n id,\n organization_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": "organization_id",+ "type_info": "Int4"+ },+ {+ "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"+ ]+ }+ }+ }+ },+ {+ "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": "732141210551d42218ce027266c6dfa3dd1f0ddb2c37493ed1235fe488073d89"+}diff --git a/rust/cloud-storage/properties/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.json b/rust/cloud-storage/properties/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.jsonnew file mode 100644index 0000000000..a33e79f60e--- /dev/null+++ b/rust/cloud-storage/properties/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.json@@ -0,0 +1,34 @@+{+ "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/Cargo.toml b/rust/cloud-storage/properties/Cargo.tomlindex 0346b25a0b..43a9667341 100644--- a/rust/cloud-storage/properties/Cargo.toml+++ b/rust/cloud-storage/properties/Cargo.toml@@ -6,11 +6,16 @@ version = "0.1.0"[dependencies]anyhow = { workspace = true }+comms_service_client = { path = "../comms_service_client" }+email_db_client = { path = "../email_db_client" }+macro_middleware = { path = "../macro_middleware", default-features = false, features = ["cloud_storage", "user_permissions"] }macro_uuid = { path = "../macro_uuid" }+models_permissions = { path = "../models_permissions" }models_properties = { path = "../models_properties" }serde_json = { workspace = true }sqlx = { workspace = true }system_properties = { path = "../system_properties" }+thiserror = { workspace = true }tracing = { workspace = true }uuid = { workspace = true }diff --git a/rust/cloud-storage/properties/src/domain.rs b/rust/cloud-storage/properties/src/domain.rsindex 6b5ed36281..9094ac7e03 100644--- a/rust/cloud-storage/properties/src/domain.rs+++ b/rust/cloud-storage/properties/src/domain.rs@@ -1,3 +1,4 @@+pub mod error;pub mod ports;pub mod service;pub mod service_impl;diff --git a/rust/cloud-storage/properties/src/domain/error.rs b/rust/cloud-storage/properties/src/domain/error.rsnew file mode 100644index 0000000000..84451dec16--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/error.rs@@ -0,0 +1,19 @@+//! Domain error types for properties.++use thiserror::Error;++/// Domain error type for property operations.+#[derive(Debug, Error)]+pub enum PropertiesErr {+ /// Validation errors (includes property not found) - maps to 400+ #[error("{0}")]+ Validation(String),++ /// Permission denied - maps to 403+ #[error("Access denied")]+ PermissionDenied,++ /// Repository/database errors - maps to 500+ #[error(transparent)]+ Repo(#[from] anyhow::Error),+}diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsindex 3b5a733d48..3aaf6e0740 100644--- a/rust/cloud-storage/properties/src/domain/ports.rs+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -4,6 +4,7 @@//! Implementations live in the outbound module.use models_properties::EntityType;+use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_value::PropertyValue;use uuid::Uuid;@@ -15,6 +16,20 @@ use uuid::Uuid;pub trait PropertiesRepo: Send + Sync + 'static {type Err;+ /// Get a property definition by ID.+ /// Returns `None` if the property definition doesn't exist.+ fn get_property_definition(+ &self,+ property_definition_id: Uuid,+ ) -> impl Future<Output = Result<Option<PropertyDefinition>, Self::Err>> + Send;++ /// Count how many of the provided option IDs exist for the property definition.+ fn count_valid_property_options(+ &self,+ property_definition_id: Uuid,+ option_ids: &[Uuid],+ ) -> impl Future<Output = Result<i64, Self::Err>> + Send;+/// Atomically update a property value if the property is attached to the entity./// No-op if the property is not attached.fn update_entity_property_value_if_exists(@@ -25,6 +40,17 @@ pub trait PropertiesRepo: Send + Sync + 'static {value: Option<PropertyValue>,) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Upsert an entity property value (insert or update).+ /// If the property doesn't exist, it will be created and attached to the entity.+ /// If it exists, the value will be updated.+ fn upsert_entity_property(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ value: Option<PropertyValue>,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+/// Atomically link or unlink a task's parent (for Parent Task property).////// When `parent_task_id` is `Some(parent)`:@@ -61,3 +87,21 @@ pub trait PropertiesRepo: Send + Sync + 'static {property_definition_id: Uuid,) -> impl Future<Output = Result<Option<PropertyValue>, Self::Err>> + Send;}++/// Permission service trait for entity access control.+///+/// This trait abstracts permission operations (checking and granting), allowing for different implementations+/// (e.g., database-backed, mock for testing).+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+pub trait PermissionService: Send + Sync + 'static {+ type Err;++ /// 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(+ &self,+ user_id: &str,+ entity_id: &str,+ entity_type: EntityType,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;+}diff --git a/rust/cloud-storage/properties/src/domain/service.rs b/rust/cloud-storage/properties/src/domain/service.rsindex 5a073fab5b..ab0379fe66 100644--- a/rust/cloud-storage/properties/src/domain/service.rs+++ b/rust/cloud-storage/properties/src/domain/service.rs@@ -1,21 +1,22 @@//! Service trait for properties.use models_properties::EntityType;+use models_properties::api::requests::SetPropertyValue;use models_properties::service::property_value::PropertyValue;use system_properties::SystemPropertyKey;use uuid::Uuid;+use super::error::PropertiesErr;+/// Service trait for property operations.pub trait PropertiesService: Send + Sync + 'static {- type Err;-/// Set an entity's status system property to "Completed"./// No-op if the entity doesn't have a status property.fn set_system_property_status_complete(&self,entity_id: &str,entity_type: EntityType,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;/// Bidirectionally link or unlink a task's parent.///@@ -31,7 +32,7 @@ pub trait PropertiesService: Send + Sync + 'static {&self,task_id: Uuid,parent_task_id: Option<Uuid>,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;/// Bidirectionally set a task's subtasks.///@@ -42,7 +43,7 @@ pub trait PropertiesService: Send + Sync + 'static {&self,task_id: Uuid,subtask_ids: Vec<Uuid>,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;/// Get a property value for an entity by property definition ID./// Returns `None` if the property is not attached to the entity.@@ -51,7 +52,7 @@ pub trait PropertiesService: Send + Sync + 'static {entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,- ) -> impl Future<Output = Result<Option<PropertyValue>, Self::Err>> + Send;+ ) -> impl Future<Output = Result<Option<PropertyValue>, PropertiesErr>> + Send;/// Get a system property value for an entity./// Returns `None` if the property is not attached to the entity.@@ -60,5 +61,17 @@ pub trait PropertiesService: Send + Sync + 'static {entity_id: &str,entity_type: EntityType,property_key: SystemPropertyKey,- ) -> impl Future<Output = Result<Option<PropertyValue>, Self::Err>> + Send;+ ) -> impl Future<Output = Result<Option<PropertyValue>, PropertiesErr>> + Send;++ /// Set or update a property value for an entity, or attach a property without a value.+ /// Validates property options if the value contains select options.+ /// Requires edit access to the entity.+ fn set_entity_property(+ &self,+ user_id: &str,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ value: Option<SetPropertyValue>,+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;}diff --git a/rust/cloud-storage/properties/src/domain/service_impl.rs b/rust/cloud-storage/properties/src/domain/service_impl.rsdeleted file mode 100644index af4fd03004..0000000000--- a/rust/cloud-storage/properties/src/domain/service_impl.rs+++ /dev/null@@ -1,99 +0,0 @@-//! Service implementation for properties.--use std::fmt::Debug;--use models_properties::EntityType;-use models_properties::service::property_value::PropertyValue;-use system_properties::{StatusOption, SystemPropertyKey};-use uuid::Uuid;--use super::ports::PropertiesRepo;-use super::service::PropertiesService;--/// Implementation of PropertiesService using a repository.-#[derive(Debug)]-pub struct PropertiesServiceImpl<R>-where- R: PropertiesRepo,-{- repository: R,-}--impl<R> PropertiesServiceImpl<R>-where- R: PropertiesRepo,-{- /// Create a new PropertiesService.- pub fn new(repository: R) -> Self {- Self { repository }- }-}--impl<R> PropertiesService for PropertiesServiceImpl<R>-where- R: PropertiesRepo,- R::Err: Debug,-{- type Err = R::Err;-- #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type))]- async fn set_system_property_status_complete(- &self,- entity_id: &str,- entity_type: EntityType,- ) -> Result<(), Self::Err> {- let status_property_id = SystemPropertyKey::STATUS_UUID;- let completed_value = PropertyValue::SelectOption(vec![StatusOption::COMPLETED_UUID]);-- // Atomically update status to "Completed" if the property is attached- self.repository- .update_entity_property_value_if_exists(- entity_id,- entity_type,- status_property_id,- Some(completed_value),- )- .await?;-- Ok(())- }-- #[tracing::instrument(skip(self))]- async fn link_parent_task(- &self,- task_id: Uuid,- parent_task_id: Option<Uuid>,- ) -> Result<(), Self::Err> {- self.repository- .link_parent_task(task_id, parent_task_id)- .await- }-- #[tracing::instrument(skip(self))]- async fn link_subtasks(&self, task_id: Uuid, subtask_ids: Vec<Uuid>) -> Result<(), Self::Err> {- self.repository.link_subtasks(task_id, subtask_ids).await- }-- #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type, property_definition_id = %property_definition_id))]- async fn get_property_value(- &self,- entity_id: &str,- entity_type: EntityType,- property_definition_id: Uuid,- ) -> Result<Option<PropertyValue>, Self::Err> {- self.repository- .get_entity_property_value(entity_id, entity_type, property_definition_id)- .await- }-- #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type, property_key = ?property_key))]- async fn get_system_property_value(- &self,- entity_id: &str,- entity_type: EntityType,- property_key: SystemPropertyKey,- ) -> Result<Option<PropertyValue>, Self::Err> {- self.get_property_value(entity_id, entity_type, property_key.uuid())- .await- }-}diff --git a/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs b/rust/cloud-storage/properties/src/domain/service_impl/helpers.rsnew file mode 100644index 0000000000..6f2dab0798--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/service_impl/helpers.rs@@ -0,0 +1,26 @@+//! Helper functions for property service implementation.++use models_properties::EntityType;+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).+pub fn extract_option_ids_from_property_value(value: &Option<PropertyValue>) -> Vec<Uuid> {+ match value {+ Some(PropertyValue::SelectOption(ids)) => ids.clone(),+ _ => Vec::new(),+ }+}++/// Check if a property can be attached to the given entity type.+pub fn is_property_applicable_to(property_id: 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/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rsnew file mode 100644index 0000000000..0ec2bba487--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs@@ -0,0 +1,273 @@+//! Service implementation for properties.++mod helpers;+mod task_properties;++use models_properties::EntityType;+use models_properties::api::requests::SetPropertyValue;+use models_properties::convert_set_property_value_to_property_value;+use models_properties::service::property_value::PropertyValue;+use system_properties::{StatusOption, SystemPropertyKey};+use uuid::Uuid;++use super::error::PropertiesErr;+use super::ports::{PermissionService, PropertiesRepo};+use super::service::PropertiesService;++use helpers::{extract_option_ids_from_property_value, is_property_applicable_to};++/// Implementation of PropertiesService using a repository and optional permission service.+#[derive(Debug)]+pub struct PropertiesServiceImpl<R, P>+where+ R: PropertiesRepo,+ P: PermissionService,+{+ repository: R,+ permission_service: Option<P>,+}++impl<R, P> PropertiesServiceImpl<R, P>+where+ R: PropertiesRepo,+ P: PermissionService,+{+ /// Create a new PropertiesService with an optional permission service.+ pub fn new(repository: R, permission_service: Option<P>) -> Self {+ Self {+ repository,+ permission_service,+ }+ }++ /// 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(+ &self,+ property_definition_id: Uuid,+ option_ids: &[Uuid],+ ) -> Result<(), PropertiesErr>+ where+ anyhow::Error: From<R::Err>,+ {+ if option_ids.is_empty() {+ return Ok(());+ }++ tracing::debug!(+ property_definition_id = %property_definition_id,+ option_ids = ?option_ids,+ "validating property options"+ );++ let valid_count = self+ .repository+ .count_valid_property_options(property_definition_id, option_ids)+ .await+ .map_err(anyhow::Error::from)?;++ if valid_count != option_ids.len() as i64 {+ return Err(PropertiesErr::Validation(format!(+ "Invalid property options: {} provided but only {} valid for property {}",+ option_ids.len(),+ valid_count,+ property_definition_id+ )));+ }++ Ok(())+ }+}++impl<R, P> PropertiesService for PropertiesServiceImpl<R, P>+where+ R: PropertiesRepo,+ P: PermissionService,+ anyhow::Error: From<R::Err> + From<P::Err>,+{+ #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type))]+ async fn set_system_property_status_complete(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<(), PropertiesErr> {+ let status_property_id = SystemPropertyKey::STATUS_UUID;+ let completed_value = PropertyValue::SelectOption(vec![StatusOption::COMPLETED_UUID]);++ // Atomically update status to "Completed" if the property is attached+ self.repository+ .update_entity_property_value_if_exists(+ entity_id,+ entity_type,+ status_property_id,+ Some(completed_value),+ )+ .await+ .map_err(anyhow::Error::from)?;++ Ok(())+ }++ #[tracing::instrument(skip(self))]+ async fn link_parent_task(+ &self,+ task_id: Uuid,+ parent_task_id: Option<Uuid>,+ ) -> Result<(), PropertiesErr> {+ self.repository+ .link_parent_task(task_id, parent_task_id)+ .await+ .map_err(anyhow::Error::from)?;+ Ok(())+ }++ #[tracing::instrument(skip(self))]+ async fn link_subtasks(+ &self,+ task_id: Uuid,+ subtask_ids: Vec<Uuid>,+ ) -> Result<(), PropertiesErr> {+ self.repository+ .link_subtasks(task_id, subtask_ids)+ .await+ .map_err(anyhow::Error::from)?;+ Ok(())+ }++ #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type, property_definition_id = %property_definition_id))]+ async fn get_property_value(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ ) -> Result<Option<PropertyValue>, PropertiesErr> {+ Ok(self+ .repository+ .get_entity_property_value(entity_id, entity_type, property_definition_id)+ .await+ .map_err(anyhow::Error::from)?)+ }++ #[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type, property_key = ?property_key))]+ async fn get_system_property_value(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ property_key: SystemPropertyKey,+ ) -> Result<Option<PropertyValue>, PropertiesErr> {+ self.get_property_value(entity_id, entity_type, property_key.uuid())+ .await+ }++ #[tracing::instrument(+ skip(self),+ fields(+ entity_id = %entity_id,+ entity_type = ?entity_type,+ property_definition_id = %property_definition_id,+ has_value = value.is_some()+ )+ )]+ async fn set_entity_property(+ &self,+ user_id: &str,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ value: Option<SetPropertyValue>,+ ) -> Result<(), PropertiesErr> {+ // Check edit permission first (permission service is required)+ let permission_service = self+ .permission_service+ .as_ref()+ .ok_or(PropertiesErr::PermissionDenied)?;+ permission_service+ .check_entity_edit_permission(user_id, entity_id, entity_type)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)?;++ // Get property definition to validate it exists and for validation+ let property_definition = self+ .repository+ .get_property_definition(property_definition_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or_else(|| {+ PropertiesErr::Validation(format!(+ "Property definition not found: {}",+ property_definition_id+ ))+ })?;++ // Determine the value to set (if any) and validate+ let property_value = match &value {+ Some(set_value) => {+ // Validate that the request value is compatible with the property definition+ set_value+ .validate_compatibility(+ &property_definition.data_type,+ property_definition.is_multi_select,+ )+ .map_err(|e| {+ PropertiesErr::Validation(format!(+ "Property value validation failed: {}",+ e+ ))+ })?;++ // Convert SetPropertyValue to PropertyValue (JSONB format)+ Some(convert_set_property_value_to_property_value(set_value))+ }+ None => {+ tracing::debug!("no value provided, attaching property without value");+ None+ }+ };++ // Validate property options at service layer (before upserting)+ let option_ids = extract_option_ids_from_property_value(&property_value);+ if !option_ids.is_empty() {+ self.validate_property_options(property_definition_id, &option_ids)+ .await?;+ }++ // Check if this property can be attached to the given entity type+ if !is_property_applicable_to(property_definition_id, entity_type) {+ return Err(PropertiesErr::Validation(+ "This property cannot be attached to this entity type".to_string(),+ ));+ }++ // Handle special property types that require custom logic+ match property_definition_id {+ SystemPropertyKey::PARENT_TASK_UUID | SystemPropertyKey::SUBTASKS_UUID+ if entity_type == EntityType::Task =>+ {+ return self+ .handle_task_relationship_property(entity_id, property_definition_id, value)+ .await;+ }+ SystemPropertyKey::ASSIGNEES_UUID if entity_type == EntityType::Task => {+ self.handle_task_assignees_property(entity_id, value)+ .await?;+ }+ _ => {+ // No special handling needed+ }+ }++ // For all properties (including those with special handling that don't return early),+ // upsert the already-converted PropertyValue+ self.repository+ .upsert_entity_property(+ entity_id,+ entity_type,+ property_definition_id,+ property_value,+ )+ .await+ .map_err(anyhow::Error::from)?;++ Ok(())+ }+}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.rsnew file mode 100644index 0000000000..1ce0c4d505--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/service_impl/task_properties.rs@@ -0,0 +1,143 @@+//! Task-specific property handlers.++use models_properties::EntityType;+use models_properties::api::requests::SetPropertyValue;+use system_properties::SystemPropertyKey;+use uuid::Uuid;++use crate::domain::error::PropertiesErr;+use crate::domain::ports::{PermissionService, PropertiesRepo};+use crate::domain::service::PropertiesService;+use crate::domain::service_impl::PropertiesServiceImpl;++impl<R, P> PropertiesServiceImpl<R, P>+where+ R: PropertiesRepo,+ P: PermissionService,+ anyhow::Error: From<R::Err> + From<P::Err>,+{+ /// Handle task relationship properties (Parent Task / Subtasks) with bidirectional linking.+ /// Entity type is guaranteed to be Task (enforced by match guard).+ pub async fn handle_task_relationship_property(+ &self,+ entity_id: &str,+ property_definition_id: Uuid,+ value: Option<SetPropertyValue>,+ ) -> Result<(), PropertiesErr> {+ let task_id = Uuid::parse_str(entity_id)+ .map_err(|_| PropertiesErr::Validation("Invalid task ID".to_string()))?;++ match property_definition_id {+ SystemPropertyKey::PARENT_TASK_UUID => {+ // Extract parent task ID (None to clear)+ let parent_task_id = match &value {+ None => None,+ Some(SetPropertyValue::EntityReference { reference }) => {+ if reference.entity_type != EntityType::Task {+ return Err(PropertiesErr::Validation(+ "Parent Task must reference a Task entity".to_string(),+ ));+ }+ Some(Uuid::parse_str(&reference.entity_id).map_err(|_| {+ PropertiesErr::Validation("Invalid task ID".to_string())+ })?)+ }+ Some(_) => {+ return Err(PropertiesErr::Validation(+ "Parent Task requires a single entity reference".to_string(),+ ));+ }+ };++ PropertiesService::link_parent_task(self, task_id, parent_task_id).await?;+ }+ SystemPropertyKey::SUBTASKS_UUID => {+ // Extract subtask IDs (empty to clear)+ let subtask_ids = match &value {+ None => vec![],+ Some(SetPropertyValue::MultiEntityReference { references }) => {+ let mut ids = Vec::with_capacity(references.len());+ for ref_ in references {+ if ref_.entity_type != EntityType::Task {+ return Err(PropertiesErr::Validation(+ "Subtasks must reference Task entities".to_string(),+ ));+ }+ ids.push(Uuid::parse_str(&ref_.entity_id).map_err(|_| {+ PropertiesErr::Validation("Invalid task ID".to_string())+ })?);+ }+ ids+ }+ Some(_) => {+ return Err(PropertiesErr::Validation(+ "Subtasks requires multiple entity references".to_string(),+ ));+ }+ };++ PropertiesService::link_subtasks(self, task_id, subtask_ids).await?;+ }+ _ => {+ // This should never happen due to the match guard, but handle it for completeness+ return Err(PropertiesErr::Validation(+ "Invalid property for task relationship handling".to_string(),+ ));+ }+ }++ Ok(())+ }++ /// Handle task assignees property with notifications and permissions.+ /// Assignees is a multi-select entity property, so only accepts MultiEntityReference.+ /// If value is None (clearing assignees), there's nothing to do for notifications/permissions.+ pub async fn handle_task_assignees_property(+ &self,+ entity_id: &str,+ value: Option<SetPropertyValue>,+ ) -> Result<(), PropertiesErr> {+ // Clearing assignees - nothing to do for notifications/permissions+ let Some(SetPropertyValue::MultiEntityReference { references }) = &value else {+ if value.is_some() {+ // Assignees is multi-select, so only MultiEntityReference is valid+ // This should be caught by validate_compatibility, but handle it here for safety+ return Err(PropertiesErr::Validation(+ "Assignees requires multiple entity references".to_string(),+ ));+ }+ return Ok(());+ };++ let assignee_ids: Vec<String> = references.iter().map(|r| r.entity_id.clone()).collect();+ let task_id = Uuid::parse_str(entity_id)+ .map_err(|_| PropertiesErr::Validation("Invalid task ID".to_string()))?;+ self.handle_task_assignee_notifications(task_id, &assignee_ids)+ .await?;+ self.handle_task_assignee_permissions(task_id, &assignee_ids)+ .await?;+ Ok(())+ }++ /// Handle notifications when task assignees are updated.+ /// This is a no-op for now.+ pub async fn handle_task_assignee_notifications(+ &self,+ _task_id: Uuid,+ _assignee_ids: &[String],+ ) -> Result<(), PropertiesErr> {+ // No-op for now+ Ok(())+ }++ /// Handle permissions when task assignees are updated.+ /// This is a no-op for now.+ pub async fn handle_task_assignee_permissions(+ &self,+ _task_id: Uuid,+ _assignee_ids: &[String],+ ) -> Result<(), PropertiesErr> {+ // No-op for now+ Ok(())+ }+}diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rsindex 61c7c8daaf..4dee503f8b 100644--- a/rust/cloud-storage/properties/src/domain/test.rs+++ b/rust/cloud-storage/properties/src/domain/test.rs@@ -1,12 +1,24 @@//! Unit tests for PropertiesServiceImpl using mockall-generated repo.use super::service_impl::PropertiesServiceImpl;-use crate::domain::{ports::MockPropertiesRepo, service::PropertiesService};+use crate::domain::{+ ports::{MockPermissionService, MockPropertiesRepo},+ service::PropertiesService,+};use anyhow::anyhow;use models_properties::{EntityType, service::property_value::PropertyValue};use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;+/// Creates a mock permission service with default expectations for entity edit permission checks.+fn create_mock_permission_service() -> MockPermissionService {+ let mut perm_checker = MockPermissionService::new();+ perm_checker+ .expect_check_entity_edit_permission()+ .returning(|_, _, _| Box::pin(async { Ok(()) }));+ perm_checker+}+#[tokio::test]async fn test_set_system_property_status_complete_happy_path() {let mut repo = MockPropertiesRepo::new();@@ -31,7 +43,7 @@ async fn test_set_system_property_status_complete_happy_path() {}).returning(|_, _, _, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let entity_id = "e1";let entity_type = EntityType::Document;@@ -50,7 +62,7 @@ async fn test_set_system_property_status_complete_error_path() {repo.expect_update_entity_property_value_if_exists().returning(|_, _, _, _| Box::pin(async { Err(anyhow!("boom")) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let err = service.set_system_property_status_complete("e1", EntityType::Document)@@ -75,7 +87,7 @@ async fn test_link_parent_task_delegates_to_repo() {.withf(move |t, p| *t == task_id && *p == Some(parent_id)).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));service.link_parent_task(task_id, Some(parent_id))@@ -93,7 +105,7 @@ async fn test_link_parent_task_clear_parent() {.withf(move |t, p| *t == task_id && p.is_none()).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));service.link_parent_task(task_id, None).await.unwrap();}@@ -105,7 +117,7 @@ async fn test_link_parent_task_error_propagates() {repo.expect_link_parent_task().returning(|_, _| Box::pin(async { Err(anyhow!("link failed")) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let err = service.link_parent_task(Uuid::nil(), Some(Uuid::nil()))@@ -133,7 +145,7 @@ async fn test_link_subtasks_delegates_to_repo() {}).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));service.link_subtasks(task_id, vec![subtask_1, subtask_2])@@ -151,7 +163,7 @@ async fn test_link_subtasks_clear_all() {.withf(move |t, s| *t == task_id && s.is_empty()).returning(|_, _| Box::pin(async { Ok(()) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));service.link_subtasks(task_id, vec![]).await.unwrap();}@@ -162,7 +174,7 @@ async fn test_link_subtasks_error_propagates() {repo.expect_link_subtasks().returning(|_, _| Box::pin(async { Err(anyhow!("subtask link failed")) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let err = service.link_subtasks(Uuid::nil(), vec![Uuid::nil()])@@ -188,7 +200,7 @@ async fn test_get_property_value_returns_value_when_exists() {}).returning(|_, _, _| Box::pin(async { Ok(Some(PropertyValue::Str("hello".to_string()))) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let result = service.get_property_value("e1", EntityType::Document, prop_id)@@ -205,7 +217,7 @@ async fn test_get_property_value_returns_none_when_not_attached() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Ok(None) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let result = service.get_property_value("e1", EntityType::Document, Uuid::nil())@@ -222,7 +234,7 @@ async fn test_get_property_value_error_path() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Err(anyhow!("db error")) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let err = service.get_property_value("e1", EntityType::Document, Uuid::nil())@@ -254,7 +266,7 @@ async fn test_get_system_property_value_returns_value_when_exists() {})});- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let result = service.get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)@@ -276,7 +288,7 @@ async fn test_get_system_property_value_returns_none_when_not_attached() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Ok(None) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let result = service.get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)@@ -293,7 +305,7 @@ async fn test_get_system_property_value_error_path() {repo.expect_get_entity_property_value().returning(|_, _, _| Box::pin(async { Err(anyhow!("db error")) }));- let service = PropertiesServiceImpl::new(repo);+ let service = PropertiesServiceImpl::new(repo, Some(create_mock_permission_service()));let err = service.get_system_property_value("e1", EntityType::Document, SystemPropertyKey::Status)diff --git a/rust/cloud-storage/properties/src/lib.rs b/rust/cloud-storage/properties/src/lib.rsindex 5d33b86a54..2bec390dba 100644--- a/rust/cloud-storage/properties/src/lib.rs+++ b/rust/cloud-storage/properties/src/lib.rs@@ -13,7 +13,9 @@pub mod domain;pub mod outbound;-pub use domain::ports::PropertiesRepo;+pub use domain::error::PropertiesErr;+pub use domain::ports::{PermissionService, PropertiesRepo};pub use domain::service::PropertiesService;pub use domain::service_impl::PropertiesServiceImpl;+pub use outbound::permission_service::PermissionServiceImpl;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 be2005a853..171a153252 100644--- a/rust/cloud-storage/properties/src/outbound.rs+++ b/rust/cloud-storage/properties/src/outbound.rs@@ -1,5 +1,7 @@pub mod entity_property_queries;+pub mod permission_service;pub mod properties_pg_repo;+pub mod property_definition_queries;pub mod task_property_queries;#[cfg(test)]pub mod test;diff --git a/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rsindex 9be659bb63..8cdeea0cad 100644--- a/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs+++ b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs@@ -47,3 +47,70 @@ pub async fn update_entity_property_value_if_exists(Ok(())}++/// Upsert an entity property value (insert or update).+/// If the property doesn't exist, it will be created and attached to the entity.+/// If it exists, the value will be updated.+pub async fn upsert_entity_property(+ pool: &Pool<Postgres>,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ value: Option<PropertyValue>,+) -> anyhow::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)?,+ None => serde_json::Value::Null,+ };++ tracing::debug!(value_json = ?value_json, "upserting entity property");++ // 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(pool)+ .await?;++ tracing::debug!("successfully upserted entity property");++ Ok(())+}++/// Counts how many of the provided option IDs exist for the property definition.+pub async fn count_valid_property_options(+ pool: &Pool<Postgres>,+ property_definition_id: Uuid,+ option_ids: &[Uuid],+) -> anyhow::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(option_ids)+ .fetch_one(pool)+ .await?;++ Ok(count.0)+}diff --git a/rust/cloud-storage/properties/src/outbound/permission_service.rs b/rust/cloud-storage/properties/src/outbound/permission_service.rsnew file mode 100644index 0000000000..9e8a031060--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/permission_service.rs@@ -0,0 +1,85 @@+//! Permission service implementation for properties.++use models_permissions::share_permission::access_level::AccessLevel;+use models_properties::EntityType;+use sqlx::{Pool, Postgres};+use uuid::Uuid;++use crate::domain::ports::PermissionService;+use comms_service_client::CommsServiceClient;+use email_db_client::threads::get::get_macro_id_from_thread_id;++/// Permission service implementation using database and comms service client.+pub struct PermissionServiceImpl {+ db: Pool<Postgres>,+ comms_service_client: CommsServiceClient,+}++impl PermissionServiceImpl {+ pub fn new(db: Pool<Postgres>, comms_service_client: CommsServiceClient) -> Self {+ Self {+ db,+ comms_service_client,+ }+ }+}++impl PermissionService for PermissionServiceImpl {+ 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: &str,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<(), Self::Err> {+ let item_type = match entity_type {+ EntityType::Document => "document",+ EntityType::Chat => "chat",+ EntityType::Project => "project",+ EntityType::Thread => "thread",+ EntityType::Channel => "channel",+ EntityType::Task => "document",+ EntityType::Company | EntityType::User => {+ tracing::warn!("property operations not supported for this entity type");+ anyhow::bail!("Unsupported entity type");+ }+ };++ let access_level =+ macro_middleware::cloud_storage::ensure_access::get_users_access_level_v2(+ &self.db,+ &self.comms_service_client,+ user_id,+ entity_id,+ item_type,+ )+ .await+ .map_err(|(status_code, message)| {+ tracing::error!(+ status_code = ?status_code,+ message = %message,+ "failed to get user access level"+ );+ anyhow::anyhow!("Failed to get user access level: {}", message)+ })?;++ // 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_type == EntityType::Thread+ && 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 access_level {+ Some(AccessLevel::Edit) | Some(AccessLevel::Owner) => Ok(()),+ Some(_) | None => anyhow::bail!("Access denied"),+ }+ }+}diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rsindex 44ea8c7afd..d1892721c1 100644--- a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs@@ -5,8 +5,9 @@ use models_properties::service::property_value::PropertyValue;use sqlx::{Pool, Postgres};use uuid::Uuid;-use super::{entity_property_queries, task_property_queries};+use super::{entity_property_queries, property_definition_queries, task_property_queries};use crate::domain::ports::PropertiesRepo;+use models_properties::service::property_definition::PropertyDefinition;/// PostgreSQL implementation of PropertiesRepo.#[derive(Debug, Clone)]@@ -24,6 +25,29 @@ impl PropertiesPgRepo {impl PropertiesRepo for PropertiesPgRepo {type Err = anyhow::Error;+ #[tracing::instrument(skip(self))]+ async fn get_property_definition(+ &self,+ property_definition_id: Uuid,+ ) -> Result<Option<PropertyDefinition>, Self::Err> {+ property_definition_queries::get_property_definition(&self.pool, property_definition_id)+ .await+ }++ #[tracing::instrument(skip(self))]+ async fn count_valid_property_options(+ &self,+ property_definition_id: Uuid,+ option_ids: &[Uuid],+ ) -> Result<i64, Self::Err> {+ entity_property_queries::count_valid_property_options(+ &self.pool,+ property_definition_id,+ option_ids,+ )+ .await+ }+#[tracing::instrument(skip(self, value))]async fn update_entity_property_value_if_exists(&self,@@ -42,6 +66,24 @@ impl PropertiesRepo for PropertiesPgRepo {.await}+ #[tracing::instrument(skip(self, value))]+ async fn upsert_entity_property(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ value: Option<PropertyValue>,+ ) -> Result<(), Self::Err> {+ entity_property_queries::upsert_entity_property(+ &self.pool,+ entity_id,+ entity_type,+ property_definition_id,+ value,+ )+ .await+ }+#[tracing::instrument(skip(self))]async fn link_parent_task(&self,diff --git a/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs b/rust/cloud-storage/properties/src/outbound/property_definition_queries.rsnew file mode 100644index 0000000000..793325a51b--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/property_definition_queries.rs@@ -0,0 +1,51 @@+//! Property definition query helpers.++use models_properties::service::property_definition::PropertyDefinition;+use models_properties::{DataType, EntityType, db};+use sqlx::{Pool, Postgres};+use uuid::Uuid;++/// Gets a single property definition by ID (includes system properties).+pub async fn get_property_definition(+ pool: &Pool<Postgres>,+ property_id: Uuid,+) -> anyhow::Result<Option<PropertyDefinition>> {+ let row = sqlx::query!(+ r#"+ SELECT+ id,+ organization_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(pool)+ .await?;++ let result = row.map(|row| {+ let db_prop = db::PropertyDefinition {+ id: row.id,+ organization_id: row.organization_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)+}diff --git a/rust/cloud-storage/properties_service/src/api/context.rs b/rust/cloud-storage/properties_service/src/api/context.rsindex 1be4e95b88..dba9b7f065 100644--- a/rust/cloud-storage/properties_service/src/api/context.rs+++ b/rust/cloud-storage/properties_service/src/api/context.rs@@ -17,5 +17,6 @@ pub struct ApiContext {pub config: Arc<Config>,pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,pub comms_service_client: Arc<CommsServiceClient>,- pub properties_service: Arc<PropertiesServiceImpl<properties::PropertiesPgRepo>>,+ pub properties_service:+ Arc<PropertiesServiceImpl<properties::PropertiesPgRepo, properties::PermissionServiceImpl>>,}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.rsindex c4a804ced0..1dba9ea50d 100644--- a/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs+++ b/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs@@ -4,7 +4,6 @@ use axum::{http::StatusCode,response::{IntoResponse, Response},};-use std::collections::HashSet;use system_properties::SystemPropertyKey;use thiserror::Error;use uuid::Uuid;@@ -16,7 +15,6 @@ use crate::api::{},};use model::user::UserContext;-use models_properties::service::property_value::PropertyValue;use models_properties::{EntityReference, EntityType, api::SetPropertyValue};use properties::PropertiesService;use properties_db_client::{@@ -129,7 +127,7 @@ pub async fn set_entity_property(}// Convert SetPropertyValue to PropertyValue (JSONB format)- convert_property_value_to_jsonb(value)+ Some(models_properties::convert_set_property_value_to_property_value(value))}None => {tracing::debug!("no value provided, attaching property without value");@@ -290,99 +288,12 @@ pub async fn set_entity_property(Ok(StatusCode::NO_CONTENT)}-/// Convert SetPropertyValue to PropertyValue for JSONB storage-fn convert_property_value_to_jsonb(value: &SetPropertyValue) -> Option<PropertyValue> {- Some(match value {- // Single primitive values- SetPropertyValue::Boolean { value } => PropertyValue::Bool(*value),- SetPropertyValue::Date { value } => PropertyValue::Date(*value),- SetPropertyValue::Number { value } => PropertyValue::Num(*value),- SetPropertyValue::String { value } => PropertyValue::Str(value.clone()),-- // Single select option- SetPropertyValue::SelectOption { option_id } => {- PropertyValue::SelectOption(vec![*option_id])- }-- // Multi-select options- SetPropertyValue::MultiSelectOption { option_ids } => {- let original_count = option_ids.len();- let unique_ids: HashSet<Uuid> = option_ids.iter().copied().collect();-- if unique_ids.len() < original_count {- tracing::warn!(- original_count = original_count,- unique_count = unique_ids.len(),- "Duplicate option IDs detected in MultiSelectOption, deduplicating"- );- }-- let ids: Vec<Uuid> = unique_ids.into_iter().collect();- PropertyValue::SelectOption(ids)- }-- // Single entity reference- SetPropertyValue::EntityReference { reference } => {- PropertyValue::EntityRef(vec![EntityReference {- entity_type: reference.entity_type,- entity_id: reference.entity_id.clone(),- specific_message_id: reference.specific_message_id,- }])- }-- // Multi-entity references- SetPropertyValue::MultiEntityReference { references } => {- let original_count = references.len();-- let mut seen_ids: HashSet<String> = HashSet::new();- let unique_refs: Vec<EntityReference> = references- .iter()- .filter(|ref_| seen_ids.insert(ref_.entity_id.clone()))- .map(|ref_| EntityReference {- entity_type: ref_.entity_type,- entity_id: ref_.entity_id.clone(),- specific_message_id: ref_.specific_message_id,- })- .collect();-- if unique_refs.len() < original_count {- tracing::warn!(- original_count = original_count,- unique_count = unique_refs.len(),- "Duplicate entity references detected in MultiEntityReference, deduplicating by entity_id"- );- }-- PropertyValue::EntityRef(unique_refs)- }-- // Single link- SetPropertyValue::Link { url } => PropertyValue::Link(vec![url.clone()]),-- // Multi-link- SetPropertyValue::MultiLink { urls } => {- let original_count = urls.len();- let unique_urls: HashSet<String> = urls.iter().cloned().collect();-- if unique_urls.len() < original_count {- tracing::warn!(- original_count = original_count,- unique_count = unique_urls.len(),- "Duplicate URLs detected in MultiLink, deduplicating"- );- }-- let links: Vec<String> = unique_urls.into_iter().collect();- PropertyValue::Link(links)- }- })-}-#[cfg(test)]mod tests {use super::*;use chrono::Utc;use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};+ use models_properties::service::property_value::PropertyValue;use std::collections::HashSet;use uuid::Uuid;@@ -488,10 +399,14 @@ mod tests {],};- let result = convert_property_value_to_jsonb(&multi_option_with_dupes).unwrap();+ let result = Some(+ models_properties::convert_set_property_value_to_property_value(+ &multi_option_with_dupes,+ ),+ );// Should have only 3 unique values- let PropertyValue::SelectOption(option_ids) = result else {+ let Some(PropertyValue::SelectOption(option_ids)) = result else {panic!("Expected SelectOption variant");};assert_eq!(option_ids.len(), 3);@@ -514,10 +429,11 @@ mod tests {option_ids: vec![option_id_1, option_id_2],};- let result = convert_property_value_to_jsonb(&multi_option).unwrap();+ let result =+ Some(models_properties::convert_set_property_value_to_property_value(&multi_option));// Should have 2 values- let PropertyValue::SelectOption(option_ids) = result else {+ let Some(PropertyValue::SelectOption(option_ids)) = result else {panic!("Expected SelectOption variant");};assert_eq!(option_ids.len(), 2);@@ -544,10 +460,14 @@ mod tests {],};- let result = convert_property_value_to_jsonb(&multi_entity_ref_with_dupes).unwrap();+ 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 PropertyValue::EntityRef(entity_refs) = result else {+ let Some(PropertyValue::EntityRef(entity_refs)) = result else {panic!("Expected EntityRef variant");};assert_eq!(entity_refs.len(), 2);@@ -577,10 +497,12 @@ mod tests {references: vec![entity_ref_1, entity_ref_2],};- let result = convert_property_value_to_jsonb(&multi_entity_ref).unwrap();+ 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 PropertyValue::EntityRef(entity_refs) = result else {+ let Some(PropertyValue::EntityRef(entity_refs)) = result else {panic!("Expected EntityRef variant");};assert_eq!(entity_refs.len(), 1);diff --git a/rust/cloud-storage/properties_service/src/main.rs b/rust/cloud-storage/properties_service/src/main.rsindex b4213527d3..00d7e1053c 100644--- a/rust/cloud-storage/properties_service/src/main.rs+++ b/rust/cloud-storage/properties_service/src/main.rs@@ -68,8 +68,11 @@ async fn main() -> anyhow::Result<()> {// Initialize properties servicelet properties_repository = properties::PropertiesPgRepo::new(db.clone());+ let permission_service =+ properties::PermissionServiceImpl::new(db.clone(), comms_service_client.clone());let properties_service = Arc::new(properties::PropertiesServiceImpl::new(properties_repository,+ Some(permission_service),));tracing::info!("initialized properties service");