Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor [properties-be] - properties service hexagon set_entity_property (#752)

Daniel Kweonda0b3571f4ac
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.rs
index 1dba9ea50d..a2b0f6f23f 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,50 +4,28 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use system_properties::SystemPropertyKey;
use thiserror::Error;
use uuid::Uuid;
-use crate::api::{
- context::ApiContext,
- properties::{
- definitions::list::is_property_applicable_to, entities::types::SetEntityPropertyRequest,
- },
-};
+use crate::api::{context::ApiContext, properties::entities::types::SetEntityPropertyRequest};
use model::user::UserContext;
-use models_properties::{EntityReference, EntityType, api::SetPropertyValue};
-use properties::PropertiesService;
-use properties_db_client::{
- entity_properties::upsert as entity_properties_upsert, error::PropertiesDatabaseError,
- property_definitions::get as property_definitions_get,
-};
+use models_properties::EntityType;
+use properties::{PropertiesErr, PropertiesService};
#[derive(Debug, Error)]
pub enum SetEntityPropertyErr {
- #[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("Property definition not found")]
- PropertyNotFound,
- #[error("{0}")]
- InvalidRequest(String),
- #[error("Invalid property options")]
- InvalidPropertyOptions,
+ #[error(transparent)]
+ Properties(#[from] PropertiesErr),
}
impl IntoResponse for SetEntityPropertyErr {
fn into_response(self) -> Response {
let status_code = match &self {
- SetEntityPropertyErr::InternalError(_) | SetEntityPropertyErr::DatabaseError(_) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
- SetEntityPropertyErr::Permission(e) => e.status_code(),
- SetEntityPropertyErr::PropertyNotFound => StatusCode::NOT_FOUND,
- SetEntityPropertyErr::InvalidRequest(_)
- | SetEntityPropertyErr::InvalidPropertyOptions => StatusCode::BAD_REQUEST,
+ SetEntityPropertyErr::Properties(e) => match e {
+ PropertiesErr::Validation(_) => StatusCode::BAD_REQUEST,
+ PropertiesErr::PermissionDenied => StatusCode::FORBIDDEN,
+ PropertiesErr::Repo(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ },
};
if status_code.is_server_error() {
@@ -89,209 +67,26 @@ pub async fn set_entity_property(
) -> Result<StatusCode, SetEntityPropertyErr> {
tracing::info!("setting entity property");
- let entity_ref = EntityReference::new(entity_id.clone(), entity_type);
- crate::api::permissions::check_entity_edit_permission(
- &context,
- &user_context.user_id,
- &entity_ref,
- )
- .await?;
-
- let property_definition =
- property_definitions_get::get_property_definition(&context.db, property_uuid)
- .await
- .inspect_err(|e| {
- tracing::error!(
- error = ?e,
- "failed to get property definition"
- );
- })?
- .ok_or(SetEntityPropertyErr::PropertyNotFound)?;
-
- // Determine the value to set (if any) and validate
- let property_value = match &request.value {
- Some(value) => {
- // Validate that the request value is compatible with the property definition
- if let Err(err) = value.validate_compatibility(
- &property_definition.data_type,
- property_definition.is_multi_select,
- ) {
- tracing::error!(
- data_type = ?property_definition.data_type,
- is_multi_select = property_definition.is_multi_select,
- value_type = ?value,
- error = %err,
- "property value type doesn't match property definition"
- );
- return Err(SetEntityPropertyErr::InvalidRequest(err.to_string()));
- }
-
- // Convert SetPropertyValue to PropertyValue (JSONB format)
- Some(models_properties::convert_set_property_value_to_property_value(value))
- }
- None => {
- tracing::debug!("no value provided, attaching property without value");
- None
- }
- };
-
- // Validate property options at service layer (before upserting)
- let option_ids = entity_properties_upsert::extract_option_ids(&property_value);
- if !option_ids.is_empty() {
- entity_properties_upsert::validate_property_options(
- &context.db,
+ context
+ .properties_service
+ .set_entity_property(
+ &user_context.user_id,
+ &entity_id,
+ entity_type,
property_uuid,
- &option_ids,
+ request.value,
)
- .await
- .map_err(|e| {
- // Check if this is a validation error for invalid options
- if matches!(e, PropertiesDatabaseError::InvalidPropertyOptions { .. }) {
- tracing::warn!(
- error = %e,
- "invalid property options provided"
- );
- return SetEntityPropertyErr::InvalidPropertyOptions;
- }
- tracing::error!(
- error = ?e,
- "option validation failed"
- );
- SetEntityPropertyErr::InternalError(anyhow::anyhow!("Option validation failed: {}", e))
- })?;
- }
-
- let has_value = property_value.is_some();
-
- tracing::debug!(has_value = has_value, "setting property in database");
-
- // Check if this property can be attached to the given entity type
- if !is_property_applicable_to(property_uuid, entity_type) {
- return Err(SetEntityPropertyErr::InvalidRequest(
- "This property cannot be attached to this entity type".to_string(),
- ));
- }
-
- // Handle bidirectional linking for task Parent Task / Subtasks properties
- // (if is_parent_or_subtask_property is true, entity_type is guaranteed to be Task by the earlier check)
- if property_uuid == SystemPropertyKey::PARENT_TASK_UUID
- || property_uuid == SystemPropertyKey::SUBTASKS_UUID
- {
- let task_id = Uuid::parse_str(&entity_id)
- .map_err(|_| SetEntityPropertyErr::InvalidRequest("Invalid task ID".to_string()))?;
-
- if property_uuid == SystemPropertyKey::PARENT_TASK_UUID {
- // Extract parent task ID (None to clear)
- let parent_task_id = match &request.value {
- None => None,
- Some(SetPropertyValue::EntityReference { reference }) => {
- if reference.entity_type != EntityType::Task {
- return Err(SetEntityPropertyErr::InvalidRequest(
- "Parent Task must reference a Task entity".to_string(),
- ));
- }
- Some(Uuid::parse_str(&reference.entity_id).map_err(|_| {
- SetEntityPropertyErr::InvalidRequest("Invalid task ID".to_string())
- })?)
- }
- _ => {
- return Err(SetEntityPropertyErr::InvalidRequest(
- "Parent Task requires a single entity reference".to_string(),
- ));
- }
- };
-
- context
- .properties_service
- .link_parent_task(task_id, parent_task_id)
- .await
- .map_err(|e| {
- tracing::error!(error = ?e, "failed to link parent task");
- SetEntityPropertyErr::InternalError(anyhow::anyhow!(
- "Failed to link parent task: {}",
- e
- ))
- })?;
- tracing::info!("successfully linked parent task");
- } else {
- // Extract subtask IDs (empty to clear)
- let subtask_ids = match &request.value {
- None => vec![],
- Some(SetPropertyValue::MultiEntityReference { references }) => {
- let mut ids = Vec::with_capacity(references.len());
- for reference in references {
- if reference.entity_type != EntityType::Task {
- return Err(SetEntityPropertyErr::InvalidRequest(
- "Subtasks must reference Task entities".to_string(),
- ));
- }
- ids.push(Uuid::parse_str(&reference.entity_id).map_err(|_| {
- SetEntityPropertyErr::InvalidRequest("Invalid task ID".to_string())
- })?);
- }
- ids
- }
- _ => {
- return Err(SetEntityPropertyErr::InvalidRequest(
- "Subtasks requires multiple entity references".to_string(),
- ));
- }
- };
-
- context
- .properties_service
- .link_subtasks(task_id, subtask_ids)
- .await
- .map_err(|e| {
- tracing::error!(error = ?e, "failed to link subtasks");
- SetEntityPropertyErr::InternalError(anyhow::anyhow!(
- "Failed to link subtasks: {}",
- e
- ))
- })?;
- tracing::info!("successfully linked subtasks");
- }
+ .await?;
- return Ok(StatusCode::NO_CONTENT);
- }
-
- entity_properties_upsert::upsert_entity_property_values(
- &context.db,
- &entity_id,
- entity_type,
- property_uuid,
- property_value,
- )
- .await
- .map_err(|e| {
- // Check if this is a validation error for invalid options
- if matches!(e, PropertiesDatabaseError::InvalidPropertyOptions { .. }) {
- tracing::warn!(
- error = %e,
- "invalid property options provided"
- );
- return SetEntityPropertyErr::InvalidPropertyOptions;
- }
-
- tracing::error!(
- error = ?e,
- "failed to set entity property"
- );
- SetEntityPropertyErr::InternalError(anyhow::anyhow!(
- "Failed to upsert entity property: {}",
- e
- ))
- })?;
-
- tracing::info!(has_value = has_value, "successfully set entity property");
+ 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;