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.

properties literal (#1966)

Will Hutchinson22a3a7629653
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
index e4510f8119..9cfd6d353f 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
@@ -9,6 +9,7 @@ import type { ChatFilters } from './chatFilters';
import type { DocumentFilters } from './documentFilters';
import type { EmailFilters } from './emailFilters';
import type { ProjectFilters } from './projectFilters';
+import type { PropertyFilter } from './propertyFilter';
/**
* a bundle of all of the filters for each entity type
@@ -24,4 +25,6 @@ export interface EntityFilters {
email_filters?: EmailFilters;
/** the bundled [ProjectFilters] */
project_filters?: ProjectFilters;
+ /** property-based filters applied across entity types */
+ property_filters?: PropertyFilter[];
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 6816a8a380..1c30aad776 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -442,6 +442,8 @@ export * from './projectType';
export * from './projectUpdatedAt';
export * from './propertyDefinition';
export * from './propertyDefinitionSpecificEntityType';
+export * from './propertyFilter';
+export * from './propertyFilterEntityType';
export * from './propertyInput';
export * from './propertyOwner';
export * from './propertyOwnerOneOf';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/propertyFilter.ts b/js/app/packages/service-clients/service-storage/generated/schemas/propertyFilter.ts
new file mode 100644
index 0000000000..b615773d14
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/propertyFilter.ts
@@ -0,0 +1,27 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PropertyFilterEntityType } from './propertyFilterEntityType';
+
+/**
+ * A single property-based filter condition.
+
+Each filter targets a specific property definition on entities of a given type,
+matching against select option UUIDs or entity reference IDs.
+Multiple values within a single filter are OR'd together.
+Multiple filters are AND'd together.
+ */
+export interface PropertyFilter {
+ /** Entity reference IDs to match. Multiple values are OR'd together. */
+ entity_ids?: string[];
+ /** The entity type for the property lookup (e.g., "TASK", "DOCUMENT", "PROJECT").
+When None, matches across all entity types. */
+ entity_type?: PropertyFilterEntityType;
+ /** Select option UUIDs to match. Multiple values are OR'd together. */
+ option_ids?: string[];
+ /** The UUID of the property definition to filter on. */
+ property_definition_id: string;
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/propertyFilterEntityType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/propertyFilterEntityType.ts
new file mode 100644
index 0000000000..6bdee6580a
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/propertyFilterEntityType.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The entity type for the property lookup (e.g., "TASK", "DOCUMENT", "PROJECT").
+When None, matches across all entity types.
+ */
+export type PropertyFilterEntityType = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index a42a7c04f7..7a3405c61b 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -4367,6 +4367,38 @@ export const postItemsSoupBody = zod
.describe(
'The project filters used to filter down what projects you search over.'
),
+ property_filters: zod
+ .array(
+ zod
+ .object({
+ entity_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "Entity reference IDs to match. Multiple values are OR'd together."
+ ),
+ entity_type: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The entity type for the property lookup (e.g., \"TASK\", \"DOCUMENT\", \"PROJECT\").\nWhen None, matches across all entity types.'
+ ),
+ option_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ "Select option UUIDs to match. Multiple values are OR'd together."
+ ),
+ property_definition_id: zod
+ .string()
+ .describe('The UUID of the property definition to filter on.'),
+ })
+ .describe(
+ "A single property-based filter condition.\n\nEach filter targets a specific property definition on entities of a given type,\nmatching against select option UUIDs or entity reference IDs.\nMultiple values within a single filter are OR'd together.\nMultiple filters are AND'd together."
+ )
+ )
+ .optional()
+ .describe('property-based filters applied across entity types'),
})
.describe('a bundle of all of the filters for each entity type')
.and(
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 3d3612a0b0..d2e88c78a3 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6974,6 +6974,13 @@
"project_filters": {
"$ref": "#/components/schemas/ProjectFilters",
"description": "the bundled [ProjectFilters]"
+ },
+ "property_filters": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PropertyFilter"
+ },
+ "description": "property-based filters applied across entity types"
}
}
},
@@ -9086,6 +9093,35 @@
}
}
},
+ "PropertyFilter": {
+ "type": "object",
+ "description": "A single property-based filter condition.\n\nEach filter targets a specific property definition on entities of a given type,\nmatching against select option UUIDs or entity reference IDs.\nMultiple values within a single filter are OR'd together.\nMultiple filters are AND'd together.",
+ "required": ["property_definition_id"],
+ "properties": {
+ "entity_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Entity reference IDs to match. Multiple values are OR'd together."
+ },
+ "entity_type": {
+ "type": ["string", "null"],
+ "description": "The entity type for the property lookup (e.g., \"TASK\", \"DOCUMENT\", \"PROJECT\").\nWhen None, matches across all entity types."
+ },
+ "option_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Select option UUIDs to match. Multiple values are OR'd together."
+ },
+ "property_definition_id": {
+ "type": "string",
+ "description": "The UUID of the property definition to filter on."
+ }
+ }
+ },
"PropertyInput": {
"type": "object",
"description": "Property input for setting a property value on a task.",
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index a41032d028..3ed3e0984b 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -3,11 +3,13 @@
use crate::{
ChannelFilters, ChatFilters, DocumentFilters, EmailFilters, EntityFilters, ProjectFilters,
+ PropertyFilter,
ast::{
channel::{ChannelLiteral, ChannelTypeFilter},
chat::{ChatLiteral, ChatRole},
email::EmailLiteral,
project::ProjectLiteral,
+ properties::PropertiesLiteral,
},
};
use document::DocumentLiteral;
@@ -27,6 +29,8 @@ pub mod document;
pub mod email;
/// contains the ast literal value for projects
pub mod project;
+/// contains the ast literal value for property-based filtering
+pub mod properties;
#[cfg(test)]
mod tests;
@@ -82,6 +86,9 @@ pub struct EntityFilterAst {
/// the filters taht should be applied to the channel entity
#[serde(default, rename = "chanf")]
pub channel_filter: LiteralTree<ChannelLiteral>,
+ /// the filters that should be applied based on entity properties
+ #[serde(default, rename = "propf")]
+ pub properties_filter: LiteralTree<PropertiesLiteral>,
}
impl EntityFilterAst {
@@ -99,6 +106,8 @@ impl EntityFilterAst {
email_filter: EmailFilters::expand_ast(entity_filter.email_filters)?.map(Arc::new),
channel_filter: ChannelFilters::expand_ast(entity_filter.channel_filters)?
.map(Arc::new),
+ properties_filter: Vec::<PropertyFilter>::expand_ast(entity_filter.property_filters)?
+ .map(Arc::new),
}))
}
@@ -111,6 +120,7 @@ impl EntityFilterAst {
chat_filter: None,
email_filter: None,
channel_filter: None,
+ properties_filter: None,
}
}
}
@@ -123,11 +133,13 @@ impl IsEmpty for EntityFilterAst {
chat_filter,
email_filter,
channel_filter,
+ properties_filter,
} = self;
document_filter.is_none()
&& project_filter.is_none()
&& chat_filter.is_none()
&& email_filter.is_none()
&& channel_filter.is_none()
+ && properties_filter.is_none()
}
}
diff --git a/rust/cloud-storage/item_filters/src/ast/properties.rs b/rust/cloud-storage/item_filters/src/ast/properties.rs
new file mode 100644
index 0000000000..1340f845f7
--- /dev/null
+++ b/rust/cloud-storage/item_filters/src/ast/properties.rs
@@ -0,0 +1,79 @@
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use crate::PropertyFilter;
+use crate::ast::ExpandErr;
+use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};
+
+/// Describes how to match against a property value in the entity_properties table.
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub enum PropertyMatchValue {
+ /// Match a select option by its UUID. Uses the `?` jsonb operator on `values->'value'`.
+ #[serde(rename = "so")]
+ SelectOption(Uuid),
+ /// Match an entity reference by entity_id. Uses the `@>` jsonb operator on `values->'value'`.
+ #[serde(rename = "er")]
+ EntityRef(String),
+}
+
+/// A single property-based filter condition for the AST.
+///
+/// When converted to SQL, this generates an EXISTS subquery against the
+/// `entity_properties` table, checking that the given property has a matching value.
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct PropertiesLiteral {
+ /// The property definition UUID to filter on.
+ #[serde(rename = "pd")]
+ pub property_definition_id: Uuid,
+ /// The entity type for the property lookup (e.g., "TASK", "DOCUMENT", "PROJECT").
+ /// When None, matches across all entity types.
+ #[serde(default, rename = "et", skip_serializing_if = "Option::is_none")]
+ pub entity_type: Option<String>,
+ /// The value to match against.
+ #[serde(rename = "v")]
+ pub value: PropertyMatchValue,
+}
+
+impl ExpandFrame<PropertiesLiteral> for Vec<PropertyFilter> {
+ type Err = ExpandErr;
+ fn expand_ast(
+ filters: Vec<PropertyFilter>,
+ ) -> Result<Option<Expr<PropertiesLiteral>>, ExpandErr> {
+ let nodes: Vec<Option<Expr<PropertiesLiteral>>> = filters
+ .into_iter()
+ .map(|pf| {
+ let prop_def_id = Uuid::parse_str(&pf.property_definition_id)?;
+
+ let option_nodes = pf
+ .option_ids
+ .iter()
+ .map(|s| Uuid::parse_str(s))
+ .try_expand(
+ |r| {
+ r.map(|uuid| PropertiesLiteral {
+ property_definition_id: prop_def_id,
+ entity_type: pf.entity_type.clone(),
+ value: PropertyMatchValue::SelectOption(uuid),
+ })
+ },
+ Expr::or,
+ )?;
+
+ let entity_ref_nodes = pf.entity_ids.iter().cloned().expand(
+ |id| PropertiesLiteral {
+ property_definition_id: prop_def_id,
+ entity_type: pf.entity_type.clone(),
+ value: PropertyMatchValue::EntityRef(id),
+ },
+ Expr::or,
+ );
+
+ Ok([option_nodes, entity_ref_nodes]
+ .into_iter()
+ .fold_with(Expr::or))
+ })
+ .collect::<Result<_, ExpandErr>>()?;
+
+ Ok(nodes.into_iter().fold_with(Expr::and))
+ }
+}
diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rs
index fbe0e4629d..6afc531559 100644
--- a/rust/cloud-storage/item_filters/src/ast/tests.rs
+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs
@@ -1,6 +1,7 @@
use std::str::FromStr;
use super::*;
+use crate::PropertyFilter;
use cool_asserts::assert_matches;
use model_file_type::FileType;
use serde_json::json;
@@ -405,3 +406,228 @@ fn task_include_cbm_atm_nc_false_is_noop() {
"false should be equivalent to not setting the include flag"
);
}
+
+#[test]
+fn it_expands_single_property_select_option() {
+ let prop_def_id = Uuid::new_v4();
+ let option_id = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![option_id.to_string()],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let ast_result = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ assert!(ast_result.properties_filter.is_some());
+}
+
+#[test]
+fn it_expands_multiple_option_ids_as_or() {
+ let prop_def_id = Uuid::new_v4();
+ let option_a = Uuid::new_v4();
+ let option_b = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![option_a.to_string(), option_b.to_string()],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let ast_result = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let ast = Arc::into_inner(ast_result.properties_filter.unwrap()).unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ // Two options should be OR'd together
+ assert!(
+ json.get("|").is_some(),
+ "multiple option_ids should OR together"
+ );
+}
+
+#[test]
+fn it_expands_entity_ref_filter() {
+ let prop_def_id = Uuid::new_v4();
+ let entity_id = "macro|[email protected]".to_string();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![],
+ entity_ids: vec![entity_id.clone()],
+ }],
+ ..Default::default()
+ };
+
+ let ast_result = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let ast = Arc::into_inner(ast_result.properties_filter.unwrap()).unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ let exp = json!({
+ "l": {
+ "pd": prop_def_id,
+ "et": "TASK",
+ "v": { "er": entity_id }
+ }
+ });
+
+ assert_eq!(json, exp);
+}
+
+#[test]
+fn it_ands_multiple_property_filters() {
+ let status_id = Uuid::new_v4();
+ let priority_id = Uuid::new_v4();
+ let option_a = Uuid::new_v4();
+ let option_b = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![
+ PropertyFilter {
+ property_definition_id: status_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![option_a.to_string()],
+ entity_ids: vec![],
+ },
+ PropertyFilter {
+ property_definition_id: priority_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![option_b.to_string()],
+ entity_ids: vec![],
+ },
+ ],
+ ..Default::default()
+ };
+
+ let ast_result = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let ast = Arc::into_inner(ast_result.properties_filter.unwrap()).unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ // Two property filters should be AND'd together
+ assert!(
+ json.get("&").is_some(),
+ "multiple property filters should AND together"
+ );
+}
+
+#[test]
+fn it_ors_mixed_option_and_entity_ref_within_single_filter() {
+ let prop_def_id = Uuid::new_v4();
+ let option_id = Uuid::new_v4();
+ let entity_id = "some-entity-id".to_string();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![option_id.to_string()],
+ entity_ids: vec![entity_id],
+ }],
+ ..Default::default()
+ };
+
+ let ast_result = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let ast = Arc::into_inner(ast_result.properties_filter.unwrap()).unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ // option_id and entity_id should be OR'd within the same filter
+ assert!(
+ json.get("|").is_some(),
+ "option_ids and entity_ids within one filter should OR together"
+ );
+}
+
+#[test]
+fn empty_property_filters_produce_no_ast() {
+ let f = EntityFilters {
+ property_filters: vec![],
+ ..Default::default()
+ };
+
+ assert!(
+ EntityFilterAst::new_from_filters(f).unwrap().is_none(),
+ "empty property_filters should produce no AST"
+ );
+}
+
+#[test]
+fn property_filter_with_empty_values_produce_no_ast() {
+ let prop_def_id = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ assert!(
+ EntityFilterAst::new_from_filters(f).unwrap().is_none(),
+ "property filter with no values should produce no AST"
+ );
+}
+
+#[test]
+fn it_expands_property_filter_without_entity_type() {
+ let prop_def_id = Uuid::new_v4();
+ let option_id = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: None,
+ option_ids: vec![option_id.to_string()],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let ast_result = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let ast = Arc::into_inner(ast_result.properties_filter.unwrap()).unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ let exp = json!({
+ "l": {
+ "pd": prop_def_id,
+ "v": { "so": option_id }
+ }
+ });
+
+ // entity_type should be absent in serialization when None
+ assert_eq!(json, exp);
+}
+
+#[test]
+fn it_expands_property_filter_with_entity_type() {
+ let prop_def_id = Uuid::new_v4();
+ let option_id = Uuid::new_v4();
+ let f = EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: prop_def_id.to_string(),
+ entity_type: Some("TASK".to_string()),
+ option_ids: vec![option_id.to_string()],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let ast_result = EntityFilterAst::new_from_filters(f).unwrap().unwrap();
+ let ast = Arc::into_inner(ast_result.properties_filter.unwrap()).unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ let exp = json!({
+ "l": {
+ "pd": prop_def_id,
+ "et": "TASK",
+ "v": { "so": option_id }
+ }
+ });
+
+ // entity_type should be present when Some
+ assert_eq!(json, exp);
+}
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index a20221e5a3..d996ee0738 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -287,6 +287,35 @@ impl IsEmpty for ChannelFilters {
}
}
+/// A single property-based filter condition.
+///
+/// Each filter targets a specific property definition on entities of a given type,
+/// matching against select option UUIDs or entity reference IDs.
+/// Multiple values within a single filter are OR'd together.
+/// Multiple filters are AND'd together.
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
+pub struct PropertyFilter {
+ /// The UUID of the property definition to filter on.
+ pub property_definition_id: String,
+ /// The entity type for the property lookup (e.g., "TASK", "DOCUMENT", "PROJECT").
+ /// When None, matches across all entity types.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub entity_type: Option<String>,
+ /// Select option UUIDs to match. Multiple values are OR'd together.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub option_ids: Vec<String>,
+ /// Entity reference IDs to match. Multiple values are OR'd together.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub entity_ids: Vec<String>,
+}
+
+impl IsEmpty for PropertyFilter {
+ fn is_empty(&self) -> bool {
+ self.option_ids.is_empty() && self.entity_ids.is_empty()
+ }
+}
+
/// The project filters used to filter down what projects you search over.
#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
@@ -342,6 +371,9 @@ pub struct EntityFilters {
/// the bundled [EmailFilters]
#[serde(default)]
pub email_filters: EmailFilters,
+ /// property-based filters applied across entity types
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub property_filters: Vec<PropertyFilter>,
}
impl IsEmpty for EntityFilters {
@@ -352,6 +384,7 @@ impl IsEmpty for EntityFilters {
chat_filters,
channel_filters,
email_filters,
+ property_filters,
} = self;
project_filters.is_empty()
&& document_filters.is_empty()
@@ -359,5 +392,6 @@ impl IsEmpty for EntityFilters {
&& chat_filters.is_empty()
&& email_filters.is_empty()
&& channel_filters.is_empty()
+ && property_filters.iter().all(IsEmpty::is_empty)
}
}
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
index 4ab0d0c678..f9bac4bc5f 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -7,7 +7,11 @@ use chrono::{DateTime, Utc};
use document_sub_type::DocumentSubType;
use filter_ast::Expr;
use item_filters::ast::{
- EntityFilterAst, chat::ChatLiteral, document::DocumentLiteral, project::ProjectLiteral,
+ EntityFilterAst,
+ chat::ChatLiteral,
+ document::DocumentLiteral,
+ project::ProjectLiteral,
+ properties::{PropertiesLiteral, PropertyMatchValue},
};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use models_pagination::{Query, SimpleSortMethod};
@@ -430,6 +434,51 @@ fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {
}
}
+fn build_properties_filter(ast: Option<&Expr<PropertiesLiteral>>, entity_id_sql: &str) -> String {
+ let Some(expr) = ast else {
+ return String::new();
+ };
+ let formatting = expr.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+ filter_ast::ExprFrame::Literal(PropertiesLiteral {
+ property_definition_id,
+ entity_type,
+ value,
+ }) => {
+ let value_predicate = match value {
+ PropertyMatchValue::SelectOption(option_id) => {
+ format!("ep_prop.values->'value' ? '{option_id}'")
+ }
+ PropertyMatchValue::EntityRef(entity_id) => {
+ format!(
+ "ep_prop.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', '{entity_id}'))"
+ )
+ }
+ };
+ let entity_type_clause = match entity_type {
+ Some(et) => format!("AND ep_prop.entity_type = '{et}'"),
+ None => String::new(),
+ };
+ format!(
+ r#"EXISTS (
+ SELECT 1 FROM entity_properties ep_prop
+ WHERE ep_prop.entity_id = {entity_id_sql}
+ {entity_type_clause}
+ AND ep_prop.property_definition_id = '{property_definition_id}'
+ AND {value_predicate}
+ )"#
+ )
+ }
+ });
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
+}
+
fn build_query(filter_ast: &EntityFilterAst, exclude_frecency: bool) -> QueryBuilder<'_, Postgres> {
let mut builder = sqlx::QueryBuilder::new(PREFIX);
@@ -440,18 +489,30 @@ fn build_query(filter_ast: &EntityFilterAst, exclude_frecency: bool) -> QueryBui
// Document top clause (lightweight)
builder.push(DOCUMENT_TOP_CLAUSE);
builder.push(build_document_filter(filter_ast.document_filter.as_deref()));
+ builder.push(build_properties_filter(
+ filter_ast.properties_filter.as_deref(),
+ "d.id",
+ ));
builder.push(" UNION ALL ");
// Chat top clause (lightweight)
builder.push(CHAT_TOP_CLAUSE);
builder.push(build_chat_filter(filter_ast.chat_filter.as_deref()));
+ builder.push(build_properties_filter(
+ filter_ast.properties_filter.as_deref(),
+ "c.id",
+ ));
builder.push(" UNION ALL ");
// Project top clause (lightweight)
builder.push(PROJECT_TOP_CLAUSE);
builder.push(build_project_filter(filter_ast.project_filter.as_deref()));
+ builder.push(build_properties_filter(
+ filter_ast.properties_filter.as_deref(),
+ "p.id",
+ ));
builder.push(") all_items ");
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index 1defca3245..21ea28c137 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -3,7 +3,7 @@ use crate::outbound::pg_soup_repo::expanded::{
by_ids::expanded_soup_by_ids,
dynamic::{ExpandedDynamicCursorArgs, expanded_dynamic_cursor_soup},
};
-use item_filters::ast::EntityFilterAst;
+use item_filters::{PropertyFilter, ast::EntityFilterAst};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model_entity::EntityType;
@@ -4630,6 +4630,7 @@ async fn test_all_filter_types_combined(db: PgPool) -> anyhow::Result<()> {
owners: vec!["macro|[email protected]".to_string()],
..Default::default()
},
+ ..Default::default()
};
let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
@@ -4654,3 +4655,399 @@ async fn test_all_filter_types_combined(db: PgPool) -> anyhow::Result<()> {
Ok(())
}
+
+// ---------- Property-based filtering tests ----------
+
+// Test filtering documents by a single property select option (Priority = Low)
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("soup_items_with_properties")
+ )
+)]
+async fn test_property_filter_by_select_option(db: Pool<Postgres>) -> anyhow::Result<()> {
+ // Filter for Priority = Low (both doc A and doc B have Priority = Low)
+ let entity_filters = item_filters::EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000003".to_string(), // Priority
+ entity_type: Some("DOCUMENT".to_string()),
+ option_ids: vec!["00000001-0000-0000-0003-000000000001".to_string()], // Low
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 100,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ // Both doc A and doc B have Priority = Low, plus projects/chats have no property filter
+ // so they should all pass through. But only documents match the property filter on DOCUMENT entity_type.
+ let doc_ids: HashSet<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Document(d) => Some(d.id),
+ _ => None,
+ })
+ .collect();
+
+ assert!(
+ doc_ids.contains(&Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap()),
+ "Doc A should match Priority = Low"
+ );
+ assert!(
+ doc_ids.contains(&Uuid::parse_str("11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap()),
+ "Doc B should match Priority = Low"
+ );
+
+ Ok(())
+}
+
+// Test filtering by a property value that only matches one document
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("soup_items_with_properties")
+ )
+)]
+async fn test_property_filter_by_status_completed(db: Pool<Postgres>) -> anyhow::Result<()> {
+ // Filter for Status = Completed (only doc A has this)
+ let entity_filters = item_filters::EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000002".to_string(), // Status
+ entity_type: Some("DOCUMENT".to_string()),
+ option_ids: vec!["00000001-0000-0000-0002-000000000004".to_string()], // Completed
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 100,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let doc_ids: Vec<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Document(d) => Some(d.id),
+ _ => None,
+ })
+ .collect();
+
+ assert_eq!(
+ doc_ids.len(),
+ 1,
+ "Only doc A should match Status = Completed"
+ );
+ assert_eq!(
+ doc_ids[0],
+ Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap(),
+ "Doc A should match Status = Completed"
+ );
+
+ Ok(())
+}
+
+// Test AND-ing multiple property filters (Priority = Low AND Status = Completed)
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("soup_items_with_properties")
+ )
+)]
+async fn test_property_filter_multiple_and(db: Pool<Postgres>) -> anyhow::Result<()> {
+ // Filter for Priority = Low AND Status = Completed (only doc A has both)
+ let entity_filters = item_filters::EntityFilters {
+ property_filters: vec![
+ PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000003".to_string(), // Priority
+ entity_type: Some("DOCUMENT".to_string()),
+ option_ids: vec!["00000001-0000-0000-0003-000000000001".to_string()], // Low
+ entity_ids: vec![],
+ },
+ PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000002".to_string(), // Status
+ entity_type: Some("DOCUMENT".to_string()),
+ option_ids: vec!["00000001-0000-0000-0002-000000000004".to_string()], // Completed
+ entity_ids: vec![],
+ },
+ ],
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 100,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let doc_ids: Vec<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Document(d) => Some(d.id),
+ _ => None,
+ })
+ .collect();
+
+ assert_eq!(
+ doc_ids.len(),
+ 1,
+ "Only doc A should match both Priority = Low AND Status = Completed"
+ );
+ assert_eq!(
+ doc_ids[0],
+ Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap()
+ );
+
+ Ok(())
+}
+
+// Test that a non-matching property filter returns no documents
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("soup_items_with_properties")
+ )
+)]
+async fn test_property_filter_no_match(db: Pool<Postgres>) -> anyhow::Result<()> {
+ // Filter for Priority = Critical (no documents have this)
+ let entity_filters = item_filters::EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000003".to_string(), // Priority
+ entity_type: Some("DOCUMENT".to_string()),
+ option_ids: vec!["00000001-0000-0000-0003-000000000004".to_string()], // Critical
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 100,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let doc_count = items
+ .iter()
+ .filter(|i| matches!(i, SoupItem::Document(_)))
+ .count();
+
+ assert_eq!(
+ doc_count, 0,
+ "No documents should match Priority = Critical"
+ );
+
+ Ok(())
+}
+
+// Test OR-ing multiple option values within a single property filter
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("soup_items_with_properties")
+ )
+)]
+async fn test_property_filter_multiple_options_or(db: Pool<Postgres>) -> anyhow::Result<()> {
+ // Filter for Priority = Low OR Priority = Medium
+ // Doc A and Doc B have Priority = Low, Project A has Priority = Medium on PROJECT entity_type
+ // Since we filter on DOCUMENT entity_type, only docs match
+ let entity_filters = item_filters::EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000003".to_string(), // Priority
+ entity_type: Some("DOCUMENT".to_string()),
+ option_ids: vec![
+ "00000001-0000-0000-0003-000000000001".to_string(), // Low
+ "00000001-0000-0000-0003-000000000002".to_string(), // Medium
+ ],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 100,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let doc_ids: HashSet<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Document(d) => Some(d.id),
+ _ => None,
+ })
+ .collect();
+
+ assert!(
+ doc_ids.contains(&Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap()),
+ "Doc A should match Priority = Low"
+ );
+ assert!(
+ doc_ids.contains(&Uuid::parse_str("11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap()),
+ "Doc B should match Priority = Low"
+ );
+
+ Ok(())
+}
+
+// Test filtering without entity_type matches across all entity types
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("soup_items_with_properties")
+ )
+)]
+async fn test_property_filter_without_entity_type(db: Pool<Postgres>) -> anyhow::Result<()> {
+ // Filter for Priority = Low OR Medium without specifying entity_type.
+ // Doc A and Doc B have Priority = Low on DOCUMENT entity_type.
+ // Project A has Priority = Medium on PROJECT entity_type.
+ // With entity_type = None, the filter should match across both entity types.
+ let entity_filters = item_filters::EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000003".to_string(), // Priority
+ entity_type: None, // match across all entity types
+ option_ids: vec![
+ "00000001-0000-0000-0003-000000000001".to_string(), // Low
+ "00000001-0000-0000-0003-000000000002".to_string(), // Medium
+ ],
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 100,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let item_ids: HashSet<Uuid> = items.iter().map(|i| i.id()).collect();
+
+ // Documents with Priority = Low
+ assert!(
+ item_ids.contains(&Uuid::parse_str("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap()),
+ "Doc A should match Priority = Low (DOCUMENT entity_type)"
+ );
+ assert!(
+ item_ids.contains(&Uuid::parse_str("11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap()),
+ "Doc B should match Priority = Low (DOCUMENT entity_type)"
+ );
+ // Project with Priority = Medium
+ assert!(
+ item_ids.contains(&Uuid::parse_str("aaaaaaaa-ffff-ffff-ffff-ffffffffffff").unwrap()),
+ "Project A should match Priority = Medium (PROJECT entity_type)"
+ );
+
+ Ok(())
+}
+
+// Test that specifying entity_type scopes the filter to only that type
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("soup_items_with_properties")
+ )
+)]
+async fn test_property_filter_scoped_entity_type(db: Pool<Postgres>) -> anyhow::Result<()> {
+ // Filter for Priority = Medium on PROJECT entity_type only.
+ // Project A has Priority = Medium on PROJECT. Docs do not.
+ // With entity_type = Some("PROJECT"), only projects should match.
+ let entity_filters = item_filters::EntityFilters {
+ property_filters: vec![PropertyFilter {
+ property_definition_id: "00000001-0000-0000-0000-000000000003".to_string(), // Priority
+ entity_type: Some("PROJECT".to_string()),
+ option_ids: vec!["00000001-0000-0000-0003-000000000002".to_string()], // Medium
+ entity_ids: vec![],
+ }],
+ ..Default::default()
+ };
+
+ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();
+
+ let items = dyn_fetch(
+ &db,
+ 100,
+ SimpleSortMethod::UpdatedAt,
+ filters,
+ false,
+ )
+ .await?;
+
+ let project_ids: Vec<Uuid> = items
+ .iter()
+ .filter_map(|i| match i {
+ SoupItem::Project(p) => Some(p.id),
+ _ => None,
+ })
+ .collect();
+
+ assert_eq!(
+ project_ids.len(),
+ 1,
+ "Only Project A should match Priority = Medium on PROJECT"
+ );
+ assert_eq!(
+ project_ids[0],
+ Uuid::parse_str("aaaaaaaa-ffff-ffff-ffff-ffffffffffff").unwrap()
+ );
+
+ // No documents should match since they only have Priority on DOCUMENT entity_type
+ let doc_count = items
+ .iter()
+ .filter(|i| matches!(i, SoupItem::Document(_)))
+ .count();
+ assert_eq!(
+ doc_count, 0,
+ "No documents should match Priority = Medium on PROJECT entity_type"
+ );
+
+ Ok(())
+}