Skip to content

armgit / macro

Public Imported from GitHub
0

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

add [properties & tasks] - show assignee status priority in unified list (#659)

Daniel Kweond0674f2b794e
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index 1f57bfb667..9e149fb892 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -14,6 +14,7 @@ import { ToggleButton } from '@core/component/FormControls/ToggleButton';
import { ToggleSwitch } from '@core/component/FormControls/ToggleSwitch';
import { IconButton } from '@core/component/IconButton';
import { ContextMenuContent, MenuSeparator } from '@core/component/Menu';
+import { useTaskProperties } from '@core/component/Properties/hooks';
import { getSuggestedProperties } from '@core/component/Properties/utils';
import { RecipientSelector } from '@core/component/RecipientSelector';
import {
@@ -227,6 +228,10 @@ export function UnifiedListView(props: UnifiedListViewProps) {
entitiesSignal: [entities_, setEntities],
emailViewSignal: [emailView],
} = unifiedListContext;
+
+ // Properties for task entities
+ const [taskPropertiesStore] = useTaskProperties(entities_);
+
const view = createMemo(() => viewsData[selectedView()]);
const selectedEntity = createMemo(() => view()?.selectedEntity);
@@ -1495,6 +1500,11 @@ export function UnifiedListView(props: UnifiedListViewProps) {
});
}}
entity={innerProps.entity}
+ properties={
+ isTaskEntity(innerProps.entity)
+ ? taskPropertiesStore[innerProps.entity.id]
+ : undefined
+ }
timestamp={timestamp()}
onClick={entityClickHandler}
onClickRowAction={
diff --git a/js/app/packages/core/component/Properties/api/fetchProperties.ts b/js/app/packages/core/component/Properties/api/fetchProperties.ts
index ad477edd78..7e145476ae 100644
--- a/js/app/packages/core/component/Properties/api/fetchProperties.ts
+++ b/js/app/packages/core/component/Properties/api/fetchProperties.ts
@@ -1,16 +1,40 @@
import { isErr } from '@core/util/maybeResult';
+import { queryClient } from '@queries/client';
import { propertiesServiceClient } from '@service-properties/client';
+import type { EntityReference } from '@service-properties/generated/schemas/entityReference';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import type { Property, Result } from '../types';
import { ERROR_MESSAGES } from '../utils/errorHandling';
import { entityPropertyFromApi } from './converters';
/**
- * Fetch all properties for an entity
+ * Query keys for properties cache.
*
- * @param entityId - The ID of the entity to fetch properties for
- * @param entityType - The type of entity (e.g., 'document', 'channel', 'project')
- * @param includeMetadata - Whether to include metadata properties
+ * Cache is keyed by (entity + propertyDefinitionIds set) rather than per individual property.
+ * This is simpler and sufficient because:
+ * 1. Our main consumer (useTaskProperties) always requests the same fixed set of properties
+ * 2. Per-property caching wouldn't save API calls anyway - if any property is missing,
+ * we'd still need to fetch all requested properties for that entity
+ */
+export const propertyQueryKeys = {
+ all: ['properties'] as const,
+ entity: (
+ entityType: EntityType,
+ entityId: string,
+ propertyDefinitionIds?: string[]
+ ) =>
+ [
+ ...propertyQueryKeys.all,
+ 'entity',
+ entityType,
+ entityId,
+ propertyDefinitionIds?.sort(),
+ ] as const,
+};
+
+/**
+ * Fetch all properties for an entity.
+ * Returns a Result type for backward compatibility with existing hooks.
*/
export async function fetchEntityProperties(
entityId: string,
@@ -60,3 +84,80 @@ export async function fetchEntityProperties(
};
}
}
+
+/**
+ * Fetch properties for multiple entities in bulk.
+ * Uses TanStack Query cache - only fetches entities not already cached.
+ *
+ * Note: This is not standard TanStack Query usage (normally you'd use useQuery/useQueries).
+ * We use queryClient manually because we need bulk fetching (1 API call for N entities)
+ * rather than N individual queries. Using TanStack as a cache layer is fine for this use case.
+ *
+ * @param entities - Array of entity references to fetch properties for
+ * @param propertyDefinitionIds - Property definition IDs to fetch (required for cache correctness)
+ */
+export async function fetchBulkEntityProperties(
+ entities: EntityReference[],
+ propertyDefinitionIds: string[]
+): Promise<Map<string, Property[]>> {
+ if (entities.length === 0) {
+ return new Map();
+ }
+
+ const result = new Map<string, Property[]>();
+ const entitiesToFetch: EntityReference[] = [];
+
+ // Check cache for each entity
+ for (const entity of entities) {
+ const queryKey = propertyQueryKeys.entity(
+ entity.entity_type,
+ entity.entity_id,
+ propertyDefinitionIds
+ );
+ const cached = queryClient.getQueryData<Property[]>(queryKey);
+
+ if (cached) {
+ result.set(entity.entity_id, cached);
+ } else {
+ entitiesToFetch.push(entity);
+ }
+ }
+
+ // Fetch only uncached entities
+ if (entitiesToFetch.length > 0) {
+ const fetchResult = await propertiesServiceClient.getBulkEntityProperties({
+ body: { entities: entitiesToFetch, property_ids: propertyDefinitionIds },
+ });
+
+ if (isErr(fetchResult)) {
+ console.error(
+ 'api.properties.fetchBulkEntityProperties:',
+ fetchResult,
+ ERROR_MESSAGES.PROPERTY_FETCH
+ );
+ // Return what we have from cache, don't throw
+ return result;
+ }
+
+ const [, data] = fetchResult;
+
+ // Update cache and result for each fetched entity
+ for (const [entityId, response] of Object.entries(data)) {
+ const properties = response.properties.map(entityPropertyFromApi);
+ const entity = entitiesToFetch.find((e) => e.entity_id === entityId);
+
+ if (entity) {
+ const queryKey = propertyQueryKeys.entity(
+ entity.entity_type,
+ entity.entity_id,
+ propertyDefinitionIds
+ );
+ queryClient.setQueryData(queryKey, properties);
+ }
+
+ result.set(entityId, properties);
+ }
+ }
+
+ return result;
+}
diff --git a/js/app/packages/core/component/Properties/hooks/index.ts b/js/app/packages/core/component/Properties/hooks/index.ts
index b8f18c6f3c..b808f8c793 100644
--- a/js/app/packages/core/component/Properties/hooks/index.ts
+++ b/js/app/packages/core/component/Properties/hooks/index.ts
@@ -4,3 +4,4 @@ export { useInlineEditor } from './useInlineEditor';
export { usePropertyEditor } from './usePropertyEditor';
export { usePropertyEntityDisplay } from './usePropertyEntityDisplay';
export { usePropertySelection } from './usePropertySelection';
+export { useTaskProperties } from './useTaskProperties';
diff --git a/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts b/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts
new file mode 100644
index 0000000000..54932e1d64
--- /dev/null
+++ b/js/app/packages/core/component/Properties/hooks/useTaskProperties.ts
@@ -0,0 +1,63 @@
+import { createEffect } from 'solid-js';
+import { createStore, type SetStoreFunction } from 'solid-js/store';
+import { fetchBulkEntityProperties } from '../api/fetchProperties';
+import { SYSTEM_PROPERTY_IDS } from '../constants';
+import type { Property } from '../types';
+
+export type TaskPropertiesStore = Record<string, Property[]>;
+
+interface Entity {
+ id: string;
+ type: string;
+ subType?: string | null;
+}
+
+const TASK_PROPERTY_DEFINITION_IDS = [
+ SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ SYSTEM_PROPERTY_IDS.STATUS,
+ SYSTEM_PROPERTY_IDS.PRIORITY,
+];
+
+function isTaskEntity(entity: Entity): boolean {
+ return entity.type === 'document' && entity.subType === 'task';
+}
+
+/**
+ * Hook to fetch and cache properties for task entities.
+ * Returns a store where keys are entity IDs and values are property arrays.
+ *
+ * Uses TanStack Query cache internally - properties are cached per entity
+ * and won't be refetched if already in cache.
+ *
+ * @param entities - Accessor for the list of entities to fetch properties for
+ */
+export function useTaskProperties(
+ entities: () => Entity[] | undefined
+): [TaskPropertiesStore, SetStoreFunction<TaskPropertiesStore>] {
+ const [store, setStore] = createStore<TaskPropertiesStore>({});
+
+ createEffect(() => {
+ const allEntities = entities();
+ if (!allEntities?.length) return;
+
+ const taskEntities = allEntities.filter(isTaskEntity);
+ if (taskEntities.length === 0) return;
+
+ const entityRefs = taskEntities.map((e) => ({
+ entity_id: e.id,
+ entity_type: 'TASK' as const,
+ }));
+
+ fetchBulkEntityProperties(entityRefs, TASK_PROPERTY_DEFINITION_IDS).then(
+ (result) => {
+ for (const [id, props] of result) {
+ if (!(id in store)) {
+ setStore(id, props);
+ }
+ }
+ }
+ );
+ });
+
+ return [store, setStore];
+}
diff --git a/js/app/packages/service-clients/service-properties/client.ts b/js/app/packages/service-clients/service-properties/client.ts
index 8c5f0b41b1..d89866f27c 100644
--- a/js/app/packages/service-clients/service-properties/client.ts
+++ b/js/app/packages/service-clients/service-properties/client.ts
@@ -12,9 +12,11 @@ import {
import { registerClient } from '@core/util/mockClient';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { AddPropertyOptionRequest } from './generated/schemas/addPropertyOptionRequest';
+import type { BulkEntityPropertiesRequest } from './generated/schemas/bulkEntityPropertiesRequest';
import type { CreatePropertyDefinitionRequest } from './generated/schemas/createPropertyDefinitionRequest';
import type { EntityPropertiesResponse } from './generated/schemas/entityPropertiesResponse';
import type { EntityType } from './generated/schemas/entityType';
+import type { GetBulkEntityProperties200 } from './generated/schemas/getBulkEntityProperties200';
import type { GetEntityPropertiesParams } from './generated/schemas/getEntityPropertiesParams';
import type { ListPropertiesParams } from './generated/schemas/listPropertiesParams';
import type { PropertyDefinition } from './generated/schemas/propertyDefinition';
@@ -60,6 +62,9 @@ type SetPropertyStatusCompleteArgs = {
entity_type: PropertiesEntityType;
entity_id: string;
};
+type GetBulkEntityPropertiesArgs = {
+ body: BulkEntityPropertiesRequest;
+};
const propertiesHost: string = SERVER_HOSTS['properties-service'];
@@ -194,6 +199,16 @@ export const propertiesServiceClient = {
});
return mapOk(result, () => ({ success: true }));
},
+
+ getBulkEntityProperties: async (args: GetBulkEntityPropertiesArgs) => {
+ return await propertiesFetch<GetBulkEntityProperties200>(
+ `/properties/entities/bulk`,
+ {
+ method: 'POST',
+ body: JSON.stringify(args.body),
+ }
+ );
+ },
};
registerClient('properties', propertiesServiceClient);
diff --git a/js/app/packages/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.ts b/js/app/packages/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.ts
index 6f199c2e30..3a7e63dcbe 100644
--- a/js/app/packages/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.ts
+++ b/js/app/packages/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequest.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { EntityReference } from './entityReference';
+import type { BulkEntityPropertiesRequestPropertyIds } from './bulkEntityPropertiesRequestPropertyIds';
/**
* Request for getting properties for multiple entities in bulk
@@ -12,4 +13,6 @@ import type { EntityReference } from './entityReference';
export interface BulkEntityPropertiesRequest {
/** Array of entity references (entity_id and entity_type pairs) */
entities: EntityReference[];
+ /** Optional: only return properties with these definition IDs. If empty/None, returns all. */
+ property_ids?: BulkEntityPropertiesRequestPropertyIds;
}
diff --git a/js/app/packages/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequestPropertyIds.ts b/js/app/packages/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequestPropertyIds.ts
new file mode 100644
index 0000000000..8c3276a135
--- /dev/null
+++ b/js/app/packages/service-clients/service-properties/generated/schemas/bulkEntityPropertiesRequestPropertyIds.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional: only return properties with these definition IDs. If empty/None, returns all.
+ */
+export type BulkEntityPropertiesRequestPropertyIds = string[] | null;
diff --git a/js/app/packages/service-clients/service-properties/generated/schemas/getBulkEntityProperties200.ts b/js/app/packages/service-clients/service-properties/generated/schemas/getBulkEntityProperties200.ts
new file mode 100644
index 0000000000..2b0112e635
--- /dev/null
+++ b/js/app/packages/service-clients/service-properties/generated/schemas/getBulkEntityProperties200.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityPropertiesResponse } from './entityPropertiesResponse';
+
+export type GetBulkEntityProperties200 = {[key: string]: EntityPropertiesResponse};
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 28d4f77267..b9cdead5a9 100644
--- a/js/app/packages/service-clients/service-properties/generated/zod.ts
+++ b/js/app/packages/service-clients/service-properties/generated/zod.ts
@@ -197,6 +197,99 @@ export const deletePropertyOptionParams = zod.object({
})
+/**
+ * Only returns properties for entities the user has view permission for.
+Entities without permission are silently omitted from the response.
+ * @summary Get properties for multiple entities in bulk (public endpoint with user auth)
+ */
+export const getBulkEntityPropertiesBody = zod.object({
+ "entities": zod.array(zod.object({
+ "entity_id": zod.string(),
+ "entity_type": zod.enum(['CHANNEL', 'CHAT', 'COMPANY', 'DOCUMENT', 'PROJECT', 'TASK', 'THREAD', 'USER']).describe('Type of entity that can be referenced by entity properties.'),
+ "specific_message_id": zod.string().uuid().nullish().describe('For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread/channel/chat.')
+}).describe('Entity reference for entity-type property values.')).describe('Array of entity references (entity_id and entity_type pairs)'),
+ "property_ids": zod.array(zod.string().uuid()).nullish().describe('Optional: only return properties with these definition IDs. If empty/None, returns all.')
+}).describe('Request for getting properties for multiple entities in bulk')
+
+export const getBulkEntityPropertiesResponse = zod.record(zod.string(), zod.object({
+ "entity_id": zod.string(),
+ "properties": zod.array(zod.object({
+ "definition": zod.object({
+ "created_at": zod.string().datetime({}),
+ "data_type": zod.enum(['BOOLEAN', 'DATE', 'NUMBER', 'STRING', 'SELECT_NUMBER', 'SELECT_STRING', 'ENTITY', 'LINK']).describe('Data type for property values, determining storage and validation.'),
+ "display_name": zod.string(),
+ "id": zod.string().uuid(),
+ "is_metadata": zod.boolean().describe('Flag to indicate if this is a system-generated metadata property.\nNot stored in database - computed at service layer.'),
+ "is_multi_select": zod.boolean(),
+ "is_system": zod.boolean().describe('Flag to indicate if this is a system property (stored in DB).'),
+ "owner": zod.union([zod.object({
+ "scope": zod.enum(['user']),
+ "user_id": zod.string()
+}).describe('User-scoped property only'),zod.object({
+ "organization_id": zod.number(),
+ "scope": zod.enum(['organization'])
+}).describe('Organization-scoped property only'),zod.object({
+ "organization_id": zod.number(),
+ "scope": zod.enum(['user_and_organization']),
+ "user_id": zod.string()
+}).describe('Both user and organization-scoped'),zod.object({
+ "scope": zod.enum(['system'])
+}).describe('System-owned property (no user or org owner)')]).describe('Defines who owns a property - user-scoped, org-scoped, system, or both user and org.'),
+ "specific_entity_type": zod.union([zod.null(),zod.enum(['CHANNEL', 'CHAT', 'COMPANY', 'DOCUMENT', 'PROJECT', 'TASK', 'THREAD', 'USER']).describe('Type of entity that can be referenced by entity properties.')]).optional(),
+ "updated_at": zod.string().datetime({})
+}).describe('Property definition model (service representation).'),
+ "options": zod.array(zod.object({
+ "created_at": zod.string().datetime({}),
+ "display_order": zod.number(),
+ "id": zod.string().uuid(),
+ "property_definition_id": zod.string().uuid(),
+ "updated_at": zod.string().datetime({}),
+ "value": zod.union([zod.object({
+ "type": zod.enum(['string']),
+ "value": zod.string().describe('String value for SelectString properties')
+}).describe('String value for SelectString properties'),zod.object({
+ "type": zod.enum(['number']),
+ "value": zod.number().describe('Number value for SelectNumber properties')
+}).describe('Number value for SelectNumber properties')]).describe('The value of a property option - either a string or a number.')
+}).describe('A selectable option for select-type properties (service representation).')).nullish(),
+ "property": zod.object({
+ "created_at": zod.string().datetime({}),
+ "entity_id": zod.string(),
+ "entity_type": zod.enum(['CHANNEL', 'CHAT', 'COMPANY', 'DOCUMENT', 'PROJECT', 'TASK', 'THREAD', 'USER']).describe('Type of entity that can be referenced by entity properties.'),
+ "id": zod.string().uuid(),
+ "property_definition_id": zod.string().uuid(),
+ "updated_at": zod.string().datetime({})
+}).describe('Assignment of a property definition to a specific entity (service representation).'),
+ "value": zod.union([zod.null(),zod.union([zod.object({
+ "type": zod.enum(['Boolean']),
+ "value": zod.boolean().describe('Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}')
+}).describe('Boolean value\nSerializes as: {\"type\": \"Boolean\", \"value\": true}'),zod.object({
+ "type": zod.enum(['Number']),
+ "value": zod.number().describe('Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}')
+}).describe('Numeric value\nSerializes as: {\"type\": \"Number\", \"value\": 42.5}'),zod.object({
+ "type": zod.enum(['String']),
+ "value": zod.string().describe('String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}')
+}).describe('String value\nSerializes as: {\"type\": \"String\", \"value\": \"text\"}'),zod.object({
+ "type": zod.enum(['Date']),
+ "value": zod.string().datetime({}).describe('Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}')
+}).describe('Date/timestamp value\nSerializes as: {\"type\": \"Date\", \"value\": \"2025-01-01T00:00:00Z\"}'),zod.object({
+ "type": zod.enum(['SelectOption']),
+ "value": zod.array(zod.string().uuid()).describe('Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)')
+}).describe('Select option(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"SelectOption\", \"value\": [\"uuid\"]} (length 0 or 1)\nMulti-select: {\"type\": \"SelectOption\", \"value\": [\"uuid1\", \"uuid2\", ...]} (length 0+)'),zod.object({
+ "type": zod.enum(['EntityReference']),
+ "value": zod.array(zod.object({
+ "entity_id": zod.string(),
+ "entity_type": zod.enum(['CHANNEL', 'CHAT', 'COMPANY', 'DOCUMENT', 'PROJECT', 'TASK', 'THREAD', 'USER']).describe('Type of entity that can be referenced by entity properties.'),
+ "specific_message_id": zod.string().uuid().nullish().describe('For CHANNEL, CHAT, THREAD entity types - optional specific message ID.\nThis allows referencing a specific message within a thread/channel/chat.')
+}).describe('Entity reference for entity-type property values.')).describe('Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)')
+}).describe('Entity reference(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"EntityReference\", \"value\": [{...}]} (length 0 or 1)\nMulti-select: {\"type\": \"EntityReference\", \"value\": [{...}, {...}, ...]} (length 0+)'),zod.object({
+ "type": zod.enum(['Link']),
+ "value": zod.array(zod.string()).describe('Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)')
+}).describe('Link value(s) - always an array (check is_multi_select to determine if single or multi)\nSingle-select: {\"type\": \"Link\", \"value\": [\"https://example.com\"]} (length 0 or 1)\nMulti-select: {\"type\": \"Link\", \"value\": [\"https://example.com\", \"https://other.com\"]} (length 0+)')]).describe('Property value (service representation).\n\nRepresents the actual value stored for an entity property.\nThis is serialized to/from JSONB in the database.')]).optional()
+}).describe('Entity property with its definition, value, and options (service representation).'))
+}).describe('Response for document/entity properties endpoint.'))
+
+
/**
* @summary Get all properties for an entity
*/
diff --git a/js/app/packages/service-clients/service-properties/openapi.json b/js/app/packages/service-clients/service-properties/openapi.json
index 513fbd5531..4d3f7092a5 100644
--- a/js/app/packages/service-clients/service-properties/openapi.json
+++ b/js/app/packages/service-clients/service-properties/openapi.json
@@ -204,6 +204,43 @@
}
}
},
+ "/properties/entities/bulk": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Get properties for multiple entities in bulk (public endpoint with user auth)",
+ "description": "Only returns properties for entities the user has view permission for.\nEntities without permission are silently omitted from the response.",
+ "operationId": "get_bulk_entity_properties",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BulkEntityPropertiesRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Bulk entity properties retrieved successfully",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/components/schemas/EntityPropertiesResponse"
+ },
+ "propertyNames": { "type": "string" }
+ }
+ }
+ }
+ },
+ "400": { "description": "Invalid request body" },
+ "403": { "description": "Forbidden - User does not have permission" },
+ "500": { "description": "Internal server error" }
+ }
+ }
+ },
"/properties/entities/{entity_type}/{entity_id}": {
"get": {
"tags": ["Properties"],
@@ -381,6 +418,11 @@
"type": "array",
"items": { "$ref": "#/components/schemas/EntityReference" },
"description": "Array of entity references (entity_id and entity_type pairs)"
+ },
+ "property_ids": {
+ "type": ["array", "null"],
+ "items": { "type": "string", "format": "uuid" },
+ "description": "Optional: only return properties with these definition IDs. If empty/None, returns all."
}
}
},
diff --git a/rust/cloud-storage/properties_db_client/.sqlx/query-e004bed4c36a09e5b178eae38953fe204bea43e98071e554aea716d18538dc66.json b/rust/cloud-storage/properties_db_client/.sqlx/query-e004bed4c36a09e5b178eae38953fe204bea43e98071e554aea716d18538dc66.json
new file mode 100644
index 0000000000..2715715799
--- /dev/null
+++ b/rust/cloud-storage/properties_db_client/.sqlx/query-e004bed4c36a09e5b178eae38953fe204bea43e98071e554aea716d18538dc66.json
@@ -0,0 +1,185 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT \n ep.id as entity_property_id,\n ep.entity_id,\n ep.entity_type as \"entity_type: EntityType\",\n ep.property_definition_id,\n ep.values as \"values: sqlx::types::JsonValue\",\n ep.created_at as entity_property_created_at,\n ep.updated_at as entity_property_updated_at,\n pd.organization_id as definition_organization_id,\n pd.user_id as definition_user_id,\n pd.display_name,\n pd.data_type as \"data_type: DataType\",\n pd.is_multi_select,\n pd.specific_entity_type as \"specific_entity_type: Option<EntityType>\",\n pd.created_at as definition_created_at,\n pd.updated_at as definition_updated_at,\n pd.is_system as definition_is_system\n FROM entity_properties ep\n INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id\n WHERE (ep.entity_id, ep.entity_type) IN (\n SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])\n )\n AND pd.id = ANY($3::UUID[])\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_property_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type: EntityType",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "values: sqlx::types::JsonValue",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "entity_property_created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "entity_property_updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "definition_organization_id",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 8,
+ "name": "definition_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "display_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "data_type: DataType",
+ "type_info": {
+ "Custom": {
+ "name": "property_data_type",
+ "kind": {
+ "Enum": [
+ "BOOLEAN",
+ "DATE",
+ "NUMBER",
+ "STRING",
+ "SELECT_NUMBER",
+ "SELECT_STRING",
+ "ENTITY",
+ "LINK"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 11,
+ "name": "is_multi_select",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 12,
+ "name": "specific_entity_type: Option<EntityType>",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 13,
+ "name": "definition_created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 14,
+ "name": "definition_updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "definition_is_system",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ {
+ "Custom": {
+ "name": "property_entity_type[]",
+ "kind": {
+ "Array": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK"
+ ]
+ }
+ }
+ }
+ }
+ }
+ },
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ true,
+ true,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "e004bed4c36a09e5b178eae38953fe204bea43e98071e554aea716d18538dc66"
+}
diff --git a/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs b/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs
index e811022257..b832ac8ac4 100644
--- a/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs
+++ b/rust/cloud-storage/properties_db_client/src/entity_properties/get.rs
@@ -426,6 +426,108 @@ pub async fn get_bulk_entity_properties_values(
Ok(entity_properties_map)
}
+/// Gets entity properties with their definitions and values for multiple entities, filtered by property definition IDs.
+/// Returns a HashMap where the key is the entity_id and the value is Vec<EntityPropertyWithDefinition>.
+/// Only returns properties matching the specified property_ids.
+#[tracing::instrument(skip(db))]
+pub async fn get_bulk_entity_properties_values_filtered(
+ db: &Pool<Postgres>,
+ entity_refs: &[EntityReference],
+ property_ids: Vec<Uuid>,
+) -> Result<HashMap<String, Vec<EntityPropertyWithDefinition>>> {
+ if entity_refs.is_empty() || property_ids.is_empty() {
+ // If no property_ids specified, return empty map for each entity
+ let mut result = HashMap::new();
+ for entity_ref in entity_refs {
+ result.insert(entity_ref.entity_id.clone(), Vec::new());
+ }
+ return Ok(result);
+ }
+
+ let entity_ids: Vec<String> = entity_refs.iter().map(|r| r.entity_id.clone()).collect();
+ let entity_types: Vec<EntityType> = entity_refs.iter().map(|r| r.entity_type).collect();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT
+ ep.id as entity_property_id,
+ ep.entity_id,
+ ep.entity_type as "entity_type: EntityType",
+ ep.property_definition_id,
+ ep.values as "values: sqlx::types::JsonValue",
+ ep.created_at as entity_property_created_at,
+ ep.updated_at as entity_property_updated_at,
+ pd.organization_id as definition_organization_id,
+ pd.user_id as definition_user_id,
+ pd.display_name,
+ pd.data_type as "data_type: DataType",
+ pd.is_multi_select,
+ pd.specific_entity_type as "specific_entity_type: Option<EntityType>",
+ pd.created_at as definition_created_at,
+ pd.updated_at as definition_updated_at,
+ pd.is_system as definition_is_system
+ FROM entity_properties ep
+ INNER JOIN property_definitions pd ON ep.property_definition_id = pd.id
+ WHERE (ep.entity_id, ep.entity_type) IN (
+ SELECT * FROM UNNEST($1::TEXT[], $2::property_entity_type[])
+ )
+ AND pd.id = ANY($3::UUID[])
+ "#,
+ &entity_ids,
+ &entity_types as &[EntityType],
+ &property_ids
+ )
+ .fetch_all(db)
+ .await?;
+
+ let mut entity_properties_map: HashMap<String, Vec<EntityPropertyWithDefinition>> =
+ HashMap::new();
+
+ for row in rows {
+ let entity_id = row.entity_id.clone();
+ let property_with_definition = row_to_entity_property_with_definition(EntityPropertyRow {
+ entity_property_id: row.entity_property_id,
+ entity_id: row.entity_id,
+ entity_type: row.entity_type,
+ property_definition_id: row.property_definition_id,
+ entity_property_created_at: row.entity_property_created_at,
+ entity_property_updated_at: row.entity_property_updated_at,
+ definition_organization_id: row.definition_organization_id,
+ definition_user_id: row.definition_user_id,
+ display_name: row.display_name,
+ data_type: row.data_type,
+ is_multi_select: row.is_multi_select,
+ specific_entity_type: row.specific_entity_type,
+ definition_created_at: row.definition_created_at,
+ definition_updated_at: row.definition_updated_at,
+ definition_is_system: row.definition_is_system,
+ values: row.values,
+ })?;
+
+ entity_properties_map
+ .entry(entity_id)
+ .or_default()
+ .push(property_with_definition);
+ }
+
+ for properties in entity_properties_map.values_mut() {
+ sort_properties_by_display_name(properties);
+ }
+
+ for properties in entity_properties_map.values_mut() {
+ attach_property_options(db, properties).await?;
+ }
+
+ // Ensure all requested entity_ids are present in the result
+ for entity_ref in entity_refs {
+ entity_properties_map
+ .entry(entity_ref.entity_id.clone())
+ .or_default();
+ }
+
+ Ok(entity_properties_map)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/rust/cloud-storage/properties_service/src/api/internal.rs b/rust/cloud-storage/properties_service/src/api/internal.rs
index 906fb75a26..e5c907483c 100644
--- a/rust/cloud-storage/properties_service/src/api/internal.rs
+++ b/rust/cloud-storage/properties_service/src/api/internal.rs
@@ -14,6 +14,6 @@ pub fn router() -> Router<ApiContext> {
// Bulk operations (POST with body)
.route(
"/properties/entities/bulk",
- axum::routing::post(entities::get_bulk::get_bulk_entity_properties),
+ axum::routing::post(entities::get_bulk::get_bulk_entity_properties_internal),
)
}
diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/get_bulk.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/get_bulk.rs
index 6ff913fcb3..6730d32dcf 100644
--- a/rust/cloud-storage/properties_service/src/api/properties/entities/get_bulk.rs
+++ b/rust/cloud-storage/properties_service/src/api/properties/entities/get_bulk.rs
@@ -1,5 +1,5 @@
use axum::{
- Json,
+ Extension, Json,
extract::State,
http::StatusCode,
response::{IntoResponse, Response},
@@ -11,6 +11,7 @@ use crate::api::{
context::ApiContext,
properties::entities::types::{BulkEntityPropertiesRequest, EntityPropertiesResponse},
};
+use model::user::UserContext;
use properties_db_client::{
entity_properties::get as entity_properties_get, error::PropertiesDatabaseError,
};
@@ -23,6 +24,8 @@ pub enum GetBulkEntityPropertiesErr {
DatabaseError(#[from] PropertiesDatabaseError),
#[error("Entities array cannot be empty")]
InvalidRequest,
+ #[error("Access denied")]
+ Permission(#[from] crate::api::permissions::PermissionError),
}
impl IntoResponse for GetBulkEntityPropertiesErr {
@@ -31,6 +34,7 @@ impl IntoResponse for GetBulkEntityPropertiesErr {
GetBulkEntityPropertiesErr::InternalError(_)
| GetBulkEntityPropertiesErr::DatabaseError(_) => StatusCode::INTERNAL_SERVER_ERROR,
GetBulkEntityPropertiesErr::InvalidRequest => StatusCode::BAD_REQUEST,
+ GetBulkEntityPropertiesErr::Permission(e) => e.status_code(),
};
if status_code.is_server_error() {
@@ -45,23 +49,11 @@ impl IntoResponse for GetBulkEntityPropertiesErr {
}
}
-/// Get properties for multiple entities in bulk
-#[utoipa::path(
- post,
- path = "/internal/properties/entities/bulk",
- request_body = BulkEntityPropertiesRequest,
- responses(
- (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),
- (status = 400, description = "Invalid request body"),
- (status = 500, description = "Internal server error")
- ),
- tag = "Internal"
-)]
-#[tracing::instrument(skip(context, request), fields(entity_count = request.entities.len()), err)]
-pub async fn get_bulk_entity_properties(
- State(context): State<ApiContext>,
- Json(request): Json<BulkEntityPropertiesRequest>,
-) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {
+/// Shared implementation for bulk entity properties retrieval
+async fn get_bulk_entity_properties_impl(
+ context: &ApiContext,
+ request: BulkEntityPropertiesRequest,
+) -> Result<HashMap<String, EntityPropertiesResponse>, GetBulkEntityPropertiesErr> {
if request.entities.is_empty() {
tracing::error!("empty entities array in request");
return Err(GetBulkEntityPropertiesErr::InvalidRequest);
@@ -69,15 +61,26 @@ pub async fn get_bulk_entity_properties(
tracing::info!("retrieving bulk entity properties");
- let bulk_properties =
+ // Use filtered query if property_ids specified, otherwise fetch all.
+ // Note: the public endpoint requires property_ids, but internal callers can
+ // pass an empty vec to fetch all properties for the given entities.
+ let bulk_properties = if request.property_ids.is_empty() {
entity_properties_get::get_bulk_entity_properties_values(&context.db, &request.entities)
.await
- .inspect_err(|e| {
- tracing::error!(
- error = ?e,
- "failed to retrieve bulk entity properties"
- );
- })?;
+ } else {
+ entity_properties_get::get_bulk_entity_properties_values_filtered(
+ &context.db,
+ &request.entities,
+ request.property_ids,
+ )
+ .await
+ }
+ .inspect_err(|e| {
+ tracing::error!(
+ error = ?e,
+ "failed to retrieve bulk entity properties"
+ );
+ })?;
let mut result = HashMap::new();
@@ -95,5 +98,96 @@ pub async fn get_bulk_entity_properties(
"successfully retrieved bulk entity properties"
);
- Ok(Json(result))
+ Ok(result)
+}
+
+/// Get properties for multiple entities in bulk (internal endpoint - service-to-service)
+#[utoipa::path(
+ post,
+ path = "/internal/properties/entities/bulk",
+ request_body = BulkEntityPropertiesRequest,
+ responses(
+ (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),
+ (status = 400, description = "Invalid request body"),
+ (status = 500, description = "Internal server error")
+ ),
+ tag = "Internal"
+)]
+#[tracing::instrument(skip(context, request), fields(entity_count = request.entities.len()), err)]
+pub async fn get_bulk_entity_properties_internal(
+ State(context): State<ApiContext>,
+ Json(request): Json<BulkEntityPropertiesRequest>,
+) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {
+ get_bulk_entity_properties_impl(&context, request)
+ .await
+ .map(Json)
+}
+
+/// Get properties for multiple entities in bulk (public endpoint with user auth)
+///
+/// Only returns properties for entities the user has view permission for.
+/// Entities without permission are silently omitted from the response.
+#[utoipa::path(
+ post,
+ path = "/properties/entities/bulk",
+ request_body = BulkEntityPropertiesRequest,
+ responses(
+ (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),
+ (status = 400, description = "Invalid request body"),
+ (status = 403, description = "Forbidden - User does not have permission"),
+ (status = 500, description = "Internal server error")
+ ),
+ tag = "Properties"
+)]
+#[tracing::instrument(skip(context, request, user_context), fields(user_id = %user_context.user_id, entity_count = request.entities.len()), err)]
+pub async fn get_bulk_entity_properties(
+ State(context): State<ApiContext>,
+ Extension(user_context): Extension<UserContext>,
+ Json(request): Json<BulkEntityPropertiesRequest>,
+) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {
+ // Unlike the internal endpoint, the public endpoint requires explicit property IDs.
+ // An empty property_ids means "no properties requested", so return early with empty result.
+ if request.entities.is_empty() || request.property_ids.is_empty() {
+ return Ok(Json(HashMap::new()));
+ }
+
+ // Filter to only entities the user has permission to view
+ let mut permitted_entities = Vec::with_capacity(request.entities.len());
+ for entity_ref in &request.entities {
+ match crate::api::permissions::check_entity_view_permission(
+ &context,
+ &user_context.user_id,
+ entity_ref,
+ )
+ .await
+ {
+ Ok(()) => permitted_entities.push(entity_ref.clone()),
+ Err(e) => {
+ tracing::debug!(
+ entity_id = %entity_ref.entity_id,
+ entity_type = ?entity_ref.entity_type,
+ error = ?e,
+ "user lacks permission, skipping entity"
+ );
+ }
+ }
+ }
+
+ tracing::info!(
+ permitted = permitted_entities.len(),
+ "filtered entities by permission"
+ );
+
+ if permitted_entities.is_empty() {
+ return Ok(Json(HashMap::new()));
+ }
+
+ let filtered_request = BulkEntityPropertiesRequest {
+ entities: permitted_entities,
+ property_ids: request.property_ids.clone(),
+ };
+
+ get_bulk_entity_properties_impl(&context, filtered_request)
+ .await
+ .map(Json)
}
diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/types.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/types.rs
index 388a780380..07f9dfb2d3 100644
--- a/rust/cloud-storage/properties_service/src/api/properties/entities/types.rs
+++ b/rust/cloud-storage/properties_service/src/api/properties/entities/types.rs
@@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
+use uuid::Uuid;
use models_properties::EntityReference;
use models_properties::api::SetPropertyValue;
@@ -28,4 +29,7 @@ pub struct SetEntityPropertyRequest {
pub struct BulkEntityPropertiesRequest {
/// Array of entity references (entity_id and entity_type pairs)
pub entities: Vec<EntityReference>,
+ /// Optional: only return properties with these definition IDs. If empty, returns all.
+ #[serde(default)]
+ pub property_ids: Vec<Uuid>,
}
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 a3319bbd8d..0913854c7e 100644
--- a/rust/cloud-storage/properties_service/src/api/properties/mod.rs
+++ b/rust/cloud-storage/properties_service/src/api/properties/mod.rs
@@ -1,7 +1,7 @@
use crate::api::context::ApiContext;
use axum::{
Router,
- routing::{delete, get, patch, put},
+ routing::{delete, get, patch, post, put},
};
pub mod definitions;
@@ -43,6 +43,11 @@ pub fn router() -> Router<ApiContext> {
"/entities/:entity_type/:entity_id",
get(entities::get::get_entity_properties),
)
+ // Bulk entity properties - requires authentication
+ .route(
+ "/entities/bulk",
+ post(entities::get_bulk::get_bulk_entity_properties).layer(ensure_user_exists.clone()),
+ )
// PUT/DELETE require authentication
.route(
"/entities/:entity_type/:entity_id/:property_id",
diff --git a/rust/cloud-storage/properties_service/src/api/swagger.rs b/rust/cloud-storage/properties_service/src/api/swagger.rs
index 8699cd7ab6..b0a628ad3c 100644
--- a/rust/cloud-storage/properties_service/src/api/swagger.rs
+++ b/rust/cloud-storage/properties_service/src/api/swagger.rs
@@ -24,6 +24,7 @@ use utoipa::OpenApi;
crate::api::properties::options::delete::delete_property_option,
// Entity properties
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::delete_property::delete_entity_property,
),