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] - set property status to done for 'e' in unified list (#510)
Daniel Kweonf634eab2670b
diff --git a/js/app/packages/app/component/PropertyDisplayControl.tsx b/js/app/packages/app/component/PropertyDisplayControl.tsxindex 34f7068a51..cc7acb9aff 100644--- a/js/app/packages/app/component/PropertyDisplayControl.tsx+++ b/js/app/packages/app/component/PropertyDisplayControl.tsx@@ -178,7 +178,11 @@ export const PropertyDisplayControl: Component<PropertyDisplayControlProps> = (const [, data] = result;const properties = Array.isArray(data) ? data : [];- setAvailableProperties(properties);+ const normalizedProperties = properties.map((item) =>+ 'definition' in item ? item.definition : item+ );++ setAvailableProperties(normalizedProperties);setIsLoading(false);} catch (_apiError) {setError(ERROR_MESSAGES.PROPERTY_FETCH);diff --git a/js/app/packages/app/component/SoupContext.tsx b/js/app/packages/app/component/SoupContext.tsxindex a955a5b456..e5e9121fee 100644--- a/js/app/packages/app/component/SoupContext.tsx+++ b/js/app/packages/app/component/SoupContext.tsx@@ -1,6 +1,7 @@import { globalSplitManager } from '@app/signal/splitLayout';import { useChannelsContext } from '@core/component/ChannelsProvider';import { fileTypeToBlockName } from '@core/constant/allBlocks';+import { ENABLE_PROPERTIES_METADATA } from '@core/constant/featureFlags';import { HotkeyTags } from '@core/hotkey/constants';import { activeScope, hotkeyScopeTree } from '@core/hotkey/state';import { TOKENS } from '@core/hotkey/tokens';@@ -14,6 +15,10 @@ import type { EntityData } from '@macro-entity';import { entityHasUnreadNotifications } from '@notifications';import type { PreviewViewStandardLabel } from '@service-email/generated/schemas';import { useTutorialCompleted } from '@service-gql/client';+import {+ type PropertiesEntityType,+ propertiesServiceClient,+} from '@service-properties/client';import { storageServiceClient } from '@service-storage/client';import { createLazyMemo } from '@solid-primitives/memo';import { useQuery } from '@tanstack/solid-query';@@ -295,7 +300,18 @@ export function createNavigationEntityListShortcut({async (entities) => {const handler =VIEWCONFIG_DEFAULTS[selectedView() as DefaultView]?.hotkeyOptions?.e;- if (handler) {+ const propertiesEntityTypeMap: Record<string, PropertiesEntityType> = {+ email: 'THREAD',+ document: 'DOCUMENT',+ project: 'PROJECT',+ task: 'TASK',+ };++ const hasSupportedEntity = entities.some(+ (entity) => propertiesEntityTypeMap[entity.type]+ );++ if (handler || hasSupportedEntity) {if (isEntityLastItem()) {navigateThroughList({ axis: 'start', mode: 'step' });} else {@@ -303,10 +319,23 @@ export function createNavigationEntityListShortcut({}for (const entity of entities) {- handler(entity, {- soupContext: unifiedListContext,- notificationSource,- });+ if (handler) {+ handler(entity, {+ soupContext: unifiedListContext,+ notificationSource,+ });+ }+ const entityType = propertiesEntityTypeMap[entity.type];+ if (entityType && ENABLE_PROPERTIES_METADATA) {+ propertiesServiceClient+ .setPropertyStatusComplete({+ entity_type: entityType,+ entity_id: entity.id,+ })+ .catch((err) =>+ console.error('Failed to set status complete', err)+ );+ }}setViewDataStore(selectedView(), 'selectedEntities', []);@@ -316,9 +345,15 @@ export function createNavigationEntityListShortcut({},{canExecute: (entity) => {+ // notificationsif (entity.type === 'email' || entity.type === 'channel') return true;- if (entityHasUnreadNotifications(notificationSource, entity))++ // property status complete+ if (['document', 'project', 'task'].includes(entity.type)) return true;++ if (entityHasUnreadNotifications(notificationSource, entity)) {return true;+ }return false;},}diff --git a/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts b/js/app/packages/core/component/Properties/hooks/usePropertySelection.tsindex 05de208da2..f653e148d3 100644--- a/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts+++ b/js/app/packages/core/component/Properties/hooks/usePropertySelection.ts@@ -84,11 +84,20 @@ export function usePropertySelection(const [, data] = result;const availableProperties = Array.isArray(data) ? data : [];- // Transform the nested structure to flat structure- const transformedProperties = availableProperties.map((item) => ({- ...item.definition,- propertyOptions: item.property_options || [],- }));+ // Transform the nested or flat API response to a flat structure+ const transformedProperties = availableProperties.map((item) => {+ if ('definition' in item) {+ return {+ ...item.definition,+ propertyOptions: item.property_options || [],+ };+ }++ return {+ ...item,+ propertyOptions: [],+ };+ });setState((prev) => ({...prev,diff --git a/js/app/packages/core/component/Properties/types.ts b/js/app/packages/core/component/Properties/types.tsindex 5c5632183c..3480f6d96a 100644--- a/js/app/packages/core/component/Properties/types.ts+++ b/js/app/packages/core/component/Properties/types.ts@@ -87,6 +87,7 @@ export type PropertyDefinitionFlat = {id: string;is_metadata: boolean;is_multi_select: boolean;+ is_system: boolean;owner:| {scope: 'user';@@ -100,7 +101,11 @@ export type PropertyDefinitionFlat = {scope: 'user_and_organization';user_id: string;organization_id: number;+ }+ | {+ scope: 'system';};+ propertyOptions?: PropertyOption[];specific_entity_type?: EntityType | null;updated_at: string;};diff --git a/js/app/packages/macro-entity/src/components/Sort.tsx b/js/app/packages/macro-entity/src/components/Sort.tsxindex e8e3c79ed2..2cbeabdd46 100644--- a/js/app/packages/macro-entity/src/components/Sort.tsx+++ b/js/app/packages/macro-entity/src/components/Sort.tsx@@ -60,7 +60,10 @@ function PropertySortSearch(props: PropertySortSearchProps) {const [, data] = result;const properties = Array.isArray(data) ? data : [];- setAvailableProperties(properties);+ const normalizedProperties = properties.map((item) =>+ 'definition' in item ? item.definition : item+ );+ setAvailableProperties(normalizedProperties);} catch (_apiError) {// Silently fail}@@ -341,7 +344,10 @@ export function createSort<if (isErr(result)) return;const [, data] = result;const properties = Array.isArray(data) ? data : [];- const property = properties.find((p) => p.id === id);+ const normalizedProperties = properties.map((item) =>+ 'definition' in item ? item.definition : item+ );+ const property = normalizedProperties.find((p) => p.id === id);if (property) {setSelectedProperty(property);}diff --git a/js/app/packages/service-clients/service-properties/client.ts b/js/app/packages/service-clients/service-properties/client.tsindex 44b8f88c10..963b537967 100644--- a/js/app/packages/service-clients/service-properties/client.ts+++ b/js/app/packages/service-clients/service-properties/client.ts@@ -1,5 +1,4 @@import { SERVER_HOSTS } from '@core/constant/servers';-import type { ServiceClient } from '@core/service';import {type FetchWithTokenErrorCode,fetchWithToken,@@ -12,9 +11,55 @@ import {} from '@core/util/maybeResult';import { registerClient } from '@core/util/mockClient';import type { SafeFetchInit } from '@core/util/safeFetch';-import type { z } from 'zod';-import type * as schemas from './generated/zod';-import type { PropertiesService } from './service';+import type { AddPropertyOptionRequest } from './generated/schemas/addPropertyOptionRequest';+import type { CreatePropertyDefinitionRequest } from './generated/schemas/createPropertyDefinitionRequest';+import type { EntityPropertiesResponse } from './generated/schemas/entityPropertiesResponse';+import type { EntityType } from './generated/schemas/entityType';+import type { GetEntityPropertiesParams } from './generated/schemas/getEntityPropertiesParams';+import type { ListPropertiesParams } from './generated/schemas/listPropertiesParams';+import type { PropertyDefinition } from './generated/schemas/propertyDefinition';+import type { PropertyDefinitionResponse } from './generated/schemas/propertyDefinitionResponse';+import type { PropertyOption } from './generated/schemas/propertyOption';+import type { SetEntityPropertyRequest } from './generated/schemas/setEntityPropertyRequest';++type PropertiesEntityType = EntityType;++type ListPropertiesArgs = ListPropertiesParams;+type CreatePropertyDefinitionArgs = {+ body: CreatePropertyDefinitionRequest;+};+type DeletePropertyDefinitionArgs = {+ definition_id: string;+};+type GetEntityPropertiesArgs = {+ entity_type: EntityType;+ entity_id: string;+ query: GetEntityPropertiesParams;+};+type SetEntityPropertyArgs = {+ entity_type: EntityType;+ entity_id: string;+ property_id: string;+ body: SetEntityPropertyRequest;+};+type DeleteEntityPropertyArgs = {+ entity_property_id: string;+};+type GetPropertyOptionsArgs = {+ definition_id: string;+};+type AddPropertyOptionArgs = {+ definition_id: string;+ body: AddPropertyOptionRequest;+};+type DeletePropertyOptionArgs = {+ definition_id: string;+ option_id: string;+};+type SetPropertyStatusCompleteArgs = {+ entity_type: PropertiesEntityType;+ entity_id: string;+};const propertiesHost: string = SERVER_HOSTS['properties-service'];@@ -35,60 +80,33 @@ export function propertiesFetch<T extends ObjectLike = never>(return fetchWithToken<T>(`${propertiesHost}${url}`, init);}-export const propertiesServiceClient: ServiceClient<PropertiesService> = {- listProperties: async (args) => {+export const propertiesServiceClient = {+ listProperties: async (args: ListPropertiesArgs) => {const queryParams = new URLSearchParams();queryParams.set('scope', args.scope);if (args.include_options !== undefined) {queryParams.set('include_options', String(args.include_options));}- return await propertiesFetch<- z.infer<typeof schemas.listPropertiesResponse>- >(`/properties/definitions?${queryParams}`, {- method: 'GET',- });+ return await propertiesFetch<PropertyDefinitionResponse[]>(+ `/properties/definitions?${queryParams}`,+ {+ method: 'GET',+ }+ );},- createPropertyDefinition: async (args) => {- return await propertiesFetch<{- created_at: string;- data_type:- | 'boolean'- | 'date'- | 'number'- | 'string'- | 'select_number'- | 'select_string'- | 'entity';- display_name: string;- id: string;- is_metadata: boolean;- is_multi_select: boolean;- owner:- | { scope: 'user'; user_id: string }- | { scope: 'organization'; organization_id: number }- | {- scope: 'user_and_organization';- user_id: string;- organization_id: number;- };- specific_entity_type?:- | 'channel'- | 'chat'- | 'document'- | 'project'- | 'thread'- | 'user'- | null;- updated_at: string;- }>(`/properties/definitions`, {- method: 'POST',- body: JSON.stringify(args.body),- });+ createPropertyDefinition: async (args: CreatePropertyDefinitionArgs) => {+ return await propertiesFetch<PropertyDefinition>(+ `/properties/definitions`,+ {+ method: 'POST',+ body: JSON.stringify(args.body),+ }+ );},- deletePropertyDefinition: async (args) => {+ deletePropertyDefinition: async (args: DeletePropertyDefinitionArgs) => {const result = await propertiesFetch<{}>(`/properties/definitions/${args.definition_id}`,{@@ -99,7 +117,7 @@ export const propertiesServiceClient: ServiceClient<PropertiesService> = {return mapOk(result, () => ({ success: true }));},- getEntityProperties: async (args) => {+ getEntityProperties: async (args: GetEntityPropertiesArgs) => {const queryParams = new URLSearchParams();if (args.query.include_metadata !== undefined) {@@ -109,14 +127,12 @@ export const propertiesServiceClient: ServiceClient<PropertiesService> = {const queryString = queryParams.toString();const url = `/properties/entities/${args.entity_type}/${args.entity_id}${queryString ? `?${queryString}` : ''}`;- return await propertiesFetch<- z.infer<typeof schemas.getEntityPropertiesResponse>- >(url, {+ return await propertiesFetch<EntityPropertiesResponse>(url, {method: 'GET',});},- setEntityProperty: async (args) => {+ setEntityProperty: async (args: SetEntityPropertyArgs) => {const url = `/properties/entities/${args.entity_type}/${args.entity_id}/${args.property_id}`;const result = await propertiesFetch<{}>(url, {@@ -127,7 +143,7 @@ export const propertiesServiceClient: ServiceClient<PropertiesService> = {return mapOk(result, () => ({ success: true }));},- deleteEntityProperty: async (args) => {+ deleteEntityProperty: async (args: DeleteEntityPropertyArgs) => {const result = await propertiesFetch<{}>(`/properties/entity_properties/${args.entity_property_id}`,{@@ -138,31 +154,26 @@ export const propertiesServiceClient: ServiceClient<PropertiesService> = {return mapOk(result, () => ({ success: true }));},- getPropertyOptions: async (args) => {- return await propertiesFetch<- z.infer<typeof schemas.getPropertyOptionsResponse>- >(`/properties/definitions/${args.definition_id}/options`, {- method: 'GET',- });+ getPropertyOptions: async (args: GetPropertyOptionsArgs) => {+ return await propertiesFetch<PropertyOption[]>(+ `/properties/definitions/${args.definition_id}/options`,+ {+ method: 'GET',+ }+ );},- addPropertyOption: async (args) => {- return await propertiesFetch<{- created_at: string;- display_order: number;- id: string;- property_definition_id: string;- updated_at: string;- value:- | { type: 'string'; value: string }- | { type: 'number'; value: number };- }>(`/properties/definitions/${args.definition_id}/options`, {- method: 'POST',- body: JSON.stringify(args.body),- });+ addPropertyOption: async (args: AddPropertyOptionArgs) => {+ return await propertiesFetch<PropertyOption>(+ `/properties/definitions/${args.definition_id}/options`,+ {+ method: 'POST',+ body: JSON.stringify(args.body),+ }+ );},- deletePropertyOption: async (args) => {+ deletePropertyOption: async (args: DeletePropertyOptionArgs) => {const result = await propertiesFetch<{}>(`/properties/definitions/${args.definition_id}/options/${args.option_id}`,{@@ -172,6 +183,16 @@ export const propertiesServiceClient: ServiceClient<PropertiesService> = {return mapOk(result, () => ({ success: true }));},++ setPropertyStatusComplete: async (args: SetPropertyStatusCompleteArgs) => {+ const url = `/properties/entities/${args.entity_type}/${args.entity_id}/status/complete`;+ const result = await propertiesFetch<{}>(url, {+ method: 'PATCH',+ });+ return mapOk(result, () => ({ success: true }));+ },};registerClient('properties', propertiesServiceClient);++export type { PropertiesEntityType };diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 01394d81b8..82a752cb37 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -6522,6 +6522,23 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "properties"+version = "0.1.0"+dependencies = [+ "anyhow",+ "macro_db_migrator",+ "macro_uuid",+ "mockall",+ "models_properties",+ "serde_json",+ "sqlx",+ "system_properties",+ "tokio",+ "tracing",+ "uuid",+]+[[package]]name = "properties_db_client"version = "0.1.0"@@ -6563,6 +6580,7 @@ dependencies = ["model","models_permissions","models_properties",+ "properties","properties_db_client","secretsmanager_client","serde",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex e053f5a745..a030df567b 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -86,6 +86,7 @@ members = ["organization_service","organization_service_client","permission",+ "properties","properties_db_client","properties_service","properties_service_client",diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 59128f7ac4..804f2f90a7 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -57,6 +57,7 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./soup/.envecho "DATABASE_URL={{ MACRODB }}" >> ./email/.envecho "DATABASE_URL={{ MACRODB }}" >> ./system_properties/.env+ echo "DATABASE_URL={{ MACRODB }}" >> ./properties/.envsetup_macrodb:just macro_db_client/migrate_dbdiff --git a/rust/cloud-storage/properties/.sqlx/query-7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a.json b/rust/cloud-storage/properties/.sqlx/query-7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a.jsonnew file mode 100644index 0000000000..f5068aa5c5--- /dev/null+++ b/rust/cloud-storage/properties/.sqlx/query-7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a.json@@ -0,0 +1,33 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK"+ ]+ }+ }+ },+ "Uuid",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a"+}diff --git a/rust/cloud-storage/properties/Cargo.toml b/rust/cloud-storage/properties/Cargo.tomlnew file mode 100644index 0000000000..0346b25a0b--- /dev/null+++ b/rust/cloud-storage/properties/Cargo.toml@@ -0,0 +1,23 @@+[package]+edition = "2024"+name = "properties"+publish = false+version = "0.1.0"++[dependencies]+anyhow = { workspace = true }+macro_uuid = { path = "../macro_uuid" }+models_properties = { path = "../models_properties" }+serde_json = { workspace = true }+sqlx = { workspace = true }+system_properties = { path = "../system_properties" }+tracing = { workspace = true }+uuid = { workspace = true }++[dev-dependencies]+mockall = { workspace = true }+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }++[package.metadata.sqlx]+offline = truediff --git a/rust/cloud-storage/properties/fixtures/properties_seed.sql b/rust/cloud-storage/properties/fixtures/properties_seed.sqlnew file mode 100644index 0000000000..adf7c66161--- /dev/null+++ b/rust/cloud-storage/properties/fixtures/properties_seed.sql@@ -0,0 +1,40 @@+-- Entity with status attached but not completed (in progress)+INSERT INTO entity_properties (+ id,+ entity_id,+ entity_type,+ property_definition_id,+ values,+ created_at,+ updated_at+ )+VALUES (+ '00000001-0000-0000-0000-000000000301',+ 'entity-status-incomplete',+ 'DOCUMENT',+ '00000001-0000-0000-0000-000000000002',+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000002"]}'::jsonb,+ -- In Progress+ NOW(),+ NOW()+ );+-- Entity with status already completed+INSERT INTO entity_properties (+ id,+ entity_id,+ entity_type,+ property_definition_id,+ values,+ created_at,+ updated_at+ )+VALUES (+ '00000001-0000-0000-0000-000000000302',+ 'entity-status-complete',+ 'DOCUMENT',+ '00000001-0000-0000-0000-000000000002',+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000004"]}'::jsonb,+ -- Completed+ NOW(),+ NOW()+ );\ No newline at end of filediff --git a/rust/cloud-storage/properties/src/domain.rs b/rust/cloud-storage/properties/src/domain.rsnew file mode 100644index 0000000000..6b5ed36281--- /dev/null+++ b/rust/cloud-storage/properties/src/domain.rs@@ -0,0 +1,5 @@+pub mod ports;+pub mod service;+pub mod service_impl;+#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsnew file mode 100644index 0000000000..7c82e335b6--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -0,0 +1,27 @@+//! Port definitions (traits) for properties.+//!+//! These traits define the interfaces that the domain layer uses.+//! Implementations live in the outbound module.++use models_properties::EntityType;+use models_properties::service::property_value::PropertyValue;+use uuid::Uuid;++/// Repository trait for property operations.+///+/// This trait abstracts the database layer, allowing for different implementations+/// (e.g., PostgreSQL, mock for testing).+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+pub trait PropertiesRepo: Send + Sync + 'static {+ type Err;++ /// 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(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ value: Option<PropertyValue>,+ ) -> 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.rsnew file mode 100644index 0000000000..08ce33bb91--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/service.rs@@ -0,0 +1,16 @@+//! Service trait for properties.++use models_properties::EntityType;++/// 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;+}diff --git a/rust/cloud-storage/properties/src/domain/service_impl.rs b/rust/cloud-storage/properties/src/domain/service_impl.rsnew file mode 100644index 0000000000..bd3520ffdb--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/service_impl.rs@@ -0,0 +1,59 @@+//! 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 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(())+ }+}diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rsnew file mode 100644index 0000000000..a1a6d2d589--- /dev/null+++ b/rust/cloud-storage/properties/src/domain/test.rs@@ -0,0 +1,60 @@+//! Unit tests for PropertiesServiceImpl using mockall-generated repo.++use super::service_impl::PropertiesServiceImpl;+use crate::domain::{ports::MockPropertiesRepo, service::PropertiesService};+use anyhow::anyhow;+use models_properties::{EntityType, service::property_value::PropertyValue};+use system_properties::{StatusOption, SystemPropertyKey};++#[tokio::test]+async fn test_set_system_property_status_complete_happy_path() {+ let mut repo = MockPropertiesRepo::new();++ repo.expect_update_entity_property_value_if_exists()+ .withf(|entity_id, entity_type, prop_id, value| {+ if entity_id != "e1" {+ return false;+ }+ if *entity_type != EntityType::Document {+ return false;+ }+ if *prop_id != SystemPropertyKey::STATUS_UUID {+ return false;+ }+ match value {+ Some(PropertyValue::SelectOption(ids)) => {+ ids.len() == 1 && ids[0] == StatusOption::COMPLETED_UUID+ }+ _ => false,+ }+ })+ .returning(|_, _, _, _| Box::pin(async { Ok(()) }));++ let service = PropertiesServiceImpl::new(repo);++ let entity_id = "e1";+ let entity_type = EntityType::Document;++ service+ .set_system_property_status_complete(entity_id, entity_type)+ .await+ .unwrap();++ // expectations on the mock validate the call shape+}++#[tokio::test]+async fn test_set_system_property_status_complete_error_path() {+ let mut repo = MockPropertiesRepo::new();+ repo.expect_update_entity_property_value_if_exists()+ .returning(|_, _, _, _| Box::pin(async { Err(anyhow!("boom")) }));++ let service = PropertiesServiceImpl::new(repo);++ let err = service+ .set_system_property_status_complete("e1", EntityType::Document)+ .await+ .unwrap_err();++ assert_eq!(err.to_string(), "boom");+}diff --git a/rust/cloud-storage/properties/src/lib.rs b/rust/cloud-storage/properties/src/lib.rsnew file mode 100644index 0000000000..5d33b86a54--- /dev/null+++ b/rust/cloud-storage/properties/src/lib.rs@@ -0,0 +1,19 @@+//! Properties crate.+//!+//! Provides domain logic for property operations following hexagonal architecture.+//!+//! # Architecture+//!+//! This crate follows hexagonal architecture:+//! - `domain::ports` - Port definitions (traits/interfaces)+//! - `domain::service` - Service trait+//! - `domain::service_impl` - Service implementation+//! - `outbound` - Outbound adapters (e.g., PostgreSQL implementation)++pub mod domain;+pub mod outbound;++pub use domain::ports::PropertiesRepo;+pub use domain::service::PropertiesService;+pub use domain::service_impl::PropertiesServiceImpl;+pub use outbound::properties_pg_repo::PropertiesPgRepo;diff --git a/rust/cloud-storage/properties/src/outbound.rs b/rust/cloud-storage/properties/src/outbound.rsnew file mode 100644index 0000000000..a5b981b231--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound.rs@@ -0,0 +1,3 @@+pub mod properties_pg_repo;+#[cfg(test)]+pub mod test;diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rsnew file mode 100644index 0000000000..571c334026--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs@@ -0,0 +1,69 @@+//! PostgreSQL implementation for properties repository.++use anyhow::Context;+use models_properties::EntityType;+use models_properties::service::property_value::PropertyValue;+use sqlx::{Pool, Postgres};+use uuid::Uuid;++use crate::domain::ports::PropertiesRepo;++/// PostgreSQL implementation of PropertiesRepo.+#[derive(Debug, Clone)]+pub struct PropertiesPgRepo {+ pool: Pool<Postgres>,+}++impl PropertiesPgRepo {+ /// Create a new PropertiesPgRepo.+ pub fn new(pool: Pool<Postgres>) -> Self {+ Self { pool }+ }+}++impl PropertiesRepo for PropertiesPgRepo {+ type Err = anyhow::Error;++ #[tracing::instrument(skip(self, value))]+ async fn update_entity_property_value_if_exists(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+ value: Option<PropertyValue>,+ ) -> Result<(), Self::Err> {+ // Serialize PropertyValue to JSONB (or NULL if None)+ let value_json = match value {+ Some(v) => serde_json::to_value(&v).context("failed to serialize property value")?,+ None => serde_json::Value::Null,+ };++ tracing::debug!(value_json = ?value_json, "updating entity property if exists");++ // Atomic update - only updates if the property is already attached+ let result = sqlx::query!(+ r#"+ UPDATE entity_properties+ SET values = $4, updated_at = NOW()+ WHERE entity_id = $1+ AND entity_type = $2+ AND property_definition_id = $3+ "#,+ entity_id,+ entity_type as EntityType,+ property_definition_id,+ value_json+ )+ .execute(&self.pool)+ .await+ .context("failed to update entity property")?;++ if result.rows_affected() > 0 {+ tracing::info!("successfully updated entity property");+ } else {+ tracing::debug!("entity property not attached, no-op");+ }++ Ok(())+ }+}diff --git a/rust/cloud-storage/properties/src/outbound/test.rs b/rust/cloud-storage/properties/src/outbound/test.rsnew file mode 100644index 0000000000..d2fecdb8f4--- /dev/null+++ b/rust/cloud-storage/properties/src/outbound/test.rs@@ -0,0 +1,124 @@+//! Integration tests for PropertiesPgRepo using sqlx and real migrations.++use super::properties_pg_repo::PropertiesPgRepo;+use crate::domain::ports::PropertiesRepo;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use models_properties::{EntityType, service::property_value::PropertyValue};+use sqlx::{Pool, Postgres};+use system_properties::{StatusOption, SystemPropertyKey};++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties_seed"))+)]+async fn updates_existing_property(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool.clone());+ let entity_id = "entity-status-incomplete";+ let property_id = SystemPropertyKey::STATUS_UUID;++ // Update value to completed+ repo.update_entity_property_value_if_exists(+ entity_id,+ EntityType::Document,+ property_id,+ Some(PropertyValue::SelectOption(vec![+ StatusOption::COMPLETED_UUID,+ ])),+ )+ .await?;++ // Verify+ let stored: serde_json::Value = sqlx::query_scalar::<_, serde_json::Value>(+ r#"+ SELECT values FROM entity_properties+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3+ "#,+ )+ .bind(entity_id)+ .bind(EntityType::Document)+ .bind(property_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(+ stored,+ serde_json::json!({"type": "SelectOption", "value": [StatusOption::COMPLETED_UUID]})+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties_seed"))+)]+async fn no_op_when_property_not_attached(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool.clone());+ let entity_id = "entity-no-status";+ let property_id = SystemPropertyKey::STATUS_UUID;++ repo.update_entity_property_value_if_exists(+ entity_id,+ EntityType::Document,+ property_id,+ Some(PropertyValue::SelectOption(vec![+ StatusOption::COMPLETED_UUID,+ ])),+ )+ .await?;++ let count: i64 = sqlx::query_scalar::<_, i64>(+ r#"+ SELECT COUNT(*) FROM entity_properties+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3+ "#,+ )+ .bind(entity_id)+ .bind(EntityType::Document)+ .bind(property_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(count, 0, "no rows should be created or updated");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("properties_seed"))+)]+async fn idempotent_when_already_completed(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = PropertiesPgRepo::new(pool.clone());+ let entity_id = "entity-status-complete";+ let property_id = SystemPropertyKey::STATUS_UUID;++ repo.update_entity_property_value_if_exists(+ entity_id,+ EntityType::Document,+ property_id,+ Some(PropertyValue::SelectOption(vec![+ StatusOption::COMPLETED_UUID,+ ])),+ )+ .await?;++ let stored: serde_json::Value = sqlx::query_scalar::<_, serde_json::Value>(+ r#"+ SELECT values FROM entity_properties+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3+ "#,+ )+ .bind(entity_id)+ .bind(EntityType::Document)+ .bind(property_id)+ .fetch_one(&pool)+ .await?;++ assert_eq!(+ stored,+ serde_json::json!({"type": "SelectOption", "value": [StatusOption::COMPLETED_UUID]})+ );++ Ok(())+}diff --git a/rust/cloud-storage/properties_service/Cargo.toml b/rust/cloud-storage/properties_service/Cargo.tomlindex 103afae96a..a9ea86a52b 100644--- a/rust/cloud-storage/properties_service/Cargo.toml+++ b/rust/cloud-storage/properties_service/Cargo.toml@@ -37,8 +37,9 @@ model = { path = "../model" }models_permissions = { path = "../models_permissions" }models_properties = { path = "../models_properties" }properties_db_client = { path = "../properties_db_client" }-secretsmanager_client = { path = "../secretsmanager_client" }+properties = { path = "../properties" }system_properties = { path = "../system_properties" }+secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }serde_json = { workspace = true }serde_with = { workspace = true }diff --git a/rust/cloud-storage/properties_service/src/api/context.rs b/rust/cloud-storage/properties_service/src/api/context.rsindex 293672e776..1be4e95b88 100644--- a/rust/cloud-storage/properties_service/src/api/context.rs+++ b/rust/cloud-storage/properties_service/src/api/context.rs@@ -7,6 +7,7 @@ use sqlx::PgPool;use std::sync::Arc;use crate::config::Config;+use properties::PropertiesServiceImpl;#[derive(Clone, FromRef)]pub struct ApiContext {@@ -16,4 +17,5 @@ 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>>,}diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rsindex 6ae1acdfe1..b13c50bd41 100644--- a/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rs+++ b/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rs@@ -3,6 +3,7 @@ pub mod delete_property;pub mod get;pub mod get_bulk;pub mod set;+pub mod set_property_status_complete;pub mod types;// Re-export commonly used typesdiff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/set_property_status_complete.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/set_property_status_complete.rsnew file mode 100644index 0000000000..a874ab750b--- /dev/null+++ b/rust/cloud-storage/properties_service/src/api/properties/entities/set_property_status_complete.rs@@ -0,0 +1,88 @@+//! Set entity status to complete endpoint.+//!+//! If the entity has the system status property attached, set it to "Completed".+//! If not attached, this is a no-op (still returns 204).++use axum::{+ extract::{Extension, Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+};+use thiserror::Error;++use crate::api::context::ApiContext;+use crate::api::permissions::{PermissionError, check_entity_edit_permission};+use model::user::UserContext;+use models_properties::{EntityReference, EntityType};+use properties::PropertiesService;++#[derive(Debug, Error)]+pub enum SetPropertyStatusCompleteErr {+ #[error("An internal error occurred")]+ InternalError(String),+ #[error("{0}")]+ Permission(#[from] PermissionError),+}++impl IntoResponse for SetPropertyStatusCompleteErr {+ fn into_response(self) -> Response {+ let status_code = match &self {+ SetPropertyStatusCompleteErr::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ SetPropertyStatusCompleteErr::Permission(e) => e.status_code(),+ };++ if status_code.is_server_error() {+ tracing::error!(+ error = ?self,+ error_type = "SetPropertyStatusCompleteErr",+ "Internal server error"+ );+ }++ (status_code, self.to_string()).into_response()+ }+}++/// Set an entity's status property to "Completed".+///+/// If the entity has a status property attached, it will be set to "Completed".+/// If the entity does not have a status property, this is a no-op and returns success.+#[utoipa::path(+ patch,+ path = "/properties/entities/{entity_type}/{entity_id}/status/complete",+ params(+ ("entity_type" = EntityType, Path, description = "Entity type (document, channel, project, thread, chat)"),+ ("entity_id" = String, Path, description = "Entity ID")+ ),+ responses(+ (status = 204, description = "Status set to complete"),+ (status = 403, description = "Access denied"),+ (status = 500, description = "Internal server error")+ ),+ tags = ["Properties"]+)]+#[tracing::instrument(skip(context, user_context), fields(entity_id = %entity_id, entity_type = ?entity_type, user_id = %user_context.user_id), err)]+pub async fn set_property_status_complete(+ Path((entity_type, entity_id)): Path<(EntityType, String)>,+ State(context): State<ApiContext>,+ Extension(user_context): Extension<UserContext>,+) -> Result<StatusCode, SetPropertyStatusCompleteErr> {+ tracing::info!("setting entity status to complete");++ // Check edit permissions+ let entity_ref = EntityReference {+ entity_id: entity_id.clone(),+ entity_type,+ };+ check_entity_edit_permission(&context, &user_context.user_id, &entity_ref).await?;++ // Delegate to service layer for business logic+ context+ .properties_service+ .set_system_property_status_complete(&entity_id, entity_type)+ .await+ .map_err(|e| SetPropertyStatusCompleteErr::InternalError(e.to_string()))?;++ tracing::debug!("status complete handled");+ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/cloud-storage/properties_service/src/api/properties/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/mod.rsindex edbea244b0..a3319bbd8d 100644--- a/rust/cloud-storage/properties_service/src/api/properties/mod.rs+++ b/rust/cloud-storage/properties_service/src/api/properties/mod.rs@@ -1,7 +1,7 @@use crate::api::context::ApiContext;use axum::{Router,- routing::{delete, get, put},+ routing::{delete, get, patch, put},};pub mod definitions;@@ -50,6 +50,13 @@ pub fn router() -> Router<ApiContext> {).route("/entity_properties/:entity_property_id",- delete(entities::delete_property::delete_entity_property).layer(ensure_user_exists),+ delete(entities::delete_property::delete_entity_property)+ .layer(ensure_user_exists.clone()),+ )+ // Status shortcut - requires authentication+ .route(+ "/entities/:entity_type/:entity_id/status/complete",+ patch(entities::set_property_status_complete::set_property_status_complete)+ .layer(ensure_user_exists),)}diff --git a/rust/cloud-storage/properties_service/src/main.rs b/rust/cloud-storage/properties_service/src/main.rsindex 1be8e34e07..b4213527d3 100644--- a/rust/cloud-storage/properties_service/src/main.rs+++ b/rust/cloud-storage/properties_service/src/main.rs@@ -66,12 +66,20 @@ async fn main() -> anyhow::Result<()> {"initialized comms service client");+ // Initialize properties service+ let properties_repository = properties::PropertiesPgRepo::new(db.clone());+ let properties_service = Arc::new(properties::PropertiesServiceImpl::new(+ properties_repository,+ ));+ tracing::info!("initialized properties service");+api::setup_and_serve(ApiContext {db,jwt_args,config: Arc::new(config),internal_auth_key,comms_service_client: Arc::new(comms_service_client),+ properties_service,}).await?;Ok(())