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.

add [properties-be] - system properties for tasks (#461)

Daniel Kweon3b951f5309c1
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 7760cd1d0a..2674ebeb72 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2647,6 +2647,7 @@ dependencies = [
"sqlx",
"sqs_client",
"sync_service_client",
+ "system_properties",
"thiserror 2.0.17",
"tokio",
"tower 0.5.2",
@@ -8580,6 +8581,9 @@ dependencies = [
name = "system_properties"
version = "0.1.0"
dependencies = [
+ "anyhow",
+ "macro_db_migrator",
+ "macro_uuid",
"models_properties",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/deny.toml b/rust/cloud-storage/deny.toml
index 579dca9dda..114b4a2083 100644
--- a/rust/cloud-storage/deny.toml
+++ b/rust/cloud-storage/deny.toml
@@ -76,6 +76,7 @@ ignore = [
{ id = "RUSTSEC-2024-0436", reason = "Paste is a 'finished' crate which is heavily depended on" },
{ id = "RUSTSEC-2025-0012", reason = "Cannot remove dep due to 3rd party openai dependency" },
{ id = "RUSTSEC-2025-0057", reason = "We should switch to rustc-hash, but haven't got to that yet" },
+ { id = "RUSTSEC-2025-0134", reason = "rustls-pemfile is unmaintained but still functional; waiting for AWS SDK to update dependencies" },
#{ id = "RUSTSEC-0000-0000", reason = "you can specify a reason the advisory is ignored" },
#"[email protected]", # you can also ignore yanked crate versions if you wish
#{ crate = "[email protected]", reason = "you can specify why you are ignoring the yanked crate" },
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index b2e6f86b22..b70bd7913a 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -98,6 +98,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = [
"search",
] }
sync_service_client = { path = "../sync_service_client" }
+system_properties = { path = "../system_properties" }
thiserror = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index f1d342ac16..aee0856966 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -15,6 +15,7 @@ use soup::{
use sqlx::PgPool;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};
#[derive(Debug, Clone)]
pub struct InternalFlag {
@@ -30,6 +31,8 @@ type DssSoupState = SoupRouterState<
EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>>,
>;
+type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;
+
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
pub db: PgPool,
@@ -44,6 +47,7 @@ pub(crate) struct ApiContext {
pub email_service_client: Arc<EmailServiceClient>,
pub conn_gateway_client: Arc<ConnectionGatewayClient>,
pub sync_service_client: Arc<SyncServiceClient>,
+ pub system_properties_service: Arc<SystemPropertiesService>,
pub jwt_validation_args: JwtValidationArgs,
pub config: Arc<Config>,
pub dss_auth_key: DocumentStorageServiceAuthKey,
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
index 04e924fb7b..16fc58d8fa 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/copy_document/copy_document_v2.rs
@@ -11,6 +11,7 @@ use model::{
response::GenericResponse,
};
use models_permissions::share_permission::SharePermissionV2;
+use system_properties::SystemPropertiesService;
#[tracing::instrument(skip(ctx))]
pub async fn copy_document<'a>(
@@ -291,6 +292,24 @@ pub async fn copy_document<'a>(
));
}
+ // Copy task properties if the original document is a task
+ if original_document_metadata.is_task
+ && let Err(e) = ctx
+ .system_properties_service
+ .copy_task_properties(
+ &original_document_metadata.document_id,
+ &updated_document_metadata.document_id,
+ )
+ .await
+ {
+ tracing::error!(error=?e, document_id=?updated_document_metadata.document_id, "failed to copy task properties");
+ return Err((
+ Some(updated_document_metadata.document_id.clone()),
+ e.into(),
+ "failed to copy task properties",
+ ));
+ }
+
let response_data = DocumentResponse {
document_metadata: document_response_metadata,
// Only used in create/update
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
index 42d609fcea..ba5cf271c2 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/create_document/create_document_v2.rs
@@ -6,6 +6,7 @@ use model::document::response::{DocumentResponse, DocumentResponseMetadata};
use model::document::{ContentType, FileType, build_cloud_storage_bucket_document_key};
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::{IS_PUBLIC_DEFAULT, SharePermissionV2};
+use system_properties::SystemPropertiesService;
use uuid::Uuid;
/// Parameters for creating a document
@@ -177,6 +178,21 @@ pub async fn create_document(
)
.await;
+ // Attach task properties if creating a task
+ if document_response_metadata.is_task
+ && let Err(e) = ctx
+ .system_properties_service
+ .attach_task_properties(vec![document_response_metadata.document_id.clone()])
+ .await
+ {
+ tracing::error!(error=?e, document_id=?document_response_metadata.document_id, "failed to attach task properties");
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to attach task properties".to_string(),
+ Some(document_response_metadata.document_id),
+ ));
+ }
+
let response_data = CreateDocumentResponseData {
document_response: DocumentResponse {
document_metadata: document_response_metadata,
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 103c449f6d..63fb92186e 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -24,6 +24,7 @@ use soup::{
use sqlx::postgres::PgPoolOptions;
use std::sync::Arc;
use sync_service_client::SyncServiceClient;
+use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};
mod api;
mod config;
@@ -184,6 +185,8 @@ async fn main() -> anyhow::Result<()> {
let frecency_service = FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone()));
let email_service =
EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());
+ let system_properties_service =
+ SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));
let api_context = ApiContext {
soup_router_state: SoupRouterState::new(
SoupImpl::new(
@@ -209,6 +212,7 @@ async fn main() -> anyhow::Result<()> {
comms_service_client: Arc::new(comms_service_client),
conn_gateway_client: Arc::new(conn_gateway_client),
sync_service_client: Arc::new(sync_service_client),
+ system_properties_service: Arc::new(system_properties_service),
config: Arc::new(config),
jwt_validation_args,
dss_auth_key,
diff --git a/rust/cloud-storage/system_properties/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/system_properties/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
new file mode 100644
index 0000000000..d2b084cf10
--- /dev/null
+++ b/rust/cloud-storage/system_properties/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\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": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"
+}
diff --git a/rust/cloud-storage/system_properties/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/system_properties/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
new file mode 100644
index 0000000000..6d97183829
--- /dev/null
+++ b/rust/cloud-storage/system_properties/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"
+}
diff --git a/rust/cloud-storage/system_properties/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/system_properties/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
new file mode 100644
index 0000000000..9d717fa5f9
--- /dev/null
+++ b/rust/cloud-storage/system_properties/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "values",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"
+}
diff --git a/rust/cloud-storage/system_properties/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/system_properties/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
new file mode 100644
index 0000000000..182e0858ba
--- /dev/null
+++ b/rust/cloud-storage/system_properties/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\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": [
+ "UuidArray",
+ "TextArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"
+}
diff --git a/rust/cloud-storage/system_properties/Cargo.toml b/rust/cloud-storage/system_properties/Cargo.toml
index e7fccd0e37..e584b70a55 100644
--- a/rust/cloud-storage/system_properties/Cargo.toml
+++ b/rust/cloud-storage/system_properties/Cargo.toml
@@ -5,6 +5,7 @@ publish = false
version = "0.1.0"
[dependencies]
+macro_uuid = { path = "../macro_uuid" }
models_properties = { path = "../models_properties" }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -12,3 +13,7 @@ sqlx = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
+
+[dev-dependencies]
+anyhow = { workspace = true }
+macro_db_migrator = { path = "../macro_db_migrator" }
diff --git a/rust/cloud-storage/system_properties/fixtures/system_properties.sql b/rust/cloud-storage/system_properties/fixtures/system_properties.sql
new file mode 100644
index 0000000000..6b5bc5a467
--- /dev/null
+++ b/rust/cloud-storage/system_properties/fixtures/system_properties.sql
@@ -0,0 +1,69 @@
+-- Test fixture for system properties
+
+-- Test user (same as properties_db_client fixtures)
+INSERT INTO "User" (id, email, name, "stripeCustomerId")
+VALUES ('user1', '[email protected]', 'Test User 1', 'cus_test1')
+ON CONFLICT (id) DO NOTHING;
+
+-- Custom property definitions
+INSERT INTO property_definitions (id, organization_id, user_id, display_name, data_type, is_multi_select, specific_entity_type)
+VALUES
+ ('cccccccc-cccc-cccc-cccc-cccccccccc01', NULL, 'user1', 'Custom Notes', 'STRING', false, 'TASK'),
+ ('cccccccc-cccc-cccc-cccc-cccccccccc02', NULL, 'user1', 'Custom Tags', 'SELECT_STRING', true, 'TASK')
+ON CONFLICT (id) DO NOTHING;
+
+-- Property options for Custom Tags
+INSERT INTO property_options (id, property_definition_id, display_order, number_value, string_value)
+VALUES
+ ('00000000-0000-0000-0000-000000000101', 'cccccccc-cccc-cccc-cccc-cccccccccc02', 0, NULL, 'urgent'),
+ ('00000000-0000-0000-0000-000000000102', 'cccccccc-cccc-cccc-cccc-cccccccccc02', 1, NULL, 'blocked')
+ON CONFLICT (id) DO NOTHING;
+
+-- Entity properties
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+VALUES
+ -- source-task-with-props
+ (
+ 'f1111111-1111-1111-1111-111111111111',
+ 'source-task-with-props',
+ 'TASK',
+ '00000001-0000-0000-0000-000000000002', -- Status
+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000002"]}' -- In Progress
+ ),
+ (
+ 'f2222222-2222-2222-2222-222222222222',
+ 'source-task-with-props',
+ 'TASK',
+ '00000001-0000-0000-0000-000000000003', -- Priority
+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0003-000000000003"]}' -- High
+ ),
+ (
+ 'f5555555-5555-5555-5555-555555555555',
+ 'source-task-with-props',
+ 'TASK',
+ 'cccccccc-cccc-cccc-cccc-cccccccccc01', -- Custom Notes
+ '{"type": "String", "value": "This is a custom note"}'
+ ),
+ (
+ 'f6666666-6666-6666-6666-666666666666',
+ 'source-task-with-props',
+ 'TASK',
+ 'cccccccc-cccc-cccc-cccc-cccccccccc02', -- Custom Tags
+ '{"type": "SelectOption", "value": ["00000000-0000-0000-0000-000000000101"]}' -- urgent
+ ),
+ -- source-task-overwrite
+ (
+ 'f3333333-3333-3333-3333-333333333333',
+ 'source-task-overwrite',
+ 'TASK',
+ '00000001-0000-0000-0000-000000000002', -- Status
+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000004"]}' -- Completed
+ ),
+ -- dest-task-existing
+ (
+ 'f4444444-4444-4444-4444-444444444444',
+ 'dest-task-existing',
+ 'TASK',
+ '00000001-0000-0000-0000-000000000002', -- Status
+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000001"]}' -- Not Started
+ );
diff --git a/rust/cloud-storage/system_properties/src/domain/model/repository/property_row.rs b/rust/cloud-storage/system_properties/src/domain/model/repository/property_row.rs
index 0b3dfbefdb..5008975050 100644
--- a/rust/cloud-storage/system_properties/src/domain/model/repository/property_row.rs
+++ b/rust/cloud-storage/system_properties/src/domain/model/repository/property_row.rs
@@ -76,6 +76,22 @@ impl PropertyRow {
}
}
+ /// Create a property row with a null JSON value.
+ ///
+ /// Used to initialize system properties with empty/null values.
+ pub fn null_value(
+ entity_id: impl Into<String>,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ ) -> Self {
+ Self {
+ entity_id: entity_id.into(),
+ entity_type,
+ property_definition_id,
+ values: serde_json::Value::Null,
+ }
+ }
+
// =========================================================================
// Getters - for repository access
// =========================================================================
diff --git a/rust/cloud-storage/system_properties/src/domain/port.rs b/rust/cloud-storage/system_properties/src/domain/port.rs
index 3fc956edd1..2d5b7d0e73 100644
--- a/rust/cloud-storage/system_properties/src/domain/port.rs
+++ b/rust/cloud-storage/system_properties/src/domain/port.rs
@@ -15,4 +15,11 @@ pub trait SystemPropertiesRepository: Clone + Send + Sync + 'static {
&self,
rows: Vec<crate::domain::model::PropertyRow>,
) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;
+
+ /// Copy all task properties from one entity to another.
+ fn copy_task_properties(
+ &self,
+ from_task_id: &str,
+ to_task_id: &str,
+ ) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;
}
diff --git a/rust/cloud-storage/system_properties/src/domain/service.rs b/rust/cloud-storage/system_properties/src/domain/service.rs
index b2a559a233..be04cf2847 100644
--- a/rust/cloud-storage/system_properties/src/domain/service.rs
+++ b/rust/cloud-storage/system_properties/src/domain/service.rs
@@ -20,6 +20,25 @@ pub trait SystemPropertiesService: Clone + Send + Sync + 'static {
&self,
items: Vec<EmailAttachmentInput>,
) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;
+
+ /// Set empty task system properties for multiple entities.
+ ///
+ /// Initializes all task-related system properties with null values.
+ /// All properties are upserted in a single query.
+ fn attach_task_properties(
+ &self,
+ entity_ids: Vec<String>,
+ ) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;
+
+ /// Copy all task properties from one entity to another.
+ ///
+ /// Copies all task-related system properties from the source entity
+ /// to the destination entity, overwriting any existing values.
+ fn copy_task_properties(
+ &self,
+ from_task_id: &str,
+ to_task_id: &str,
+ ) -> impl Future<Output = Result<(), SystemPropertyError>> + Send;
}
/// Implementation of SystemPropertiesService using a repository.
@@ -57,6 +76,30 @@ where
self.repository.bulk_upsert_properties(rows).await
}
+
+ #[tracing::instrument(skip(self, entity_ids))]
+ async fn attach_task_properties(
+ &self,
+ entity_ids: Vec<String>,
+ ) -> Result<(), SystemPropertyError> {
+ let rows: Vec<PropertyRow> = entity_ids
+ .iter()
+ .flat_map(|entity_id| collect_task_property_rows(entity_id))
+ .collect();
+
+ self.repository.bulk_upsert_properties(rows).await
+ }
+
+ #[tracing::instrument(skip(self))]
+ async fn copy_task_properties(
+ &self,
+ from_task_id: &str,
+ to_task_id: &str,
+ ) -> Result<(), SystemPropertyError> {
+ self.repository
+ .copy_task_properties(from_task_id, to_task_id)
+ .await
+ }
}
/// Collect property rows for a single entity's email attachment properties.
@@ -128,3 +171,41 @@ fn collect_email_property_rows(
rows
}
+
+/// Collect property rows for a single entity's task properties.
+/// All task properties are initialized with null values.
+/// Tasks are always applied to Task entities.
+fn collect_task_property_rows(entity_id: &str) -> Vec<PropertyRow> {
+ let entity_type = EntityType::Task;
+
+ vec![
+ // Assignees
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::Assignees.uuid()),
+ // Status
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::Status.uuid()),
+ // Priority
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::Priority.uuid()),
+ // Due Date
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::DueDate.uuid()),
+ // Parent Task
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::ParentTask.uuid()),
+ // Subtasks
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::Subtasks.uuid()),
+ // Depends On
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::DependsOn.uuid()),
+ // Effort
+ PropertyRow::null_value(entity_id, entity_type, SystemPropertyKey::Effort.uuid()),
+ // Story Points
+ PropertyRow::null_value(
+ entity_id,
+ entity_type,
+ SystemPropertyKey::StoryPoints.uuid(),
+ ),
+ // Relevant Documents
+ PropertyRow::null_value(
+ entity_id,
+ entity_type,
+ SystemPropertyKey::RelevantDocuments.uuid(),
+ ),
+ ]
+}
diff --git a/rust/cloud-storage/system_properties/src/outbound/pgpool.rs b/rust/cloud-storage/system_properties/src/outbound/pgpool.rs
deleted file mode 100644
index 90ed964b71..0000000000
--- a/rust/cloud-storage/system_properties/src/outbound/pgpool.rs
+++ /dev/null
@@ -1,80 +0,0 @@
-//! PostgreSQL implementation for system properties repository.
-
-use sqlx::{Pool, Postgres};
-use uuid::Uuid;
-
-use crate::domain::{
- model::{PropertyRow, SystemPropertyError},
- port::SystemPropertiesRepository,
-};
-
-/// PostgreSQL implementation of SystemPropertiesRepository.
-#[derive(Clone)]
-pub struct PgSystemPropertiesRepository {
- pool: Pool<Postgres>,
-}
-
-impl PgSystemPropertiesRepository {
- /// Create a new PgSystemPropertiesRepository.
- pub fn new(pool: Pool<Postgres>) -> Self {
- Self { pool }
- }
-}
-
-impl SystemPropertiesRepository for PgSystemPropertiesRepository {
- async fn bulk_upsert_properties(
- &self,
- rows: Vec<PropertyRow>,
- ) -> Result<(), SystemPropertyError> {
- if rows.is_empty() {
- return Ok(());
- }
-
- let ids: Vec<Uuid> = rows.iter().map(|_| Uuid::now_v7()).collect();
- let entity_ids: Vec<&str> = rows.iter().map(|r| r.entity_id()).collect();
- let entity_types: Vec<String> = rows
- .iter()
- .map(|r| {
- serde_json::to_value(r.entity_type())
- .expect("EntityType serializes to JSON")
- .as_str()
- .expect("EntityType serializes to string")
- .to_string()
- })
- .collect();
- let property_ids: Vec<Uuid> = rows.iter().map(|r| r.property_definition_id()).collect();
- let values: Vec<serde_json::Value> = rows.iter().map(|r| r.values().clone()).collect();
-
- sqlx::query(
- r#"
- INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
- SELECT
- u.id,
- u.entity_id,
- u.entity_type::property_entity_type,
- u.property_definition_id,
- u.values
- FROM UNNEST(
- $1::UUID[],
- $2::TEXT[],
- $3::TEXT[],
- $4::UUID[],
- $5::JSONB[]
- ) AS u(id, entity_id, entity_type, property_definition_id, values)
- ON CONFLICT (entity_id, entity_type, property_definition_id)
- DO UPDATE SET
- values = EXCLUDED.values,
- updated_at = NOW()
- "#,
- )
- .bind(&ids)
- .bind(&entity_ids)
- .bind(&entity_types)
- .bind(&property_ids)
- .bind(&values)
- .execute(&self.pool)
- .await?;
-
- Ok(())
- }
-}
diff --git a/rust/cloud-storage/system_properties/src/outbound/pgpool/mod.rs b/rust/cloud-storage/system_properties/src/outbound/pgpool/mod.rs
new file mode 100644
index 0000000000..4ab2454b89
--- /dev/null
+++ b/rust/cloud-storage/system_properties/src/outbound/pgpool/mod.rs
@@ -0,0 +1,197 @@
+//! PostgreSQL implementation for system properties repository.
+
+#[cfg(test)]
+mod test;
+
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+use crate::domain::{
+ model::{PropertyRow, SystemPropertyError, SystemPropertyKey},
+ port::SystemPropertiesRepository,
+};
+use macro_uuid::generate_uuid_v7;
+
+/// PostgreSQL implementation of SystemPropertiesRepository.
+#[derive(Clone)]
+pub struct PgSystemPropertiesRepository {
+ pool: Pool<Postgres>,
+}
+
+impl PgSystemPropertiesRepository {
+ /// Create a new PgSystemPropertiesRepository.
+ pub fn new(pool: Pool<Postgres>) -> Self {
+ Self { pool }
+ }
+}
+
+impl SystemPropertiesRepository for PgSystemPropertiesRepository {
+ async fn bulk_upsert_properties(
+ &self,
+ rows: Vec<PropertyRow>,
+ ) -> Result<(), SystemPropertyError> {
+ if rows.is_empty() {
+ return Ok(());
+ }
+
+ let ids: Vec<Uuid> = rows.iter().map(|_| generate_uuid_v7()).collect();
+ let entity_ids: Vec<&str> = rows.iter().map(|r| r.entity_id()).collect();
+ let entity_types: Vec<String> = rows
+ .iter()
+ .map(|r| {
+ serde_json::to_value(r.entity_type())
+ .expect("EntityType serializes to JSON")
+ .as_str()
+ .expect("EntityType serializes to string")
+ .to_string()
+ })
+ .collect();
+ let property_ids: Vec<Uuid> = rows.iter().map(|r| r.property_definition_id()).collect();
+ let values: Vec<serde_json::Value> = rows.iter().map(|r| r.values().clone()).collect();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+ SELECT
+ u.id,
+ u.entity_id,
+ u.entity_type::property_entity_type,
+ u.property_definition_id,
+ u.values
+ FROM UNNEST(
+ $1::UUID[],
+ $2::TEXT[],
+ $3::TEXT[],
+ $4::UUID[],
+ $5::JSONB[]
+ ) AS u(id, entity_id, entity_type, property_definition_id, values)
+ ON CONFLICT (entity_id, entity_type, property_definition_id)
+ DO UPDATE SET
+ values = EXCLUDED.values,
+ updated_at = NOW()
+ "#,
+ &ids,
+ &entity_ids as &[&str],
+ &entity_types,
+ &property_ids,
+ &values,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ async fn copy_task_properties(
+ &self,
+ from_task_id: &str,
+ to_task_id: &str,
+ ) -> Result<(), SystemPropertyError> {
+ let system_task_property_ids: Vec<Uuid> = vec![
+ SystemPropertyKey::Assignees.uuid(),
+ SystemPropertyKey::Status.uuid(),
+ SystemPropertyKey::Priority.uuid(),
+ SystemPropertyKey::DueDate.uuid(),
+ SystemPropertyKey::ParentTask.uuid(),
+ SystemPropertyKey::Subtasks.uuid(),
+ SystemPropertyKey::DependsOn.uuid(),
+ SystemPropertyKey::Effort.uuid(),
+ SystemPropertyKey::StoryPoints.uuid(),
+ SystemPropertyKey::RelevantDocuments.uuid(),
+ ];
+
+ // Step 1: Fetch all properties from source task
+ let source_properties = sqlx::query!(
+ r#"
+ SELECT property_definition_id, values
+ FROM entity_properties
+ WHERE entity_id = $1
+ AND entity_type = 'TASK'
+ "#,
+ from_task_id
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ // Step 2: Copy all properties to destination task (with v7 UUIDs)
+ if !source_properties.is_empty() {
+ let ids: Vec<Uuid> = source_properties
+ .iter()
+ .map(|_| generate_uuid_v7())
+ .collect();
+ let entity_ids: Vec<&str> = source_properties.iter().map(|_| to_task_id).collect();
+ let property_ids: Vec<Uuid> = source_properties
+ .iter()
+ .map(|r| r.property_definition_id)
+ .collect();
+ let values: Vec<serde_json::Value> = source_properties
+ .iter()
+ .map(|r| r.values.clone().unwrap_or(serde_json::Value::Null))
+ .collect();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+ SELECT
+ u.id,
+ u.entity_id,
+ 'TASK'::property_entity_type,
+ u.property_definition_id,
+ u.values
+ FROM UNNEST(
+ $1::UUID[],
+ $2::TEXT[],
+ $3::UUID[],
+ $4::JSONB[]
+ ) AS u(id, entity_id, property_definition_id, values)
+ ON CONFLICT (entity_id, entity_type, property_definition_id)
+ DO UPDATE SET
+ values = EXCLUDED.values,
+ updated_at = NOW()
+ "#,
+ &ids,
+ &entity_ids as &[&str],
+ &property_ids,
+ &values,
+ )
+ .execute(&self.pool)
+ .await?;
+ }
+
+ // Step 3: Ensure all system task properties exist (insert with null if missing)
+ let ids: Vec<Uuid> = system_task_property_ids
+ .iter()
+ .map(|_| generate_uuid_v7())
+ .collect();
+ let entity_ids: Vec<&str> = system_task_property_ids
+ .iter()
+ .map(|_| to_task_id)
+ .collect();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+ SELECT
+ u.id,
+ u.entity_id,
+ 'TASK'::property_entity_type,
+ u.property_definition_id,
+ NULL
+ FROM UNNEST(
+ $1::UUID[],
+ $2::TEXT[],
+ $3::UUID[]
+ ) AS u(id, entity_id, property_definition_id)
+ ON CONFLICT (entity_id, entity_type, property_definition_id)
+ DO NOTHING
+ "#,
+ &ids,
+ &entity_ids as &[&str],
+ &system_task_property_ids,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/system_properties/src/outbound/pgpool/test.rs b/rust/cloud-storage/system_properties/src/outbound/pgpool/test.rs
new file mode 100644
index 0000000000..75c2e15240
--- /dev/null
+++ b/rust/cloud-storage/system_properties/src/outbound/pgpool/test.rs
@@ -0,0 +1,298 @@
+//! Tests for system properties PostgreSQL repository.
+
+use models_properties::EntityType;
+
+use super::*;
+use crate::domain::model::{PropertyRow, SystemPropertyKey};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+
+/// Helper to count task properties
+async fn count_task_properties(pool: &Pool<Postgres>, entity_id: &str) -> i64 {
+ sqlx::query_scalar::<_, i64>(
+ "SELECT COUNT(*) FROM entity_properties WHERE entity_id = $1 AND entity_type = 'TASK'",
+ )
+ .bind(entity_id)
+ .fetch_one(pool)
+ .await
+ .unwrap()
+}
+
+/// Helper to get task property values
+async fn get_task_property_values(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+) -> Vec<(Uuid, Option<serde_json::Value>)> {
+ sqlx::query_as::<_, (Uuid, Option<serde_json::Value>)>(
+ "SELECT property_definition_id, values FROM entity_properties WHERE entity_id = $1 AND entity_type = 'TASK' ORDER BY property_definition_id",
+ )
+ .bind(entity_id)
+ .fetch_all(pool)
+ .await
+ .unwrap()
+}
+
+// ============================================================================
+// bulk_upsert_properties tests
+// ============================================================================
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_bulk_upsert_properties_insert(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let entity_id = "test-task-insert";
+ let rows = vec![
+ PropertyRow::null_value(
+ entity_id,
+ EntityType::Task,
+ SystemPropertyKey::Status.uuid(),
+ ),
+ PropertyRow::null_value(
+ entity_id,
+ EntityType::Task,
+ SystemPropertyKey::Priority.uuid(),
+ ),
+ ];
+
+ repo.bulk_upsert_properties(rows).await?;
+
+ let count = count_task_properties(&pool, entity_id).await;
+ assert_eq!(count, 2, "Should have inserted 2 properties");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("system_properties"))
+)]
+async fn test_bulk_upsert_properties_update(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let entity_id = "source-task-with-props";
+ let custom_notes_id: Uuid = "cccccccc-cccc-cccc-cccc-cccccccccc01".parse().unwrap();
+
+ // Update Custom Notes (STRING type) - already has "This is a custom note" from fixture
+ let rows = vec![PropertyRow::string_value(
+ entity_id,
+ EntityType::Task,
+ custom_notes_id,
+ "Updated note",
+ )];
+
+ repo.bulk_upsert_properties(rows).await?;
+
+ let properties = get_task_property_values(&pool, entity_id).await;
+ let notes_prop = properties.iter().find(|(id, _)| *id == custom_notes_id);
+
+ assert_eq!(
+ notes_prop.unwrap().1.as_ref().unwrap(),
+ &serde_json::json!({"type": "String", "value": "Updated note"}),
+ "Custom Notes should be updated"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_bulk_upsert_properties_empty(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ // Empty input should succeed without error
+ repo.bulk_upsert_properties(vec![]).await?;
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_bulk_upsert_properties_multiple_entities(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let rows = vec![
+ PropertyRow::null_value("task-a", EntityType::Task, SystemPropertyKey::Status.uuid()),
+ PropertyRow::null_value(
+ "task-a",
+ EntityType::Task,
+ SystemPropertyKey::Priority.uuid(),
+ ),
+ PropertyRow::null_value("task-b", EntityType::Task, SystemPropertyKey::Status.uuid()),
+ PropertyRow::null_value("task-c", EntityType::Task, SystemPropertyKey::Status.uuid()),
+ ];
+
+ repo.bulk_upsert_properties(rows).await?;
+
+ assert_eq!(count_task_properties(&pool, "task-a").await, 2);
+ assert_eq!(count_task_properties(&pool, "task-b").await, 1);
+ assert_eq!(count_task_properties(&pool, "task-c").await, 1);
+
+ Ok(())
+}
+
+// ============================================================================
+// copy_task_properties tests
+// ============================================================================
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_copy_task_properties_empty_source(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let from_task_id = "source-task-123";
+ let to_task_id = "dest-task-456";
+
+ // Copy from empty source - should still create system properties with null values
+ repo.copy_task_properties(from_task_id, to_task_id).await?;
+
+ // Should have 10 system properties with null values
+ let count = count_task_properties(&pool, to_task_id).await;
+ assert_eq!(count, 10, "Should have 10 system task properties");
+
+ // All values should be null
+ let properties = get_task_property_values(&pool, to_task_id).await;
+ for (_, value) in &properties {
+ assert!(value.is_none(), "All properties should be null");
+ }
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("system_properties"))
+)]
+async fn test_copy_task_properties_with_existing_properties(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let from_task_id = "source-task-with-props";
+ let to_task_id = "dest-task-new";
+
+ // Copy properties (source has 2 system + 2 custom properties from fixture)
+ repo.copy_task_properties(from_task_id, to_task_id).await?;
+
+ // Destination should have 12 properties:
+ // - 4 copied (Status, Priority, Custom Notes, Custom Tags)
+ // - 8 null system properties backfilled
+ let count = count_task_properties(&pool, to_task_id).await;
+ assert_eq!(
+ count, 12,
+ "Should have 12 properties (4 copied + 8 backfilled)"
+ );
+
+ // Check that status was copied with correct SelectOption value
+ let properties = get_task_property_values(&pool, to_task_id).await;
+
+ let status_prop = properties
+ .iter()
+ .find(|(id, _)| *id == SystemPropertyKey::Status.uuid());
+ assert!(status_prop.is_some(), "Status property should exist");
+ assert_eq!(
+ status_prop.unwrap().1.as_ref().unwrap(),
+ &serde_json::json!({"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000002"]}), // In Progress
+ "Status value should be copied"
+ );
+
+ let priority_prop = properties
+ .iter()
+ .find(|(id, _)| *id == SystemPropertyKey::Priority.uuid());
+ assert!(priority_prop.is_some(), "Priority property should exist");
+ assert_eq!(
+ priority_prop.unwrap().1.as_ref().unwrap(),
+ &serde_json::json!({"type": "SelectOption", "value": ["00000001-0000-0000-0003-000000000003"]}), // High
+ "Priority value should be copied"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("system_properties"))
+)]
+async fn test_copy_task_properties_copies_custom_properties(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let from_task_id = "source-task-with-props";
+ let to_task_id = "dest-task-custom";
+
+ // Custom property IDs from fixture
+ let custom_notes_id: Uuid = "cccccccc-cccc-cccc-cccc-cccccccccc01".parse().unwrap();
+ let custom_tags_id: Uuid = "cccccccc-cccc-cccc-cccc-cccccccccc02".parse().unwrap();
+
+ repo.copy_task_properties(from_task_id, to_task_id).await?;
+
+ let properties = get_task_property_values(&pool, to_task_id).await;
+
+ // Check Custom Notes was copied
+ let notes_prop = properties.iter().find(|(id, _)| *id == custom_notes_id);
+ assert!(
+ notes_prop.is_some(),
+ "Custom Notes property should be copied"
+ );
+ assert_eq!(
+ notes_prop.unwrap().1.as_ref().unwrap(),
+ &serde_json::json!({"type": "String", "value": "This is a custom note"}),
+ "Custom Notes value should be copied"
+ );
+
+ // Check Custom Tags was copied
+ let tags_prop = properties.iter().find(|(id, _)| *id == custom_tags_id);
+ assert!(tags_prop.is_some(), "Custom Tags property should be copied");
+ assert_eq!(
+ tags_prop.unwrap().1.as_ref().unwrap(),
+ &serde_json::json!({"type": "SelectOption", "value": ["00000000-0000-0000-0000-000000000101"]}), // urgent
+ "Custom Tags value should be copied"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("system_properties"))
+)]
+async fn test_copy_task_properties_overwrites_existing(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let from_task_id = "source-task-overwrite"; // Status = Completed
+ let to_task_id = "dest-task-existing"; // Status = Not Started
+
+ // Copy should overwrite destination value
+ repo.copy_task_properties(from_task_id, to_task_id).await?;
+
+ let properties = get_task_property_values(&pool, to_task_id).await;
+ let status_prop = properties
+ .iter()
+ .find(|(id, _)| *id == SystemPropertyKey::Status.uuid());
+
+ assert_eq!(
+ status_prop.unwrap().1.as_ref().unwrap(),
+ &serde_json::json!({"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000004"]}), // Completed (from source)
+ "Destination value should be overwritten with source value"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_copy_task_properties_idempotent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PgSystemPropertiesRepository::new(pool.clone());
+
+ let from_task_id = "source-task-idempotent";
+ let to_task_id = "dest-task-idempotent";
+
+ // Copy twice
+ repo.copy_task_properties(from_task_id, to_task_id).await?;
+ repo.copy_task_properties(from_task_id, to_task_id).await?;
+
+ // Should still have exactly 10 properties
+ let count = count_task_properties(&pool, to_task_id).await;
+ assert_eq!(
+ count, 10,
+ "Should have exactly 10 properties after idempotent copies"
+ );
+
+ Ok(())
+}