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.

fix(properties): tag deletion cascade + atomic option delta endpoints (#4415)

gbirmanf74dc94d466c
diff --git a/js/app/packages/property/src/tags/useDocTags.ts b/js/app/packages/property/src/tags/useDocTags.ts
index 41e1ce942f..0e72ac49c9 100644
--- a/js/app/packages/property/src/tags/useDocTags.ts
+++ b/js/app/packages/property/src/tags/useDocTags.ts
@@ -1,4 +1,7 @@
-import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
+import {
+ useAddEntityPropertyOptionMutation,
+ useRemoveEntityPropertyOptionMutation,
+} from '@queries/properties/entity';
import {
useEnsureTagSetMutation,
useTagsQuery,
@@ -42,7 +45,8 @@ function definitionDomain(
export function useDocTags(entityId: string, entityType: EntityType) {
const tagsQuery = useTagsQuery();
const ensureTagSet = useEnsureTagSetMutation();
- const saveMutation = useBulkSaveEntityPropertiesMutation();
+ const addOption = useAddEntityPropertyOptionMutation();
+ const removeOption = useRemoveEntityPropertyOptionMutation();
const { properties } = useEntityProperties(entityId, entityType, false);
const tagSets = (): TagSetResponse[] => tagsQuery.data ?? [];
@@ -107,30 +111,17 @@ export function useDocTags(entityId: string, entityType: EntityType) {
return provisioned.definition;
};
- const saveScope = async (
- definition: PropertyDefinitionDetailResponse,
- optionIds: string[]
- ) => {
- await saveMutation.mutateAsync({
- properties: [
- {
- entityId,
- entityType,
- property: definitionDomain(definition),
- apiValues: {
- valueType: 'SELECT_STRING',
- values: optionIds.length > 0 ? optionIds : null,
- },
- },
- ],
- });
- };
-
const applyTag = async (scope: TagScope, optionId: string) => {
const definition = await resolveDefinition(scope);
const current = appliedOptionIdsForDefinition(definition.id);
if (current.includes(optionId)) return;
- await saveScope(definition, [...current, optionId]);
+ await addOption.mutateAsync({
+ entityId,
+ entityType,
+ property: definitionDomain(definition),
+ optionId,
+ optimisticOptionIds: [...current, optionId],
+ });
};
const removeTag = async (scope: TagScope, optionId: string) => {
@@ -138,10 +129,13 @@ export function useDocTags(entityId: string, entityType: EntityType) {
if (!definition) return;
const current = appliedOptionIdsForDefinition(definition.id);
if (!current.includes(optionId)) return;
- await saveScope(
- definition,
- current.filter((id) => id !== optionId)
- );
+ await removeOption.mutateAsync({
+ entityId,
+ entityType,
+ property: definitionDomain(definition),
+ optionId,
+ optimisticOptionIds: current.filter((id) => id !== optionId),
+ });
};
const toggleTag = async (scope: TagScope, optionId: string) => {
diff --git a/js/app/packages/queries/properties/entity.ts b/js/app/packages/queries/properties/entity.ts
index 0a47c451a1..7c19394c3c 100644
--- a/js/app/packages/queries/properties/entity.ts
+++ b/js/app/packages/queries/properties/entity.ts
@@ -290,6 +290,122 @@ export function useAddEntityPropertyMutation(
}));
}
+type EntityPropertyOptionParams = {
+ entityId: string;
+ entityType: EntityType;
+ property: Property | PropertyDefinitionDomain;
+ optionId: string;
+ /**
+ * Full option-id array to show optimistically (current value ± optionId). The
+ * server applies the single-option delta atomically under a row lock; this
+ * array only drives the local cache so the UI updates instantly.
+ */
+ optimisticOptionIds: string[];
+};
+
+type EntityPropertyOptionContext = {
+ soupTxn?: SoupTransaction;
+};
+
+function entityPropertyOptionCallbacks(
+ failureMessage: string,
+ callbacks?: MutationCallbacks<
+ void,
+ Error,
+ EntityPropertyOptionParams,
+ EntityPropertyOptionContext
+ >
+) {
+ return withCallbacks<
+ void,
+ Error,
+ EntityPropertyOptionParams,
+ EntityPropertyOptionContext
+ >(
+ {
+ onMutate: (vars): EntityPropertyOptionContext => {
+ const value: SoupPropertyValue =
+ vars.optimisticOptionIds.length > 0
+ ? { type: 'SelectOption', value: vars.optimisticOptionIds }
+ : null;
+ const soupTxn = optimisticUpdateSoupEntityProperty(
+ vars.entityId,
+ vars.property,
+ value
+ );
+ return { soupTxn };
+ },
+ onError: (error, _vars, context) => {
+ context?.soupTxn?.rollback();
+ console.error(failureMessage, error);
+ toast.failure(failureMessage);
+ },
+ onSettled: (_data, _error, variables) => {
+ invalidatePropertiesForEntity(variables.entityType, variables.entityId);
+ invalidateSoupEntity(variables.entityId);
+ },
+ },
+ callbacks
+ );
+}
+
+/**
+ * Adds a single option to a multi-select value via the atomic delta endpoint.
+ * Unlike the full-value save, concurrent edits to the same value merge instead
+ * of clobbering each other.
+ */
+export function useAddEntityPropertyOptionMutation(
+ callbacks?: MutationCallbacks<
+ void,
+ Error,
+ EntityPropertyOptionParams,
+ EntityPropertyOptionContext
+ >
+) {
+ return useMutation(() => ({
+ mutationFn: async (vars: EntityPropertyOptionParams) => {
+ await throwOnErr(
+ async () =>
+ await propertiesServiceClient.addEntityPropertyOption({
+ entity_type: vars.entityType,
+ entity_id: vars.entityId,
+ property_id: getPropertyDefinitionId(vars.property),
+ option_id: vars.optionId,
+ })
+ );
+ },
+ ...entityPropertyOptionCallbacks('Failed to add tag', callbacks),
+ }));
+}
+
+/**
+ * Removes a single option from a multi-select value via the atomic delta
+ * endpoint. A no-op server-side if the option is already gone.
+ */
+export function useRemoveEntityPropertyOptionMutation(
+ callbacks?: MutationCallbacks<
+ void,
+ Error,
+ EntityPropertyOptionParams,
+ EntityPropertyOptionContext
+ >
+) {
+ return useMutation(() => ({
+ mutationFn: async (vars: EntityPropertyOptionParams) => {
+ await throwOnErr(
+ async () =>
+ await propertiesServiceClient.removeEntityPropertyOption({
+ entity_type: vars.entityType,
+ entity_id: vars.entityId,
+ property_id: getPropertyDefinitionId(vars.property),
+ option_id: vars.optionId,
+ })
+ );
+ },
+ ...entityPropertyOptionCallbacks('Failed to remove tag', callbacks),
+ }));
+}
+
type BulkSaveEntityPropertiesParams = {
properties: Array<{
entityId: string;
diff --git a/js/app/packages/service-clients/service-properties/client.ts b/js/app/packages/service-clients/service-properties/client.ts
index 93950bc193..9de9b4ec05 100644
--- a/js/app/packages/service-clients/service-properties/client.ts
+++ b/js/app/packages/service-clients/service-properties/client.ts
@@ -46,6 +46,12 @@ type SetEntityPropertyArgs = {
type DeleteEntityPropertyArgs = {
entity_property_id: string;
};
+type EntityPropertyOptionArgs = {
+ entity_type: EntityType;
+ entity_id: string;
+ property_id: string;
+ option_id: string;
+};
type GetPropertyOptionsArgs = {
definition_id: string;
};
@@ -169,6 +175,22 @@ export const propertiesServiceClient = {
return result.map(() => ({ success: true }));
},
+ addEntityPropertyOption: async (args: EntityPropertyOptionArgs) => {
+ const url = `/properties/entities/${args.entity_type}/${args.entity_id}/${args.property_id}/options/${args.option_id}`;
+ const result = await propertiesFetch<{}>(url, {
+ method: 'POST',
+ });
+ return result.map(() => ({ success: true }));
+ },
+
+ removeEntityPropertyOption: async (args: EntityPropertyOptionArgs) => {
+ const url = `/properties/entities/${args.entity_type}/${args.entity_id}/${args.property_id}/options/${args.option_id}`;
+ const result = await propertiesFetch<{}>(url, {
+ method: 'DELETE',
+ });
+ return result.map(() => ({ success: true }));
+ },
+
getPropertyOptions: async (args: GetPropertyOptionsArgs) => {
return await propertiesFetch<PropertyOption[]>(
`/properties/definitions/${args.definition_id}/options`,
diff --git a/js/app/packages/service-clients/service-properties/generated/zod.ts b/js/app/packages/service-clients/service-properties/generated/zod.ts
index 514b841800..dc4316c887 100644
--- a/js/app/packages/service-clients/service-properties/generated/zod.ts
+++ b/js/app/packages/service-clients/service-properties/generated/zod.ts
@@ -1284,6 +1284,55 @@ export const setEntityPropertyBody = zod
})
.describe('Type-safe request for setting entity property values.');
+/**
+ * Atomic delta: the option is appended to the current stored value (deduped,
+attaching the property if needed), so concurrent edits to the same value
+merge rather than overwrite each other. Prefer this over the full-value PUT
+when adding one option.
+ * @summary Add a single option to an entity's multi-select property value.
+ */
+export const addEntityPropertyOptionParams = zod.object({
+ entity_type: zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe('Entity type (user, document, channel, project, thread)'),
+ entity_id: zod.string().describe('Entity ID'),
+ property_id: zod.uuid().describe('Property ID'),
+ option_id: zod.uuid().describe('Option ID to add'),
+});
+
+/**
+ * Atomic delta: the option is stripped from the current stored value (a no-op
+if absent), so concurrent edits to the same value merge rather than overwrite
+each other.
+ * @summary Remove a single option from an entity's multi-select property value.
+ */
+export const removeEntityPropertyOptionParams = zod.object({
+ entity_type: zod
+ .enum([
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'TASK',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe('Entity type (user, document, channel, project, thread)'),
+ entity_id: zod.string().describe('Entity ID'),
+ property_id: zod.uuid().describe('Property ID'),
+ option_id: zod.uuid().describe('Option ID to remove'),
+});
+
/**
* @summary Remove a specific entity property by its ID
*/
diff --git a/js/app/packages/service-clients/service-properties/openapi.json b/js/app/packages/service-clients/service-properties/openapi.json
index 0ecbf524ff..804974123c 100644
--- a/js/app/packages/service-clients/service-properties/openapi.json
+++ b/js/app/packages/service-clients/service-properties/openapi.json
@@ -507,6 +507,125 @@
}
}
},
+ "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Add a single option to an entity's multi-select property value.",
+ "description": "Atomic delta: the option is appended to the current stored value (deduped,\nattaching the property if needed), so concurrent edits to the same value\nmerge rather than overwrite each other. Prefer this over the full-value PUT\nwhen adding one option.",
+ "operationId": "add_entity_property_option",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "description": "Entity type (user, document, channel, project, thread)",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/EntityType"
+ }
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "description": "Entity ID",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "property_id",
+ "in": "path",
+ "description": "Property ID",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "option_id",
+ "in": "path",
+ "description": "Option ID to add",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "Option added successfully"
+ },
+ "400": {
+ "description": "Invalid request, property is not multi-select, or option does not belong to the property"
+ },
+ "403": {
+ "description": "No edit access to the entity"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ },
+ "delete": {
+ "tags": ["Properties"],
+ "summary": "Remove a single option from an entity's multi-select property value.",
+ "description": "Atomic delta: the option is stripped from the current stored value (a no-op\nif absent), so concurrent edits to the same value merge rather than overwrite\neach other.",
+ "operationId": "remove_entity_property_option",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "description": "Entity type (user, document, channel, project, thread)",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/EntityType"
+ }
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "description": "Entity ID",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "property_id",
+ "in": "path",
+ "description": "Property ID",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "option_id",
+ "in": "path",
+ "description": "Option ID to remove",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "Option removed successfully"
+ },
+ "403": {
+ "description": "No edit access to the entity"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ }
+ },
"/properties/entity_properties/{entity_property_id}": {
"delete": {
"tags": ["Properties"],
diff --git a/rust/cloud-storage/.sqlx/query-17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f.json b/rust/cloud-storage/.sqlx/query-17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f.json
new file mode 100644
index 0000000000..c3e8e5b7f1
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f.json
@@ -0,0 +1,33 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($4::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n AND values ->> 'type' = 'SelectOption'\n AND values -> 'value' @> jsonb_build_array($4::text)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK"
+ ]
+ }
+ }
+ },
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f"
+}
diff --git a/rust/cloud-storage/.sqlx/query-517d22edfe5421d848804d496cf8a1ac59b76474ad1c8a695f41f324833bdcd6.json b/rust/cloud-storage/.sqlx/query-517d22edfe5421d848804d496cf8a1ac59b76474ad1c8a695f41f324833bdcd6.json
new file mode 100644
index 0000000000..8e74d1f011
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-517d22edfe5421d848804d496cf8a1ac59b76474ad1c8a695f41f324833bdcd6.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT values as \"values: serde_json::Value\"\n FROM entity_properties\n WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "values: serde_json::Value",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK"
+ ]
+ }
+ }
+ },
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "517d22edfe5421d848804d496cf8a1ac59b76474ad1c8a695f41f324833bdcd6"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf.json b/rust/cloud-storage/.sqlx/query-9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf.json
new file mode 100644
index 0000000000..785d0addfd
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET\n values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($2::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE property_definition_id = $1\n AND values @> jsonb_build_object('value', jsonb_build_array($2::text))\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9d1892f8bb8ba65131fa035ffe3e79f932f8668dd7dce998e2a885bcaf0d8bbf"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887.json b/rust/cloud-storage/.sqlx/query-c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887.json
new file mode 100644
index 0000000000..01d15647d7
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887.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 (\n $1, $2, $3, $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n )\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\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",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887"
+}
diff --git a/rust/cloud-storage/properties/Cargo.toml b/rust/cloud-storage/properties/Cargo.toml
index e47e1e7074..8d7bd4cd1a 100644
--- a/rust/cloud-storage/properties/Cargo.toml
+++ b/rust/cloud-storage/properties/Cargo.toml
@@ -42,6 +42,7 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
ai_toolset = { path = "../ai_toolset" }
+chrono = { workspace = true }
mockall = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rs
index d3aa070899..116da7f371 100644
--- a/rust/cloud-storage/properties/src/domain/ports.rs
+++ b/rust/cloud-storage/properties/src/domain/ports.rs
@@ -59,6 +59,27 @@ pub trait PropertiesRepo: Send + Sync + 'static {
value: Option<PropertyValue>,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Atomically add one option to a multi-select entity property value,
+ /// attaching the property if needed. Re-adding a present option is a no-op.
+ /// Composes with concurrent option changes without a lost update.
+ fn add_entity_property_option(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Atomically remove one option from a multi-select entity property value.
+ /// A no-op if the property is unattached or the option is not present.
+ fn remove_entity_property_option(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> 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)`:
diff --git a/rust/cloud-storage/properties/src/domain/service.rs b/rust/cloud-storage/properties/src/domain/service.rs
index a639a89a8a..26551f1ad7 100644
--- a/rust/cloud-storage/properties/src/domain/service.rs
+++ b/rust/cloud-storage/properties/src/domain/service.rs
@@ -97,6 +97,31 @@ pub trait PropertiesService: Send + Sync + 'static {
value: Option<SetPropertyValue>,
) -> impl Future<Output = Result<(), PropertiesErr>> + Send;
+ /// Add one option to a multi-select entity property value atomically.
+ /// Attaches the property if needed and dedupes. Validates the option belongs
+ /// to the (multi-select) property. Requires edit access. Prefer this over
+ /// `set_entity_property` for add/remove of a single option: it composes with
+ /// concurrent changes instead of clobbering them.
+ fn add_entity_property_option(
+ &self,
+ user_id: &str,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;
+
+ /// Remove one option from a multi-select entity property value atomically.
+ /// A no-op if absent. Requires edit access.
+ fn remove_entity_property_option(
+ &self,
+ user_id: &str,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;
+
/// Gets the owner of the entity and whether it's deleted
fn get_owner_and_deleted(
&self,
diff --git a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs
index 36715df336..482f118c71 100644
--- a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs
+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs
@@ -343,6 +343,110 @@ where
Ok(())
}
+ #[tracing::instrument(
+ skip(self),
+ fields(
+ entity_id = %entity_id,
+ entity_type = ?entity_type,
+ property_definition_id = %property_definition_id,
+ option_id = %option_id
+ )
+ )]
+ async fn add_entity_property_option(
+ &self,
+ user_id: &str,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> Result<(), PropertiesErr> {
+ 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)?;
+
+ 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
+ ))
+ })?;
+
+ if !property_definition.is_multi_select {
+ return Err(PropertiesErr::Validation(
+ "Option add/remove is only supported for multi-select properties".to_string(),
+ ));
+ }
+
+ 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(),
+ ));
+ }
+
+ self.validate_property_options(property_definition_id, &[option_id])
+ .await?;
+
+ self.repository
+ .add_entity_property_option(entity_id, entity_type, property_definition_id, option_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ self.enqueue_property_upsert(entity_id, entity_type).await;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(
+ skip(self),
+ fields(
+ entity_id = %entity_id,
+ entity_type = ?entity_type,
+ property_definition_id = %property_definition_id,
+ option_id = %option_id
+ )
+ )]
+ async fn remove_entity_property_option(
+ &self,
+ user_id: &str,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> Result<(), PropertiesErr> {
+ 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)?;
+
+ self.repository
+ .remove_entity_property_option(
+ entity_id,
+ entity_type,
+ property_definition_id,
+ option_id,
+ )
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ self.enqueue_property_upsert(entity_id, entity_type).await;
+
+ Ok(())
+ }
+
#[tracing::instrument(skip(self), err)]
async fn get_owner_and_deleted(
&self,
diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rs
index 5fab0c0d13..c970ac5f04 100644
--- a/rust/cloud-storage/properties/src/domain/test.rs
+++ b/rust/cloud-storage/properties/src/domain/test.rs
@@ -7,7 +7,10 @@ use crate::domain::{
};
use anyhow::anyhow;
use macro_user_id::user_id::MacroUserIdStr;
-use models_properties::{EntityType, service::property_value::PropertyValue};
+use models_properties::{
+ EntityType,
+ service::{property_definition::PropertyDefinition, property_value::PropertyValue},
+};
use system_properties::{StatusOption, SystemPropertyKey};
use uuid::Uuid;
@@ -741,3 +744,174 @@ async fn test_handle_task_assignees_property_clearing_assignees() {
.await
.unwrap();
}
+
+// ============================================================================
+// add/remove_entity_property_option unit tests
+// ============================================================================
+
+fn multi_select_definition(id: Uuid, is_multi_select: bool) -> PropertyDefinition {
+ PropertyDefinition {
+ id,
+ owner: models_properties::PropertyOwner::System,
+ display_name: "Tags".to_string(),
+ data_type: models_properties::DataType::SelectString,
+ is_multi_select,
+ specific_entity_type: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ is_system: false,
+ is_metadata: false,
+ }
+}
+
+#[tokio::test]
+async fn test_add_entity_property_option_happy_path() {
+ let mut repo = MockPropertiesRepo::new();
+ let def_id = Uuid::from_u128(0xA1);
+ let option_id = Uuid::from_u128(0xB2);
+
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_add_entity_property_option()
+ .withf(move |entity_id, entity_type, prop, opt| {
+ entity_id == "doc1"
+ && *entity_type == EntityType::Document
+ && *prop == def_id
+ && *opt == option_id
+ })
+ .returning(|_, _, _, _| Box::pin(async { Ok(()) }));
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ service
+ .add_entity_property_option("user1", "doc1", EntityType::Document, def_id, option_id)
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn test_add_entity_property_option_rejects_single_select() {
+ let mut repo = MockPropertiesRepo::new();
+ let def_id = Uuid::from_u128(0xA1);
+
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, false))) })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .add_entity_property_option(
+ "user1",
+ "doc1",
+ EntityType::Document,
+ def_id,
+ Uuid::from_u128(0xB2),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ crate::domain::error::PropertiesErr::Validation(_)
+ ));
+}
+
+#[tokio::test]
+async fn test_add_entity_property_option_rejects_invalid_option() {
+ let mut repo = MockPropertiesRepo::new();
+ let def_id = Uuid::from_u128(0xA1);
+
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ // Option does not belong to the property.
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(0) }));
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .add_entity_property_option(
+ "user1",
+ "doc1",
+ EntityType::Document,
+ def_id,
+ Uuid::from_u128(0xB2),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ crate::domain::error::PropertiesErr::Validation(_)
+ ));
+}
+
+#[tokio::test]
+async fn test_add_entity_property_option_no_permission_service() {
+ let repo = MockPropertiesRepo::new();
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .add_entity_property_option(
+ "user1",
+ "doc1",
+ EntityType::Document,
+ Uuid::from_u128(0xA1),
+ Uuid::from_u128(0xB2),
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ crate::domain::error::PropertiesErr::PermissionDenied
+ ));
+}
+
+#[tokio::test]
+async fn test_remove_entity_property_option_happy_path() {
+ let mut repo = MockPropertiesRepo::new();
+ let def_id = Uuid::from_u128(0xA1);
+ let option_id = Uuid::from_u128(0xB2);
+
+ repo.expect_remove_entity_property_option()
+ .withf(move |entity_id, entity_type, prop, opt| {
+ entity_id == "doc1"
+ && *entity_type == EntityType::Document
+ && *prop == def_id
+ && *opt == option_id
+ })
+ .returning(|_, _, _, _| Box::pin(async { Ok(()) }));
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ service
+ .remove_entity_property_option("user1", "doc1", EntityType::Document, def_id, option_id)
+ .await
+ .unwrap();
+}
diff --git a/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs
index bb4d211ffe..3f7ea58b2f 100644
--- a/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs
+++ b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs
@@ -93,6 +93,100 @@ pub async fn upsert_entity_property(
Ok(())
}
+/// Atomically add one option to a multi-select entity property value, creating
+/// the row if the property is not yet attached. Re-adding a present option is a
+/// no-op (deduped). The whole change is one row-locked statement applied to the
+/// current stored value, so concurrent adds merge instead of one overwriting
+/// the other (no read-modify-write lost update). A NULL or non-SelectOption
+/// existing value is coerced to a single-element SelectOption.
+pub async fn add_entity_property_option(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+) -> anyhow::Result<()> {
+ let id = macro_uuid::generate_uuid_v7();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
+ VALUES (
+ $1, $2, $3, $4,
+ jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))
+ )
+ ON CONFLICT (entity_id, entity_type, property_definition_id)
+ DO UPDATE SET
+ values = CASE
+ WHEN entity_properties.values ->> 'type' = 'SelectOption'
+ AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)
+ THEN entity_properties.values
+ WHEN entity_properties.values ->> 'type' = 'SelectOption'
+ THEN jsonb_set(
+ entity_properties.values,
+ '{value}',
+ (entity_properties.values -> 'value') || jsonb_build_array($5::text)
+ )
+ ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))
+ END,
+ updated_at = NOW()
+ "#,
+ id,
+ entity_id,
+ entity_type as EntityType,
+ property_definition_id,
+ option_id.to_string(),
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+/// Atomically remove one option from a multi-select entity property value. A
+/// no-op if the property is unattached or the option is not present. One
+/// row-locked statement applied to the current stored value, so it composes
+/// with concurrent adds/removes without a lost update.
+pub async fn remove_entity_property_option(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE entity_properties
+ SET values = jsonb_set(
+ values,
+ '{value}',
+ COALESCE(
+ (
+ SELECT jsonb_agg(elem)
+ FROM jsonb_array_elements(values -> 'value') AS elem
+ WHERE elem <> to_jsonb($4::text)
+ ),
+ '[]'::jsonb
+ )
+ ),
+ updated_at = NOW()
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND property_definition_id = $3
+ AND values ->> 'type' = 'SelectOption'
+ AND values -> 'value' @> jsonb_build_array($4::text)
+ "#,
+ entity_id,
+ entity_type as EntityType,
+ property_definition_id,
+ option_id.to_string(),
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
/// Counts how many of the provided option IDs exist for the property definition.
#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
pub async fn count_valid_property_options(
diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs
index e5070b875b..046a9e869c 100644
--- a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs
+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs
@@ -90,6 +90,42 @@ impl PropertiesRepo for PropertiesPgRepo {
.await
}
+ #[tracing::instrument(skip(self))]
+ async fn add_entity_property_option(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> Result<(), Self::Err> {
+ entity_property_queries::add_entity_property_option(
+ &self.pool,
+ entity_id,
+ entity_type,
+ property_definition_id,
+ option_id,
+ )
+ .await
+ }
+
+ #[tracing::instrument(skip(self))]
+ async fn remove_entity_property_option(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_id: Uuid,
+ ) -> Result<(), Self::Err> {
+ entity_property_queries::remove_entity_property_option(
+ &self.pool,
+ entity_id,
+ entity_type,
+ property_definition_id,
+ option_id,
+ )
+ .await
+ }
+
#[tracing::instrument(skip(self))]
async fn link_parent_task(
&self,
diff --git a/rust/cloud-storage/properties/src/outbound/test.rs b/rust/cloud-storage/properties/src/outbound/test.rs
index 09e2eccd03..3ced1edf9d 100644
--- a/rust/cloud-storage/properties/src/outbound/test.rs
+++ b/rust/cloud-storage/properties/src/outbound/test.rs
@@ -819,3 +819,117 @@ async fn mutual_subtask_link_fails(pool: Pool<Postgres>) -> anyhow::Result<()> {
Ok(())
}
+
+/// Seeds an ownerless system multi-select select-string property definition and
+/// returns its id. is_system satisfies the single-owner constraint without
+/// needing a team/user row.
+async fn seed_multi_select_definition(pool: &Pool<Postgres>, display_name: &str) -> Uuid {
+ let def_id = macro_uuid::generate_uuid_v7();
+ sqlx::query(
+ r#"
+ INSERT INTO property_definitions (id, display_name, data_type, is_multi_select, is_system)
+ VALUES ($1, $2, 'SELECT_STRING', true, true)
+ "#,
+ )
+ .bind(def_id)
+ .bind(display_name)
+ .execute(pool)
+ .await
+ .expect("seed definition");
+ def_id
+}
+
+async fn read_select_value(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ def_id: Uuid,
+) -> 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(def_id)
+ .fetch_one(pool)
+ .await
+ .expect("read value")
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn add_option_attaches_appends_and_dedupes(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let def_id = seed_multi_select_definition(&pool, "Test Tags Add").await;
+ let entity_id = "entity-tags-add";
+ let opt_a = macro_uuid::generate_uuid_v7();
+ let opt_b = macro_uuid::generate_uuid_v7();
+
+ // First add attaches the property and creates the value.
+ repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
+ .await?;
+ // Second add appends to the current stored value.
+ repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_b)
+ .await?;
+ // Re-adding a present option is a no-op.
+ repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
+ .await?;
+
+ assert_eq!(
+ read_select_value(&pool, entity_id, def_id).await,
+ serde_json::json!({"type": "SelectOption", "value": [opt_a, opt_b]})
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn remove_option_strips_and_is_tolerant(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let def_id = seed_multi_select_definition(&pool, "Test Tags Remove").await;
+ let entity_id = "entity-tags-remove";
+ let opt_a = macro_uuid::generate_uuid_v7();
+ let opt_b = macro_uuid::generate_uuid_v7();
+ let opt_c = macro_uuid::generate_uuid_v7();
+
+ for opt in [opt_a, opt_b, opt_c] {
+ repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt)
+ .await?;
+ }
+
+ // Remove a middle option.
+ repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_b)
+ .await?;
+ assert_eq!(
+ read_select_value(&pool, entity_id, def_id).await,
+ serde_json::json!({"type": "SelectOption", "value": [opt_a, opt_c]})
+ );
+
+ // Removing an absent option is a no-op.
+ let absent = macro_uuid::generate_uuid_v7();
+ repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, absent)
+ .await?;
+ assert_eq!(
+ read_select_value(&pool, entity_id, def_id).await,
+ serde_json::json!({"type": "SelectOption", "value": [opt_a, opt_c]})
+ );
+
+ // Removing the rest leaves an empty array, not NULL.
+ repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
+ .await?;
+ repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_c)
+ .await?;
+ assert_eq!(
+ read_select_value(&pool, entity_id, def_id).await,
+ serde_json::json!({"type": "SelectOption", "value": []})
+ );
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/properties_db_client/src/property_options/delete.rs b/rust/cloud-storage/properties_db_client/src/property_options/delete.rs
index 41398d9fae..81e732b734 100644
--- a/rust/cloud-storage/properties_db_client/src/property_options/delete.rs
+++ b/rust/cloud-storage/properties_db_client/src/property_options/delete.rs
@@ -5,20 +5,54 @@ use sqlx::{Pool, Postgres};
type Result<T> = std::result::Result<T, PropertiesDatabaseError>;
-/// Deletes a property option.
+/// Deletes a property option and strips its id from every entity value that
+/// references it, atomically. Without the cleanup a stored value keeps the
+/// dead id and a later set-value that echoes the full id list fails option
+/// validation.
/// Returns Ok(true) if the option was deleted, Ok(false) if it didn't exist.
#[tracing::instrument(skip(db))]
pub async fn delete_property_option(
db: &Pool<Postgres>,
+ property_definition_id: uuid::Uuid,
property_option_id: uuid::Uuid,
) -> Result<bool> {
+ let mut tx = db.begin().await?;
+
+ sqlx::query!(
+ r#"
+ UPDATE entity_properties
+ SET
+ values = jsonb_set(
+ values,
+ '{value}',
+ COALESCE(
+ (
+ SELECT jsonb_agg(elem)
+ FROM jsonb_array_elements(values -> 'value') AS elem
+ WHERE elem <> to_jsonb($2::text)
+ ),
+ '[]'::jsonb
+ )
+ ),
+ updated_at = NOW()
+ WHERE property_definition_id = $1
+ AND values @> jsonb_build_object('value', jsonb_build_array($2::text))
+ "#,
+ property_definition_id,
+ property_option_id.to_string(),
+ )
+ .execute(&mut *tx)
+ .await?;
+
let result = sqlx::query!(
"DELETE FROM property_options WHERE id = $1",
property_option_id
)
- .execute(db)
+ .execute(&mut *tx)
.await?;
+ tx.commit().await?;
+
Ok(result.rows_affected() > 0)
}
@@ -26,7 +60,17 @@ pub async fn delete_property_option(
mod tests {
use super::*;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
+ use models_properties::EntityType;
+ use models_properties::service::property_option::PropertyOptionValue;
+ use models_properties::service::property_value::PropertyValue;
use sqlx::{Pool, Postgres};
+ use uuid::Uuid;
+
+ const PRIORITY_PROPERTY_ID: &str = "11111111-1111-1111-1111-111111111111";
+ const PRIORITY_OPTION_LOW: &str = "10111111-1111-1111-1111-111111111111";
+ const PRIORITY_OPTION_MEDIUM: &str = "10111111-1111-1111-1111-111111111112";
+ const PRIORITY_OPTION_HIGH: &str = "10111111-1111-1111-1111-111111111113";
+ const PRIORITY_OPTION_URGENT: &str = "10111111-1111-1111-1111-111111111114";
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
@@ -35,9 +79,8 @@ mod tests {
async fn test_delete_property_option(pool: Pool<Postgres>) -> anyhow::Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
- let option_id = "10111111-1111-1111-1111-111111111111"
- .parse::<uuid::Uuid>()
- .unwrap();
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();
// Verify it exists
let option_before =
@@ -45,7 +88,7 @@ mod tests {
assert!(option_before.is_some());
// Delete it
- let deleted = delete_property_option(&pool, option_id).await?;
+ let deleted = delete_property_option(&pool, property_id, option_id).await?;
assert!(deleted);
// Verify it's gone
@@ -63,12 +106,13 @@ mod tests {
async fn test_delete_nonexistent_property_option(pool: Pool<Postgres>) -> anyhow::Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
let option_id = "00000000-0000-0000-0000-000000000000"
- .parse::<uuid::Uuid>()
+ .parse::<Uuid>()
.unwrap();
// Deleting non-existent option should return false
- let deleted = delete_property_option(&pool, option_id).await?;
+ let deleted = delete_property_option(&pool, property_id, option_id).await?;
assert!(!deleted);
Ok(())
@@ -81,12 +125,8 @@ mod tests {
async fn test_delete_property_option_reduces_count(pool: Pool<Postgres>) -> anyhow::Result<()> {
const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
- let property_id = "11111111-1111-1111-1111-111111111111"
- .parse::<uuid::Uuid>()
- .unwrap();
- let option_id = "10111111-1111-1111-1111-111111111111"
- .parse::<uuid::Uuid>()
- .unwrap();
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let option_id = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();
// Get initial count
let options_before =
@@ -94,7 +134,7 @@ mod tests {
let count_before = options_before.len();
// Delete one option
- delete_property_option(&pool, option_id).await?;
+ delete_property_option(&pool, property_id, option_id).await?;
// Verify count decreased
let options_after =
@@ -105,4 +145,83 @@ mod tests {
Ok(())
}
+
+ /// Reproduces the dangling-option bug: an entity value referencing
+ /// [A, B, C, D] must drop D once option D is deleted, so a later set-value
+ /// echoing the surviving ids passes option validation.
+ #[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+ )]
+ async fn test_delete_property_option_strips_value_references(
+ pool: Pool<Postgres>,
+ ) -> anyhow::Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let property_id = PRIORITY_PROPERTY_ID.parse::<Uuid>().unwrap();
+ let opt_a = PRIORITY_OPTION_LOW.parse::<Uuid>().unwrap();
+ let opt_b = PRIORITY_OPTION_MEDIUM.parse::<Uuid>().unwrap();
+ let opt_c = PRIORITY_OPTION_HIGH.parse::<Uuid>().unwrap();
+ let opt_d = PRIORITY_OPTION_URGENT.parse::<Uuid>().unwrap();
+
+ // Entity selects all four options.
+ crate::entity_properties::upsert::upsert_entity_property_values(
+ &pool,
+ "doc_cascade",
+ EntityType::Document,
+ property_id,
+ Some(PropertyValue::SelectOption(vec![
+ opt_a, opt_b, opt_c, opt_d,
+ ])),
+ )
+ .await?;
+
+ // A new option created after selection (the "new tag" in the repro).
+ let opt_e = crate::property_options::insert::create_property_option(
+ &pool,
+ property_id,
+ 4,
+ PropertyOptionValue::String("New".to_string()),
+ None,
+ )
+ .await?
+ .id;
+
+ // Delete option D.
+ let deleted = delete_property_option(&pool, property_id, opt_d).await?;
+ assert!(deleted);
+
+ // Read the raw stored value (bypassing the read-path cleaner) to prove
+ // the dangling id is gone from storage, not just filtered on read.
+ let raw: Option<serde_json::Value> = sqlx::query_scalar!(
+ r#"
+ SELECT values as "values: serde_json::Value"
+ FROM entity_properties
+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
+ "#,
+ "doc_cascade",
+ EntityType::Document as EntityType,
+ property_id,
+ )
+ .fetch_one(&pool)
+ .await?;
+
+ let stored: PropertyValue = serde_json::from_value(raw.expect("value present"))?;
+ let PropertyValue::SelectOption(ids) = stored else {
+ panic!("expected SelectOption");
+ };
+ assert_eq!(ids, vec![opt_a, opt_b, opt_c]);
+
+ // The surviving selection plus the new option all validate, so the
+ // set-value that previously 400'd now succeeds.
+ let valid = crate::property_options::get::count_property_options_by_ids(
+ &pool,
+ property_id,
+ &[opt_a, opt_b, opt_c, opt_e],
+ )
+ .await?;
+ assert_eq!(valid, 4);
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/mod.rs
index b13c50bd41..c86598b6eb 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
@@ -2,6 +2,7 @@ pub mod delete_entity;
pub mod delete_property;
pub mod get;
pub mod get_bulk;
+pub mod option;
pub mod set;
pub mod set_property_status_complete;
pub mod types;
diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/option.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/option.rs
new file mode 100644
index 0000000000..9cd78e96a6
--- /dev/null
+++ b/rust/cloud-storage/properties_service/src/api/properties/entities/option.rs
@@ -0,0 +1,140 @@
+use axum::{
+ extract::{Extension, Path, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use thiserror::Error;
+use uuid::Uuid;
+
+use crate::api::context::PropertiesHandlerState;
+use model::user::UserContext;
+use models_properties::EntityType;
+use properties::{PropertiesErr, PropertiesService};
+
+#[derive(Debug, Error)]
+pub enum EntityPropertyOptionErr {
+ #[error(transparent)]
+ Properties(#[from] PropertiesErr),
+}
+
+impl IntoResponse for EntityPropertyOptionErr {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ EntityPropertyOptionErr::Properties(e) => match e {
+ PropertiesErr::Validation(_) => StatusCode::BAD_REQUEST,
+ PropertiesErr::PermissionDenied => StatusCode::FORBIDDEN,
+ PropertiesErr::Repo(_) | PropertiesErr::PermissionServiceNotConfigured => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ },
+ };
+
+ if status_code.is_server_error() {
+ tracing::error!(
+ error = ?self,
+ error_type = "EntityPropertyOptionErr",
+ "Internal server error"
+ );
+ }
+
+ (status_code, self.to_string()).into_response()
+ }
+}
+
+/// Add a single option to an entity's multi-select property value.
+///
+/// Atomic delta: the option is appended to the current stored value (deduped,
+/// attaching the property if needed), so concurrent edits to the same value
+/// merge rather than overwrite each other. Prefer this over the full-value PUT
+/// when adding one option.
+#[utoipa::path(
+ post,
+ path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",
+ params(
+ ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),
+ ("entity_id" = String, Path, description = "Entity ID"),
+ ("property_id" = Uuid, Path, description = "Property ID"),
+ ("option_id" = Uuid, Path, description = "Option ID to add")
+ ),
+ responses(
+ (status = 204, description = "Option added successfully"),
+ (status = 400, description = "Invalid request, property is not multi-select, or option does not belong to the property"),
+ (status = 403, description = "No edit access to the entity"),
+ (status = 500, description = "Internal server error")
+ ),
+ tags = ["Properties"]
+)]
+#[tracing::instrument(skip(state, user_context), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type, user_id = %user_context.user_id), err)]
+pub async fn add_entity_property_option(
+ Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(
+ EntityType,
+ String,
+ Uuid,
+ Uuid,
+ )>,
+ State(state): State<PropertiesHandlerState>,
+ Extension(user_context): Extension<UserContext>,
+) -> Result<StatusCode, EntityPropertyOptionErr> {
+ tracing::info!("adding entity property option");
+
+ state
+ .properties_service
+ .add_entity_property_option(
+ &user_context.user_id,
+ &entity_id,
+ entity_type,
+ property_uuid,
+ option_uuid,
+ )
+ .await?;
+
+ Ok(StatusCode::NO_CONTENT)
+}
+
+/// Remove a single option from an entity's multi-select property value.
+///
+/// Atomic delta: the option is stripped from the current stored value (a no-op
+/// if absent), so concurrent edits to the same value merge rather than overwrite
+/// each other.
+#[utoipa::path(
+ delete,
+ path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",
+ params(
+ ("entity_type" = EntityType, Path, description = "Entity type (user, document, channel, project, thread)"),
+ ("entity_id" = String, Path, description = "Entity ID"),
+ ("property_id" = Uuid, Path, description = "Property ID"),
+ ("option_id" = Uuid, Path, description = "Option ID to remove")
+ ),
+ responses(
+ (status = 204, description = "Option removed successfully"),
+ (status = 403, description = "No edit access to the entity"),
+ (status = 500, description = "Internal server error")
+ ),
+ tags = ["Properties"]
+)]
+#[tracing::instrument(skip(state, user_context), fields(entity_id = %entity_id, property_id = %property_uuid, option_id = %option_uuid, entity_type = ?entity_type, user_id = %user_context.user_id), err)]
+pub async fn remove_entity_property_option(
+ Path((entity_type, entity_id, property_uuid, option_uuid)): Path<(
+ EntityType,
+ String,
+ Uuid,
+ Uuid,
+ )>,
+ State(state): State<PropertiesHandlerState>,
+ Extension(user_context): Extension<UserContext>,
+) -> Result<StatusCode, EntityPropertyOptionErr> {
+ tracing::info!("removing entity property option");
+
+ state
+ .properties_service
+ .remove_entity_property_option(
+ &user_context.user_id,
+ &entity_id,
+ entity_type,
+ property_uuid,
+ option_uuid,
+ )
+ .await?;
+
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/rust/cloud-storage/properties_service/src/api/properties/mod.rs b/rust/cloud-storage/properties_service/src/api/properties/mod.rs
index 2156ef3957..17143f9224 100644
--- a/rust/cloud-storage/properties_service/src/api/properties/mod.rs
+++ b/rust/cloud-storage/properties_service/src/api/properties/mod.rs
@@ -63,6 +63,13 @@ pub fn router() -> Router<PropertiesHandlerState> {
"/entities/{entity_type}/{entity_id}/{property_id}",
put(entities::set::set_entity_property).layer(ensure_user_exists.clone()),
)
+ // Atomic single-option delta on a multi-select value (merges concurrent edits)
+ .route(
+ "/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",
+ post(entities::option::add_entity_property_option)
+ .delete(entities::option::remove_entity_property_option)
+ .layer(ensure_user_exists.clone()),
+ )
.route(
"/entity_properties/{entity_property_id}",
delete(entities::delete_property::delete_entity_property)
diff --git a/rust/cloud-storage/properties_service/src/api/properties/options/delete.rs b/rust/cloud-storage/properties_service/src/api/properties/options/delete.rs
index 85fa908c17..5aba54d7f1 100644
--- a/rust/cloud-storage/properties_service/src/api/properties/options/delete.rs
+++ b/rust/cloud-storage/properties_service/src/api/properties/options/delete.rs
@@ -122,7 +122,7 @@ pub async fn delete_property_option(
return Err(DeletePropertyOptionErr::OptionNotFound);
}
- let deleted = property_options_delete::delete_property_option(&state.db, option_uuid)
+ let deleted = property_options_delete::delete_property_option(&state.db, def_uuid, option_uuid)
.await
.inspect_err(|e| {
tracing::error!(
diff --git a/rust/cloud-storage/properties_service/src/api/swagger.rs b/rust/cloud-storage/properties_service/src/api/swagger.rs
index 4293a1a5fe..4b223ba141 100644
--- a/rust/cloud-storage/properties_service/src/api/swagger.rs
+++ b/rust/cloud-storage/properties_service/src/api/swagger.rs
@@ -30,6 +30,8 @@ use utoipa::OpenApi;
crate::api::properties::entities::get::get_entity_properties,
crate::api::properties::entities::get_bulk::get_bulk_entity_properties,
crate::api::properties::entities::set::set_entity_property,
+ crate::api::properties::entities::option::add_entity_property_option,
+ crate::api::properties::entities::option::remove_entity_property_option,
crate::api::properties::entities::delete_property::delete_entity_property,
),
components(