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.

feat(properties): bulk entity property option updates (#4975)

gbirman489e0ea3f493
diff --git a/.sqlx/query-5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3.json b/.sqlx/query-5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3.json
new file mode 100644
index 0000000000..440caf8209
--- /dev/null
+++ b/.sqlx/query-5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1 AND entity_type = $2 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",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ },
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3"
+}
diff --git a/.sqlx/query-7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b.json b/.sqlx/query-7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b.json
new file mode 100644
index 0000000000..a6f7cd5922
--- /dev/null
+++ b/.sqlx/query-7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b.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)\n )\n ON CONFLICT (entity_id, entity_type, property_definition_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ },
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7c4b46b16a635d672e78bcfa44d07bc3c5cdd851ed623b1a068022eed85fa96b"
+}
diff --git a/.sqlx/query-ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43.json b/.sqlx/query-ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43.json
new file mode 100644
index 0000000000..d2f6d4250c
--- /dev/null
+++ b/.sqlx/query-ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43.json
@@ -0,0 +1,41 @@
+{
+ "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 FOR UPDATE\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",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ },
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "ad97ba51e2f2fa5f9a82426e4fee151044d5b6ba667d90bd8a63a21f28ce6b43"
+}
diff --git a/apps/web/src/features/property/tags/TagPicker.tsx b/apps/web/src/features/property/tags/TagPicker.tsx
index 3800bd4c97..fe70d8d7a8 100644
--- a/apps/web/src/features/property/tags/TagPicker.tsx
+++ b/apps/web/src/features/property/tags/TagPicker.tsx
@@ -289,7 +289,7 @@ function TagPickerBody(props: {
new Set(props.docTags.appliedTags().map((tag) => tag.optionId))
);
const [createStep, setCreateStep] = createSignal<CreateStep | null>(null);
- const [createDraftLabel] = createSignal('');
+ const [createDraftLabel, setCreateDraftLabel] = createSignal('');
const [selectedColorIndex, setSelectedColorIndex] = createSignal(0);
const [selectedScopeIndex, setSelectedScopeIndex] = createSignal(0);
const currentTeamQuery = useCurrentTeamQuery();
@@ -448,7 +448,12 @@ function TagPickerBody(props: {
createStep() === 'color' ? TAG_COLOR_OPTIONS.length : scopeOptions().length;
const beginCreate = () => {
- void openCreateEditor();
+ const label = createLabel();
+ if (!showCreateRow() || !label) return;
+ setCreateDraftLabel(label);
+ setSelectedColorIndex(0);
+ setSelectedScopeIndex(0);
+ setCreateStep('color');
};
const editableTagForItem = (item: TagOptionItem): EditableTag => ({
@@ -465,23 +470,6 @@ function TagPickerBody(props: {
});
};
- const openCreateEditor = async () => {
- const label = createLabel();
- if (!showCreateRow() || !label) return;
- if (!(await persistSelection())) return;
-
- props.onOpenCreateEditor(
- {
- type: 'create',
- initialScope: currentTeamQuery.data?.team ? 'team' : 'user',
- initialLabel: label,
- },
- async (result) => {
- await props.docTags.applyTag(result.scope, result.option.id);
- }
- );
- };
-
const createTag = async (scope: TagScope) => {
const value = createDraftLabel().trim();
if (!value) return;
diff --git a/apps/web/src/features/property/tags/useDocTags.ts b/apps/web/src/features/property/tags/useDocTags.ts
index 8f939fcc62..b114b2c43b 100644
--- a/apps/web/src/features/property/tags/useDocTags.ts
+++ b/apps/web/src/features/property/tags/useDocTags.ts
@@ -1,8 +1,6 @@
import {
- BulkUpdateEntityPropertyOptionsError,
- getEntityPropertyOptionDeltas,
- rollbackEntityPropertyOptionDelta,
useBulkUpdateEntityPropertyOptionsMutation,
+ useInFlightEntityPropertyOptions,
} from '@queries/properties/entity';
import {
useEnsureTagSetMutation,
@@ -14,12 +12,7 @@ import type { PropertyOptionResponse } from '@service-properties/generated/schem
import type { TagScope } from '@service-properties/generated/schemas/tagScope';
import type { TagSetResponse } from '@service-properties/generated/schemas/tagSetResponse';
import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';
-import {
- type Accessor,
- createEffect,
- createMemo,
- createSignal,
-} from 'solid-js';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
import { useEntityProperties } from '../hooks';
import type { PropertyDefinitionDomain } from '../types';
import { useTagSets } from './tag-sets-context';
@@ -72,7 +65,7 @@ function usePersistTagSelection(
entityId: string,
entityType: EntityType
): PersistTagSelection {
- const mutation = useBulkUpdateEntityPropertyOptionsMutation();
+ const mutation = useBulkUpdateEntityPropertyOptionsMutation(entityId);
return async (updates) => {
await mutation.mutateAsync({
@@ -90,11 +83,14 @@ function usePersistTagSelection(
function createDocTags(
appliedOptionIdsForDefinition: (definitionId: string) => string[],
persistTagSelection: PersistTagSelection,
- tagSets: Accessor<TagSetResponse[]>
+ tagSets: Accessor<TagSetResponse[]>,
+ // Optimistic overlay for query-backed sources (undefined for soup/local,
+ // whose sources update optimistically on their own).
+ inFlightOptionIdsForDefinition?: (
+ definitionId: string
+ ) => string[] | undefined
) {
const ensureTagSet = useEnsureTagSetMutation();
- const [pendingOptionIdsByDefinition, setPendingOptionIdsByDefinition] =
- createSignal<Map<string, string[]>>(new Map());
const [displayOptionOrder, setDisplayOptionOrder] = createSignal<string[]>(
[]
);
@@ -124,7 +120,7 @@ function createDocTags(
});
const visibleOptionIdsForDefinition = (definitionId: string): string[] =>
- pendingOptionIdsByDefinition().get(definitionId) ??
+ inFlightOptionIdsForDefinition?.(definitionId) ??
appliedOptionIdsForDefinition(definitionId);
const visibleTags = createMemo((): ResolvedTag[] => {
@@ -159,25 +155,6 @@ function createDocTags(
const isApplied = (optionId: string): boolean =>
appliedTags().some((tag) => tag.optionId === optionId);
- createEffect(() => {
- const pending = pendingOptionIdsByDefinition();
- if (pending.size === 0) return;
-
- let changed = false;
- const next = new Map(pending);
- for (const [definitionId, pendingIds] of pending) {
- const sourceIds = appliedOptionIdsForDefinition(definitionId);
- if (sameOptionIds(sourceIds, pendingIds)) {
- next.delete(definitionId);
- changed = true;
- }
- }
-
- if (changed) {
- setPendingOptionIdsByDefinition(next);
- }
- });
-
const resolveDefinition = async (
scope: TagScope
): Promise<PropertyDefinitionDetailResponse> => {
@@ -190,53 +167,13 @@ function createDocTags(
return provisioned.definition;
};
- const updatePendingOptionIds = (
- definitionId: string,
- update: (optionIds: string[]) => string[]
- ) => {
- setPendingOptionIdsByDefinition((prev) => {
- const next = new Map(prev);
- const current =
- prev.get(definitionId) ?? appliedOptionIdsForDefinition(definitionId);
- next.set(definitionId, update(current));
- return next;
- });
- };
-
+ // Optimism and rollback live in the persistence layer: the soup/local sources
+ // update optimistically, and the query source reads the in-flight overlay
+ // above. A failed commit persists nothing and leaves no in-flight state, so
+ // there is nothing to unwind here.
const commitTagSelection = async (updates: TagSelectionUpdate[]) => {
if (updates.length === 0) return;
-
- setPendingOptionIdsByDefinition((prev) => {
- const next = new Map(prev);
- for (const update of updates) {
- next.set(update.definition.id, update.nextOptionIds);
- }
- return next;
- });
-
- try {
- await persistTagSelection(updates);
- } catch (error) {
- const failed =
- error instanceof BulkUpdateEntityPropertyOptionsError
- ? error.failedDeltas.flatMap(({ updateIndex, delta }) => {
- const update = updates[updateIndex];
- return update ? [{ update, delta }] : [];
- })
- : updates.flatMap((update) =>
- getEntityPropertyOptionDeltas(
- update.currentOptionIds,
- update.nextOptionIds
- ).map((delta) => ({ update, delta }))
- );
-
- for (const { update, delta } of failed) {
- updatePendingOptionIds(update.definition.id, (optionIds) =>
- rollbackEntityPropertyOptionDelta(optionIds, delta)
- );
- }
- throw error;
- }
+ await persistTagSelection(updates);
};
const applyTag = async (scope: TagScope, optionId: string) => {
@@ -342,11 +279,16 @@ export function useDocTags(entityId: string, entityType: EntityType) {
const persistTagSelection = usePersistTagSelection(entityId, entityType);
const tagsQuery = useTagsQuery();
const tagSets = (): TagSetResponse[] => tagsQuery.data ?? [];
+ // The properties query isn't optimistically written, so surface in-flight
+ // bulk updates as the optimistic value until the refetch lands.
+ const inFlightOptionIdsForDefinition =
+ useInFlightEntityPropertyOptions(entityId);
return createDocTags(
appliedOptionIdsForDefinition,
persistTagSelection,
- tagSets
+ tagSets,
+ inFlightOptionIdsForDefinition
);
}
diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.ts
index f46c3d49a0..a1753c5038 100644
--- a/apps/web/src/lib/queries/properties/entity.ts
+++ b/apps/web/src/lib/queries/properties/entity.ts
@@ -1,7 +1,7 @@
import { analytics } from '@app/lib/analytics';
import { toast } from '@core/component/Toast/Toast';
import { ENABLE_GRAPHQL_SOUP } from '@core/constant/featureFlags';
-import { throwOnErr } from '@core/util/result';
+import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';
import {
entityPropertyFromApi,
propertyValueToApi,
@@ -13,7 +13,7 @@ import type {
PropertyDefinitionDomain,
} from '@property/types';
import { isInstantiatedProperty } from '@property/utils';
-import { useMutation, useQuery } from '@tanstack/solid-query';
+import { useMutation, useMutationState, useQuery } from '@tanstack/solid-query';
import { type Accessor, batch } from 'solid-js';
import { propertiesServiceClient } from '../../service-clients/service-properties/client';
import type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';
@@ -98,7 +98,7 @@ function invalidatePropertiesForEntity(
entityType: EntityType | PropertyTargetEntityType,
entityId: string
) {
- queryClient.invalidateQueries({
+ return queryClient.invalidateQueries({
queryKey: propertiesKeys.entity({ entityType, entityId }).queryKey,
});
}
@@ -447,12 +447,12 @@ export function useRemoveEntityPropertyOptionMutation(
}));
}
-export type EntityPropertyOptionDelta = {
+type EntityPropertyOptionDelta = {
type: 'add' | 'remove';
optionId: string;
};
-export function getEntityPropertyOptionDeltas(
+function getEntityPropertyOptionDeltas(
currentOptionIds: string[],
nextOptionIds: string[]
): EntityPropertyOptionDelta[] {
@@ -468,18 +468,6 @@ export function getEntityPropertyOptionDeltas(
];
}
-export function rollbackEntityPropertyOptionDelta(
- optionIds: string[],
- delta: EntityPropertyOptionDelta
-): string[] {
- if (delta.type === 'add') {
- return optionIds.filter((id) => id !== delta.optionId);
- }
- return optionIds.includes(delta.optionId)
- ? optionIds
- : [...optionIds, delta.optionId];
-}
-
type BulkUpdateEntityPropertyOptionsParams = {
entityId: string;
entityType: EntityType;
@@ -490,124 +478,114 @@ type BulkUpdateEntityPropertyOptionsParams = {
}>;
};
-export type FailedEntityPropertyOptionDelta = {
- updateIndex: number;
- delta: EntityPropertyOptionDelta;
+/** A property's reconciled final option ids after a bulk update. */
+export type EntityPropertyOptionSelection = {
+ propertyDefinitionId: string;
+ optionIds: string[];
};
-export class BulkUpdateEntityPropertyOptionsError extends Error {
- constructor(readonly failedDeltas: FailedEntityPropertyOptionDelta[]) {
- super('Failed to update some tags');
- this.name = 'BulkUpdateEntityPropertyOptionsError';
- }
-}
-
type BulkUpdateEntityPropertyOptionsContext = {
soupTxn?: SoupTransaction;
};
-function optionIdsFromSoupProperty(property: SoupProperty | undefined) {
- return property?.value?.type === 'SelectOption' ? property.value.value : [];
+/**
+ * Mutation-cache key for an entity's bulk option updates. Used both as the
+ * mutation's serialization scope and to read its in-flight variables for
+ * optimistic display.
+ */
+function bulkEntityPropertyOptionsKey(entityId: string) {
+ return ['bulkEntityPropertyOptions', entityId] as const;
}
-function rollbackFailedOptionDeltas(
- variables: BulkUpdateEntityPropertyOptionsParams,
- failedDeltas: FailedEntityPropertyOptionDelta[]
-) {
- const failedByUpdate = new Map<number, EntityPropertyOptionDelta[]>();
- for (const { updateIndex, delta } of failedDeltas) {
- const deltas = failedByUpdate.get(updateIndex) ?? [];
- deltas.push(delta);
- failedByUpdate.set(updateIndex, deltas);
- }
-
- const current = getSoupEntityById(variables.entityId);
- const updates: {
- property: Property | PropertyDefinitionDomain;
- value: SoupPropertyValue;
- }[] = [];
- for (const [updateIndex, deltas] of failedByUpdate) {
- const update = variables.properties[updateIndex];
- if (!update) continue;
- const propertyDefinitionId = getPropertyDefinitionId(update.property);
- const soupProperty =
- current &&
- current.tag !== 'channel' &&
- current.tag !== 'call' &&
- current.tag !== 'foreignEntity' &&
- current.tag !== 'channelThread'
- ? current.data.properties?.find(
- (property) => property.definition.id === propertyDefinitionId
- )
- : undefined;
- const optionIds = deltas.reduce(
- rollbackEntityPropertyOptionDelta,
- optionIdsFromSoupProperty(soupProperty)
- );
- updates.push({
- property: update.property,
- value:
- optionIds.length > 0
- ? { type: 'SelectOption', value: optionIds }
- : null,
- });
- }
+/**
+ * Optimistic overlay for a query-backed tag source: the option ids an in-flight
+ * bulk update is applying to a property, so a query-backed view reflects the
+ * change before its refetch lands. Returns `undefined` when nothing is in
+ * flight for the property, so callers fall back to the persisted value. On
+ * settle the mutation leaves `pending` and the overlay disappears — no manual
+ * rollback. Soup-backed sources don't need this: their optimism rides the
+ * soup-cache update in the mutation lifecycle below.
+ */
+export function useInFlightEntityPropertyOptions(entityId: string) {
+ const inFlight = useMutationState(() => ({
+ filters: {
+ mutationKey: bulkEntityPropertyOptionsKey(entityId),
+ status: 'pending' as const,
+ },
+ select: (mutation) =>
+ mutation.state.variables as
+ | BulkUpdateEntityPropertyOptionsParams
+ | undefined,
+ }));
- optimisticUpdateSoupEntityProperties(variables.entityId, updates);
+ return (propertyDefinitionId: string): string[] | undefined => {
+ const pending = inFlight();
+ // Latest in-flight update targeting this property wins.
+ for (let index = pending.length - 1; index >= 0; index--) {
+ const match = pending[index]?.properties.find(
+ (update) =>
+ getPropertyDefinitionId(update.property) === propertyDefinitionId
+ );
+ if (match) return match.nextOptionIds;
+ }
+ return undefined;
+ };
}
/**
- * Applies a complete multi-select change with one optimistic soup transaction.
- * The service currently exposes only idempotent delta endpoints, so persistence
- * fans out until a true bulk endpoint is available.
+ * Persists a complete multi-select selection across one or more properties in a
+ * single transactional request, then reconciles the soup cache from the final
+ * option ids the server returns (which may differ from the optimistic value if a
+ * concurrent edit merged in). The optimistic soup update is atomic and rolls
+ * back as a whole on failure. Commits for the same entity are serialized via a
+ * mutation scope, so concurrent edits can't interleave and corrupt optimistic
+ * state.
*/
export function useBulkUpdateEntityPropertyOptionsMutation(
+ entityId: string,
callbacks?: MutationCallbacks<
- void,
+ EntityPropertyOptionSelection[],
Error,
BulkUpdateEntityPropertyOptionsParams,
BulkUpdateEntityPropertyOptionsContext
>
) {
return useMutation(() => ({
- mutationFn: async (variables: BulkUpdateEntityPropertyOptionsParams) => {
- const operations = variables.properties.flatMap((update, updateIndex) =>
- getEntityPropertyOptionDeltas(
- update.currentOptionIds,
- update.nextOptionIds
- ).map((delta) => ({ update, updateIndex, delta }))
- );
- const results = await Promise.allSettled(
- operations.map(({ update, delta }) => {
- const params = {
- entity_type: toPropertyTargetEntityType(variables.entityType),
- entity_id: variables.entityId,
- property_id: getPropertyDefinitionId(update.property),
- option_id: delta.optionId,
- };
- return throwOnErr(async () =>
- delta.type === 'add'
- ? await propertiesServiceClient.addEntityPropertyOption(params)
- : await propertiesServiceClient.removeEntityPropertyOption(params)
- );
+ mutationKey: bulkEntityPropertyOptionsKey(entityId),
+ scope: { id: `entity-property-options:${entityId}` },
+ mutationFn: async (
+ variables: BulkUpdateEntityPropertyOptionsParams
+ ): Promise<EntityPropertyOptionSelection[]> => {
+ const response = await throwOnErr(async () =>
+ propertiesServiceClient.bulkUpdateEntityPropertyOptions({
+ entity_type: toPropertyTargetEntityType(variables.entityType),
+ entity_id: variables.entityId,
+ body: {
+ properties: variables.properties.map((update) => {
+ const deltas = getEntityPropertyOptionDeltas(
+ update.currentOptionIds,
+ update.nextOptionIds
+ );
+ return {
+ property_id: getPropertyDefinitionId(update.property),
+ add_option_ids: deltas
+ .filter((delta) => delta.type === 'add')
+ .map((delta) => delta.optionId),
+ remove_option_ids: deltas
+ .filter((delta) => delta.type === 'remove')
+ .map((delta) => delta.optionId),
+ };
+ }),
+ },
})
);
- const failedDeltas = results.flatMap((result, index) =>
- result.status === 'rejected'
- ? [
- {
- updateIndex: operations[index].updateIndex,
- delta: operations[index].delta,
- },
- ]
- : []
- );
- if (failedDeltas.length > 0) {
- throw new BulkUpdateEntityPropertyOptionsError(failedDeltas);
- }
+ return response.properties.map((property) => ({
+ propertyDefinitionId: property.property_id,
+ optionIds: property.option_ids,
+ }));
},
...withCallbacks<
- void,
+ EntityPropertyOptionSelection[],
Error,
BulkUpdateEntityPropertyOptionsParams,
BulkUpdateEntityPropertyOptionsContext
@@ -626,21 +604,53 @@ export function useBulkUpdateEntityPropertyOptionsMutation(
);
return { soupTxn };
},
- onError: (error, variables, context) => {
- if (error instanceof BulkUpdateEntityPropertyOptionsError) {
- rollbackFailedOptionDeltas(variables, error.failedDeltas);
- } else {
- context?.soupTxn?.rollback();
- }
+ onSuccess: (selections, variables) => {
+ const propertyByDefinitionId = new Map(
+ variables.properties.map((update) => [
+ getPropertyDefinitionId(update.property),
+ update.property,
+ ])
+ );
+ optimisticUpdateSoupEntityProperties(
+ variables.entityId,
+ selections.flatMap((selection) => {
+ const property = propertyByDefinitionId.get(
+ selection.propertyDefinitionId
+ );
+ if (!property) return [];
+ return [
+ {
+ property,
+ value:
+ selection.optionIds.length > 0
+ ? {
+ type: 'SelectOption' as const,
+ value: selection.optionIds,
+ }
+ : null,
+ },
+ ];
+ })
+ );
+ },
+ onError: (error, _variables, context) => {
+ context?.soupTxn?.rollback();
console.error('Failed to update tags', error);
- toast.failure('Failed to update tags');
+ toast.failure(
+ thrownResultErrorHasCode(error, 'FORBIDDEN')
+ ? 'Edit permissions are required to update tags'
+ : 'Failed to update tags'
+ );
},
onSettled: (_data, _error, variables) => {
- invalidatePropertiesForEntity(
+ invalidateSoupEntity(variables.entityId);
+ // Returned so the mutation stays `pending` until the refetch lands,
+ // keeping the in-flight optimistic overlay visible through the
+ // reconcile with no flash back to the stale value.
+ return invalidatePropertiesForEntity(
variables.entityType,
variables.entityId
);
- invalidateSoupEntity(variables.entityId);
},
},
callbacks
diff --git a/apps/web/src/lib/service-clients/service-properties/client.ts b/apps/web/src/lib/service-clients/service-properties/client.ts
index 0434c0052a..08c132fa5b 100644
--- a/apps/web/src/lib/service-clients/service-properties/client.ts
+++ b/apps/web/src/lib/service-clients/service-properties/client.ts
@@ -9,6 +9,8 @@ import type { SafeFetchInit } from '@core/util/safeFetch';
import type { Result } from 'neverthrow';
import type { AddPropertyOptionRequest } from './generated/schemas/addPropertyOptionRequest';
import type { BulkEntityPropertiesRequest } from './generated/schemas/bulkEntityPropertiesRequest';
+import type { BulkUpdateEntityPropertyOptionsRequest } from './generated/schemas/bulkUpdateEntityPropertyOptionsRequest';
+import type { BulkUpdateEntityPropertyOptionsResponse } from './generated/schemas/bulkUpdateEntityPropertyOptionsResponse';
import type { CreatePropertyDefinitionRequest } from './generated/schemas/createPropertyDefinitionRequest';
import type { EnsureTagSetRequest } from './generated/schemas/ensureTagSetRequest';
import type { EntityPropertiesResponse } from './generated/schemas/entityPropertiesResponse';
@@ -52,6 +54,11 @@ type EntityPropertyOptionArgs = {
property_id: string;
option_id: string;
};
+type BulkUpdateEntityPropertyOptionsArgs = {
+ entity_type: PropertyTargetEntityType;
+ entity_id: string;
+ body: BulkUpdateEntityPropertyOptionsRequest;
+};
type GetPropertyOptionsArgs = {
definition_id: string;
};
@@ -187,6 +194,16 @@ export const propertiesServiceClient = {
return result.map(() => ({ success: true }));
},
+ bulkUpdateEntityPropertyOptions: async (
+ args: BulkUpdateEntityPropertyOptionsArgs
+ ) => {
+ const url = `/properties/entities/${args.entity_type}/${args.entity_id}/options/bulk`;
+ return await propertiesFetch<BulkUpdateEntityPropertyOptionsResponse>(url, {
+ method: 'POST',
+ body: JSON.stringify(args.body),
+ });
+ },
+
getPropertyOptions: async (args: GetPropertyOptionsArgs) => {
return await propertiesFetch<PropertyOption[]>(
`/properties/definitions/${args.definition_id}/options`,
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntityPropertyOptionsRequest.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntityPropertyOptionsRequest.ts
new file mode 100644
index 0000000000..a5cfc22aad
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntityPropertyOptionsRequest.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityPropertyOptionUpdateRequest } from './entityPropertyOptionUpdateRequest';
+
+/**
+ * Request to apply option deltas across one or more of an entity's multi-select
+properties in a single transaction.
+ */
+export interface BulkUpdateEntityPropertyOptionsRequest {
+ /** The per-property option changes to apply. */
+ properties: EntityPropertyOptionUpdateRequest[];
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntityPropertyOptionsResponse.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntityPropertyOptionsResponse.ts
new file mode 100644
index 0000000000..4525f4cab3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntityPropertyOptionsResponse.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityPropertyOptionSelectionResponse } from './entityPropertyOptionSelectionResponse';
+
+/**
+ * Response for a bulk option update: each property's reconciled final ids.
+ */
+export interface BulkUpdateEntityPropertyOptionsResponse {
+ /** The final option ids per updated property. */
+ properties: EntityPropertyOptionSelectionResponse[];
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/entityPropertyOptionSelectionResponse.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/entityPropertyOptionSelectionResponse.ts
new file mode 100644
index 0000000000..093b54d0c0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/entityPropertyOptionSelectionResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The reconciled final option ids stored for one property after a bulk update.
+ */
+export interface EntityPropertyOptionSelectionResponse {
+ /** The final option ids the server persisted, in stored order. */
+ option_ids: string[];
+ /** The property definition the options belong to. */
+ property_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/entityPropertyOptionUpdateRequest.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/entityPropertyOptionUpdateRequest.ts
new file mode 100644
index 0000000000..0bdbdaa133
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/entityPropertyOptionUpdateRequest.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * One property's option changes in a bulk selection update. The change is a
+delta (options to add / remove) so it composes with concurrent edits rather
+than replacing the whole value.
+ */
+export interface EntityPropertyOptionUpdateRequest {
+ /** Options to add (deduped against the current value). */
+ add_option_ids?: string[];
+ /** The multi-select property definition being changed. */
+ property_id: string;
+ /** Options to remove (a no-op if not present). */
+ remove_option_ids?: string[];
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts b/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
index e7a2927706..3d41c44e4b 100644
--- a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
@@ -1132,6 +1132,84 @@ export const getEntityPropertiesResponse = zod
})
.describe('Response for document\/entity properties endpoint.');
+/**
+ * Each property change is expressed as an option delta and applied to the
+current stored value under a per-row lock inside a single transaction, so the
+selection persists atomically and composes with concurrent edits instead of
+clobbering them. Returns the reconciled final option ids per property for
+cache reconciliation.
+ * @summary Apply a complete tag-picker selection across an entity's multi-select
+properties in one request.
+ */
+export const bulkUpdateEntityPropertyOptionsParams = zod.object({
+ entity_type: zod
+ .enum([
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe('Canonical entity type; tasks use DOCUMENT'),
+ entity_id: zod.string().describe('Entity ID'),
+});
+
+export const bulkUpdateEntityPropertyOptionsBody = zod
+ .object({
+ properties: zod
+ .array(
+ zod
+ .object({
+ add_option_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe('Options to add (deduped against the current value).'),
+ property_id: zod
+ .uuid()
+ .describe('The multi-select property definition being changed.'),
+ remove_option_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe('Options to remove (a no-op if not present).'),
+ })
+ .describe(
+ "One property's option changes in a bulk selection update. The change is a\ndelta (options to add \/ remove) so it composes with concurrent edits rather\nthan replacing the whole value."
+ )
+ )
+ .describe('The per-property option changes to apply.'),
+ })
+ .describe(
+ "Request to apply option deltas across one or more of an entity's multi-select\nproperties in a single transaction."
+ );
+
+export const bulkUpdateEntityPropertyOptionsResponse = zod
+ .object({
+ properties: zod
+ .array(
+ zod
+ .object({
+ option_ids: zod
+ .array(zod.uuid())
+ .describe(
+ 'The final option ids the server persisted, in stored order.'
+ ),
+ property_id: zod
+ .uuid()
+ .describe('The property definition the options belong to.'),
+ })
+ .describe(
+ 'The reconciled final option ids stored for one property after a bulk update.'
+ )
+ )
+ .describe('The final option ids per updated property.'),
+ })
+ .describe(
+ "Response for a bulk option update: each property's reconciled final ids."
+ );
+
/**
* @summary Set or update a property value for an entity, or attach a property without a value
*/
diff --git a/apps/web/src/lib/service-clients/service-properties/openapi.json b/apps/web/src/lib/service-clients/service-properties/openapi.json
index 720b784908..3b031314bf 100644
--- a/apps/web/src/lib/service-clients/service-properties/openapi.json
+++ b/apps/web/src/lib/service-clients/service-properties/openapi.json
@@ -446,6 +446,65 @@
}
}
},
+ "/properties/entities/{entity_type}/{entity_id}/options/bulk": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Apply a complete tag-picker selection across an entity's multi-select\nproperties in one request.",
+ "description": "Each property change is expressed as an option delta and applied to the\ncurrent stored value under a per-row lock inside a single transaction, so the\nselection persists atomically and composes with concurrent edits instead of\nclobbering them. Returns the reconciled final option ids per property for\ncache reconciliation.",
+ "operationId": "bulk_update_entity_property_options",
+ "parameters": [
+ {
+ "name": "entity_type",
+ "in": "path",
+ "description": "Canonical entity type; tasks use DOCUMENT",
+ "required": true,
+ "schema": {
+ "$ref": "#/components/schemas/PropertyTargetEntityType"
+ }
+ },
+ {
+ "name": "entity_id",
+ "in": "path",
+ "description": "Entity ID",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BulkUpdateEntityPropertyOptionsRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Options updated; returns final ids per property",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BulkUpdateEntityPropertyOptionsResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request, a property is not multi-select, or an option does not belong to its property"
+ },
+ "403": {
+ "description": "No edit access to the entity"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ }
+ },
"/properties/entities/{entity_type}/{entity_id}/{property_id}": {
"put": {
"tags": ["Properties"],
@@ -810,6 +869,34 @@
}
}
},
+ "BulkUpdateEntityPropertyOptionsRequest": {
+ "type": "object",
+ "description": "Request to apply option deltas across one or more of an entity's multi-select\nproperties in a single transaction.",
+ "required": ["properties"],
+ "properties": {
+ "properties": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/EntityPropertyOptionUpdateRequest"
+ },
+ "description": "The per-property option changes to apply."
+ }
+ }
+ },
+ "BulkUpdateEntityPropertyOptionsResponse": {
+ "type": "object",
+ "description": "Response for a bulk option update: each property's reconciled final ids.",
+ "required": ["properties"],
+ "properties": {
+ "properties": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/EntityPropertyOptionSelectionResponse"
+ },
+ "description": "The final option ids per updated property."
+ }
+ }
+ },
"CreatePropertyDefinitionRequest": {
"type": "object",
"description": "Request to create a new property definition.",
@@ -908,6 +995,54 @@
}
}
},
+ "EntityPropertyOptionSelectionResponse": {
+ "type": "object",
+ "description": "The reconciled final option ids stored for one property after a bulk update.",
+ "required": ["property_id", "option_ids"],
+ "properties": {
+ "option_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "The final option ids the server persisted, in stored order."
+ },
+ "property_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The property definition the options belong to."
+ }
+ }
+ },
+ "EntityPropertyOptionUpdateRequest": {
+ "type": "object",
+ "description": "One property's option changes in a bulk selection update. The change is a\ndelta (options to add / remove) so it composes with concurrent edits rather\nthan replacing the whole value.",
+ "required": ["property_id"],
+ "properties": {
+ "add_option_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "Options to add (deduped against the current value)."
+ },
+ "property_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The multi-select property definition being changed."
+ },
+ "remove_option_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "Options to remove (a no-op if not present)."
+ }
+ }
+ },
"EntityPropertyResponse": {
"type": "object",
"description": "Entity property response (API representation).",
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index 17cd7c8b6b..fd1653a14b 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -175,6 +175,34 @@ pub struct TagSet {
pub options: Vec<PropertyOption>,
}
+/// One property's requested option changes in a bulk selection update.
+///
+/// The change is expressed as a delta (options to add, options to remove) rather
+/// than a target set so it composes with concurrent edits under the row lock: a
+/// bulk update only touches the options it names, leaving any options a
+/// concurrent writer added or removed intact.
+#[derive(Debug, Clone)]
+pub struct EntityPropertyOptionUpdate {
+ /// The multi-select property definition being changed.
+ pub property_definition_id: Uuid,
+ /// Options to add to the current stored value (deduped, order-preserving).
+ pub add_option_ids: Vec<Uuid>,
+ /// Options to strip from the current stored value (a no-op if absent).
+ pub remove_option_ids: Vec<Uuid>,
+}
+
+/// The reconciled final option ids for one property after a bulk update. The
+/// caller uses these to reconcile its cache with the value the server actually
+/// persisted (which may differ from the requested delta if a concurrent edit
+/// merged in).
+#[derive(Debug, Clone)]
+pub struct EntityPropertyOptionSelection {
+ /// The property definition the options belong to.
+ pub property_definition_id: Uuid,
+ /// The final option ids stored for the entity's property, in stored order.
+ pub option_ids: Vec<Uuid>,
+}
+
/// Outcome of an in-place property option update.
#[derive(Debug, Clone)]
pub enum UpdatePropertyOptionOutcome {
diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rs
index e6e3734cc2..b21bdf2a79 100644
--- a/crates/properties/src/domain/ports.rs
+++ b/crates/properties/src/domain/ports.rs
@@ -21,8 +21,9 @@ use models_properties::{DataType, EntityPropertyReference, EntityReference, Enti
use uuid::Uuid;
use super::model::{
- EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner,
- TaskAssignedNotification, UpdatePropertyOptionOutcome, ViewReceipt,
+ EditReceipt, EntityPropertiesKey, EntityPropertyInfo, EntityPropertyOptionSelection,
+ EntityPropertyOptionUpdate, PropertyDefinitionOwner, TaskAssignedNotification,
+ UpdatePropertyOptionOutcome, ViewReceipt,
};
/// Repository trait for property operations.
@@ -193,6 +194,20 @@ pub trait PropertiesRepo: Send + Sync + 'static {
option_id: Uuid,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Apply option deltas to several of an entity's multi-select property values
+ /// in a single transaction, returning each property's final option ids.
+ ///
+ /// Each property's row is locked (`SELECT ... FOR UPDATE`) before its current
+ /// value is read, diffed, and rewritten, so the whole selection composes with
+ /// concurrent edits without a lost update. The transaction is all-or-nothing:
+ /// any failure rolls back every property in the batch.
+ fn bulk_update_entity_property_options(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ updates: &[EntityPropertyOptionUpdate],
+ ) -> impl Future<Output = Result<Vec<EntityPropertyOptionSelection>, 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/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rs
index b23293131f..5dea08ebad 100644
--- a/crates/properties/src/domain/service.rs
+++ b/crates/properties/src/domain/service.rs
@@ -27,7 +27,8 @@ use uuid::Uuid;
use super::error::PropertiesErr;
use super::model::{
- EditReceipt, EntityPropertyInfo, PropertyTargetKey, TagScope, TagSet, ViewReceipt,
+ EditReceipt, EntityPropertyInfo, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
+ PropertyTargetKey, TagScope, TagSet, ViewReceipt,
};
/// The caller's team-membership proof, used to scope definition/option/tag
@@ -105,6 +106,21 @@ pub trait PropertiesService: Send + Sync + 'static {
option_id: Uuid,
) -> impl Future<Output = Result<(), PropertiesErr>> + Send;
+ /// Apply a complete tag-picker selection across one or more of an entity's
+ /// multi-select properties in a single transaction, returning each
+ /// property's final option ids for cache reconciliation.
+ ///
+ /// Each property change is a delta (options to add / remove) so the whole
+ /// selection composes with concurrent edits under a per-row lock rather than
+ /// clobbering them. Validates that every added option belongs to its
+ /// (multi-select) property before any write; the persistence is
+ /// all-or-nothing, so a failure on any property rolls back the whole batch.
+ fn bulk_update_entity_property_options(
+ &self,
+ access: &EditReceipt,
+ updates: Vec<EntityPropertyOptionUpdate>,
+ ) -> impl Future<Output = Result<Vec<EntityPropertyOptionSelection>, PropertiesErr>> + Send;
+
/// List property definitions owned by the given team and/or user, sorted by
/// display name. Set `include_system` to true to also include system properties.
/// When `for_entity_type` is provided, definitions that cannot be attached to
diff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rs
index 561793d78f..73a3d07143 100644
--- a/crates/properties/src/domain/service_impl/mod.rs
+++ b/crates/properties/src/domain/service_impl/mod.rs
@@ -31,9 +31,9 @@ use std::sync::Arc;
use super::error::PropertiesErr;
use super::metadata;
use super::model::{
- EditReceipt, EntityPropertyInfo, PropertyAccessReceiptExt, PropertyDefinitionOwner,
- PropertyTargetKey, ResolvedPropertySubject, TagScope, TagSet, UpdatePropertyOptionOutcome,
- ViewReceipt,
+ EditReceipt, EntityPropertyInfo, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
+ PropertyAccessReceiptExt, PropertyDefinitionOwner, PropertyTargetKey, ResolvedPropertySubject,
+ TagScope, TagSet, UpdatePropertyOptionOutcome, ViewReceipt,
};
use super::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer};
use super::service::{PropertiesService, TeamReceipt, team_id_from_receipt};
@@ -574,6 +574,73 @@ where
Ok(())
}
+ #[tracing::instrument(
+ skip(self, access, updates),
+ fields(
+ entity_id = %access.entity_id(),
+ entity_type = ?access.entity_type(),
+ property_count = updates.len()
+ ),
+ err
+ )]
+ async fn bulk_update_entity_property_options(
+ &self,
+ access: &EditReceipt,
+ updates: Vec<EntityPropertyOptionUpdate>,
+ ) -> Result<Vec<EntityPropertyOptionSelection>, PropertiesErr> {
+ let subject = self.resolve_subject(access).await?;
+ let entity_type = subject.storage_entity_type;
+
+ // Validate every property up front so an invalid option never triggers a
+ // partial write: the persistence below is a single transaction and only
+ // runs once all properties pass.
+ for update in &updates {
+ let property_definition = self
+ .repository
+ .get_property_definition(update.property_definition_id)
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or_else(|| {
+ PropertiesErr::Validation(format!(
+ "Property definition not found: {}",
+ update.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(update.property_definition_id, entity_type) {
+ return Err(PropertiesErr::Validation(
+ "This property cannot be attached to this entity type".to_string(),
+ ));
+ }
+
+ // Only additions need option validation; removing an id that is not a
+ // valid option is a harmless no-op. Dedupe first so an accidentally
+ // repeated id is not miscounted as an invalid one.
+ let mut add_option_ids = update.add_option_ids.clone();
+ add_option_ids.sort();
+ add_option_ids.dedup();
+ self.validate_property_options(update.property_definition_id, &add_option_ids)
+ .await?;
+ }
+
+ let selections = self
+ .repository
+ .bulk_update_entity_property_options(access.entity_id(), entity_type, &updates)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ self.enqueue_property_upsert(access.entity_id(), entity_type)
+ .await;
+
+ Ok(selections)
+ }
+
#[tracing::instrument(skip(self, team), err)]
async fn list_property_definitions(
&self,
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 671bf8171a..4f53776eb9 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -1502,3 +1502,182 @@ async fn mixed_document_bulk_read_batches_subtypes_and_returns_canonical_keys()
})
);
}
+
+#[tokio::test]
+async fn test_bulk_update_entity_property_options_happy_path() {
+ use crate::domain::model::{EntityPropertyOptionSelection, EntityPropertyOptionUpdate};
+
+ let mut repo = MockPropertiesRepo::new();
+ let def_id = Uuid::from_u128(0xA1);
+ let add_id = Uuid::from_u128(0xB2);
+ let remove_id = Uuid::from_u128(0xB3);
+
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ // Only the added option is validated; the removed one is not.
+ repo.expect_count_valid_property_options()
+ .withf(move |_, option_ids| option_ids == [add_id])
+ .returning(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_bulk_update_entity_property_options()
+ .withf(move |entity_id, entity_type, updates| {
+ entity_id == "doc1"
+ && *entity_type == EntityType::Document
+ && updates.len() == 1
+ && updates[0].property_definition_id == def_id
+ && updates[0].add_option_ids == [add_id]
+ && updates[0].remove_option_ids == [remove_id]
+ })
+ .returning(move |_, _, _| {
+ Box::pin(async move {
+ Ok(vec![EntityPropertyOptionSelection {
+ property_definition_id: def_id,
+ option_ids: vec![add_id],
+ }])
+ })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let selections = service
+ .bulk_update_entity_property_options(
+ &edit_receipt("doc1", EntityType::Document),
+ vec![EntityPropertyOptionUpdate {
+ property_definition_id: def_id,
+ add_option_ids: vec![add_id],
+ remove_option_ids: vec![remove_id],
+ }],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(selections.len(), 1);
+ assert_eq!(selections[0].property_definition_id, def_id);
+ assert_eq!(selections[0].option_ids, vec![add_id]);
+}
+
+#[tokio::test]
+async fn test_bulk_update_entity_property_options_rejects_single_select() {
+ use crate::domain::model::EntityPropertyOptionUpdate;
+
+ 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))) })
+ });
+ // No write should be attempted for an invalid batch.
+ repo.expect_bulk_update_entity_property_options().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .bulk_update_entity_property_options(
+ &edit_receipt("doc1", EntityType::Document),
+ vec![EntityPropertyOptionUpdate {
+ property_definition_id: def_id,
+ add_option_ids: vec![Uuid::from_u128(0xB2)],
+ remove_option_ids: vec![],
+ }],
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ crate::domain::error::PropertiesErr::Validation(_)
+ ));
+}
+
+#[tokio::test]
+async fn test_bulk_update_entity_property_options_rejects_invalid_option() {
+ use crate::domain::model::EntityPropertyOptionUpdate;
+
+ 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))) })
+ });
+ // Added option does not belong to the property.
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(0) }));
+ // A validation failure must abort before any persistence runs.
+ repo.expect_bulk_update_entity_property_options().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let err = service
+ .bulk_update_entity_property_options(
+ &edit_receipt("doc1", EntityType::Document),
+ vec![EntityPropertyOptionUpdate {
+ property_definition_id: def_id,
+ add_option_ids: vec![Uuid::from_u128(0xB2)],
+ remove_option_ids: vec![],
+ }],
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ crate::domain::error::PropertiesErr::Validation(_)
+ ));
+}
+
+#[tokio::test]
+async fn test_bulk_update_entity_property_options_dedupes_added_options() {
+ use crate::domain::model::{EntityPropertyOptionSelection, EntityPropertyOptionUpdate};
+
+ let mut repo = MockPropertiesRepo::new();
+ let def_id = Uuid::from_u128(0xA1);
+ let add_id = Uuid::from_u128(0xB2);
+
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ // A repeated add id is deduped before the validity count, so the single
+ // valid option is not miscounted as invalid.
+ repo.expect_count_valid_property_options()
+ .withf(move |_, option_ids| option_ids == [add_id])
+ .returning(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_bulk_update_entity_property_options()
+ .returning(move |_, _, _| {
+ Box::pin(async move {
+ Ok(vec![EntityPropertyOptionSelection {
+ property_definition_id: def_id,
+ option_ids: vec![add_id],
+ }])
+ })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ service
+ .bulk_update_entity_property_options(
+ &edit_receipt("doc1", EntityType::Document),
+ vec![EntityPropertyOptionUpdate {
+ property_definition_id: def_id,
+ add_option_ids: vec![add_id, add_id],
+ remove_option_ids: vec![],
+ }],
+ )
+ .await
+ .unwrap();
+}
diff --git a/crates/properties/src/inbound/axum_router.rs b/crates/properties/src/inbound/axum_router.rs
index 9dbdd8bc80..380d76b62e 100644
--- a/crates/properties/src/inbound/axum_router.rs
+++ b/crates/properties/src/inbound/axum_router.rs
@@ -156,6 +156,11 @@ where
post(entities::add_entity_property_option::<S, A, Auth>)
.delete(entities::remove_entity_property_option::<S, A, Auth>),
)
+ // Transactional multi-property option deltas (one tag-picker selection)
+ .route(
+ "/entities/{entity_type}/{entity_id}/options/bulk",
+ post(entities::bulk_update_entity_property_options::<S, A, Auth>),
+ )
.route(
"/entity_properties/{entity_property_id}",
delete(entities::delete_entity_property::<S, A, Auth>),
diff --git a/crates/properties/src/inbound/axum_router/entities.rs b/crates/properties/src/inbound/axum_router/entities.rs
index 6a222bffeb..56d0838665 100644
--- a/crates/properties/src/inbound/axum_router/entities.rs
+++ b/crates/properties/src/inbound/axum_router/entities.rs
@@ -27,9 +27,13 @@ use super::extract::{EditReceiptExtractor, ViewReceiptExtractor};
use super::extract::{mint_authenticated_receipt, mint_view_receipt, target_entity_type};
use super::{PropertiesRouterState, properties_err_status};
use crate::domain::error::PropertiesErr;
+use crate::domain::model::EntityPropertyOptionUpdate;
use crate::domain::model::PropertyAccessReceiptExt;
use crate::domain::service::PropertiesService;
+#[cfg(test)]
+mod test;
+
// Re-export EntityQueryParams from models_properties for convenience
pub use models_properties::api::EntityQueryParams;
@@ -500,6 +504,169 @@ pub async fn remove_entity_property_option<
Ok(StatusCode::NO_CONTENT)
}
+/// One property's option changes in a bulk selection update. The change is a
+/// delta (options to add / remove) so it composes with concurrent edits rather
+/// than replacing the whole value.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct EntityPropertyOptionUpdateRequest {
+ /// The multi-select property definition being changed.
+ pub property_id: Uuid,
+ /// Options to add (deduped against the current value).
+ #[serde(default)]
+ pub add_option_ids: Vec<Uuid>,
+ /// Options to remove (a no-op if not present).
+ #[serde(default)]
+ pub remove_option_ids: Vec<Uuid>,
+}
+
+/// Request to apply option deltas across one or more of an entity's multi-select
+/// properties in a single transaction.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct BulkUpdateEntityPropertyOptionsRequest {
+ /// The per-property option changes to apply.
+ pub properties: Vec<EntityPropertyOptionUpdateRequest>,
+}
+
+/// The reconciled final option ids stored for one property after a bulk update.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct EntityPropertyOptionSelectionResponse {
+ /// The property definition the options belong to.
+ pub property_id: Uuid,
+ /// The final option ids the server persisted, in stored order.
+ pub option_ids: Vec<Uuid>,
+}
+
+/// Response for a bulk option update: each property's reconciled final ids.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct BulkUpdateEntityPropertyOptionsResponse {
+ /// The final option ids per updated property.
+ pub properties: Vec<EntityPropertyOptionSelectionResponse>,
+}
+
+/// Maximum properties changeable in one bulk option request.
+const MAX_BULK_OPTION_PROPERTIES: usize = 100;
+/// Maximum option ids (added plus removed) per property in one bulk request.
+const MAX_OPTION_IDS_PER_PROPERTY: usize = 500;
+
+#[derive(Debug, Error)]
+pub enum BulkUpdateEntityPropertyOptionsErr {
+ #[error(transparent)]
+ Properties(#[from] PropertiesErr),
+ #[error("Duplicate property id in request")]
+ DuplicateProperty,
+ #[error("Cannot update more than {MAX_BULK_OPTION_PROPERTIES} properties at once")]
+ TooManyProperties,
+ #[error("Cannot change more than {MAX_OPTION_IDS_PER_PROPERTY} options for a property at once")]
+ TooManyOptions,
+}
+
+impl IntoResponse for BulkUpdateEntityPropertyOptionsErr {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ BulkUpdateEntityPropertyOptionsErr::Properties(e) => properties_err_status(e),
+ BulkUpdateEntityPropertyOptionsErr::DuplicateProperty
+ | BulkUpdateEntityPropertyOptionsErr::TooManyProperties
+ | BulkUpdateEntityPropertyOptionsErr::TooManyOptions => StatusCode::BAD_REQUEST,
+ };
+
+ if status_code.is_server_error() {
+ tracing::error!(
+ error = ?self,
+ error_type = "BulkUpdateEntityPropertyOptionsErr",
+ "Internal server error"
+ );
+ }
+
+ (status_code, self.to_string()).into_response()
+ }
+}
+
+/// Reject oversized or duplicate-property requests before any database work, so
+/// one authenticated call can't force unbounded query and lock work.
+fn validate_bulk_option_request(
+ request: &BulkUpdateEntityPropertyOptionsRequest,
+) -> Result<(), BulkUpdateEntityPropertyOptionsErr> {
+ if request.properties.len() > MAX_BULK_OPTION_PROPERTIES {
+ return Err(BulkUpdateEntityPropertyOptionsErr::TooManyProperties);
+ }
+ let mut seen = std::collections::HashSet::with_capacity(request.properties.len());
+ for property in &request.properties {
+ if !seen.insert(property.property_id) {
+ return Err(BulkUpdateEntityPropertyOptionsErr::DuplicateProperty);
+ }
+ if property.add_option_ids.len() + property.remove_option_ids.len()
+ > MAX_OPTION_IDS_PER_PROPERTY
+ {
+ return Err(BulkUpdateEntityPropertyOptionsErr::TooManyOptions);
+ }
+ }
+ Ok(())
+}
+
+/// Apply a complete tag-picker selection across an entity's multi-select
+/// properties in one request.
+///
+/// Each property change is expressed as an option delta and applied to the
+/// current stored value under a per-row lock inside a single transaction, so the
+/// selection persists atomically and composes with concurrent edits instead of
+/// clobbering them. Returns the reconciled final option ids per property for
+/// cache reconciliation.
+#[utoipa::path(
+ post,
+ path = "/properties/entities/{entity_type}/{entity_id}/options/bulk",
+ params(
+ ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),
+ ("entity_id" = String, Path, description = "Entity ID")
+ ),
+ request_body = BulkUpdateEntityPropertyOptionsRequest,
+ responses(
+ (status = 200, description = "Options updated; returns final ids per property", body = BulkUpdateEntityPropertyOptionsResponse),
+ (status = 400, description = "Invalid request, a property is not multi-select, or an option does not belong to its property"),
+ (status = 403, description = "No edit access to the entity"),
+ (status = 500, description = "Internal server error")
+ ),
+ tags = ["Properties"]
+)]
+#[tracing::instrument(skip(state, access, request), fields(entity_id = %access.0.entity_id(), entity_type = ?access.0.entity_type(), property_count = request.properties.len()), err)]
+pub async fn bulk_update_entity_property_options<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ access: EditReceiptExtractor,
+ Json(request): Json<BulkUpdateEntityPropertyOptionsRequest>,
+) -> Result<Json<BulkUpdateEntityPropertyOptionsResponse>, BulkUpdateEntityPropertyOptionsErr> {
+ tracing::info!("bulk updating entity property options");
+
+ validate_bulk_option_request(&request)?;
+
+ let updates = request
+ .properties
+ .into_iter()
+ .map(|property| EntityPropertyOptionUpdate {
+ property_definition_id: property.property_id,
+ add_option_ids: property.add_option_ids,
+ remove_option_ids: property.remove_option_ids,
+ })
+ .collect();
+
+ let selections = state
+ .properties_service
+ .bulk_update_entity_property_options(&access.0, updates)
+ .await?;
+
+ Ok(Json(BulkUpdateEntityPropertyOptionsResponse {
+ properties: selections
+ .into_iter()
+ .map(|selection| EntityPropertyOptionSelectionResponse {
+ property_id: selection.property_definition_id,
+ option_ids: selection.option_ids,
+ })
+ .collect(),
+ }))
+}
+
#[derive(Debug, Error)]
pub enum DeleteEntityPropertyErr {
#[error(transparent)]
diff --git a/crates/properties/src/inbound/axum_router/entities/test.rs b/crates/properties/src/inbound/axum_router/entities/test.rs
new file mode 100644
index 0000000000..39740f7474
--- /dev/null
+++ b/crates/properties/src/inbound/axum_router/entities/test.rs
@@ -0,0 +1,53 @@
+use super::*;
+
+fn update(property_id: Uuid, add: usize, remove: usize) -> EntityPropertyOptionUpdateRequest {
+ EntityPropertyOptionUpdateRequest {
+ property_id,
+ add_option_ids: (0..add).map(|_| Uuid::new_v4()).collect(),
+ remove_option_ids: (0..remove).map(|_| Uuid::new_v4()).collect(),
+ }
+}
+
+#[test]
+fn validate_bulk_option_request_accepts_distinct_bounded() {
+ let request = BulkUpdateEntityPropertyOptionsRequest {
+ properties: vec![update(Uuid::new_v4(), 2, 1), update(Uuid::new_v4(), 0, 3)],
+ };
+ assert!(validate_bulk_option_request(&request).is_ok());
+}
+
+#[test]
+fn validate_bulk_option_request_rejects_duplicate_property() {
+ let property_id = Uuid::new_v4();
+ let request = BulkUpdateEntityPropertyOptionsRequest {
+ properties: vec![update(property_id, 1, 0), update(property_id, 0, 1)],
+ };
+ assert!(matches!(
+ validate_bulk_option_request(&request),
+ Err(BulkUpdateEntityPropertyOptionsErr::DuplicateProperty)
+ ));
+}
+
+#[test]
+fn validate_bulk_option_request_rejects_too_many_properties() {
+ let request = BulkUpdateEntityPropertyOptionsRequest {
+ properties: (0..=MAX_BULK_OPTION_PROPERTIES)
+ .map(|_| update(Uuid::new_v4(), 0, 0))
+ .collect(),
+ };
+ assert!(matches!(
+ validate_bulk_option_request(&request),
+ Err(BulkUpdateEntityPropertyOptionsErr::TooManyProperties)
+ ));
+}
+
+#[test]
+fn validate_bulk_option_request_rejects_too_many_options() {
+ let request = BulkUpdateEntityPropertyOptionsRequest {
+ properties: vec![update(Uuid::new_v4(), MAX_OPTION_IDS_PER_PROPERTY + 1, 0)],
+ };
+ assert!(matches!(
+ validate_bulk_option_request(&request),
+ Err(BulkUpdateEntityPropertyOptionsErr::TooManyOptions)
+ ));
+}
diff --git a/crates/properties/src/outbound/entity_property_queries.rs b/crates/properties/src/outbound/entity_property_queries.rs
index 939d9b0752..a155740c6b 100644
--- a/crates/properties/src/outbound/entity_property_queries.rs
+++ b/crates/properties/src/outbound/entity_property_queries.rs
@@ -5,6 +5,8 @@ use models_properties::{EntityReference, EntityType};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
+use crate::domain::model::{EntityPropertyOptionSelection, EntityPropertyOptionUpdate};
+
/// Upsert an entity property value (insert or update).
/// If the property doesn't exist, it will be created and attached to the entity.
/// If it exists, the value will be updated.
@@ -152,6 +154,134 @@ pub async fn remove_entity_property_option(
Ok(())
}
+/// Apply option deltas to several of an entity's multi-select property values in
+/// one transaction, returning each property's final option ids.
+///
+/// A property is only attached (row created) when there are options to add;
+/// otherwise the row is locked with `SELECT ... FOR UPDATE` before its current
+/// value is read, diffed, and rewritten. A removal-only update on an unattached
+/// property is a no-op — it does not create an empty row. Because each delta is
+/// applied to the freshly locked value, two bulk updates racing on the same row
+/// compose instead of overwriting each other (no lost update). The whole batch
+/// shares one transaction, so a failure on any property rolls back the batch.
+pub async fn bulk_update_entity_property_options(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ entity_type: EntityType,
+ updates: &[EntityPropertyOptionUpdate],
+) -> anyhow::Result<Vec<EntityPropertyOptionSelection>> {
+ let mut tx = pool.begin().await?;
+ let mut selections = Vec::with_capacity(updates.len());
+
+ // Acquire row locks in a consistent order across all callers so two bulk
+ // updates touching the same properties in different orders can't deadlock.
+ let mut ordered: Vec<&EntityPropertyOptionUpdate> = updates.iter().collect();
+ ordered.sort_by_key(|update| update.property_definition_id);
+
+ for update in ordered {
+ let has_additions = !update.add_option_ids.is_empty();
+
+ // Attach the property only when adding options. A concurrent creator
+ // blocks on the unique index here until it commits, after which this
+ // insert is a no-op and the FOR UPDATE below sequences the two writers.
+ if has_additions {
+ 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)
+ )
+ ON CONFLICT (entity_id, entity_type, property_definition_id) DO NOTHING
+ "#,
+ id,
+ entity_id,
+ entity_type as EntityType,
+ update.property_definition_id,
+ )
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ // Lock the row (if any) and read the current stored value before diffing.
+ let existing = 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
+ FOR UPDATE
+ "#,
+ entity_id,
+ entity_type as EntityType,
+ update.property_definition_id,
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+
+ let row_exists = existing.is_some();
+ let current_ids = match existing.flatten() {
+ Some(value) => match serde_json::from_value::<PropertyValue>(value) {
+ Ok(PropertyValue::SelectOption(ids)) => ids,
+ _ => Vec::new(),
+ },
+ None => Vec::new(),
+ };
+
+ let final_ids = apply_option_delta(
+ current_ids,
+ &update.add_option_ids,
+ &update.remove_option_ids,
+ );
+
+ // Nothing to add and no row to remove from: a no-op, leave the DB alone.
+ if row_exists {
+ let value_json = serde_json::json!({
+ "type": "SelectOption",
+ "value": final_ids,
+ });
+ 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,
+ update.property_definition_id,
+ value_json,
+ )
+ .execute(&mut *tx)
+ .await?;
+ }
+
+ selections.push(EntityPropertyOptionSelection {
+ property_definition_id: update.property_definition_id,
+ option_ids: final_ids,
+ });
+ }
+
+ tx.commit().await?;
+ Ok(selections)
+}
+
+/// Apply an add/remove delta to a stored option-id list, keeping the order of
+/// surviving options and appending new ones. An id named in both add and remove
+/// is removed (removals win), matching a delta where the two sets are disjoint.
+fn apply_option_delta(current: Vec<Uuid>, add: &[Uuid], remove: &[Uuid]) -> Vec<Uuid> {
+ let remove_set: std::collections::HashSet<Uuid> = remove.iter().copied().collect();
+ let mut result: Vec<Uuid> = current
+ .into_iter()
+ .filter(|id| !remove_set.contains(id))
+ .collect();
+ for id in add {
+ if !remove_set.contains(id) && !result.contains(id) {
+ result.push(*id);
+ }
+ }
+ result
+}
+
/// 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/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rs
index b1f8fcec8d..3a096bb5ba 100644
--- a/crates/properties/src/outbound/properties_pg_repo.rs
+++ b/crates/properties/src/outbound/properties_pg_repo.rs
@@ -300,6 +300,22 @@ impl PropertiesRepo for PropertiesPgRepo {
.await
}
+ #[tracing::instrument(skip(self, updates), err)]
+ async fn bulk_update_entity_property_options(
+ &self,
+ entity_id: &str,
+ entity_type: EntityType,
+ updates: &[crate::domain::model::EntityPropertyOptionUpdate],
+ ) -> Result<Vec<crate::domain::model::EntityPropertyOptionSelection>, Self::Err> {
+ entity_property_queries::bulk_update_entity_property_options(
+ &self.pool,
+ entity_id,
+ entity_type,
+ updates,
+ )
+ .await
+ }
+
#[tracing::instrument(skip(self))]
async fn link_parent_task(
&self,
diff --git a/crates/properties/src/outbound/test.rs b/crates/properties/src/outbound/test.rs
index 947a5c6235..8eb7ee32e7 100644
--- a/crates/properties/src/outbound/test.rs
+++ b/crates/properties/src/outbound/test.rs
@@ -817,3 +817,219 @@ async fn remove_option_strips_and_is_tolerant(pool: Pool<Postgres>) -> anyhow::R
Ok(())
}
+
+/// Extract the sorted option-id strings from a stored SelectOption value.
+fn select_option_ids(value: &serde_json::Value) -> Vec<String> {
+ let mut ids: Vec<String> = value["value"]
+ .as_array()
+ .expect("value array")
+ .iter()
+ .map(|id| id.as_str().expect("uuid string").to_string())
+ .collect();
+ ids.sort();
+ ids
+}
+
+fn option_update(
+ def_id: Uuid,
+ add: Vec<Uuid>,
+ remove: Vec<Uuid>,
+) -> crate::domain::model::EntityPropertyOptionUpdate {
+ crate::domain::model::EntityPropertyOptionUpdate {
+ property_definition_id: def_id,
+ add_option_ids: add,
+ remove_option_ids: remove,
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn bulk_update_options_composes_and_returns_finals(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let def_id = seed_multi_select_definition(&pool, "Bulk Tags Compose").await;
+ let entity_id = "entity-bulk-compose";
+ let opt_a = macro_uuid::generate_uuid_v7();
+ let opt_b = macro_uuid::generate_uuid_v7();
+ let opt_c = macro_uuid::generate_uuid_v7();
+
+ // First bulk update attaches the property and adds A and B.
+ let first = repo
+ .bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[option_update(def_id, vec![opt_a, opt_b], vec![])],
+ )
+ .await?;
+ assert_eq!(first.len(), 1);
+ assert_eq!(first[0].property_definition_id, def_id);
+ assert_eq!(first[0].option_ids, vec![opt_a, opt_b]);
+
+ // Second bulk update removes A and adds C, composing with the stored value.
+ let second = repo
+ .bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[option_update(def_id, vec![opt_c], vec![opt_a])],
+ )
+ .await?;
+ assert_eq!(second[0].option_ids, vec![opt_b, opt_c]);
+ assert_eq!(
+ read_select_value(&pool, entity_id, def_id).await,
+ serde_json::json!({"type": "SelectOption", "value": [opt_b, opt_c]})
+ );
+
+ Ok(())
+}
+
+/// Two bulk updates racing on the same row must serialize under the row lock and
+/// preserve both changes: a naive read-modify-write would drop one.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn bulk_update_options_concurrent_no_lost_update(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let def_id = seed_multi_select_definition(&pool, "Bulk Tags Concurrent").await;
+ let entity_id = "entity-bulk-concurrent";
+ let opt_a = macro_uuid::generate_uuid_v7();
+ let opt_b = macro_uuid::generate_uuid_v7();
+
+ // Start from {A}.
+ repo.bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[option_update(def_id, vec![opt_a], vec![])],
+ )
+ .await?;
+
+ // One update removes A while the other adds B, concurrently.
+ let remover = {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ tokio::spawn(async move {
+ repo.bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[option_update(def_id, vec![], vec![opt_a])],
+ )
+ .await
+ })
+ };
+ let adder = {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ tokio::spawn(async move {
+ repo.bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[option_update(def_id, vec![opt_b], vec![])],
+ )
+ .await
+ })
+ };
+
+ remover.await??;
+ adder.await??;
+
+ // Regardless of ordering: A removed, B added. A lost update would leave A.
+ assert_eq!(
+ select_option_ids(&read_select_value(&pool, entity_id, def_id).await),
+ vec![opt_b.to_string()]
+ );
+
+ Ok(())
+}
+
+/// A failure on any property rolls back the whole batch: an earlier property's
+/// change is undone when a later property in the same request fails.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn bulk_update_options_partial_failure_rolls_back(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let def_id = seed_multi_select_definition(&pool, "Bulk Tags Rollback").await;
+ let entity_id = "entity-bulk-rollback";
+ let existing = macro_uuid::generate_uuid_v7();
+ let attempted = macro_uuid::generate_uuid_v7();
+ // No such property definition, so writing it violates the foreign key.
+ let missing_def_id = macro_uuid::generate_uuid_v7();
+ let orphan_option = macro_uuid::generate_uuid_v7();
+
+ // Establish a committed baseline value on the valid property.
+ repo.bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[option_update(def_id, vec![existing], vec![])],
+ )
+ .await?;
+
+ // The first property would succeed, but the second targets a missing
+ // definition and fails the transaction.
+ let result = repo
+ .bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[
+ option_update(def_id, vec![attempted], vec![]),
+ option_update(missing_def_id, vec![orphan_option], vec![]),
+ ],
+ )
+ .await;
+ assert!(
+ result.is_err(),
+ "batch with a missing definition should fail"
+ );
+
+ // The valid property is unchanged - the attempted add was rolled back.
+ assert_eq!(
+ read_select_value(&pool, entity_id, def_id).await,
+ serde_json::json!({"type": "SelectOption", "value": [existing]})
+ );
+
+ Ok(())
+}
+
+/// A removal-only update on a property the entity has no row for is a no-op: it
+/// returns an empty selection and must not create an empty `entity_properties`
+/// row.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn bulk_update_options_removal_only_on_unattached_is_noop(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+ let def_id = seed_multi_select_definition(&pool, "Bulk Tags Noop").await;
+ let entity_id = "entity-bulk-noop";
+ let absent = macro_uuid::generate_uuid_v7();
+
+ let result = repo
+ .bulk_update_entity_property_options(
+ entity_id,
+ EntityType::Document,
+ &[option_update(def_id, vec![], vec![absent])],
+ )
+ .await?;
+ assert_eq!(result.len(), 1);
+ assert_eq!(result[0].option_ids, Vec::<Uuid>::new());
+
+ let row_count: i64 = sqlx::query_scalar(
+ r#"
+ SELECT COUNT(*) FROM entity_properties
+ WHERE entity_id = $1 AND property_definition_id = $2
+ "#,
+ )
+ .bind(entity_id)
+ .bind(def_id)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(row_count, 0, "removal-only update must not create a row");
+
+ Ok(())
+}
diff --git a/crates/properties_service/src/api/swagger.rs b/crates/properties_service/src/api/swagger.rs
index 8704e12683..3288c4261a 100644
--- a/crates/properties_service/src/api/swagger.rs
+++ b/crates/properties_service/src/api/swagger.rs
@@ -2,8 +2,10 @@ use models_properties::api;
use properties::inbound::axum_router::{
definitions::{ListPropertiesQuery, PropertyDefinitionResponse},
entities::{
- BulkEntityPropertiesRequest, EntityPropertiesResponse, EntityQueryParams,
- SetEntityPropertyRequest,
+ BulkEntityPropertiesRequest, BulkUpdateEntityPropertyOptionsRequest,
+ BulkUpdateEntityPropertyOptionsResponse, EntityPropertiesResponse,
+ EntityPropertyOptionSelectionResponse, EntityPropertyOptionUpdateRequest,
+ EntityQueryParams, SetEntityPropertyRequest,
},
tags::{EnsureTagSetRequest, TagScope, TagSetResponse},
};
@@ -32,6 +34,7 @@ use utoipa::OpenApi;
properties::inbound::axum_router::entities::set_entity_property,
properties::inbound::axum_router::entities::add_entity_property_option,
properties::inbound::axum_router::entities::remove_entity_property_option,
+ properties::inbound::axum_router::entities::bulk_update_entity_property_options,
properties::inbound::axum_router::entities::delete_entity_property,
),
components(
@@ -48,6 +51,10 @@ use utoipa::OpenApi;
SetEntityPropertyRequest,
EntityQueryParams,
BulkEntityPropertiesRequest,
+ BulkUpdateEntityPropertyOptionsRequest,
+ BulkUpdateEntityPropertyOptionsResponse,
+ EntityPropertyOptionUpdateRequest,
+ EntityPropertyOptionSelectionResponse,
api::SetPropertyValue,
models_properties::EntityReference,
api::AddPropertyOptionRequest,
diff --git a/justfile b/justfile
index 52bbc4569e..3e59bccd0f 100644
--- a/justfile
+++ b/justfile
@@ -55,9 +55,12 @@ local-e2e-seed:
# `just seed-scenario apply --file seed/scenarios/team-perms.json`.
# Add --force to drop and re-migrate the local database first (pristine world).
# `just seed-scenario status` reports what's applied and re-prints login links.
+# Set INSTANCE=<name> to target a `run_local --instance <name>` stack; it
+# resolves that instance's host ports for Postgres/FusionAuth/LocalStack/frontend.
+# Defaults to the `macro` instance (unchanged from the fixed local ports).
[positional-arguments]
seed-scenario *ARGS:
- @just tooling/seed_cli/scenario "$@"
+ @eval "$({{ xtask }} seed-env --instance "${INSTANCE:-macro}")" && just tooling/seed_cli/scenario "$@"
# Start only the services needed by the local E2E suites. Avoid unrelated
# local services with extra env/dependency requirements blocking E2E.
diff --git a/tooling/seed_cli/justfile b/tooling/seed_cli/justfile
index 2373310a86..0108a07812 100644
--- a/tooling/seed_cli/justfile
+++ b/tooling/seed_cli/justfile
@@ -57,4 +57,4 @@ scenario *ARGS:
LEXICAL_SERVICE_URL="${LEXICAL_SERVICE_URL:-http://localhost:8096}" \
INTERNAL_API_SECRET_KEY="${INTERNAL_API_SECRET_KEY:-local}" \
FRONTEND_PORT="${FRONTEND_PORT:-3000}" \
- cargo r -q -- scenario "$@"
+ cargo r -- scenario "$@"
diff --git a/tooling/seed_cli/seed/scenarios/team-perms.json b/tooling/seed_cli/seed/scenarios/team-perms.json
index bd5e4be755..fbb8d11470 100644
--- a/tooling/seed_cli/seed/scenarios/team-perms.json
+++ b/tooling/seed_cli/seed/scenarios/team-perms.json
@@ -1,6 +1,6 @@
{
"scenario": "team-perms",
- "description": "One team (acme: alice owner, bob admin, carol member), dave collaborates via channels without being on the team, eve is an outsider. The Acme members carry team_subscriber + sub_opus like real paying-team members (join_team grants exactly those); dave is a solo professional_subscriber; eve is a free account. Exercises owner/user/team/channel/public/project/delegation access edges across every entity type.",
+ "description": "One team (acme: alice owner, bob + erin admin, carol member), dave collaborates via channels without being on the team, eve is an outsider. erin is a second admin with edit shares on all of Alice's documents and tasks — a full-edit-access teammate (edit is the highest grantable share level; ownership stays with alice). The Acme members carry team_subscriber + sub_opus like real paying-team members (join_team grants exactly those); dave is a solo professional_subscriber; eve is a free account. Exercises owner/user/team/channel/public/project/delegation access edges across every entity type.",
"users": {
"alice": {
"email": "[email protected]",
@@ -17,6 +17,11 @@
"first_name": "Carol",
"roles": ["team_subscriber", "sub_opus"]
},
+ "erin": {
+ "email": "[email protected]",
+ "first_name": "Erin",
+ "roles": ["team_subscriber", "sub_opus"]
+ },
"dave": {
"email": "[email protected]",
"first_name": "Dave",
@@ -28,7 +33,7 @@
"acme": {
"name": "Acme",
"owner": "alice",
- "members": { "bob": "admin", "carol": "member" }
+ "members": { "bob": "admin", "carol": "member", "erin": "admin" }
}
},
"channels": {
@@ -49,7 +54,8 @@
"owner": "alice",
"name": "Q3 Plan",
"content": "# Q3 Plan\n\n- Ship the tagging system\n- Verify permissions across every entity type\n- Grow the Acme team\n",
- "project": "roadmap"
+ "project": "roadmap",
+ "share": [{ "with": "user:erin", "level": "edit" }]
},
"design-doc": {
"owner": "alice",
@@ -57,14 +63,16 @@
"content": "# Design Doc\n\nDave has edit access; the eng channel can view this via the share and Bob's mention.\n",
"share": [
{ "with": "user:dave", "level": "edit" },
- { "with": "channel:eng", "level": "view" }
+ { "with": "channel:eng", "level": "view" },
+ { "with": "user:erin", "level": "edit" }
]
},
"handbook": {
"owner": "alice",
"name": "Handbook",
"file": "pdf.pdf",
- "public": "view"
+ "public": "view",
+ "share": [{ "with": "user:erin", "level": "edit" }]
},
"bob-notes": { "owner": "bob", "name": "Bob Notes", "file": "md.md" }
},
@@ -75,8 +83,9 @@
"content": "# Ship the tagging system\n\n- [x] backend\n- [ ] verify perms across entity types\n",
"project": "roadmap",
"status": "in_progress",
- "assignees": ["alice", "bob"],
- "share_with_team": true
+ "assignees": ["alice", "bob", "erin"],
+ "share_with_team": true,
+ "share": [{ "with": "user:erin", "level": "edit" }]
},
"fix-perms": {
"owner": "dave",
@@ -90,7 +99,8 @@
"content": "# Write the perms docs\n\nCover every access edge the seeder exercises.\n",
"status": "in_review",
"assignees": ["carol"],
- "share_with_team": true
+ "share_with_team": true,
+ "share": [{ "with": "user:erin", "level": "edit" }]
}
},
"chats": {
diff --git a/tooling/seed_cli/src/entity/scenario/matrix/test.rs b/tooling/seed_cli/src/entity/scenario/matrix/test.rs
index d17f20c760..7a57679f6c 100644
--- a/tooling/seed_cli/src/entity/scenario/matrix/test.rs
+++ b/tooling/seed_cli/src/entity/scenario/matrix/test.rs
@@ -40,6 +40,19 @@ fn expected_matrix_covers_owner_team_channel_public_edges() {
);
assert_eq!(level(&rows, "document:q3-plan", "dave"), None);
assert_eq!(level(&rows, "document:q3-plan", "eve"), None);
+ // erin is a full-edit-access teammate: direct edit share on Alice's docs.
+ assert_eq!(
+ level(&rows, "document:q3-plan", "erin"),
+ Some(AccessLevel::Edit)
+ );
+ assert_eq!(
+ level(&rows, "document:design-doc", "erin"),
+ Some(AccessLevel::Edit)
+ );
+ assert_eq!(
+ level(&rows, "document:handbook", "erin"),
+ Some(AccessLevel::Edit)
+ );
// design-doc: dave has a direct edit share; channel share + mention give
// eng members view; carol/eve see nothing.
@@ -200,6 +213,8 @@ fn task_expectations_cover_team_share_and_inheritance() {
// ship-tags: alice owns it; the team gets comment via share_with_team;
// the project's team view is subsumed by comment; dave/eve see nothing.
+ // erin is an assignee, but her edit comes from the direct share, not the
+ // assignment.
assert_eq!(
level(&rows, "task:ship-tags", "alice"),
Some(AccessLevel::Owner)
@@ -214,6 +229,11 @@ fn task_expectations_cover_team_share_and_inheritance() {
);
assert_eq!(level(&rows, "task:ship-tags", "dave"), None);
assert_eq!(level(&rows, "task:ship-tags", "eve"), None);
+ // erin has a direct edit share, which wins over the team's comment.
+ assert_eq!(
+ level(&rows, "task:ship-tags", "erin"),
+ Some(AccessLevel::Edit)
+ );
// fix-perms: dave's personal task shared to the eng channel; assigning
// alice grants nothing by itself — her view comes from the channel.
@@ -238,4 +258,8 @@ fn task_expectations_cover_team_share_and_inheritance() {
Some(AccessLevel::Comment)
);
assert_eq!(level(&rows, "task:write-docs", "dave"), None);
+ assert_eq!(
+ level(&rows, "task:write-docs", "erin"),
+ Some(AccessLevel::Edit)
+ );
}
diff --git a/tooling/seed_cli/src/entity/scenario/spec/test.rs b/tooling/seed_cli/src/entity/scenario/spec/test.rs
index 079bdb827a..4fc6c156de 100644
--- a/tooling/seed_cli/src/entity/scenario/spec/test.rs
+++ b/tooling/seed_cli/src/entity/scenario/spec/test.rs
@@ -52,7 +52,7 @@ fn scenario_marker_shape() {
fn example_scenario_parses() {
let spec = example();
assert_eq!(spec.scenario, "team-perms");
- assert_eq!(spec.users.len(), 5);
+ assert_eq!(spec.users.len(), 6);
assert_eq!(spec.user_id("alice"), "macro|[email protected]");
}
@@ -66,7 +66,7 @@ fn team_and_channel_derivations() {
let mut hq_members = spec.channel_members("acme-hq");
hq_members.sort();
- assert_eq!(hq_members, vec!["alice", "bob", "carol"]);
+ assert_eq!(hq_members, vec!["alice", "bob", "carol", "erin"]);
assert_eq!(spec.channel_owner("acme-hq"), "alice");
assert_eq!(spec.channel_owner("dm-alice-dave"), "alice");
diff --git a/tooling/xtask/crates/xtask_local/src/local/cli.rs b/tooling/xtask/crates/xtask_local/src/local/cli.rs
index d8c400e97c..eeec6d6a8f 100644
--- a/tooling/xtask/crates/xtask_local/src/local/cli.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/cli.rs
@@ -38,6 +38,8 @@ enum Cmd {
DoctorLocal(InstanceArgs),
/// Show an instance's endpoints and container states without starting anything.
StatusLocal(InstanceArgs),
+ /// Emit host-facing connection env for seeding an instance (eval in a shell).
+ SeedEnv(InstanceArgs),
/// Stop an instance's containers (keep volumes).
StopLocal(InstanceArgs),
/// Drop, recreate, and migrate the instance database.
@@ -182,6 +184,10 @@ fn run(cli: Cli) -> Result<()> {
let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;
super::status::run(&instance)
}
+ Cmd::SeedEnv(a) => {
+ let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;
+ super::seed_env::emit(&instance)
+ }
Cmd::StopLocal(a) => super::stop(&a),
Cmd::ResetLocal(a) => super::reset(&a),
Cmd::DestroyLocal(a) => super::destroy(&a),
diff --git a/tooling/xtask/crates/xtask_local/src/local/mod.rs b/tooling/xtask/crates/xtask_local/src/local/mod.rs
index 09823f0fc9..b56e569520 100644
--- a/tooling/xtask/crates/xtask_local/src/local/mod.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/mod.rs
@@ -35,6 +35,7 @@ pub mod mailpit;
pub mod opensearch;
pub mod proxy;
pub mod resources;
+pub mod seed_env;
pub mod snapshot;
pub mod stack;
pub mod stage;
diff --git a/tooling/xtask/crates/xtask_local/src/local/seed_env.rs b/tooling/xtask/crates/xtask_local/src/local/seed_env.rs
new file mode 100644
index 0000000000..1491caba38
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/seed_env.rs
@@ -0,0 +1,50 @@
+//! Emit host-facing connection env for seeding an instance.
+//!
+//! Dockerized services reach each other over the compose network
+//! (`postgres:5432`, `fusionauth:9011`, ...), but the seed CLI runs on the host
+//! and needs `localhost:<host-port>`. This prints `eval`-able shell exports so
+//! `just seed-scenario` can target a `run_local --instance <name>` stack. Each
+//! export preserves a value already in the environment (`${VAR:-...}`), so
+//! explicit overrides still win and the default instance reproduces the
+//! recipe's historical fixed-port defaults exactly.
+//!
+//! Sync-service and lexical-service are not instance-isolated (their compose
+//! ports are hardcoded to 8787/8096), so document content is left to the seed
+//! recipe's shared defaults rather than emitted here.
+
+#[cfg(test)]
+mod test;
+
+use anyhow::Result;
+
+use super::instance::{Instance, Port};
+
+/// Print `export KEY="${KEY:-<host value>}"` lines for the instance's
+/// host-facing connection endpoints.
+pub fn emit(instance: &Instance) -> Result<()> {
+ print!("{}", render(instance));
+ Ok(())
+}
+
+/// The `eval`-able export block for the instance's host-facing endpoints. Each
+/// line preserves any value already in the environment so explicit overrides
+/// win and the default instance reproduces the recipe's fixed-port defaults.
+fn render(instance: &Instance) -> String {
+ let postgres = instance.port(Port::Postgres);
+ let localstack = instance.port(Port::LocalStack);
+ let fusionauth = instance.port(Port::FusionAuth);
+ let frontend = instance.port(Port::Frontend);
+
+ [
+ format!(
+ r#"export DATABASE_URL="${{DATABASE_URL:-postgres://user:password@localhost:{postgres}/macrodb}}""#
+ ),
+ format!(r#"export LOCAL_AWS_URL="${{LOCAL_AWS_URL:-http://localhost:{localstack}}}""#),
+ format!(
+ r#"export FUSIONAUTH_BASE_URL="${{FUSIONAUTH_BASE_URL:-http://localhost:{fusionauth}}}""#
+ ),
+ format!(r#"export FRONTEND_PORT="${{FRONTEND_PORT:-{frontend}}}""#),
+ ]
+ .join("\n")
+ + "\n"
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs
new file mode 100644
index 0000000000..7e443bed9d
--- /dev/null
+++ b/tooling/xtask/crates/xtask_local/src/local/seed_env/test.rs
@@ -0,0 +1,52 @@
+use super::*;
+
+#[test]
+fn default_instance_reproduces_the_fixed_ports() {
+ let instance = Instance::derive(None, None).unwrap();
+ let rendered = render(&instance);
+
+ assert!(
+ rendered
+ .contains(r#"export DATABASE_URL="${DATABASE_URL:-postgres://user:password@localhost:5432/macrodb}""#),
+ "{rendered}"
+ );
+ assert!(
+ rendered.contains(r#"export LOCAL_AWS_URL="${LOCAL_AWS_URL:-http://localhost:4566}""#),
+ "{rendered}"
+ );
+ assert!(
+ rendered.contains(
+ r#"export FUSIONAUTH_BASE_URL="${FUSIONAUTH_BASE_URL:-http://localhost:9011}""#
+ ),
+ "{rendered}"
+ );
+ assert!(
+ rendered.contains(r#"export FRONTEND_PORT="${FRONTEND_PORT:-3000}""#),
+ "{rendered}"
+ );
+}
+
+#[test]
+fn named_instance_shifts_into_its_port_window() {
+ let instance = Instance::derive(Some("agent-a"), None).unwrap();
+ let base = instance.port_base();
+
+ // Every emitted port sits in the instance's stride, and each keeps its
+ // per-port offset (Postgres is the stride base).
+ assert!(
+ render(&instance).contains(&format!("localhost:{base}/macrodb")),
+ "postgres should bind the stride base {base}"
+ );
+ assert_eq!(instance.port(Port::Postgres), base);
+ assert!(instance.port(Port::FusionAuth) > base);
+ assert_ne!(instance.port(Port::FusionAuth), 9011);
+}
+
+#[test]
+fn overrides_are_preserved_via_shell_default_expansion() {
+ let instance = Instance::derive(Some("agent-a"), None).unwrap();
+ // Each line is `${VAR:-...}`, so a value already exported wins.
+ for line in render(&instance).lines() {
+ assert!(line.contains(":-"), "line must preserve overrides: {line}");
+ }
+}