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: filters for favorites and reminders (#6301)

dev-rb02abc2cda0a9
diff --git a/.sqlx/query-e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698.json b/.sqlx/query-1fb6bc525a04da74731e360bac2ad36a308adc080ef5ff0683cab3b712ee1f11.json
similarity index 67%
rename from .sqlx/query-e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698.json
rename to .sqlx/query-1fb6bc525a04da74731e360bac2ad36a308adc080ef5ff0683cab3b712ee1f11.json
index ee8c08ba58..e647ef743a 100644
--- a/.sqlx/query-e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698.json
+++ b/.sqlx/query-1fb6bc525a04da74731e360bac2ad36a308adc080ef5ff0683cab3b712ee1f11.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n FROM reminder\n WHERE user_id = $1\n AND ($2::text IS NULL OR entity_type = $2)\n AND ($3::uuid IS NULL OR entity_id = $3)\n AND ($4::bool OR completed_at IS NULL)\n -- Keyset: resume strictly after the cursor position in the same\n -- (next_run_at, created_at, id) order the query returns.\n AND (\n $5::timestamptz IS NULL\n OR (next_run_at, created_at, id) > ($5::timestamptz, $6::timestamptz, $7::uuid)\n )\n ORDER BY next_run_at ASC, created_at ASC, id ASC\n LIMIT $8\n ",
+ "query": "\n SELECT\n id,\n description,\n entity_type,\n entity_id,\n remind_at,\n cron,\n timezone,\n next_run_at,\n enabled,\n completed_at,\n created_at,\n updated_at\n FROM reminder\n WHERE user_id = $1\n -- A standalone reminder has NULL in both columns, and\n -- `NULL = ANY(...)` is NULL rather than true, so a constrained\n -- dimension excludes it.\n AND ($2::text[] IS NULL OR entity_type = ANY($2))\n AND ($3::uuid[] IS NULL OR entity_id = ANY($3))\n AND ($4::bool OR completed_at IS NULL)\n -- Keyset: resume strictly after the cursor position in the same\n -- (next_run_at, created_at, id) order the query returns.\n AND (\n $5::timestamptz IS NULL\n OR (next_run_at, created_at, id) > ($5::timestamptz, $6::timestamptz, $7::uuid)\n )\n ORDER BY next_run_at ASC, created_at ASC, id ASC\n LIMIT $8\n ",
"describe": {
"columns": [
{
@@ -67,8 +67,8 @@
"parameters": {
"Left": [
"Text",
- "Text",
- "Uuid",
+ "TextArray",
+ "UuidArray",
"Bool",
"Timestamptz",
"Timestamptz",
@@ -91,5 +91,5 @@
false
]
},
- "hash": "e4ef4dc39e836e36f9e85606b1af47108c0a71b1d6248543dd6bb015b4207698"
+ "hash": "1fb6bc525a04da74731e360bac2ad36a308adc080ef5ff0683cab3b712ee1f11"
}
diff --git a/.sqlx/query-6f3e5a9da9b4b7707fe669543cca05cee88e530856bb0e1c8512c973b8bc9574.json b/.sqlx/query-27842b5a110508929ca65447af264f8d76a23b6008d0b1e46929221c21c708b8.json
similarity index 80%
rename from .sqlx/query-6f3e5a9da9b4b7707fe669543cca05cee88e530856bb0e1c8512c973b8bc9574.json
rename to .sqlx/query-27842b5a110508929ca65447af264f8d76a23b6008d0b1e46929221c21c708b8.json
index 5cefe36f50..d3758d1fa2 100644
--- a/.sqlx/query-6f3e5a9da9b4b7707fe669543cca05cee88e530856bb0e1c8512c973b8bc9574.json
+++ b/.sqlx/query-27842b5a110508929ca65447af264f8d76a23b6008d0b1e46929221c21c708b8.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n f.entity_type as \"entity_type!\",\n f.entity_id as \"entity_id!\",\n f.sort_order as \"sort_order!\",\n f.created_at as \"created_at!\",\n d.\"fileType\" as \"file_type?\",\n dt.sub_type::text as \"document_sub_type?\",\n ch.channel_type::text as \"channel_type?\",\n cm.channel_id::text as \"channel_id?\"\n FROM favorite f\n -- The comms tables key on uuid while favorite.entity_id is text.\n -- Compare in uuid (casting the favorite side) so their\n -- primary-key indexes are usable; casting the table side to text\n -- forced a full scan of each table on every listing. The regex\n -- guard keeps non-uuid entity_ids from failing the cast: they\n -- yield NULL and simply don't hydrate.\n CROSS JOIN LATERAL (\n SELECT CASE\n WHEN f.entity_id ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN f.entity_id::uuid\n END AS entity_uuid\n ) fid\n LEFT JOIN \"Document\" d ON f.entity_type = 'document' AND d.id = f.entity_id\n LEFT JOIN document_sub_type dt ON f.entity_type = 'document' AND dt.document_id = f.entity_id\n LEFT JOIN \"Chat\" c ON f.entity_type = 'chat' AND c.id = f.entity_id\n LEFT JOIN \"Project\" p ON f.entity_type = 'project' AND p.id = f.entity_id\n LEFT JOIN comms_channels ch ON f.entity_type = 'channel' AND ch.id = fid.entity_uuid\n LEFT JOIN comms_messages cm ON f.entity_type = 'channel_message' AND cm.id = fid.entity_uuid\n WHERE f.user_id = $1\n AND (f.entity_type <> 'document' OR (d.id IS NOT NULL AND d.\"deletedAt\" IS NULL))\n AND (f.entity_type <> 'chat' OR (c.id IS NOT NULL AND c.\"deletedAt\" IS NULL))\n AND (f.entity_type <> 'project' OR (p.id IS NOT NULL AND p.\"deletedAt\" IS NULL))\n ORDER BY f.sort_order ASC, f.created_at ASC\n ",
+ "query": "\n SELECT\n f.entity_type as \"entity_type!\",\n f.entity_id as \"entity_id!\",\n f.sort_order as \"sort_order!\",\n f.created_at as \"created_at!\",\n d.\"fileType\" as \"file_type?\",\n dt.sub_type::text as \"document_sub_type?\",\n ch.channel_type::text as \"channel_type?\",\n cm.channel_id::text as \"channel_id?\"\n FROM favorite f\n -- The comms tables key on uuid while favorite.entity_id is text.\n -- Compare in uuid (casting the favorite side) so their\n -- primary-key indexes are usable; casting the table side to text\n -- forced a full scan of each table on every listing. The regex\n -- guard keeps non-uuid entity_ids from failing the cast: they\n -- yield NULL and simply don't hydrate.\n CROSS JOIN LATERAL (\n SELECT CASE\n WHEN f.entity_id ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN f.entity_id::uuid\n END AS entity_uuid\n ) fid\n LEFT JOIN \"Document\" d ON f.entity_type = 'document' AND d.id = f.entity_id\n LEFT JOIN document_sub_type dt ON f.entity_type = 'document' AND dt.document_id = f.entity_id\n LEFT JOIN \"Chat\" c ON f.entity_type = 'chat' AND c.id = f.entity_id\n LEFT JOIN \"Project\" p ON f.entity_type = 'project' AND p.id = f.entity_id\n LEFT JOIN comms_channels ch ON f.entity_type = 'channel' AND ch.id = fid.entity_uuid\n LEFT JOIN comms_messages cm ON f.entity_type = 'channel_message' AND cm.id = fid.entity_uuid\n WHERE f.user_id = $1\n AND ($2::text[] IS NULL OR f.entity_type = ANY($2))\n AND ($3::text[] IS NULL OR f.entity_id = ANY($3))\n AND (f.entity_type <> 'document' OR (d.id IS NOT NULL AND d.\"deletedAt\" IS NULL))\n AND (f.entity_type <> 'chat' OR (c.id IS NOT NULL AND c.\"deletedAt\" IS NULL))\n AND (f.entity_type <> 'project' OR (p.id IS NOT NULL AND p.\"deletedAt\" IS NULL))\n ORDER BY f.sort_order ASC, f.created_at ASC\n ",
"describe": {
"columns": [
{
@@ -46,7 +46,9 @@
],
"parameters": {
"Left": [
- "Text"
+ "Text",
+ "TextArray",
+ "TextArray"
]
},
"nullable": [
@@ -60,5 +62,5 @@
null
]
},
- "hash": "6f3e5a9da9b4b7707fe669543cca05cee88e530856bb0e1c8512c973b8bc9574"
+ "hash": "27842b5a110508929ca65447af264f8d76a23b6008d0b1e46929221c21c708b8"
}
diff --git a/Cargo.lock b/Cargo.lock
index 4b080b53ae..747a1214e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2493,6 +2493,7 @@ dependencies = [
"axum-core",
"bytes",
"cookie",
+ "form_urlencoded",
"futures-util",
"headers",
"http 1.4.0",
@@ -2502,6 +2503,8 @@ dependencies = [
"pin-project-lite",
"rustversion",
"serde_core",
+ "serde_html_form",
+ "serde_path_to_error",
"tower-layer",
"tower-service",
"tracing",
@@ -6472,20 +6475,25 @@ version = "0.1.0"
dependencies = [
"anyhow",
"axum",
+ "axum-extra",
"chrono",
"cowlike",
"entity_access",
+ "http-body-util",
"macro_authorization",
"macro_db_migrator",
"macro_user_id",
"mockall",
"model-entity",
"model-error-response",
+ "model_user",
+ "rootcause",
"serde",
"serde_json",
"sqlx",
"thiserror 2.0.18",
"tokio",
+ "tower 0.5.3",
"tracing",
"utoipa",
"uuid",
@@ -13599,6 +13607,7 @@ dependencies = [
"async-trait",
"aws-sdk-sqs",
"axum",
+ "axum-extra",
"chrono",
"chrono-tz",
"cron",
@@ -14802,6 +14811,19 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "serde_html_form"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2f2d7ff8a2140333718bb329f5c40fc5f0865b84c426183ce14c97d2ab8154f"
+dependencies = [
+ "form_urlencoded",
+ "indexmap 2.14.0",
+ "itoa",
+ "ryu",
+ "serde_core",
+]
+
[[package]]
name = "serde_json"
version = "1.0.150"
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index ae495610af..46e23f7596 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -127,6 +127,7 @@ import type { GroupedSoupGroupPage } from './generated/schemas/groupedSoupGroupP
import type { GroupedSoupInitialPage } from './generated/schemas/groupedSoupInitialPage';
import type { GroupedSoupSort } from './generated/schemas/groupedSoupSort';
import type { Item } from './generated/schemas/item';
+import type { ListFavoritesParams } from './generated/schemas/listFavoritesParams';
import type { ListOccurrencesParams } from './generated/schemas/listOccurrencesParams';
import type { ListRemindersParams } from './generated/schemas/listRemindersParams';
import type { ListTeamOutOfOfficeParams } from './generated/schemas/listTeamOutOfOfficeParams';
@@ -2523,8 +2524,17 @@ export const storageServiceClient = {
},
favorites: {
- async getFavorites() {
- return await dssFetch<FavoritesList>('/favorites');
+ async getFavorites(params?: ListFavoritesParams) {
+ const query = new URLSearchParams();
+ // Each dimension repeats its key once per value; the two combine with AND.
+ params?.entityType?.forEach((entityType) =>
+ query.append('entityType', entityType)
+ );
+ params?.entityId?.forEach((entityId) =>
+ query.append('entityId', entityId)
+ );
+ const qs = query.toString();
+ return await dssFetch<FavoritesList>(`/favorites${qs ? `?${qs}` : ''}`);
},
async addFavorite(params: AddFavoriteRequest) {
return await dssFetch<Favorite>('/favorites', {
@@ -2557,8 +2567,12 @@ export const storageServiceClient = {
},
async listReminders(params?: ListRemindersParams) {
const query = new URLSearchParams();
- if (params?.entityType) query.set('entityType', params.entityType);
- if (params?.entityId) query.set('entityId', params.entityId);
+ params?.entityType?.forEach((entityType) =>
+ query.append('entityType', entityType)
+ );
+ params?.entityId?.forEach((entityId) =>
+ query.append('entityId', entityId)
+ );
if (params?.includeCompleted !== undefined) {
query.set('includeCompleted', String(params.includeCompleted));
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index a599354d25..4d7be2c4ef 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -829,8 +829,10 @@ export * from './latestMessageLatestMessage';
export * from './latestMessageLatestNonThreadMessage';
export * from './leaveCallResponse';
export * from './linkShare';
+export * from './listFavoritesEntityTypeItem';
+export * from './listFavoritesParams';
export * from './listOccurrencesParams';
-export * from './listRemindersEntityType';
+export * from './listRemindersEntityTypeItem';
export * from './listRemindersParams';
export * from './listTeamOutOfOfficeParams';
export * from './listWebhooksResponse';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityType.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesEntityTypeItem.ts
similarity index 75%
rename from apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityType.ts
rename to apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesEntityTypeItem.ts
index b573629e37..e9a2ab3c45 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesEntityTypeItem.ts
@@ -5,11 +5,14 @@
* OpenAPI spec version: 0.1.0
*/
-export type ListRemindersEntityType =
- (typeof ListRemindersEntityType)[keyof typeof ListRemindersEntityType];
+/**
+ * The type of an entity in Macro
+ */
+export type ListFavoritesEntityTypeItem =
+ (typeof ListFavoritesEntityTypeItem)[keyof typeof ListFavoritesEntityTypeItem];
// eslint-disable-next-line @typescript-eslint/no-redeclare
-export const ListRemindersEntityType = {
+export const ListFavoritesEntityTypeItem = {
user: 'user',
chat: 'chat',
channel: 'channel',
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesParams.ts
new file mode 100644
index 0000000000..c8dc13a40f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listFavoritesParams.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ListFavoritesEntityTypeItem } from './listFavoritesEntityTypeItem';
+
+export type ListFavoritesParams = {
+ /**
+ * Restrict to favorites whose entity is one of these types.
+ */
+ entityType?: ListFavoritesEntityTypeItem[];
+ /**
+ * Restrict to favorites whose entity is one of these ids.
+ */
+ entityId?: string[];
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityTypeItem.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityTypeItem.ts
new file mode 100644
index 0000000000..979c6ca2ee
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersEntityTypeItem.ts
@@ -0,0 +1,33 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The type of an entity in Macro
+ */
+export type ListRemindersEntityTypeItem =
+ (typeof ListRemindersEntityTypeItem)[keyof typeof ListRemindersEntityTypeItem];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ListRemindersEntityTypeItem = {
+ user: 'user',
+ chat: 'chat',
+ channel: 'channel',
+ channel_message: 'channel_message',
+ document: 'document',
+ project: 'project',
+ email_thread: 'email_thread',
+ calendar_event: 'calendar_event',
+ team: 'team',
+ call: 'call',
+ foreign_entity: 'foreign_entity',
+ static_file: 'static_file',
+ crm_company: 'crm_company',
+ crm_contact: 'crm_contact',
+ reminder: 'reminder',
+ skill: 'skill',
+ agent_session: 'agent_session',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersParams.ts
index 3a8fe595cc..952f084804 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersParams.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listRemindersParams.ts
@@ -4,17 +4,17 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
-import type { ListRemindersEntityType } from './listRemindersEntityType';
+import type { ListRemindersEntityTypeItem } from './listRemindersEntityTypeItem';
export type ListRemindersParams = {
/**
- * The type of an entity in Macro
+ * Restrict to reminders attached to an entity of these types.
*/
- entityType?: ListRemindersEntityType;
+ entityType?: ListRemindersEntityTypeItem[];
/**
- * Restrict to reminders attached to this entity id. Requires `entityType`.
+ * Restrict to reminders attached to these entity ids.
*/
- entityId?: string;
+ entityId?: string[];
/**
* Include reminders that have already fired.
*/
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 5b60c58085..4702d1b5b6 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -8522,6 +8522,39 @@ export const getEntityPermissionResponse = zod
/**
* @summary List the caller's favorites.
*/
+export const listFavoritesQueryParams = zod.object({
+ entityType: zod
+ .array(
+ zod
+ .enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'calendar_event',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ 'reminder',
+ 'skill',
+ 'agent_session',
+ ])
+ .describe('The type of an entity in Macro')
+ )
+ .optional()
+ .describe('Restrict to favorites whose entity is one of these types.'),
+ entityId: zod
+ .array(zod.string())
+ .optional()
+ .describe('Restrict to favorites whose entity is one of these ids.'),
+});
+
export const listFavoritesResponse = zod
.object({
favorites: zod
@@ -29083,35 +29116,35 @@ export const listRemindersQueryLimitMin = 0;
export const listRemindersQueryParams = zod.object({
entityType: zod
- .enum([
- 'user',
- 'chat',
- 'channel',
- 'channel_message',
- 'document',
- 'project',
- 'email_thread',
- 'calendar_event',
- 'team',
- 'call',
- 'foreign_entity',
- 'static_file',
- 'crm_company',
- 'crm_contact',
- 'reminder',
- 'skill',
- 'agent_session',
- ])
+ .array(
+ zod
+ .enum([
+ 'user',
+ 'chat',
+ 'channel',
+ 'channel_message',
+ 'document',
+ 'project',
+ 'email_thread',
+ 'calendar_event',
+ 'team',
+ 'call',
+ 'foreign_entity',
+ 'static_file',
+ 'crm_company',
+ 'crm_contact',
+ 'reminder',
+ 'skill',
+ 'agent_session',
+ ])
+ .describe('The type of an entity in Macro')
+ )
.optional()
- .describe(
- 'Restrict to reminders attached to this entity type. Requires `entityId`.'
- ),
+ .describe('Restrict to reminders attached to an entity of these types.'),
entityId: zod
- .string()
+ .array(zod.string())
.optional()
- .describe(
- 'Restrict to reminders attached to this entity id. Requires `entityType`.'
- ),
+ .describe('Restrict to reminders attached to these entity ids.'),
includeCompleted: zod
.boolean()
.optional()
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 0a9317c70b..848b07df37 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -8601,6 +8601,56 @@
"tags": ["favorites"],
"summary": "List the caller's favorites.",
"operationId": "list_favorites",
+ "parameters": [
+ {
+ "name": "entityType",
+ "in": "query",
+ "description": "Restrict to favorites whose entity is one of these types.",
+ "required": false,
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "calendar_event",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact",
+ "reminder",
+ "skill",
+ "agent_session"
+ ]
+ }
+ },
+ "style": "form",
+ "explode": true
+ },
+ {
+ "name": "entityId",
+ "in": "query",
+ "description": "Restrict to favorites whose entity is one of these ids.",
+ "required": false,
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "style": "form",
+ "explode": true
+ }
+ ],
"responses": {
"200": {
"description": "",
@@ -11176,40 +11226,50 @@
{
"name": "entityType",
"in": "query",
- "description": "Restrict to reminders attached to this entity type. Requires `entityId`.",
+ "description": "Restrict to reminders attached to an entity of these types.",
"required": false,
"schema": {
- "type": "string",
- "description": "The type of an entity in Macro",
- "enum": [
- "user",
- "chat",
- "channel",
- "channel_message",
- "document",
- "project",
- "email_thread",
- "calendar_event",
- "team",
- "call",
- "foreign_entity",
- "static_file",
- "crm_company",
- "crm_contact",
- "reminder",
- "skill",
- "agent_session"
- ]
- }
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "calendar_event",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact",
+ "reminder",
+ "skill",
+ "agent_session"
+ ]
+ }
+ },
+ "style": "form",
+ "explode": true
},
{
"name": "entityId",
"in": "query",
- "description": "Restrict to reminders attached to this entity id. Requires `entityType`.",
+ "description": "Restrict to reminders attached to these entity ids.",
"required": false,
"schema": {
- "type": "string"
- }
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "style": "form",
+ "explode": true
},
{
"name": "includeCompleted",
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index d533c1b97a..161e48f006 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -47,8 +47,8 @@ pub use graphql_entity_mutation::{
};
pub use graphql_favorite::{
EntityFavoriteEdgeReader, EntityFavoriteLoader, FavoriteMutationRoot, FavoriteQueryReader,
- GraphqlFavorite, NoOpFavoriteMutationService, ReorderFavoritesInput, entity_favorite_loader,
- resolve_favorites,
+ FavoritesFilterInput, GraphqlFavorite, NoOpFavoriteMutationService, ReorderFavoritesInput,
+ entity_favorite_loader, resolve_favorites,
};
pub use graphql_notification::{
EntityNotificationsLoader, GraphqlNotificationUpdateOperation, NoOpNotificationMutationService,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 04dc30aec6..ee988beb09 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -27,8 +27,8 @@ use graphql_email::{
};
use graphql_entity_mutation::EntityMutationRoot;
use graphql_favorite::{
- EntityFavoriteEdgeReader, FavoriteMutationRoot, FavoriteQueryReader, GraphqlFavorite,
- NoOpEntityFavoriteEdgeReader, NoOpFavoriteMutationService, resolve_favorites,
+ EntityFavoriteEdgeReader, FavoriteMutationRoot, FavoriteQueryReader, FavoritesFilterInput,
+ GraphqlFavorite, NoOpEntityFavoriteEdgeReader, NoOpFavoriteMutationService, resolve_favorites,
};
use graphql_notification::{
NoOpNotificationMutationService, NoOpSoupNotificationEdgeReader, NotificationMutationRoot,
@@ -562,9 +562,14 @@ where
async_graphql::ID(self.user_id.to_string())
}
- /// The authenticated user's favorites in manual order.
- async fn favorites(&self, ctx: &Context<'_>) -> async_graphql::Result<Vec<GraphqlFavorite>> {
- resolve_favorites::<FR>(ctx, &self.user_id).await
+ /// The authenticated user's favorites in manual order, optionally
+ /// restricted by entity type and entity id.
+ async fn favorites(
+ &self,
+ ctx: &Context<'_>,
+ filter: Option<FavoritesFilterInput>,
+ ) -> async_graphql::Result<Vec<GraphqlFavorite>> {
+ resolve_favorites::<FR>(ctx, &self.user_id, filter.unwrap_or_default().into_model()).await
}
/// A page of the authenticated user's own activity, newest first.
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 7d6e6548c3..040a30b038 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -15,7 +15,10 @@ fn soup_response_schema_exposes_frontend_fields() {
"threadId: ID!",
"emailLabels: [GraphqlSoupEmailLabel!]!",
"emailLinks: [GraphqlEmailLink!]!",
- "favorites: [GraphqlFavorite!]!",
+ "favorites(filter: FavoritesFilterInput): [GraphqlFavorite!]!",
+ "input FavoritesFilterInput {",
+ "entityTypes: [GraphqlEntityType!]! = []",
+ "entityIds: [ID!]! = []",
"emailThread(input: EmailThreadInput!): GraphqlSoupEmailThread",
"type GraphqlSoupEmailThread implements GraphqlSoupEntity {",
"providerId: String",
diff --git a/crates/favorites/Cargo.toml b/crates/favorites/Cargo.toml
index 787b6c443f..0b46bdc43a 100644
--- a/crates/favorites/Cargo.toml
+++ b/crates/favorites/Cargo.toml
@@ -8,6 +8,7 @@ version = "0.1.0"
default = []
inbound = [
"dep:axum",
+ "dep:axum-extra",
"dep:macro_authorization",
"dep:model-error-response",
"dep:utoipa",
@@ -22,6 +23,9 @@ postgres = ["dep:sqlx", "outbound"]
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
+# `query` brings `axum_extra::extract::Query`, whose deserializer collects
+# repeated query keys into a vector; `axum::extract::Query` keeps only one.
+axum-extra = { workspace = true, optional = true, features = ["query"] }
chrono = { workspace = true, features = ["serde"] }
cowlike = { path = "../cowlike" }
entity_access = { path = "../entity_access", optional = true, default-features = false, features = ["ports"] }
@@ -39,7 +43,11 @@ utoipa = { workspace = true, optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
+http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
+model_user = { path = "../model_user" }
+rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+tower = { workspace = true }
uuid = { workspace = true, features = ["v7"] }
diff --git a/crates/favorites/src/domain/models.rs b/crates/favorites/src/domain/models.rs
index be0d453e31..aa8ce5ec56 100644
--- a/crates/favorites/src/domain/models.rs
+++ b/crates/favorites/src/domain/models.rs
@@ -48,6 +48,27 @@ impl Favorite {
}
}
+/// Which of a user's favorites to list.
+///
+/// The two dimensions are independent. Within one, the values are
+/// alternatives. Between them they are both required, so
+/// `entity_types = [document], entity_ids = [a, b]` matches only documents
+/// `a` and `b`. An empty vector constrains nothing, which is why the default
+/// filter lists the whole collection.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+#[cfg_attr(feature = "inbound", derive(utoipa::IntoParams, Deserialize))]
+#[cfg_attr(feature = "inbound", into_params(parameter_in = Query))]
+pub struct FavoriteFilter {
+ /// Restrict to favorites whose entity is one of these types.
+ #[cfg_attr(feature = "inbound", serde(default, rename = "entityType"))]
+ #[cfg_attr(feature = "inbound", param(inline, style = Form, explode))]
+ pub entity_types: Vec<EntityType>,
+ /// Restrict to favorites whose entity is one of these ids.
+ #[cfg_attr(feature = "inbound", serde(default, rename = "entityId"))]
+ #[cfg_attr(feature = "inbound", param(style = Form, explode))]
+ pub entity_ids: Vec<String>,
+}
+
/// The user's favorites, in manual order.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
diff --git a/crates/favorites/src/domain/mutation_service.rs b/crates/favorites/src/domain/mutation_service.rs
index 9a8a7aec8b..e951ab69e5 100644
--- a/crates/favorites/src/domain/mutation_service.rs
+++ b/crates/favorites/src/domain/mutation_service.rs
@@ -9,7 +9,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use model_entity::{Entity, EntityType};
use crate::domain::{
- models::{Favorite, FavoritesError, FavoritesMutationActor, SetFavoriteResult},
+ models::{Favorite, FavoriteFilter, FavoritesError, FavoritesMutationActor, SetFavoriteResult},
ports::{FavoritesAuthorizer, FavoritesMutationService, FavoritesService},
};
@@ -76,7 +76,9 @@ where
ordered: Vec<Entity<'static>>,
) -> Result<Vec<Favorite>, FavoritesError> {
self.favorites.reorder_favorites(&user_id, &ordered).await?;
- self.favorites.list_favorites(&user_id).await
+ self.favorites
+ .list_favorites(&user_id, &FavoriteFilter::default())
+ .await
}
}
diff --git a/crates/favorites/src/domain/mutation_service/test.rs b/crates/favorites/src/domain/mutation_service/test.rs
index 7d22795154..3206d2c01d 100644
--- a/crates/favorites/src/domain/mutation_service/test.rs
+++ b/crates/favorites/src/domain/mutation_service/test.rs
@@ -13,7 +13,7 @@ enum ServiceCall {
Add(EntityType, String),
Remove(EntityType, String),
Reorder(Vec<(EntityType, String)>),
- List,
+ List(FavoriteFilter),
}
#[derive(Default)]
@@ -55,11 +55,12 @@ impl FavoritesService for FakeFavoritesService {
async fn list_favorites(
&self,
_user_id: &MacroUserIdStr<'_>,
+ filter: &FavoriteFilter,
) -> Result<Vec<Favorite>, FavoritesError> {
self.calls
.lock()
.expect("calls lock poisoned")
- .push(ServiceCall::List);
+ .push(ServiceCall::List(filter.clone()));
Ok(vec![favorite(EntityType::Document, "document-1", 0.0)])
}
@@ -353,7 +354,7 @@ async fn reorder_delegates_and_returns_the_authoritative_collection() {
favorites.calls(),
vec![
ServiceCall::Reorder(vec![(EntityType::Document, "document-1".to_string())]),
- ServiceCall::List,
+ ServiceCall::List(FavoriteFilter::default()),
]
);
}
diff --git a/crates/favorites/src/domain/ports.rs b/crates/favorites/src/domain/ports.rs
index f7f5ae01e2..53ccedefed 100644
--- a/crates/favorites/src/domain/ports.rs
+++ b/crates/favorites/src/domain/ports.rs
@@ -9,7 +9,9 @@ use entity_access::domain::{
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
-use crate::domain::models::{Favorite, FavoritesError, FavoritesMutationActor, SetFavoriteResult};
+use crate::domain::models::{
+ Favorite, FavoriteFilter, FavoritesError, FavoritesMutationActor, SetFavoriteResult,
+};
/// Outbound persistence port for favorites.
pub trait FavoritesRepo: Send + Sync + 'static {
@@ -32,11 +34,13 @@ pub trait FavoritesRepo: Send + Sync + 'static {
user_id: &MacroUserIdStr<'_>,
) -> impl Future<Output = Result<i64, Self::Err>> + Send;
- /// List the user's favorites in manual order, hydrated with display
- /// metadata. Favorites pointing at deleted entities are omitted.
+ /// List the user's favorites matching `filter`, in manual order, hydrated
+ /// with display metadata. Favorites pointing at deleted entities are
+ /// omitted.
fn list_favorites(
&self,
user_id: &MacroUserIdStr<'_>,
+ filter: &FavoriteFilter,
) -> impl Future<Output = Result<Vec<Favorite>, Self::Err>> + Send;
/// Remove the favorite for the given entity from the user's collection.
@@ -142,10 +146,11 @@ pub trait FavoritesService: Send + Sync + 'static {
entity: &Entity<'_>,
) -> impl Future<Output = Result<Favorite, FavoritesError>> + Send;
- /// List the user's favorites in manual order.
+ /// List the user's favorites in manual order, restricted by `filter`.
fn list_favorites(
&self,
user_id: &MacroUserIdStr<'_>,
+ filter: &FavoriteFilter,
) -> impl Future<Output = Result<Vec<Favorite>, FavoritesError>> + Send;
/// Remove the favorite for the given entity from the user's collection.
diff --git a/crates/favorites/src/domain/service.rs b/crates/favorites/src/domain/service.rs
index 90a0515bde..1ce539eb6a 100644
--- a/crates/favorites/src/domain/service.rs
+++ b/crates/favorites/src/domain/service.rs
@@ -9,7 +9,7 @@ use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
-use crate::domain::models::{Favorite, FavoritesError};
+use crate::domain::models::{Favorite, FavoriteFilter, FavoritesError};
use crate::domain::ports::{FavoritesRepo, FavoritesService};
/// Upper bound on favorites per user; keeps reorder payloads and sidebar
@@ -103,10 +103,11 @@ where
async fn list_favorites(
&self,
user_id: &MacroUserIdStr<'_>,
+ filter: &FavoriteFilter,
) -> Result<Vec<Favorite>, FavoritesError> {
Ok(self
.repo
- .list_favorites(user_id)
+ .list_favorites(user_id, filter)
.await
.map_err(anyhow::Error::from)?)
}
diff --git a/crates/favorites/src/domain/service/test.rs b/crates/favorites/src/domain/service/test.rs
index df0dc0620d..3a052de400 100644
--- a/crates/favorites/src/domain/service/test.rs
+++ b/crates/favorites/src/domain/service/test.rs
@@ -7,7 +7,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use model_entity::{Entity, EntityType};
use super::{FavoritesServiceImpl, MAX_FAVORITES_PER_COLLECTION};
-use crate::domain::models::{Favorite, FavoritesError};
+use crate::domain::models::{Favorite, FavoriteFilter, FavoritesError};
use crate::domain::ports::{FavoritesRepo, FavoritesService};
const USER_ID: &str = "macro|[email protected]";
@@ -87,6 +87,7 @@ impl FavoritesRepo for FakeFavoritesRepo {
async fn list_favorites(
&self,
_user_id: &MacroUserIdStr<'_>,
+ _filter: &FavoriteFilter,
) -> Result<Vec<Favorite>, Self::Err> {
Ok(Vec::new())
}
diff --git a/crates/favorites/src/inbound/axum_router.rs b/crates/favorites/src/inbound/axum_router.rs
index b978b3fdc3..37153b45a9 100644
--- a/crates/favorites/src/inbound/axum_router.rs
+++ b/crates/favorites/src/inbound/axum_router.rs
@@ -1,5 +1,8 @@
//! Axum router for favorites endpoints.
+#[cfg(test)]
+mod test;
+
use std::sync::Arc;
use axum::{
@@ -9,6 +12,7 @@ use axum::{
response::IntoResponse,
routing::{delete, get, patch, post},
};
+use axum_extra::extract::Query;
use entity_access::{
domain::{models::ViewAccessLevel, ports::EntityAccessService},
inbound::axum_extractors::EntityBodyAccessLevelExtractor,
@@ -21,7 +25,7 @@ use model_error_response::ErrorResponse;
use serde::Deserialize;
use crate::domain::{
- models::{Favorite, FavoritesError, FavoritesList},
+ models::{Favorite, FavoriteFilter, FavoritesError, FavoritesList},
ports::FavoritesService,
};
@@ -156,6 +160,7 @@ pub struct ReorderFavoritesRequest {
tag = "favorites",
operation_id = "list_favorites",
path = "/favorites",
+ params(FavoriteFilter),
responses(
(status = 200, body = FavoritesList),
(status = 401, body = ErrorResponse),
@@ -166,6 +171,7 @@ pub struct ReorderFavoritesRequest {
pub async fn list_favorites_handler<S, AccessSvc, Auth>(
State(state): State<FavoritesRouterState<S, AccessSvc, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Query(filter): Query<FavoriteFilter>,
) -> Result<Json<FavoritesList>, FavoritesError>
where
S: FavoritesService,
@@ -174,7 +180,7 @@ where
{
let favorites = state
.service
- .list_favorites(&user.authorization.user.macro_user_id)
+ .list_favorites(&user.authorization.user.macro_user_id, &filter)
.await?;
Ok(Json(FavoritesList { favorites }))
}
diff --git a/crates/favorites/src/inbound/axum_router/test.rs b/crates/favorites/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..f5b4982703
--- /dev/null
+++ b/crates/favorites/src/inbound/axum_router/test.rs
@@ -0,0 +1,252 @@
+use std::collections::HashSet;
+use std::sync::{Arc, Mutex};
+
+use axum::http::header;
+use chrono::{TimeZone, Utc};
+use entity_access::domain::ports::NoOpEntityAccessService;
+use http_body_util::BodyExt;
+use macro_authorization::{
+ InternalIdentityClaims, MacroAuthorizationError, MacroAuthorizationService,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use model_user::UserContext;
+use rootcause::Report;
+use tower::ServiceExt;
+
+use super::*;
+
+const USER_ID: &str = "macro|[email protected]";
+const VALID_JWT: &str = "valid";
+
+#[derive(Clone)]
+struct FakeAuthorizationService;
+
+impl MacroAuthorizationService for FakeAuthorizationService {
+ async fn authorize(&self, jwt: &str) -> Result<UserContext, Report<MacroAuthorizationError>> {
+ if jwt != VALID_JWT {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(UserContext {
+ user_id: USER_ID.to_string(),
+ fusion_user_id: "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".to_string(),
+ permissions: None,
+ organization_id: None,
+ })
+ }
+
+ async fn authorize_internal(
+ &self,
+ _provided_key: &str,
+ _claims: InternalIdentityClaims,
+ ) -> Result<Option<UserContext>, Report<MacroAuthorizationError>> {
+ Err(Report::new(MacroAuthorizationError::InvalidCredentials))
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeFavoritesService {
+ filters: Arc<Mutex<Vec<FavoriteFilter>>>,
+}
+
+impl FakeFavoritesService {
+ fn filters(&self) -> Vec<FavoriteFilter> {
+ self.filters.lock().expect("filter log poisoned").clone()
+ }
+}
+
+fn collection() -> Vec<Favorite> {
+ [
+ (EntityType::Document, "doc-1"),
+ (EntityType::Document, "shared-id"),
+ (EntityType::Channel, "shared-id"),
+ ]
+ .into_iter()
+ .enumerate()
+ .map(|(index, (entity_type, entity_id))| Favorite {
+ entity_type,
+ entity_id: entity_id.to_string(),
+ sort_order: index as f64,
+ created_at: Utc.with_ymd_and_hms(2026, 7, 1, 12, 0, 0).unwrap(),
+ file_type: None,
+ document_sub_type: None,
+ channel_type: None,
+ channel_id: None,
+ })
+ .collect()
+}
+
+impl FavoritesService for FakeFavoritesService {
+ async fn add_favorite(
+ &self,
+ _receipt: &entity_access::domain::models::EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<Favorite, FavoritesError> {
+ unimplemented!("the list boundary does not add favorites")
+ }
+
+ async fn add_favorite_with_established_access(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _entity: &Entity<'_>,
+ ) -> Result<Favorite, FavoritesError> {
+ unimplemented!("the list boundary does not add favorites")
+ }
+
+ async fn list_favorites(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ filter: &FavoriteFilter,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ self.filters
+ .lock()
+ .expect("filter log poisoned")
+ .push(filter.clone());
+ Ok(collection()
+ .into_iter()
+ .filter(|favorite| {
+ (filter.entity_types.is_empty()
+ || filter.entity_types.contains(&favorite.entity_type))
+ && (filter.entity_ids.is_empty()
+ || filter.entity_ids.contains(&favorite.entity_id))
+ })
+ .collect())
+ }
+
+ async fn remove_favorite_by_entity(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _entity: &Entity<'_>,
+ ) -> Result<(), FavoritesError> {
+ unimplemented!("the list boundary does not remove favorites")
+ }
+
+ async fn reorder_favorites(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _ordered: &[Entity<'_>],
+ ) -> Result<(), FavoritesError> {
+ unimplemented!("the list boundary does not reorder favorites")
+ }
+
+ async fn favorited_entities(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _entities: &[Entity<'_>],
+ ) -> Result<HashSet<Entity<'static>>, FavoritesError> {
+ unimplemented!("the list boundary does not read favorite edges")
+ }
+}
+
+fn build_router(service: FakeFavoritesService) -> axum::Router {
+ favorites_router(FavoritesRouterState::new(
+ Arc::new(service),
+ Arc::new(NoOpEntityAccessService),
+ macro_authorization::MacroAuthorizationState::new(Arc::new(FakeAuthorizationService)),
+ ))
+}
+
+async fn listed_entity_ids(service: &FakeFavoritesService, uri: &str) -> Vec<String> {
+ let response = build_router(service.clone())
+ .oneshot(
+ axum::http::Request::get(uri)
+ .header(header::AUTHORIZATION, format!("Bearer {VALID_JWT}"))
+ .body(axum::body::Body::empty())
+ .expect("request should build"),
+ )
+ .await
+ .expect("router should respond");
+
+ assert_eq!(response.status(), StatusCode::OK, "for {uri}");
+ let bytes = response
+ .into_body()
+ .collect()
+ .await
+ .expect("body should collect")
+ .to_bytes();
+ let body: serde_json::Value = serde_json::from_slice(&bytes).expect("body should be json");
+ body["favorites"]
+ .as_array()
+ .expect("favorites array")
+ .iter()
+ .map(|favorite| {
+ favorite["entityId"]
+ .as_str()
+ .expect("entityId string")
+ .to_string()
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn an_unfiltered_list_returns_the_whole_collection() {
+ let service = FakeFavoritesService::default();
+
+ assert_eq!(
+ listed_entity_ids(&service, "/").await,
+ vec![
+ "doc-1".to_string(),
+ "shared-id".to_string(),
+ "shared-id".to_string()
+ ]
+ );
+ assert_eq!(service.filters(), vec![FavoriteFilter::default()]);
+}
+
+#[tokio::test]
+async fn repeated_entity_keys_become_both_filter_dimensions() {
+ let service = FakeFavoritesService::default();
+
+ assert_eq!(
+ listed_entity_ids(
+ &service,
+ "/?entityType=document&entityType=channel&entityId=shared-id"
+ )
+ .await,
+ vec!["shared-id".to_string(), "shared-id".to_string()]
+ );
+ assert_eq!(
+ service.filters(),
+ vec![FavoriteFilter {
+ entity_types: vec![EntityType::Document, EntityType::Channel],
+ entity_ids: vec!["shared-id".to_string()],
+ }],
+ "every repeat of a key must survive, not just the last"
+ );
+}
+
+#[tokio::test]
+async fn each_dimension_stands_alone_and_the_two_combine() {
+ let service = FakeFavoritesService::default();
+
+ assert_eq!(
+ listed_entity_ids(&service, "/?entityType=channel").await,
+ vec!["shared-id".to_string()]
+ );
+ assert_eq!(
+ listed_entity_ids(&service, "/?entityId=doc-1").await,
+ vec!["doc-1".to_string()]
+ );
+ assert!(
+ listed_entity_ids(&service, "/?entityType=channel&entityId=doc-1")
+ .await
+ .is_empty(),
+ "the dimensions are combined, so a pair nothing satisfies matches nothing"
+ );
+}
+
+#[tokio::test]
+async fn an_unknown_entity_type_is_rejected_before_the_service() {
+ let service = FakeFavoritesService::default();
+ let response = build_router(service.clone())
+ .oneshot(
+ axum::http::Request::get("/?entityType=chupacabra")
+ .header(header::AUTHORIZATION, format!("Bearer {VALID_JWT}"))
+ .body(axum::body::Body::empty())
+ .expect("request should build"),
+ )
+ .await
+ .expect("router should respond");
+
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);
+ assert!(service.filters().is_empty());
+}
diff --git a/crates/favorites/src/outbound/pg_favorites_repo.rs b/crates/favorites/src/outbound/pg_favorites_repo.rs
index c82bf7ffc8..17805fa345 100644
--- a/crates/favorites/src/outbound/pg_favorites_repo.rs
+++ b/crates/favorites/src/outbound/pg_favorites_repo.rs
@@ -10,7 +10,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use model_entity::{Entity, EntityType};
use sqlx::PgPool;
-use crate::domain::models::Favorite;
+use crate::domain::models::{Favorite, FavoriteFilter};
use crate::domain::ports::FavoritesRepo;
/// Postgres-backed favorites repository.
@@ -121,7 +121,20 @@ impl FavoritesRepo for PgFavoritesRepo {
async fn list_favorites(
&self,
user_id: &MacroUserIdStr<'_>,
+ filter: &FavoriteFilter,
) -> Result<Vec<Favorite>, Self::Err> {
+ // An empty dimension means no constraint, so it binds NULL rather than
+ // an empty array. `= ANY('{}')` would match nothing.
+ let entity_types: Option<Vec<String>> = (!filter.entity_types.is_empty()).then(|| {
+ filter
+ .entity_types
+ .iter()
+ .map(|entity_type| <&str>::from(*entity_type).to_string())
+ .collect()
+ });
+ let entity_ids: Option<&[String]> =
+ (!filter.entity_ids.is_empty()).then_some(&filter.entity_ids);
+
// Resolves display metadata for the favorited entity where possible
// and omits favorites whose target is deleted. Display names are not
// hydrated here: clients resolve them from entity previews.
@@ -157,12 +170,16 @@ impl FavoritesRepo for PgFavoritesRepo {
LEFT JOIN comms_channels ch ON f.entity_type = 'channel' AND ch.id = fid.entity_uuid
LEFT JOIN comms_messages cm ON f.entity_type = 'channel_message' AND cm.id = fid.entity_uuid
WHERE f.user_id = $1
+ AND ($2::text[] IS NULL OR f.entity_type = ANY($2))
+ AND ($3::text[] IS NULL OR f.entity_id = ANY($3))
AND (f.entity_type <> 'document' OR (d.id IS NOT NULL AND d."deletedAt" IS NULL))
AND (f.entity_type <> 'chat' OR (c.id IS NOT NULL AND c."deletedAt" IS NULL))
AND (f.entity_type <> 'project' OR (p.id IS NOT NULL AND p."deletedAt" IS NULL))
ORDER BY f.sort_order ASC, f.created_at ASC
"#,
user_id.as_ref(),
+ entity_types.as_deref(),
+ entity_ids,
)
.fetch_all(&self.pool)
.await?;
diff --git a/crates/favorites/src/outbound/pg_favorites_repo/tests.rs b/crates/favorites/src/outbound/pg_favorites_repo/tests.rs
index 5465cecaee..6adf1513fd 100644
--- a/crates/favorites/src/outbound/pg_favorites_repo/tests.rs
+++ b/crates/favorites/src/outbound/pg_favorites_repo/tests.rs
@@ -6,6 +6,7 @@ use sqlx::PgPool;
use uuid::Uuid;
use super::PgFavoritesRepo;
+use crate::domain::models::FavoriteFilter;
use crate::domain::ports::FavoritesRepo;
const USER_A: &str = "macro|[email protected]";
@@ -145,7 +146,7 @@ async fn list_favorites_skips_deleted(pool: PgPool) {
.expect("email favorite should insert");
let favorites = repo
- .list_favorites(&user(USER_A))
+ .list_favorites(&user(USER_A), &FavoriteFilter::default())
.await
.expect("favorites should list");
assert_eq!(favorites.len(), 2);
@@ -184,7 +185,7 @@ async fn list_favorites_hydrates_uuid_keyed_entities(pool: PgPool) {
.expect("non-uuid channel favorite should insert");
let favorites = repo
- .list_favorites(&user(USER_A))
+ .list_favorites(&user(USER_A), &FavoriteFilter::default())
.await
.expect("favorites should list");
assert_eq!(favorites.len(), 2);
@@ -194,6 +195,156 @@ async fn list_favorites_hydrates_uuid_keyed_entities(pool: PgPool) {
assert_eq!(favorites[1].channel_type, None);
}
+async fn listed(repo: &PgFavoritesRepo, filter: &FavoriteFilter) -> Vec<(EntityType, String)> {
+ repo.list_favorites(&user(USER_A), filter)
+ .await
+ .expect("favorites should list")
+ .into_iter()
+ .map(|favorite| (favorite.entity_type, favorite.entity_id))
+ .collect()
+}
+
+async fn insert_filter_fixture(pool: &PgPool, repo: &PgFavoritesRepo) {
+ insert_user(pool, USER_A).await;
+ insert_document(pool, "doc-1", "Doc 1", USER_A).await;
+ insert_document(pool, "shared-id", "Shared", USER_A).await;
+
+ for entity in [
+ EntityType::Document.with_entity_str("doc-1"),
+ EntityType::Document.with_entity_str("shared-id"),
+ EntityType::Channel.with_entity_str("shared-id"),
+ ] {
+ repo.add_favorite(&user(USER_A), &entity)
+ .await
+ .expect("favorite should insert");
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_favorites_filters_on_each_dimension_and_on_both(pool: PgPool) {
+ let repo = PgFavoritesRepo::new(pool.clone());
+ insert_filter_fixture(&pool, &repo).await;
+
+ assert_eq!(
+ listed(&repo, &FavoriteFilter::default()).await,
+ vec![
+ (EntityType::Document, "doc-1".to_string()),
+ (EntityType::Document, "shared-id".to_string()),
+ (EntityType::Channel, "shared-id".to_string()),
+ ],
+ "empty vectors constrain nothing"
+ );
+
+ assert_eq!(
+ listed(
+ &repo,
+ &FavoriteFilter {
+ entity_types: vec![EntityType::Channel],
+ entity_ids: Vec::new(),
+ }
+ )
+ .await,
+ vec![(EntityType::Channel, "shared-id".to_string())]
+ );
+
+ assert_eq!(
+ listed(
+ &repo,
+ &FavoriteFilter {
+ entity_types: Vec::new(),
+ entity_ids: vec!["shared-id".to_string()],
+ }
+ )
+ .await,
+ vec![
+ (EntityType::Document, "shared-id".to_string()),
+ (EntityType::Channel, "shared-id".to_string()),
+ ]
+ );
+
+ assert_eq!(
+ listed(
+ &repo,
+ &FavoriteFilter {
+ entity_types: vec![EntityType::Channel],
+ entity_ids: vec!["shared-id".to_string()],
+ }
+ )
+ .await,
+ vec![(EntityType::Channel, "shared-id".to_string())],
+ "the two dimensions are combined"
+ );
+
+ assert_eq!(
+ listed(
+ &repo,
+ &FavoriteFilter {
+ entity_types: vec![EntityType::Document, EntityType::Channel],
+ entity_ids: vec!["doc-1".to_string(), "shared-id".to_string()],
+ }
+ )
+ .await,
+ vec![
+ (EntityType::Document, "doc-1".to_string()),
+ (EntityType::Document, "shared-id".to_string()),
+ (EntityType::Channel, "shared-id".to_string()),
+ ],
+ "values within a dimension are alternatives"
+ );
+
+ assert!(
+ listed(
+ &repo,
+ &FavoriteFilter {
+ entity_types: vec![EntityType::Channel],
+ entity_ids: vec!["doc-1".to_string()],
+ }
+ )
+ .await
+ .is_empty(),
+ "a pair nothing satisfies matches nothing"
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_filtered_list_keeps_the_manual_order_and_the_soft_delete_guard(pool: PgPool) {
+ let repo = PgFavoritesRepo::new(pool.clone());
+ insert_filter_fixture(&pool, &repo).await;
+
+ let reordered = [
+ EntityType::Document.with_entity_str("shared-id"),
+ EntityType::Channel.with_entity_str("shared-id"),
+ EntityType::Document.with_entity_str("doc-1"),
+ ];
+ repo.reorder_favorites(&user(USER_A), &reordered)
+ .await
+ .expect("reorder should run");
+
+ let filter = FavoriteFilter {
+ entity_types: vec![EntityType::Document],
+ entity_ids: Vec::new(),
+ };
+ assert_eq!(
+ listed(&repo, &filter).await,
+ vec![
+ (EntityType::Document, "shared-id".to_string()),
+ (EntityType::Document, "doc-1".to_string()),
+ ],
+ "the manual order survives the filter"
+ );
+
+ sqlx::query(r#"UPDATE "Document" SET "deletedAt" = now() WHERE id = 'shared-id'"#)
+ .execute(&pool)
+ .await
+ .expect("document should soft delete");
+
+ assert_eq!(
+ listed(&repo, &filter).await,
+ vec![(EntityType::Document, "doc-1".to_string())],
+ "a filter must not resurrect a favorite whose target is deleted"
+ );
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn remove_favorite_by_entity_scopes_to_user(pool: PgPool) {
insert_user(&pool, USER_A).await;
@@ -217,7 +368,7 @@ async fn remove_favorite_by_entity_scopes_to_user(pool: PgPool) {
// User B's favorite for the same entity is untouched.
let b_favorites = repo
- .list_favorites(&user(USER_B))
+ .list_favorites(&user(USER_B), &FavoriteFilter::default())
.await
.expect("user B favorites should list");
assert_eq!(b_favorites.len(), 1);
@@ -247,7 +398,7 @@ async fn reorder_favorites_sets_manual_order(pool: PgPool) {
.expect("reorder should run");
let favorites = repo
- .list_favorites(&user(USER_A))
+ .list_favorites(&user(USER_A), &FavoriteFilter::default())
.await
.expect("favorites should list");
let listed: Vec<&str> = favorites.iter().map(|f| f.entity_id.as_str()).collect();
diff --git a/crates/graphql_favorite/src/lib.rs b/crates/graphql_favorite/src/lib.rs
index 75e2b41c79..3e790d9b87 100644
--- a/crates/graphql_favorite/src/lib.rs
+++ b/crates/graphql_favorite/src/lib.rs
@@ -19,4 +19,4 @@ pub use loaders::{
};
pub use mutations::{FavoriteMutationRoot, NoOpFavoriteMutationService, ReorderFavoritesInput};
pub use objects::GraphqlFavorite;
-pub use queries::{FavoriteQueryReader, resolve_favorites};
+pub use queries::{FavoriteQueryReader, FavoritesFilterInput, resolve_favorites};
diff --git a/crates/graphql_favorite/src/queries.rs b/crates/graphql_favorite/src/queries.rs
index a195ed9377..6a2af64b64 100644
--- a/crates/graphql_favorite/src/queries.rs
+++ b/crates/graphql_favorite/src/queries.rs
@@ -1,10 +1,11 @@
use std::sync::Arc;
-use async_graphql::Context;
+use async_graphql::{Context, ID, InputObject};
use favorites::domain::{
- models::{Favorite, FavoritesError},
+ models::{Favorite, FavoriteFilter, FavoritesError},
ports::FavoritesService,
};
+use graphql_common::GraphqlEntityType;
use macro_user_id::user_id::MacroUserIdStr;
use crate::{GraphqlFavorite, NoOpEntityFavoriteEdgeReader};
@@ -12,12 +13,42 @@ use crate::{GraphqlFavorite, NoOpEntityFavoriteEdgeReader};
#[cfg(test)]
mod test;
+/// Which of the authenticated user's favorites to return.
+///
+/// The two dimensions are independent. Values of one are alternatives, and
+/// both must hold. An omitted or empty list constrains nothing, so the whole
+/// collection is the default.
+#[derive(Default, InputObject)]
+pub struct FavoritesFilterInput {
+ /// Restrict to favorites of these entity types.
+ #[graphql(default)]
+ pub entity_types: Vec<GraphqlEntityType>,
+ /// Restrict to favorites with these entity ids.
+ #[graphql(default)]
+ pub entity_ids: Vec<ID>,
+}
+
+impl FavoritesFilterInput {
+ /// Convert the transport input into the domain filter.
+ pub fn into_model(self) -> FavoriteFilter {
+ FavoriteFilter {
+ entity_types: self
+ .entity_types
+ .into_iter()
+ .map(GraphqlEntityType::into_model)
+ .collect(),
+ entity_ids: self.entity_ids.into_iter().map(|id| id.0).collect(),
+ }
+ }
+}
+
/// Reader used by GraphQL user-scoped favorites queries.
pub trait FavoriteQueryReader: Send + Sync + 'static {
- /// List a user's favorites in manual order.
+ /// List a user's favorites matching `filter`, in manual order.
fn list_favorites<'a>(
&'a self,
user_id: &'a MacroUserIdStr<'static>,
+ filter: &'a FavoriteFilter,
) -> impl Future<Output = Result<Vec<Favorite>, FavoritesError>> + Send + 'a;
}
@@ -28,8 +59,9 @@ where
async fn list_favorites(
&self,
user_id: &MacroUserIdStr<'static>,
+ filter: &FavoriteFilter,
) -> Result<Vec<Favorite>, FavoritesError> {
- FavoritesService::list_favorites(self.as_ref(), user_id).await
+ FavoritesService::list_favorites(self.as_ref(), user_id, filter).await
}
}
@@ -37,6 +69,7 @@ impl FavoriteQueryReader for NoOpEntityFavoriteEdgeReader {
async fn list_favorites(
&self,
_user_id: &MacroUserIdStr<'static>,
+ _filter: &FavoriteFilter,
) -> Result<Vec<Favorite>, FavoritesError> {
Ok(Vec::new())
}
@@ -47,13 +80,14 @@ impl FavoriteQueryReader for NoOpEntityFavoriteEdgeReader {
pub async fn resolve_favorites<R>(
ctx: &Context<'_>,
user_id: &MacroUserIdStr<'static>,
+ filter: FavoriteFilter,
) -> async_graphql::Result<Vec<GraphqlFavorite>>
where
R: FavoriteQueryReader,
{
let reader = ctx.data::<R>()?;
reader
- .list_favorites(user_id)
+ .list_favorites(user_id, &filter)
.await
.map(|favorites| favorites.into_iter().map(GraphqlFavorite::new).collect())
.map_err(|error| {
diff --git a/crates/graphql_favorite/src/queries/test.rs b/crates/graphql_favorite/src/queries/test.rs
index c977a75de2..c017fe3da2 100644
--- a/crates/graphql_favorite/src/queries/test.rs
+++ b/crates/graphql_favorite/src/queries/test.rs
@@ -8,37 +8,71 @@ use super::*;
const USER_ID: &str = "macro|[email protected]";
+fn all_favorites() -> Vec<Favorite> {
+ [
+ (EntityType::Document, "document-1", 2.5),
+ (EntityType::Document, "document-2", 3.5),
+ (EntityType::Channel, "channel-1", 4.5),
+ ]
+ .into_iter()
+ .map(|(entity_type, entity_id, sort_order)| Favorite {
+ entity_type,
+ entity_id: entity_id.to_string(),
+ sort_order,
+ created_at: Utc.with_ymd_and_hms(2025, 1, 2, 3, 4, 5).unwrap(),
+ file_type: Some("pdf".to_string()),
+ document_sub_type: Some("task".to_string()),
+ channel_type: None,
+ channel_id: None,
+ })
+ .collect()
+}
+
#[derive(Clone, Default)]
struct RecordingReader {
requested_users: Arc<Mutex<Vec<String>>>,
+ requested_filters: Arc<Mutex<Vec<FavoriteFilter>>>,
fail: bool,
}
+impl RecordingReader {
+ fn requested_filters(&self) -> Vec<FavoriteFilter> {
+ self.requested_filters
+ .lock()
+ .expect("requested filters lock poisoned")
+ .clone()
+ }
+}
+
impl FavoriteQueryReader for RecordingReader {
async fn list_favorites(
&self,
user_id: &MacroUserIdStr<'static>,
+ filter: &FavoriteFilter,
) -> Result<Vec<Favorite>, FavoritesError> {
self.requested_users
.lock()
.expect("requested users lock poisoned")
.push(user_id.to_string());
+ self.requested_filters
+ .lock()
+ .expect("requested filters lock poisoned")
+ .push(filter.clone());
if self.fail {
return Err(FavoritesError::BadRequest(
"sensitive favorites detail".to_string(),
));
}
- Ok(vec![Favorite {
- entity_type: EntityType::Document,
- entity_id: "document-1".to_string(),
- sort_order: 2.5,
- created_at: Utc.with_ymd_and_hms(2025, 1, 2, 3, 4, 5).unwrap(),
- file_type: Some("pdf".to_string()),
- document_sub_type: Some("task".to_string()),
- channel_type: None,
- channel_id: None,
- }])
+ Ok(all_favorites()
+ .into_iter()
+ .filter(|favorite| {
+ (filter.entity_types.is_empty()
+ || filter.entity_types.contains(&favorite.entity_type))
+ && (filter.entity_ids.is_empty()
+ || filter.entity_ids.contains(&favorite.entity_id))
+ })
+ .collect())
}
}
@@ -46,9 +80,14 @@ struct QueryRoot;
#[Object]
impl QueryRoot {
- async fn favorites(&self, ctx: &Context<'_>) -> async_graphql::Result<Vec<GraphqlFavorite>> {
+ async fn favorites(
+ &self,
+ ctx: &Context<'_>,
+ filter: Option<FavoritesFilterInput>,
+ ) -> async_graphql::Result<Vec<GraphqlFavorite>> {
let user_id = MacroUserIdStr::parse_from_str(USER_ID).expect("valid user id");
- resolve_favorites::<RecordingReader>(ctx, &user_id).await
+ resolve_favorites::<RecordingReader>(ctx, &user_id, filter.unwrap_or_default().into_model())
+ .await
}
}
@@ -58,6 +97,29 @@ fn schema(reader: RecordingReader) -> Schema<QueryRoot, EmptyMutation, EmptySubs
.finish()
}
+async fn queried_entity_ids(reader: &RecordingReader, query: &str) -> Vec<String> {
+ let response = schema(reader.clone()).execute(query).await;
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let async_graphql::Value::Object(data) = response.data else {
+ panic!("expected an object response");
+ };
+ let async_graphql::Value::List(favorites) = &data["favorites"] else {
+ panic!("expected a favorites list");
+ };
+ favorites
+ .iter()
+ .map(|favorite| {
+ let async_graphql::Value::Object(favorite) = favorite else {
+ panic!("expected a favorite object");
+ };
+ favorite["entityId"]
+ .to_string()
+ .trim_matches('"')
+ .to_string()
+ })
+ .collect()
+}
+
#[tokio::test]
async fn lists_ordered_favorites_for_the_bound_user() {
let reader = RecordingReader::default();
@@ -81,6 +143,26 @@ async fn lists_ordered_favorites_for_the_bound_user() {
"documentSubType": "task",
"channelType": null,
"channelId": null,
+ }, {
+ "id": "document:document-2",
+ "entityType": "DOCUMENT",
+ "entityId": "document-2",
+ "sortOrder": 3.5,
+ "createdAt": "2025-01-02T03:04:05+00:00",
+ "fileType": "pdf",
+ "documentSubType": "task",
+ "channelType": null,
+ "channelId": null,
+ }, {
+ "id": "channel:channel-1",
+ "entityType": "CHANNEL",
+ "entityId": "channel-1",
+ "sortOrder": 4.5,
+ "createdAt": "2025-01-02T03:04:05+00:00",
+ "fileType": "pdf",
+ "documentSubType": "task",
+ "channelType": null,
+ "channelId": null,
}]
})
);
@@ -91,6 +173,86 @@ async fn lists_ordered_favorites_for_the_bound_user() {
.expect("requested users lock poisoned"),
vec![USER_ID.to_string()]
);
+ assert_eq!(reader.requested_filters(), vec![FavoriteFilter::default()]);
+}
+
+#[tokio::test]
+async fn a_type_only_filter_reaches_the_reader_and_narrows_the_result() {
+ let reader = RecordingReader::default();
+ let entity_ids = queried_entity_ids(
+ &reader,
+ "{ favorites(filter: { entityTypes: [CHANNEL] }) { entityId } }",
+ )
+ .await;
+
+ assert_eq!(entity_ids, vec!["channel-1".to_string()]);
+ assert_eq!(
+ reader.requested_filters(),
+ vec![FavoriteFilter {
+ entity_types: vec![EntityType::Channel],
+ entity_ids: Vec::new(),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn an_id_only_filter_reaches_the_reader_and_narrows_the_result() {
+ let reader = RecordingReader::default();
+ let entity_ids = queried_entity_ids(
+ &reader,
+ r#"{ favorites(filter: { entityIds: ["document-2", "channel-1"] }) { entityId } }"#,
+ )
+ .await;
+
+ assert_eq!(
+ entity_ids,
+ vec!["document-2".to_string(), "channel-1".to_string()]
+ );
+ assert_eq!(
+ reader.requested_filters(),
+ vec![FavoriteFilter {
+ entity_types: Vec::new(),
+ entity_ids: vec!["document-2".to_string(), "channel-1".to_string()],
+ }]
+ );
+}
+
+#[tokio::test]
+async fn the_two_filter_dimensions_are_combined() {
+ let reader = RecordingReader::default();
+ let entity_ids = queried_entity_ids(
+ &reader,
+ r#"{ favorites(filter: {
+ entityTypes: [DOCUMENT],
+ entityIds: ["document-2", "channel-1"]
+ }) { entityId } }"#,
+ )
+ .await;
+
+ assert_eq!(entity_ids, vec!["document-2".to_string()]);
+ assert_eq!(
+ reader.requested_filters(),
+ vec![FavoriteFilter {
+ entity_types: vec![EntityType::Document],
+ entity_ids: vec!["document-2".to_string(), "channel-1".to_string()],
+ }]
+ );
+}
+
+#[tokio::test]
+async fn an_empty_filter_input_constrains_nothing() {
+ let reader = RecordingReader::default();
+ let entity_ids = queried_entity_ids(&reader, "{ favorites(filter: {}) { entityId } }").await;
+
+ assert_eq!(
+ entity_ids,
+ vec![
+ "document-1".to_string(),
+ "document-2".to_string(),
+ "channel-1".to_string()
+ ]
+ );
+ assert_eq!(reader.requested_filters(), vec![FavoriteFilter::default()]);
}
#[tokio::test]
@@ -99,7 +261,7 @@ async fn returns_a_safe_error_when_favorites_cannot_be_loaded() {
fail: true,
..Default::default()
})
- .execute("{ favorites { entityId } }")
+ .execute("{ favorites(filter: { entityTypes: [DOCUMENT] }) { entityId } }")
.await;
assert_eq!(response.errors.len(), 1);
diff --git a/crates/reminders/Cargo.toml b/crates/reminders/Cargo.toml
index 7eb64fd4fc..f7c9933fab 100644
--- a/crates/reminders/Cargo.toml
+++ b/crates/reminders/Cargo.toml
@@ -22,6 +22,7 @@ dispatch = ["dep:serde_json", "dep:tokio", "dep:tokio-util", "ports"]
dispatch-sqs = ["dep:aws-sdk-sqs", "dispatch", "outbound"]
inbound = [
"dep:axum",
+ "dep:axum-extra",
"dep:macro_authorization",
"dep:model-error-response",
"dep:utoipa",
@@ -39,6 +40,9 @@ anyhow = { workspace = true, optional = true }
async-trait = { workspace = true, optional = true }
aws-sdk-sqs = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
+# `query` brings `axum_extra::extract::Query`, whose deserializer collects
+# repeated query keys into a vector; `axum::extract::Query` keeps only one.
+axum-extra = { workspace = true, optional = true, features = ["query"] }
chrono = { workspace = true, features = ["serde"] }
chrono-tz = { workspace = true }
cron = { workspace = true }
diff --git a/crates/reminders/src/domain/models.rs b/crates/reminders/src/domain/models.rs
index 654b7b3ee7..ed85b44a93 100644
--- a/crates/reminders/src/domain/models.rs
+++ b/crates/reminders/src/domain/models.rs
@@ -469,8 +469,15 @@ impl ReminderPatch {
/// Which of a user's reminders to list, and where in the ordering to resume.
#[derive(Debug, Clone, Default)]
pub struct ReminderFilter {
- /// Restrict to reminders attached to this entity.
- pub entity: Option<Entity<'static>>,
+ /// Restrict to reminders attached to an entity of one of these types.
+ ///
+ /// Independent of [`ReminderFilter::entity_ids`]. Within a dimension the
+ /// values are alternatives, and the two dimensions are both required. An
+ /// empty vector constrains nothing. A standalone reminder is attached to
+ /// nothing, so constraining either dimension excludes it.
+ pub entity_types: Vec<EntityType>,
+ /// Restrict to reminders attached to one of these entity ids.
+ pub entity_ids: Vec<Uuid>,
/// Include reminders that have already fired.
pub include_completed: bool,
/// Resume after this position in the ordering.
diff --git a/crates/reminders/src/domain/service/test.rs b/crates/reminders/src/domain/service/test.rs
index b88abc67a1..73424e07ed 100644
--- a/crates/reminders/src/domain/service/test.rs
+++ b/crates/reminders/src/domain/service/test.rs
@@ -17,6 +17,8 @@ use crate::domain::models::{
const USER_A: &str = "macro|[email protected]";
const USER_B: &str = "macro|[email protected]";
const DAILY_9AM: &str = "0 0 9 * * *";
+const DOC_1: &str = "11111111-1111-4111-8111-111111111111";
+const DOC_2: &str = "22222222-2222-4222-8222-222222222222";
fn user(id: &str) -> MacroUserIdStr<'_> {
MacroUserIdStr::parse_from_str(id).expect("valid user id")
@@ -257,12 +259,20 @@ impl RemindersRepo for FakeRemindersRepo {
.filter(|(owner, _)| owner == user_id.as_ref())
.map(|(_, reminder)| reminder)
.filter(|reminder| filter.include_completed || reminder.completed_at.is_none())
- .filter(|reminder| match &filter.entity {
- Some(entity) => {
- reminder.entity_type == Some(entity.entity_type)
- && reminder.entity_id.as_deref() == Some(entity.entity_id.as_ref())
- }
- None => true,
+ .filter(|reminder| {
+ filter.entity_types.is_empty()
+ || reminder
+ .entity_type
+ .is_some_and(|entity_type| filter.entity_types.contains(&entity_type))
+ })
+ .filter(|reminder| {
+ filter.entity_ids.is_empty()
+ || reminder.entity_id.as_deref().is_some_and(|entity_id| {
+ filter
+ .entity_ids
+ .iter()
+ .any(|wanted| wanted.to_string() == entity_id)
+ })
})
.collect();
found.sort_by_key(sort_key);
@@ -735,7 +745,7 @@ async fn lists_reminders_filtered_by_entity() {
.create_reminder(
&user(USER_A),
create_request(once(future())),
- Some(doc_receipt("doc-1")),
+ Some(doc_receipt(DOC_1)),
)
.await
.expect("created");
@@ -745,7 +755,8 @@ async fn lists_reminders_filtered_by_entity() {
.expect("created");
let filter = ReminderFilter {
- entity: Some(EntityType::Document.with_entity_string("doc-1".to_string())),
+ entity_types: vec![EntityType::Document],
+ entity_ids: vec![DOC_1.parse().expect("valid uuid")],
..Default::default()
};
let page = service
@@ -754,7 +765,7 @@ async fn lists_reminders_filtered_by_entity() {
.expect("list should succeed");
assert_eq!(page.reminders.len(), 1);
- assert_eq!(page.reminders[0].entity_id.as_deref(), Some("doc-1"));
+ assert_eq!(page.reminders[0].entity_id.as_deref(), Some(DOC_1));
}
#[tokio::test]
@@ -1755,7 +1766,7 @@ async fn pages_within_an_entity_filter() {
.create_reminder(
&user(USER_A),
create_request(once(remind_at)),
- Some(doc_receipt("doc-1")),
+ Some(doc_receipt(DOC_1)),
)
.await
.expect("created");
@@ -1765,14 +1776,14 @@ async fn pages_within_an_entity_filter() {
.create_reminder(
&user(USER_A),
create_request(once(remind_at)),
- Some(doc_receipt("doc-2")),
+ Some(doc_receipt(DOC_2)),
)
.await
.expect("created");
}
let filter = || ReminderFilter {
- entity: Some(EntityType::Document.with_entity_string("doc-1".to_string())),
+ entity_ids: vec![DOC_1.parse().expect("valid uuid")],
limit: Some(2),
..Default::default()
};
@@ -1789,7 +1800,7 @@ async fn pages_within_an_entity_filter() {
for reminder in &page.reminders {
assert_eq!(
reminder.entity_id.as_deref(),
- Some("doc-1"),
+ Some(DOC_1),
"the filter must hold on every page"
);
}
@@ -1801,7 +1812,7 @@ async fn pages_within_an_entity_filter() {
assert!(pages < 10, "paging should terminate");
}
- assert_eq!(seen.len(), 3, "all three doc-1 reminders, and only those");
+ assert_eq!(seen.len(), 3, "all three DOC_1 reminders, and only those");
let unique: std::collections::HashSet<_> = seen.iter().collect();
assert_eq!(unique.len(), 3);
}
diff --git a/crates/reminders/src/inbound/axum_router.rs b/crates/reminders/src/inbound/axum_router.rs
index a22f47e6c0..8de8e70c8d 100644
--- a/crates/reminders/src/inbound/axum_router.rs
+++ b/crates/reminders/src/inbound/axum_router.rs
@@ -12,6 +12,7 @@ use axum::{
response::IntoResponse,
routing::{delete, get, patch, post},
};
+use axum_extra::extract::Query;
use entity_access::domain::{
models::{AccessError, AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel},
ports::EntityAccessService,
@@ -151,15 +152,23 @@ pub struct UpdateReminderRequest {
}
/// Query params for listing reminders.
-#[derive(Debug, Deserialize, utoipa::IntoParams)]
+///
+/// `entityType` and `entityId` both repeat. Values of one key are
+/// alternatives, and the two keys are combined. Either key alone is valid,
+/// leaving the other dimension unconstrained, so the single pair clients send
+/// today keeps its old meaning.
+#[derive(Debug, Default, Deserialize, utoipa::IntoParams)]
#[serde(rename_all = "camelCase")]
#[into_params(parameter_in = Query)]
pub struct ListRemindersParams {
- /// Restrict to reminders attached to this entity type. Requires `entityId`.
- #[param(inline)]
- pub entity_type: Option<EntityType>,
- /// Restrict to reminders attached to this entity id. Requires `entityType`.
- pub entity_id: Option<String>,
+ /// Restrict to reminders attached to an entity of these types.
+ #[param(inline, style = Form, explode)]
+ #[serde(default)]
+ pub entity_type: Vec<EntityType>,
+ /// Restrict to reminders attached to these entity ids.
+ #[param(style = Form, explode)]
+ #[serde(default)]
+ pub entity_id: Vec<String>,
/// Include reminders that have already fired.
#[serde(default)]
pub include_completed: bool,
@@ -178,9 +187,18 @@ pub struct ReminderIdParams {
pub id: Uuid,
}
-/// Pair an optional entity type and id into an entity, rejecting half-supplied
-/// associations and blank ids before they reach the domain. Applies to both
-/// create and list, so a filter can never carry an empty entity id.
+/// Parse filter ids to match the UUID-backed `entity_id` column.
+fn parse_filter_entity_ids(entity_ids: Vec<String>) -> Result<Vec<Uuid>, ReminderError> {
+ entity_ids
+ .iter()
+ .map(|entity_id| {
+ Uuid::parse_str(entity_id.trim())
+ .map_err(|_| ReminderError::BadRequest("entityId must be a uuid".to_string()))
+ })
+ .collect()
+}
+
+/// Pair an optional entity type and id, rejecting half-supplied associations.
fn build_entity(
entity_type: Option<EntityType>,
entity_id: Option<String>,
@@ -258,7 +276,7 @@ async fn mint_entity_receipt<Eas: EntityAccessService>(
pub async fn list_reminders_handler<S, Eas, Auth>(
State(state): State<RemindersRouterState<S, Eas, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
- axum::extract::Query(params): axum::extract::Query<ListRemindersParams>,
+ Query(params): Query<ListRemindersParams>,
) -> Result<Json<RemindersList>, ReminderError>
where
S: RemindersService,
@@ -266,7 +284,8 @@ where
Auth: MacroAuthorizationService,
{
let filter = ReminderFilter {
- entity: build_entity(params.entity_type, params.entity_id)?,
+ entity_types: params.entity_type,
+ entity_ids: parse_filter_entity_ids(params.entity_id)?,
include_completed: params.include_completed,
cursor: params
.cursor
diff --git a/crates/reminders/src/inbound/axum_router/test.rs b/crates/reminders/src/inbound/axum_router/test.rs
index 85dd5e9690..5d90a795b5 100644
--- a/crates/reminders/src/inbound/axum_router/test.rs
+++ b/crates/reminders/src/inbound/axum_router/test.rs
@@ -257,7 +257,8 @@ enum ServiceCall {
has_receipt: bool,
},
List {
- entity: Option<(EntityType, String)>,
+ entity_types: Vec<EntityType>,
+ entity_ids: Vec<Uuid>,
include_completed: bool,
limit: Option<u32>,
cursor: Option<ReminderCursor>,
@@ -313,14 +314,6 @@ fn receipt_id(receipt: &EntityAccessReceipt<OwnerAccessLevel>) -> Uuid {
.expect("the extractor only mints receipts for a parsed uuid")
}
-/// The entity named by a list filter, which is a read filter and so still
-/// carries the entity directly.
-fn entity_pair(entity: &Option<Entity<'static>>) -> Option<(EntityType, String)> {
- entity
- .as_ref()
- .map(|entity| (entity.entity_type, entity.entity_id.to_string()))
-}
-
/// The entity a create request attaches to, which the receipt carries now that
/// `create_reminder` takes a receipt rather than an entity.
fn receipt_entity_pair(
@@ -364,7 +357,8 @@ impl RemindersService for FakeRemindersService {
filter: ReminderFilter,
) -> Result<ReminderPage, ReminderError> {
self.record(ServiceCall::List {
- entity: entity_pair(&filter.entity),
+ entity_types: filter.entity_types.clone(),
+ entity_ids: filter.entity_ids.clone(),
include_completed: filter.include_completed,
limit: filter.limit,
cursor: filter.cursor,
@@ -701,7 +695,8 @@ async fn list_passes_filters_and_paging_through() {
assert_eq!(
service.calls(),
vec![ServiceCall::List {
- entity: Some((EntityType::Document, ACCESSIBLE_DOC.to_string())),
+ entity_types: vec![EntityType::Document],
+ entity_ids: vec![ACCESSIBLE_DOC.parse().expect("valid uuid")],
include_completed: true,
limit: Some(25),
cursor: Some(cursor),
@@ -710,6 +705,110 @@ async fn list_passes_filters_and_paging_through() {
);
}
+#[tokio::test]
+async fn list_collects_repeated_entity_keys_into_both_dimensions() {
+ let service = FakeRemindersService::default();
+ let uri = format!(
+ "/?entityType=document&entityType=channel&entityId={ACCESSIBLE_DOC}&entityId={FORBIDDEN_DOC}"
+ );
+
+ let response = build_router(service.clone(), FakeEntityAccessService::default())
+ .oneshot(
+ authed(axum::http::Request::get(&uri))
+ .body(axum::body::Body::empty())
+ .expect("request should build"),
+ )
+ .await
+ .expect("router should respond");
+
+ assert_eq!(response.status(), StatusCode::OK);
+ assert_eq!(
+ service.calls(),
+ vec![ServiceCall::List {
+ entity_types: vec![EntityType::Document, EntityType::Channel],
+ entity_ids: vec![
+ ACCESSIBLE_DOC.parse().expect("valid uuid"),
+ FORBIDDEN_DOC.parse().expect("valid uuid"),
+ ],
+ include_completed: false,
+ limit: None,
+ cursor: None,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn a_list_filter_with_only_one_dimension_is_accepted() {
+ let service = FakeRemindersService::default();
+ let type_only = build_router(service.clone(), FakeEntityAccessService::default())
+ .oneshot(
+ authed(axum::http::Request::get("/?entityType=document"))
+ .body(axum::body::Body::empty())
+ .expect("request should build"),
+ )
+ .await
+ .expect("router should respond");
+ assert_eq!(type_only.status(), StatusCode::OK);
+
+ let id_only = build_router(service.clone(), FakeEntityAccessService::default())
+ .oneshot(
+ authed(axum::http::Request::get(format!(
+ "/?entityId={ACCESSIBLE_DOC}"
+ )))
+ .body(axum::body::Body::empty())
+ .expect("request should build"),
+ )
+ .await
+ .expect("router should respond");
+ assert_eq!(id_only.status(), StatusCode::OK);
+
+ assert_eq!(
+ service.calls(),
+ vec![
+ ServiceCall::List {
+ entity_types: vec![EntityType::Document],
+ entity_ids: Vec::new(),
+ include_completed: false,
+ limit: None,
+ cursor: None,
+ },
+ ServiceCall::List {
+ entity_types: Vec::new(),
+ entity_ids: vec![ACCESSIBLE_DOC.parse().expect("valid uuid")],
+ include_completed: false,
+ limit: None,
+ cursor: None,
+ },
+ ]
+ );
+}
+
+#[tokio::test]
+async fn a_list_filter_entity_id_that_is_not_a_uuid_is_400() {
+ for query in ["/?entityId=not-a-uuid", "/?entityId=%20%20"] {
+ let service = FakeRemindersService::default();
+ let response = build_router(service.clone(), FakeEntityAccessService::default())
+ .oneshot(
+ authed(axum::http::Request::get(query))
+ .body(axum::body::Body::empty())
+ .expect("request should build"),
+ )
+ .await
+ .expect("router should respond");
+
+ assert_eq!(
+ response.status(),
+ StatusCode::BAD_REQUEST,
+ "expected 400 for {query}"
+ );
+ assert_eq!(
+ read_json(response).await["message"],
+ "entityId must be a uuid"
+ );
+ assert!(service.calls().is_empty());
+ }
+}
+
#[tokio::test]
async fn list_surfaces_the_next_cursor() {
let cursor = ReminderCursor {
@@ -751,22 +850,6 @@ async fn a_malformed_cursor_is_400() {
assert!(service.calls().is_empty());
}
-#[tokio::test]
-async fn a_list_filter_with_only_an_entity_type_is_400() {
- let service = FakeRemindersService::default();
- let response = build_router(service.clone(), FakeEntityAccessService::default())
- .oneshot(
- authed(axum::http::Request::get("/?entityType=document"))
- .body(axum::body::Body::empty())
- .expect("request should build"),
- )
- .await
- .expect("router should respond");
-
- assert_eq!(response.status(), StatusCode::BAD_REQUEST);
- assert!(service.calls().is_empty());
-}
-
#[tokio::test]
async fn get_returns_the_reminder() {
let service = FakeRemindersService::default();
@@ -1010,7 +1093,8 @@ async fn an_oversized_limit_clamps_instead_of_failing_to_parse() {
assert_eq!(
service.calls(),
vec![ServiceCall::List {
- entity: None,
+ entity_types: Vec::new(),
+ entity_ids: Vec::new(),
include_completed: false,
limit: Some(999_999),
cursor: None,
diff --git a/crates/reminders/src/outbound/pg_reminders_repo.rs b/crates/reminders/src/outbound/pg_reminders_repo.rs
index 515eff1f0c..badf87942f 100644
--- a/crates/reminders/src/outbound/pg_reminders_repo.rs
+++ b/crates/reminders/src/outbound/pg_reminders_repo.rs
@@ -324,11 +324,17 @@ impl RemindersRepo for PgRemindersRepo {
filter: &ReminderFilter,
limit: i64,
) -> Result<ReminderBatch, Self::Err> {
- let entity_type: Option<&str> = filter
- .entity
- .as_ref()
- .map(|entity| entity.entity_type.into());
- let entity_id = entity_uuid(filter.entity.as_ref())?;
+ // An empty dimension means no constraint, so it binds NULL rather than
+ // an empty array. `= ANY('{}')` would match nothing.
+ let entity_types: Option<Vec<String>> = (!filter.entity_types.is_empty()).then(|| {
+ filter
+ .entity_types
+ .iter()
+ .map(|entity_type| <&str>::from(*entity_type).to_string())
+ .collect()
+ });
+ let entity_ids: Option<&[Uuid]> =
+ (!filter.entity_ids.is_empty()).then_some(&filter.entity_ids);
let (cursor_next_run_at, cursor_created_at, cursor_id) = match filter.cursor {
Some(cursor) => (
Some(cursor.next_run_at),
@@ -356,8 +362,11 @@ impl RemindersRepo for PgRemindersRepo {
updated_at
FROM reminder
WHERE user_id = $1
- AND ($2::text IS NULL OR entity_type = $2)
- AND ($3::uuid IS NULL OR entity_id = $3)
+ -- A standalone reminder has NULL in both columns, and
+ -- `NULL = ANY(...)` is NULL rather than true, so a constrained
+ -- dimension excludes it.
+ AND ($2::text[] IS NULL OR entity_type = ANY($2))
+ AND ($3::uuid[] IS NULL OR entity_id = ANY($3))
AND ($4::bool OR completed_at IS NULL)
-- Keyset: resume strictly after the cursor position in the same
-- (next_run_at, created_at, id) order the query returns.
@@ -369,8 +378,8 @@ impl RemindersRepo for PgRemindersRepo {
LIMIT $8
"#,
user_id.as_ref(),
- entity_type,
- entity_id,
+ entity_types.as_deref(),
+ entity_ids,
filter.include_completed,
cursor_next_run_at,
cursor_created_at,
diff --git a/crates/reminders/src/outbound/pg_reminders_repo/test.rs b/crates/reminders/src/outbound/pg_reminders_repo/test.rs
index 15c7876efc..7f149d6844 100644
--- a/crates/reminders/src/outbound/pg_reminders_repo/test.rs
+++ b/crates/reminders/src/outbound/pg_reminders_repo/test.rs
@@ -186,43 +186,231 @@ async fn list_returns_only_the_owners_reminders_soonest_first(pool: PgPool) {
assert_eq!(batch.reminders[1].description, "later");
}
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn list_filters_by_entity(pool: PgPool) {
- insert_user(&pool, USER_A).await;
- let repo = PgRemindersRepo::new(pool);
-
- let attached = NewReminder {
- entity: Some(EntityType::Document.with_entity_string(DOC_1.to_string())),
- ..new_reminder("on doc-1", once_at(at(2026, 8, 1, 14)))
- };
- let other = NewReminder {
- entity: Some(EntityType::Document.with_entity_string(DOC_2.to_string())),
- ..new_reminder("on doc-2", once_at(at(2026, 8, 1, 14)))
- };
- repo.create_reminder(&user(USER_A), &attached)
+async fn seed_filterable_reminders(pool: &PgPool) -> PgRemindersRepo {
+ insert_user(pool, USER_A).await;
+ let repo = PgRemindersRepo::new(pool.clone());
+ let at_2pm = at(2026, 8, 1, 14);
+
+ for (description, entity) in [
+ (
+ "on doc-1",
+ Some(EntityType::Document.with_entity_string(DOC_1.to_string())),
+ ),
+ (
+ "on doc-2",
+ Some(EntityType::Document.with_entity_string(DOC_2.to_string())),
+ ),
+ (
+ "on channel doc-2",
+ Some(EntityType::Channel.with_entity_string(DOC_2.to_string())),
+ ),
+ ("standalone", None),
+ ] {
+ repo.create_reminder(
+ &user(USER_A),
+ &NewReminder {
+ entity,
+ ..new_reminder(description, once_at(at_2pm))
+ },
+ )
.await
.expect("insert");
- repo.create_reminder(&user(USER_A), &other)
+ }
+ repo
+}
+
+async fn listed_descriptions(repo: &PgRemindersRepo, filter: &ReminderFilter) -> Vec<String> {
+ repo.list_reminders(&user(USER_A), filter, 100)
.await
- .expect("insert");
- repo.create_reminder(
- &user(USER_A),
- &new_reminder("standalone", once_at(at(2026, 8, 1, 14))),
+ .expect("list should succeed")
+ .reminders
+ .into_iter()
+ .map(|reminder| reminder.description)
+ .collect()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_unfiltered_list_includes_standalone_reminders(pool: PgPool) {
+ let repo = seed_filterable_reminders(&pool).await;
+
+ let listed = listed_descriptions(&repo, &ReminderFilter::default()).await;
+ assert_eq!(listed.len(), 4);
+ assert!(listed.contains(&"standalone".to_string()));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_type_only_filter_keeps_every_id_of_those_types(pool: PgPool) {
+ let repo = seed_filterable_reminders(&pool).await;
+
+ let mut listed = listed_descriptions(
+ &repo,
+ &ReminderFilter {
+ entity_types: vec![EntityType::Document],
+ ..Default::default()
+ },
)
- .await
- .expect("insert");
+ .await;
+ listed.sort();
+
+ assert_eq!(listed, vec!["on doc-1".to_string(), "on doc-2".to_string()]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn an_id_only_filter_keeps_every_type_holding_those_ids(pool: PgPool) {
+ let repo = seed_filterable_reminders(&pool).await;
+
+ let mut listed = listed_descriptions(
+ &repo,
+ &ReminderFilter {
+ entity_ids: vec![DOC_2.parse().expect("valid uuid")],
+ ..Default::default()
+ },
+ )
+ .await;
+ listed.sort();
+
+ assert_eq!(
+ listed,
+ vec!["on channel doc-2".to_string(), "on doc-2".to_string()]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn the_two_dimensions_are_combined(pool: PgPool) {
+ let repo = seed_filterable_reminders(&pool).await;
+
+ assert_eq!(
+ listed_descriptions(
+ &repo,
+ &ReminderFilter {
+ entity_types: vec![EntityType::Channel],
+ entity_ids: vec![
+ DOC_1.parse().expect("valid uuid"),
+ DOC_2.parse().expect("valid uuid"),
+ ],
+ ..Default::default()
+ },
+ )
+ .await,
+ vec!["on channel doc-2".to_string()]
+ );
+
+ assert!(
+ listed_descriptions(
+ &repo,
+ &ReminderFilter {
+ entity_types: vec![EntityType::Channel],
+ entity_ids: vec![DOC_1.parse().expect("valid uuid")],
+ ..Default::default()
+ },
+ )
+ .await
+ .is_empty()
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn either_constrained_dimension_excludes_standalone_reminders(pool: PgPool) {
+ let repo = seed_filterable_reminders(&pool).await;
+ for filter in [
+ ReminderFilter {
+ entity_types: vec![EntityType::Document, EntityType::Channel],
+ ..Default::default()
+ },
+ ReminderFilter {
+ entity_ids: vec![
+ DOC_1.parse().expect("valid uuid"),
+ DOC_2.parse().expect("valid uuid"),
+ ],
+ ..Default::default()
+ },
+ ] {
+ let listed = listed_descriptions(&repo, &filter).await;
+ assert!(
+ !listed.contains(&"standalone".to_string()),
+ "standalone leaked through {filter:?}"
+ );
+ assert_eq!(listed.len(), 3);
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn a_filtered_list_still_pages_and_hides_completed(pool: PgPool) {
+ let repo = seed_filterable_reminders(&pool).await;
let filter = ReminderFilter {
- entity: Some(EntityType::Document.with_entity_string(DOC_1.to_string())),
+ entity_ids: vec![
+ DOC_1.parse().expect("valid uuid"),
+ DOC_2.parse().expect("valid uuid"),
+ ],
..Default::default()
};
- let batch = repo
- .list_reminders(&user(USER_A), &filter, 100)
+
+ let first = repo
+ .list_reminders(&user(USER_A), &filter, 2)
.await
.expect("list should succeed");
+ assert_eq!(first.reminders.len(), 2);
+ let second = repo
+ .list_reminders(
+ &user(USER_A),
+ &ReminderFilter {
+ cursor: first.last_examined,
+ ..filter.clone()
+ },
+ 2,
+ )
+ .await
+ .expect("list should succeed");
+ assert_eq!(second.reminders.len(), 1);
+
+ let paged: Vec<String> = first
+ .reminders
+ .iter()
+ .chain(second.reminders.iter())
+ .map(|reminder| reminder.description.clone())
+ .collect();
+ let mut sorted = paged.clone();
+ sorted.sort();
+ assert_eq!(
+ sorted,
+ vec![
+ "on channel doc-2".to_string(),
+ "on doc-1".to_string(),
+ "on doc-2".to_string(),
+ ],
+ "paging within a filter must return each matching reminder exactly once"
+ );
- assert_eq!(batch.reminders.len(), 1);
- assert_eq!(batch.reminders[0].description, "on doc-1");
+ sqlx::query(r#"UPDATE reminder SET completed_at = now() WHERE description = 'on doc-1'"#)
+ .execute(&pool)
+ .await
+ .expect("complete should update");
+
+ let mut hidden = listed_descriptions(&repo, &filter).await;
+ hidden.sort();
+ assert_eq!(
+ hidden,
+ vec!["on channel doc-2".to_string(), "on doc-2".to_string()]
+ );
+
+ let mut shown = listed_descriptions(
+ &repo,
+ &ReminderFilter {
+ include_completed: true,
+ ..filter
+ },
+ )
+ .await;
+ shown.sort();
+ assert_eq!(
+ shown,
+ vec![
+ "on channel doc-2".to_string(),
+ "on doc-1".to_string(),
+ "on doc-2".to_string(),
+ ]
+ );
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.toml
index d2da72630c..a28a1c70dd 100644
--- a/crates/workspace-hack/Cargo.toml
+++ b/crates/workspace-hack/Cargo.toml
@@ -31,7 +31,7 @@ aws-smithy-runtime-api = { version = "1", features = ["client", "http-02x", "htt
aws-smithy-types = { version = "1", default-features = false, features = ["byte-stream-poll-next", "http-body-0-4-x", "http-body-1-x", "rt-tokio", "test-util"] }
aws_lambda_events = { version = "0.16", default-features = false, features = ["eventbridge", "s3", "sns", "sqs"] }
axum = { version = "0.8", features = ["macros", "multipart", "ws"] }
-axum-extra = { version = "0.10", features = ["cookie", "typed-header"] }
+axum-extra = { version = "0.10", features = ["cookie", "query", "typed-header"] }
base64 = { version = "0.22" }
bstr = { version = "1" }
byteorder = { version = "1" }
@@ -163,7 +163,7 @@ aws-smithy-runtime-api = { version = "1", features = ["client", "http-02x", "htt
aws-smithy-types = { version = "1", default-features = false, features = ["byte-stream-poll-next", "http-body-0-4-x", "http-body-1-x", "rt-tokio", "test-util"] }
aws_lambda_events = { version = "0.16", default-features = false, features = ["eventbridge", "s3", "sns", "sqs"] }
axum = { version = "0.8", features = ["macros", "multipart", "ws"] }
-axum-extra = { version = "0.10", features = ["cookie", "typed-header"] }
+axum-extra = { version = "0.10", features = ["cookie", "query", "typed-header"] }
base64 = { version = "0.22" }
bstr = { version = "1" }
byteorder = { version = "1" }
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index a34b2619f0..7c70d6614a 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -13179,7 +13179,16 @@ export type GetEntityPermissionResponse = GetEntityPermissionResponses[keyof Get
export type ListFavoritesData = {
body?: never;
path?: never;
- query?: never;
+ query?: {
+ /**
+ * Restrict to favorites whose entity is one of these types.
+ */
+ entityType?: Array<'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session'>;
+ /**
+ * Restrict to favorites whose entity is one of these ids.
+ */
+ entityId?: Array<string>;
+ };
url: '/favorites';
};
@@ -14302,13 +14311,13 @@ export type ListRemindersData = {
path?: never;
query?: {
/**
- * The type of an entity in Macro
+ * Restrict to reminders attached to an entity of these types.
*/
- entityType?: 'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session';
+ entityType?: Array<'user' | 'chat' | 'channel' | 'channel_message' | 'document' | 'project' | 'email_thread' | 'calendar_event' | 'team' | 'call' | 'foreign_entity' | 'static_file' | 'crm_company' | 'crm_contact' | 'reminder' | 'skill' | 'agent_session'>;
/**
- * Restrict to reminders attached to this entity id. Requires `entityType`.
+ * Restrict to reminders attached to these entity ids.
*/
- entityId?: string;
+ entityId?: Array<string>;
/**
* Include reminders that have already fired.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 0a9317c70b..848b07df37 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -8601,6 +8601,56 @@
"tags": ["favorites"],
"summary": "List the caller's favorites.",
"operationId": "list_favorites",
+ "parameters": [
+ {
+ "name": "entityType",
+ "in": "query",
+ "description": "Restrict to favorites whose entity is one of these types.",
+ "required": false,
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "calendar_event",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact",
+ "reminder",
+ "skill",
+ "agent_session"
+ ]
+ }
+ },
+ "style": "form",
+ "explode": true
+ },
+ {
+ "name": "entityId",
+ "in": "query",
+ "description": "Restrict to favorites whose entity is one of these ids.",
+ "required": false,
+ "schema": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "style": "form",
+ "explode": true
+ }
+ ],
"responses": {
"200": {
"description": "",
@@ -11176,40 +11226,50 @@
{
"name": "entityType",
"in": "query",
- "description": "Restrict to reminders attached to this entity type. Requires `entityId`.",
+ "description": "Restrict to reminders attached to an entity of these types.",
"required": false,
"schema": {
- "type": "string",
- "description": "The type of an entity in Macro",
- "enum": [
- "user",
- "chat",
- "channel",
- "channel_message",
- "document",
- "project",
- "email_thread",
- "calendar_event",
- "team",
- "call",
- "foreign_entity",
- "static_file",
- "crm_company",
- "crm_contact",
- "reminder",
- "skill",
- "agent_session"
- ]
- }
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "The type of an entity in Macro",
+ "enum": [
+ "user",
+ "chat",
+ "channel",
+ "channel_message",
+ "document",
+ "project",
+ "email_thread",
+ "calendar_event",
+ "team",
+ "call",
+ "foreign_entity",
+ "static_file",
+ "crm_company",
+ "crm_contact",
+ "reminder",
+ "skill",
+ "agent_session"
+ ]
+ }
+ },
+ "style": "form",
+ "explode": true
},
{
"name": "entityId",
"in": "query",
- "description": "Restrict to reminders attached to this entity id. Requires `entityType`.",
+ "description": "Restrict to reminders attached to these entity ids.",
"required": false,
"schema": {
- "type": "string"
- }
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "style": "form",
+ "explode": true
},
{
"name": "includeCompleted",
diff --git a/packages/sdk/src/entities/favorites/namespace.ts b/packages/sdk/src/entities/favorites/namespace.ts
index 87545eb428..04e2a2f240 100644
--- a/packages/sdk/src/entities/favorites/namespace.ts
+++ b/packages/sdk/src/entities/favorites/namespace.ts
@@ -4,17 +4,37 @@ import type {
} from '../../../generated/storage/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
-import type { FavoritableEntity } from '../entity';
+import type { FavoritableEntity, MacroEntityType } from '../entity';
export type { Favorite, FavoriteEntityRef };
+/**
+ * Which favorites to list.
+ *
+ * The two dimensions are independent. Within one, the values are alternatives;
+ * between them they are both required, so `entityTypes: ['document']` with
+ * `entityIds: [a, b]` matches only documents `a` and `b`. An omitted or empty
+ * list constrains nothing, which is why the default lists the whole collection.
+ */
+export type FavoritesFilter = {
+ entityTypes?: MacroEntityType[];
+ entityIds?: string[];
+};
+
/** The user's favorites: a manually ordered collection of entity references. */
export class FavoritesNamespace {
constructor(private readonly client: MacroClient) {}
/** The user's favorites, in manual order. */
- async list(): Promise<Favorite[]> {
- const { favorites } = unwrap(await this.client.storage.listFavorites({}));
+ async list(filter: FavoritesFilter = {}): Promise<Favorite[]> {
+ const { favorites } = unwrap(
+ await this.client.storage.listFavorites({
+ query: {
+ entityType: filter.entityTypes,
+ entityId: filter.entityIds,
+ },
+ }),
+ );
return favorites;
}
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 40c98bfe95..19f6db63f9 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -228,6 +228,24 @@ input EntitySharePolicyInput {
channelSharePermissions: [ChannelSharePolicyInput!]
}
+"""
+Which of the authenticated user's favorites to return.
+
+The two dimensions are independent. Values of one are alternatives, and
+both must hold. An omitted or empty list constrains nothing, so the whole
+collection is the default.
+"""
+input FavoritesFilterInput {
+ """
+ Restrict to favorites of these entity types.
+ """
+ entityTypes: [GraphqlEntityType!]! = []
+ """
+ Restrict to favorites with these entity ids.
+ """
+ entityIds: [ID!]! = []
+}
+
"""
Item-style permission represented by the viewer's effective access level.
"""
@@ -5536,9 +5554,10 @@ type GraphqlUser {
"""
id: ID!
"""
- The authenticated user's favorites in manual order.
+ The authenticated user's favorites in manual order, optionally
+ restricted by entity type and entity id.
"""
- favorites: [GraphqlFavorite!]!
+ favorites(filter: FavoritesFilterInput): [GraphqlFavorite!]!
"""
A page of the authenticated user's own activity, newest first.
Delegated actions performed on the user's behalf are included.