Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(soup): add date ast filters (#2893)
Sean Aye9f746a70f5fb
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rsindex 4a1e5f0d7a..59d77f3721 100644--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs@@ -3,7 +3,8 @@use crate::domain::models::{AggregateFrecency, AggregateId, FrecencyData, TimestampWeight};use filter_ast::Expr;use item_filters::ast::{- EntityFilterAst, chat::ChatLiteral, document::DocumentLiteral, project::ProjectLiteral,+ EntityFilterAst, chat::ChatLiteral, date::DateLiteral, document::DocumentLiteral,+ project::ProjectLiteral,};use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_entity::EntityType;@@ -191,6 +192,30 @@ fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {r#"NOT EXISTS(SELECT 1 FROM document_email WHERE document_id = fa.entity_id)"#.to_string()}+ filter_ast::ExprFrame::Literal(DocumentLiteral::CreatedAt(DateLiteral::GreaterThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "createdAt" > '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::CreatedAt(DateLiteral::LessThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "createdAt" < '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::CreatedAt(DateLiteral::GreaterThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "createdAt" >= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::CreatedAt(DateLiteral::LessThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "createdAt" <= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::UpdatedAt(DateLiteral::GreaterThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "updatedAt" > '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::UpdatedAt(DateLiteral::LessThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "updatedAt" < '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::UpdatedAt(DateLiteral::GreaterThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "updatedAt" >= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::UpdatedAt(DateLiteral::LessThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Document" WHERE "updatedAt" <= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }});if formatting.is_empty() {String::new()@@ -244,6 +269,30 @@ fn build_chat_filter(ast: Option<&Expr<ChatLiteral>>) -> String {filter_ast::ExprFrame::Literal(ChatLiteral::NotificationSeen(seen)) => {build_notification_seen_clause("entity_id", "chat", seen)}+ filter_ast::ExprFrame::Literal(ChatLiteral::CreatedAt(DateLiteral::GreaterThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "createdAt" > '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::CreatedAt(DateLiteral::LessThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "createdAt" < '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::CreatedAt(DateLiteral::GreaterThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "createdAt" >= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::CreatedAt(DateLiteral::LessThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "createdAt" <= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::UpdatedAt(DateLiteral::GreaterThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "updatedAt" > '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::UpdatedAt(DateLiteral::LessThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "updatedAt" < '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::UpdatedAt(DateLiteral::GreaterThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "updatedAt" >= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::UpdatedAt(DateLiteral::LessThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Chat" WHERE "updatedAt" <= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }});if formatting.is_empty() {String::new()@@ -275,6 +324,30 @@ fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {filter_ast::ExprFrame::Literal(ProjectLiteral::NotificationSeen(seen)) => {build_notification_seen_clause("entity_id", "project", seen)}+ filter_ast::ExprFrame::Literal(ProjectLiteral::CreatedAt(DateLiteral::GreaterThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "createdAt" > '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::CreatedAt(DateLiteral::LessThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "createdAt" < '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::CreatedAt(DateLiteral::GreaterThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "createdAt" >= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::CreatedAt(DateLiteral::LessThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "createdAt" <= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::UpdatedAt(DateLiteral::GreaterThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "updatedAt" > '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::UpdatedAt(DateLiteral::LessThan(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "updatedAt" < '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::UpdatedAt(DateLiteral::GreaterThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "updatedAt" >= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::UpdatedAt(DateLiteral::LessThanOrEqual(dt))) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "updatedAt" <= '{}'::timestamptz AND "deletedAt" IS NULL)"#, dt.to_rfc3339())+ }});if formatting.is_empty() {String::new()diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rsindex fbc04e0cbb..4673efb280 100644--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs@@ -2,14 +2,18 @@use super::*;use crate::domain::models::{AggregateId, FrecencyData};-use chrono::Utc;+use chrono::{DateTime, Utc};+use filter_ast::Expr;+use item_filters::ast::{date::DateLiteral, document::DocumentLiteral};use item_filters::{ChatFilters, DocumentFilters, EntityFilters, NotificationFilters, ProjectFilters, TaskFilters,+ ast::EntityFilterAst,};use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_entity::EntityType;use std::collections::VecDeque;+use std::sync::Arc;use uuid::Uuid;#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -694,3 +698,412 @@ async fn test_dynamic_filter_document_task_include_cbm_atm_nc(pool: PgPool) {assert_eq!(results.len(), 1);assert_eq!(results[0].id.entity.entity_id, matching_task_id.to_string());}++async fn setup_date_filter_user(pool: &PgPool, user_id: &MacroUserIdStr<'_>) {+ let macro_user_uuid = Uuid::new_v4();+ sqlx::query(+ r#"+ INSERT INTO "macro_user" ("id", "username", "email", "stripe_customer_id")+ VALUES ($1, 'test', $2, 'stripe_test')+ ON CONFLICT ("id") DO NOTHING+ "#,+ )+ .bind(macro_user_uuid)+ .bind("[email protected]")+ .execute(pool)+ .await+ .unwrap();++ sqlx::query(+ r#"+ INSERT INTO "User" ("id", "email", "macro_user_id")+ VALUES ($1, $2, $3)+ ON CONFLICT ("id") DO NOTHING+ "#,+ )+ .bind(user_id.as_ref())+ .bind("[email protected]")+ .bind(macro_user_uuid)+ .execute(pool)+ .await+ .unwrap();+}++async fn insert_doc_with_timestamps(+ pool: &PgPool,+ id: Uuid,+ owner: &str,+ created_at: &str,+ updated_at: &str,+) {+ sqlx::query(+ r#"+ INSERT INTO "Document" ("id", "name", "owner", "fileType", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, 'txt', $4::timestamptz, $5::timestamptz)+ "#,+ )+ .bind(id.to_string())+ .bind(id.to_string())+ .bind(owner)+ .bind(created_at)+ .bind(updated_at)+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_dynamic_filter_document_date_created_at_gt(pool: PgPool) {+ let storage = FrecencyPgStorage::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ setup_date_filter_user(&pool, &user_id).await;++ let doc_early = Uuid::new_v4();+ let doc_mid = Uuid::new_v4();+ let doc_late = Uuid::new_v4();++ insert_doc_with_timestamps(+ &pool,+ doc_early,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T10:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_mid,+ user_id.as_ref(),+ "2023-01-01T12:00:00Z",+ "2023-01-01T12:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_late,+ user_id.as_ref(),+ "2023-01-01T14:00:00Z",+ "2023-01-01T14:00:00Z",+ )+ .await;++ for (id, score) in [+ (doc_early.to_string(), 100.0),+ (doc_mid.to_string(), 90.0),+ (doc_late.to_string(), 80.0),+ ] {+ storage+ .set_aggregate(AggregateFrecency {+ id: AggregateId {+ entity: EntityType::Document.with_entity_string(id),+ user_id: user_id.clone(),+ },+ data: FrecencyData {+ event_count: 1,+ frecency_score: score,+ first_event: Utc::now(),+ recent_events: VecDeque::new(),+ },+ })+ .await+ .unwrap();+ }++ let cutoff: DateTime<Utc> = DateTime::parse_from_rfc3339("2023-01-01T11:00:00Z")+ .unwrap()+ .into();+ let filter = EntityFilterAst {+ document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::CreatedAt(+ DateLiteral::GreaterThan(cutoff),+ )))),+ project_filter: None,+ chat_filter: None,+ email_filter: None,+ channel_filter: None,+ call_filter: None,+ properties_filter: None,+ };++ let results = storage+ .get_top_entities(FrecencyPageRequest {+ user_id: user_id.copied(),+ from_score: None,+ limit: 10,+ filters: Some(filter),+ })+ .await+ .unwrap();++ assert_eq!(results.len(), 2);+ let ids: Vec<String> = results+ .iter()+ .map(|r| r.id.entity.entity_id.as_ref().to_string())+ .collect();+ assert!(ids.contains(&doc_mid.to_string()));+ assert!(ids.contains(&doc_late.to_string()));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_dynamic_filter_document_date_created_at_lt(pool: PgPool) {+ let storage = FrecencyPgStorage::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ setup_date_filter_user(&pool, &user_id).await;++ let doc_early = Uuid::new_v4();+ let doc_mid = Uuid::new_v4();+ let doc_late = Uuid::new_v4();++ insert_doc_with_timestamps(+ &pool,+ doc_early,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T10:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_mid,+ user_id.as_ref(),+ "2023-01-01T12:00:00Z",+ "2023-01-01T12:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_late,+ user_id.as_ref(),+ "2023-01-01T14:00:00Z",+ "2023-01-01T14:00:00Z",+ )+ .await;++ for (id, score) in [+ (doc_early.to_string(), 100.0),+ (doc_mid.to_string(), 90.0),+ (doc_late.to_string(), 80.0),+ ] {+ storage+ .set_aggregate(AggregateFrecency {+ id: AggregateId {+ entity: EntityType::Document.with_entity_string(id),+ user_id: user_id.clone(),+ },+ data: FrecencyData {+ event_count: 1,+ frecency_score: score,+ first_event: Utc::now(),+ recent_events: VecDeque::new(),+ },+ })+ .await+ .unwrap();+ }++ let cutoff: DateTime<Utc> = DateTime::parse_from_rfc3339("2023-01-01T11:00:00Z")+ .unwrap()+ .into();+ let filter = EntityFilterAst {+ document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::CreatedAt(+ DateLiteral::LessThan(cutoff),+ )))),+ project_filter: None,+ chat_filter: None,+ email_filter: None,+ channel_filter: None,+ call_filter: None,+ properties_filter: None,+ };++ let results = storage+ .get_top_entities(FrecencyPageRequest {+ user_id: user_id.copied(),+ from_score: None,+ limit: 10,+ filters: Some(filter),+ })+ .await+ .unwrap();++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].id.entity.entity_id, doc_early.to_string());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_dynamic_filter_document_date_updated_at_gt(pool: PgPool) {+ let storage = FrecencyPgStorage::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ setup_date_filter_user(&pool, &user_id).await;++ let doc_early = Uuid::new_v4();+ let doc_mid = Uuid::new_v4();+ let doc_late = Uuid::new_v4();++ // createdAt is old for all; updatedAt varies+ insert_doc_with_timestamps(+ &pool,+ doc_early,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T10:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_mid,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T12:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_late,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T14:00:00Z",+ )+ .await;++ for (id, score) in [+ (doc_early.to_string(), 100.0),+ (doc_mid.to_string(), 90.0),+ (doc_late.to_string(), 80.0),+ ] {+ storage+ .set_aggregate(AggregateFrecency {+ id: AggregateId {+ entity: EntityType::Document.with_entity_string(id),+ user_id: user_id.clone(),+ },+ data: FrecencyData {+ event_count: 1,+ frecency_score: score,+ first_event: Utc::now(),+ recent_events: VecDeque::new(),+ },+ })+ .await+ .unwrap();+ }++ let cutoff: DateTime<Utc> = DateTime::parse_from_rfc3339("2023-01-01T11:00:00Z")+ .unwrap()+ .into();+ let filter = EntityFilterAst {+ document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::UpdatedAt(+ DateLiteral::GreaterThan(cutoff),+ )))),+ project_filter: None,+ chat_filter: None,+ email_filter: None,+ channel_filter: None,+ call_filter: None,+ properties_filter: None,+ };++ let results = storage+ .get_top_entities(FrecencyPageRequest {+ user_id: user_id.copied(),+ from_score: None,+ limit: 10,+ filters: Some(filter),+ })+ .await+ .unwrap();++ assert_eq!(results.len(), 2);+ let ids: Vec<String> = results+ .iter()+ .map(|r| r.id.entity.entity_id.as_ref().to_string())+ .collect();+ assert!(ids.contains(&doc_mid.to_string()));+ assert!(ids.contains(&doc_late.to_string()));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_dynamic_filter_document_date_updated_at_lt(pool: PgPool) {+ let storage = FrecencyPgStorage::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ setup_date_filter_user(&pool, &user_id).await;++ let doc_early = Uuid::new_v4();+ let doc_mid = Uuid::new_v4();+ let doc_late = Uuid::new_v4();++ // createdAt is old for all; updatedAt varies+ insert_doc_with_timestamps(+ &pool,+ doc_early,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T10:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_mid,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T12:00:00Z",+ )+ .await;+ insert_doc_with_timestamps(+ &pool,+ doc_late,+ user_id.as_ref(),+ "2023-01-01T10:00:00Z",+ "2023-01-01T14:00:00Z",+ )+ .await;++ for (id, score) in [+ (doc_early.to_string(), 100.0),+ (doc_mid.to_string(), 90.0),+ (doc_late.to_string(), 80.0),+ ] {+ storage+ .set_aggregate(AggregateFrecency {+ id: AggregateId {+ entity: EntityType::Document.with_entity_string(id),+ user_id: user_id.clone(),+ },+ data: FrecencyData {+ event_count: 1,+ frecency_score: score,+ first_event: Utc::now(),+ recent_events: VecDeque::new(),+ },+ })+ .await+ .unwrap();+ }++ let cutoff: DateTime<Utc> = DateTime::parse_from_rfc3339("2023-01-01T11:00:00Z")+ .unwrap()+ .into();+ let filter = EntityFilterAst {+ document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::UpdatedAt(+ DateLiteral::LessThan(cutoff),+ )))),+ project_filter: None,+ chat_filter: None,+ email_filter: None,+ channel_filter: None,+ call_filter: None,+ properties_filter: None,+ };++ let results = storage+ .get_top_entities(FrecencyPageRequest {+ user_id: user_id.copied(),+ from_score: None,+ limit: 10,+ filters: Some(filter),+ })+ .await+ .unwrap();++ assert_eq!(results.len(), 1);+ assert_eq!(results[0].id.entity.entity_id, doc_early.to_string());+}diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rsindex ee26e871ce..96018b52dc 100644--- a/rust/cloud-storage/item_filters/src/ast.rs+++ b/rust/cloud-storage/item_filters/src/ast.rs@@ -26,6 +26,8 @@ pub mod call;pub mod channel;/// contains the ast literal value for chatpub mod chat;+/// contains the date comparison literal type+pub mod date;/// contains the ast literal value for documentspub mod document;/// contains the ast literal value for emailsdiff --git a/rust/cloud-storage/item_filters/src/ast/chat.rs b/rust/cloud-storage/item_filters/src/ast/chat.rsindex 36ce09f10e..71e2c79d35 100644--- a/rust/cloud-storage/item_filters/src/ast/chat.rs+++ b/rust/cloud-storage/item_filters/src/ast/chat.rs@@ -5,26 +5,39 @@ use uuid::Uuid;use crate::{ChatFilters,- ast::{ExpandErr, ParseFromStr, UnknownValue},+ ast::{ExpandErr, ParseFromStr, UnknownValue, date::DateLiteral},};/// the literal ast type for the chat entity#[derive(Debug, Serialize, Deserialize, Clone)]pub enum ChatLiteral {/// the chat is in some nested project structure where [Uuid] is a parent node+ #[serde(rename = "pid")]ProjectId(Uuid),/// the chat has role [ChatRole]+ #[serde(rename = "r")]Role(ChatRole),/// the chat has the id [Uuid]+ #[serde(rename = "cid")]ChatId(Uuid),/// the chat is owned by [MacroUserIdStr]+ #[serde(rename = "o")]Owner(MacroUserIdStr<'static>),/// this node value filters by chat importance. false short-circuits to match nothing.+ #[serde(rename = "imp")]Importance(bool),/// this node value filters by notification done state for chats.+ #[serde(rename = "nd")]NotificationDone(bool),/// this node value filters by notification seen state for chats.+ #[serde(rename = "ns")]NotificationSeen(bool),+ /// this node value filters by chat createdAt timestamp+ #[serde(rename = "ca")]+ CreatedAt(DateLiteral),+ /// this node value filters by chat updatedAt timestamp+ #[serde(rename = "ua")]+ UpdatedAt(DateLiteral),}/// the possible roles for a chatdiff --git a/rust/cloud-storage/item_filters/src/ast/date.rs b/rust/cloud-storage/item_filters/src/ast/date.rsnew file mode 100644index 0000000000..877720e8f8--- /dev/null+++ b/rust/cloud-storage/item_filters/src/ast/date.rs@@ -0,0 +1,19 @@+use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};++/// A date comparison literal used within entity-specific filter AST nodes.+#[derive(Debug, Serialize, Deserialize, Clone)]+pub enum DateLiteral {+ /// Matches entities whose date column is strictly after this timestamp.+ #[serde(rename = "gt")]+ GreaterThan(DateTime<Utc>),+ /// Matches entities whose date column is strictly before this timestamp.+ #[serde(rename = "lt")]+ LessThan(DateTime<Utc>),+ /// Matches entities whose date column is at or after this timestamp.+ #[serde(rename = "gte")]+ GreaterThanOrEqual(DateTime<Utc>),+ /// Matches entities whose date column is at or before this timestamp.+ #[serde(rename = "lte")]+ LessThanOrEqual(DateTime<Utc>),+}diff --git a/rust/cloud-storage/item_filters/src/ast/document.rs b/rust/cloud-storage/item_filters/src/ast/document.rsindex ca99c60435..23661f11b3 100644--- a/rust/cloud-storage/item_filters/src/ast/document.rs+++ b/rust/cloud-storage/item_filters/src/ast/document.rs@@ -1,4 +1,7 @@-use crate::{DocumentFilters, ast::ExpandErr};+use crate::{+ DocumentFilters,+ ast::{ExpandErr, date::DateLiteral},+};use document_sub_type::DocumentSubType;use either::Either;use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};@@ -50,6 +53,12 @@ pub enum DocumentLiteral {/// this node value filters by email attachment status#[serde(rename = "iea")]IsEmailAttachment(bool),+ /// this node value filters by document createdAt timestamp+ #[serde(rename = "ca")]+ CreatedAt(DateLiteral),+ /// this node value filters by document updatedAt timestamp+ #[serde(rename = "ua")]+ UpdatedAt(DateLiteral),}fn prefix(s: &str) -> IResult<&str, &str> {diff --git a/rust/cloud-storage/item_filters/src/ast/project.rs b/rust/cloud-storage/item_filters/src/ast/project.rsindex b966ddf7b3..f796cbe9f7 100644--- a/rust/cloud-storage/item_filters/src/ast/project.rs+++ b/rust/cloud-storage/item_filters/src/ast/project.rs@@ -3,21 +3,35 @@ use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use serde::{Deserialize, Serialize};use uuid::Uuid;-use crate::{ProjectFilters, ast::ExpandErr};+use crate::{+ ProjectFilters,+ ast::{ExpandErr, date::DateLiteral},+};/// the literal ast types for a project#[derive(Debug, Serialize, Deserialize, Clone)]pub enum ProjectLiteral {/// the id of the project+ #[serde(rename = "pid")]ProjectId(Uuid),/// the owner of the project+ #[serde(rename = "o")]Owner(MacroUserIdStr<'static>),/// this node value filters by project importance. false short-circuits to match nothing.+ #[serde(rename = "imp")]Importance(bool),/// this node value filters by notification done state for projects.+ #[serde(rename = "nd")]NotificationDone(bool),/// this node value filters by notification seen state for projects.+ #[serde(rename = "ns")]NotificationSeen(bool),+ /// this node value filters by project createdAt timestamp+ #[serde(rename = "ca")]+ CreatedAt(DateLiteral),+ /// this node value filters by project updatedAt timestamp+ #[serde(rename = "ua")]+ UpdatedAt(DateLiteral),}impl ExpandFrame<ProjectLiteral> for ProjectFilters {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.rsindex 94bd577fef..54646a6466 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@@ -9,6 +9,7 @@ use filter_ast::Expr;use item_filters::ast::{EntityFilterAst,chat::ChatLiteral,+ date::DateLiteral,document::DocumentLiteral,project::ProjectLiteral,properties::{PropertiesLiteral, PropertyMatchValue},@@ -288,6 +289,17 @@ fn build_task_include_cbm_atm_nc_clause() -> String {.to_string()}+fn date_predicate(col: &str, lit: &DateLiteral) -> String {+ match lit {+ DateLiteral::GreaterThan(dt) => format!("{col} > '{}'::timestamptz", dt.to_rfc3339()),+ DateLiteral::LessThan(dt) => format!("{col} < '{}'::timestamptz", dt.to_rfc3339()),+ DateLiteral::GreaterThanOrEqual(dt) => {+ format!("{col} >= '{}'::timestamptz", dt.to_rfc3339())+ }+ DateLiteral::LessThanOrEqual(dt) => format!("{col} <= '{}'::timestamptz", dt.to_rfc3339()),+ }+}+fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {let Some(expr) = ast else {return String::new();@@ -346,6 +358,12 @@ fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {r#"NOT EXISTS(SELECT 1 FROM document_email WHERE document_id = d.id)"#.to_string()}+ filter_ast::ExprFrame::Literal(DocumentLiteral::CreatedAt(lit)) => {+ date_predicate(r#"d."createdAt""#, &lit)+ }+ filter_ast::ExprFrame::Literal(DocumentLiteral::UpdatedAt(lit)) => {+ date_predicate(r#"d."updatedAt""#, &lit)+ }});if formatting.is_empty() {String::new()@@ -380,6 +398,12 @@ fn build_chat_filter(ast: Option<&Expr<ChatLiteral>>) -> String {filter_ast::ExprFrame::Literal(ChatLiteral::NotificationSeen(seen)) => {build_notification_seen_clause("c.id", "chat", seen)}+ filter_ast::ExprFrame::Literal(ChatLiteral::CreatedAt(lit)) => {+ date_predicate(r#"c."createdAt""#, &lit)+ }+ filter_ast::ExprFrame::Literal(ChatLiteral::UpdatedAt(lit)) => {+ date_predicate(r#"c."updatedAt""#, &lit)+ }});if formatting.is_empty() {String::new()@@ -411,6 +435,12 @@ fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {filter_ast::ExprFrame::Literal(ProjectLiteral::NotificationSeen(seen)) => {build_notification_seen_clause("p.id", "project", seen)}+ filter_ast::ExprFrame::Literal(ProjectLiteral::CreatedAt(lit)) => {+ date_predicate(r#"p."createdAt""#, &lit)+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::UpdatedAt(lit)) => {+ date_predicate(r#"p."updatedAt""#, &lit)+ }});if formatting.is_empty() {String::new()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.rsindex c3e6f52dc4..3883743a01 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,14 @@ use crate::outbound::pg_soup_repo::expanded::{by_ids::expanded_soup_by_ids,dynamic::{ExpandedDynamicCursorArgs, expanded_dynamic_cursor_soup},};-use item_filters::{PropertyFilter, ast::EntityFilterAst};+use filter_ast::Expr;+use item_filters::{+ PropertyFilter,+ ast::{+ EntityFilterAst, chat::ChatLiteral, date::DateLiteral, document::DocumentLiteral,+ project::ProjectLiteral,+ },+};use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model_entity::EntityType;@@ -12,6 +19,7 @@ use models_pagination::{Frecency, PaginateOn, Query, SimpleSortMethod};use models_soup::item::SoupItem;use sqlx::{PgPool, Pool, Postgres};use std::collections::HashSet;+use std::sync::Arc;use uuid::Uuid;macro_rules! unwrap_enum {@@ -5371,3 +5379,669 @@ async fn test_dyn_filter_by_not_document_sub_type_task(db: PgPool) -> anyhow::ReOk(())}++// ---- Date literal filter tests ----+// Uses `entity_filter_tests` fixture which has:+// Docs (accessible): aaaa(10:00), bbbb(11:00), cccc(12:00), dddd(13:00), eeee(14:00) on 2023-01-05+// Chats (accessible): a1a1(10:00), b2b2(11:00), c3c3(12:00), d4d4(13:00) on 2023-01-06+// Projects (accessible): 1111(Jan-01 10:00), 2222(11:00), 3333(12:00), 4444(Jan-02 10:00)++fn mock_empty_ast() -> EntityFilterAst {+ EntityFilterAst {+ document_filter: None,+ project_filter: None,+ chat_filter: None,+ email_filter: None,+ channel_filter: None,+ call_filter: None,+ properties_filter: None,+ }+}++fn doc_ast(lit: DocumentLiteral) -> EntityFilterAst {+ EntityFilterAst {+ document_filter: Some(Arc::new(Expr::Literal(lit))),+ ..mock_empty_ast()+ }+}++fn chat_ast(lit: ChatLiteral) -> EntityFilterAst {+ EntityFilterAst {+ chat_filter: Some(Arc::new(Expr::Literal(lit))),+ ..mock_empty_ast()+ }+}++fn project_ast(lit: ProjectLiteral) -> EntityFilterAst {+ EntityFilterAst {+ project_filter: Some(Arc::new(Expr::Literal(lit))),+ ..mock_empty_ast()+ }+}++async fn run_and_count(+ db: &PgPool,+ ast: EntityFilterAst,+) -> anyhow::Result<(Vec<SoupItem>, usize, usize, usize)> {+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let items = expanded_dynamic_cursor_soup(+ db,+ ExpandedDynamicCursorArgs {+ user_id: user_id.copied(),+ limit: 20,+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, ast),+ exclude_frecency: false,+ },+ )+ .await?;+ let mut doc_count = 0usize;+ let mut chat_count = 0usize;+ let mut project_count = 0usize;+ for item in &items {+ match item {+ SoupItem::Document(_) => doc_count += 1,+ SoupItem::Chat(_) => chat_count += 1,+ SoupItem::Project(_) => project_count += 1,+ _ => {}+ }+ }+ Ok((items, doc_count, chat_count, project_count))+}++#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_document_created_at_gt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // cutoff between bbbb(11:00) and cccc(12:00) → expect cccc, dddd, eeee = 3 docs+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T11:30:00Z")?.into();+ let (items, doc_count, chat_count, project_count) = run_and_count(+ &db,+ doc_ast(DocumentLiteral::CreatedAt(DateLiteral::GreaterThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Document(d) = item {+ assert!(+ d.created_at > cutoff,+ "doc {} created_at {:?} should be > cutoff",+ d.id,+ d.created_at+ );+ }+ }+ assert_eq!(doc_count, 3, "expected 3 docs with createdAt after cutoff");+ assert_eq!(chat_count, 4, "chats unaffected by document date filter");+ assert_eq!(+ project_count, 4,+ "projects unaffected by document date filter"+ );+ Ok(())+}++#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_document_created_at_lt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // cutoff between bbbb(11:00) and cccc(12:00) → expect aaaa, bbbb = 2 docs+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T11:30:00Z")?.into();+ let (items, doc_count, chat_count, project_count) = run_and_count(+ &db,+ doc_ast(DocumentLiteral::CreatedAt(DateLiteral::LessThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Document(d) = item {+ assert!(+ d.created_at < cutoff,+ "doc {} created_at {:?} should be < cutoff",+ d.id,+ d.created_at+ );+ }+ }+ assert_eq!(doc_count, 2, "expected 2 docs with createdAt before cutoff");+ assert_eq!(chat_count, 4, "chats unaffected by document date filter");+ assert_eq!(+ project_count, 4,+ "projects unaffected by document date filter"+ );+ Ok(())+}++#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_chat_created_at_gt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // cutoff between b2b2(11:00) and c3c3(12:00) → expect c3c3, d4d4 = 2 chats+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-06T11:30:00Z")?.into();+ let (items, doc_count, chat_count, project_count) = run_and_count(+ &db,+ chat_ast(ChatLiteral::CreatedAt(DateLiteral::GreaterThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Chat(c) = item {+ assert!(+ c.created_at > cutoff,+ "chat {} created_at {:?} should be > cutoff",+ c.id,+ c.created_at+ );+ }+ }+ assert_eq!(doc_count, 5, "docs unaffected by chat date filter");+ assert_eq!(+ chat_count, 2,+ "expected 2 chats with createdAt after cutoff"+ );+ assert_eq!(project_count, 4, "projects unaffected by chat date filter");+ Ok(())+}++#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_project_created_at_gt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // cutoff between 2222(Jan-01 11:00) and 3333(Jan-01 12:00) → expect 3333, 4444 = 2 projects+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-01T11:30:00Z")?.into();+ let (items, doc_count, chat_count, project_count) = run_and_count(+ &db,+ project_ast(ProjectLiteral::CreatedAt(DateLiteral::GreaterThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Project(p) = item {+ assert!(+ p.created_at > cutoff,+ "project {} created_at {:?} should be > cutoff",+ p.id,+ p.created_at+ );+ }+ }+ assert_eq!(doc_count, 5, "docs unaffected by project date filter");+ assert_eq!(chat_count, 4, "chats unaffected by project date filter");+ assert_eq!(+ project_count, 2,+ "expected 2 projects with createdAt after cutoff"+ );+ Ok(())+}++// document / createdAt / AND(gt, lt)+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_document_created_at_range(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // lower after aaaa(10:00), upper before eeee(14:00) → bbbb, cccc, dddd = 3 docs+ let lower: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T10:30:00Z")?.into();+ let upper: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T13:30:00Z")?.into();+ let ast = EntityFilterAst {+ document_filter: Some(Arc::new(Expr::And(+ Box::new(Expr::Literal(DocumentLiteral::CreatedAt(+ DateLiteral::GreaterThan(lower),+ ))),+ Box::new(Expr::Literal(DocumentLiteral::CreatedAt(+ DateLiteral::LessThan(upper),+ ))),+ ))),+ ..mock_empty_ast()+ };+ let (items, doc_count, chat_count, project_count) = run_and_count(&db, ast).await?;+ for item in &items {+ if let SoupItem::Document(d) = item {+ assert!(+ d.created_at > lower && d.created_at < upper,+ "doc {} created_at {:?} outside [{:?}, {:?}]",+ d.id,+ d.created_at,+ lower,+ upper+ );+ }+ }+ assert_eq!(doc_count, 3, "expected 3 docs in range");+ assert_eq!(chat_count, 4, "chats unaffected");+ assert_eq!(project_count, 4, "projects unaffected");+ Ok(())+}++// document / updatedAt / gt+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_document_updated_at_gt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // fixture has updatedAt == createdAt; cutoff same as createdAt gt test → cccc, dddd, eeee = 3+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T11:30:00Z")?.into();+ let (items, doc_count, _, _) = run_and_count(+ &db,+ doc_ast(DocumentLiteral::UpdatedAt(DateLiteral::GreaterThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Document(d) = item {+ assert!(+ d.updated_at > cutoff,+ "doc {} updated_at {:?} should be > cutoff",+ d.id,+ d.updated_at+ );+ }+ }+ assert_eq!(doc_count, 3, "expected 3 docs with updatedAt after cutoff");+ Ok(())+}++// document / updatedAt / lt+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_document_updated_at_lt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T11:30:00Z")?.into();+ let (items, doc_count, _, _) = run_and_count(+ &db,+ doc_ast(DocumentLiteral::UpdatedAt(DateLiteral::LessThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Document(d) = item {+ assert!(+ d.updated_at < cutoff,+ "doc {} updated_at {:?} should be < cutoff",+ d.id,+ d.updated_at+ );+ }+ }+ assert_eq!(doc_count, 2, "expected 2 docs with updatedAt before cutoff");+ Ok(())+}++// document / updatedAt / AND(gt, lt)+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_document_updated_at_range(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ let lower: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T10:30:00Z")?.into();+ let upper: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-05T13:30:00Z")?.into();+ let ast = EntityFilterAst {+ document_filter: Some(Arc::new(Expr::And(+ Box::new(Expr::Literal(DocumentLiteral::UpdatedAt(+ DateLiteral::GreaterThan(lower),+ ))),+ Box::new(Expr::Literal(DocumentLiteral::UpdatedAt(+ DateLiteral::LessThan(upper),+ ))),+ ))),+ ..mock_empty_ast()+ };+ let (items, doc_count, _, _) = run_and_count(&db, ast).await?;+ for item in &items {+ if let SoupItem::Document(d) = item {+ assert!(+ d.updated_at > lower && d.updated_at < upper,+ "doc {} updated_at {:?} outside range",+ d.id,+ d.updated_at+ );+ }+ }+ assert_eq!(doc_count, 3, "expected 3 docs with updatedAt in range");+ Ok(())+}++// chat / createdAt / lt+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_chat_created_at_lt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // cutoff between b2b2(11:00) and c3c3(12:00) → a1a1, b2b2 = 2 chats+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-06T11:30:00Z")?.into();+ let (items, _, chat_count, _) = run_and_count(+ &db,+ chat_ast(ChatLiteral::CreatedAt(DateLiteral::LessThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Chat(c) = item {+ assert!(+ c.created_at < cutoff,+ "chat {} created_at {:?} should be < cutoff",+ c.id,+ c.created_at+ );+ }+ }+ assert_eq!(+ chat_count, 2,+ "expected 2 chats with createdAt before cutoff"+ );+ Ok(())+}++// chat / createdAt / AND(gt, lt)+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_chat_created_at_range(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // lower after a1a1(10:00), upper before d4d4(13:00) → b2b2, c3c3 = 2 chats+ let lower: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-06T10:30:00Z")?.into();+ let upper: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-06T12:30:00Z")?.into();+ let ast = EntityFilterAst {+ chat_filter: Some(Arc::new(Expr::And(+ Box::new(Expr::Literal(ChatLiteral::CreatedAt(+ DateLiteral::GreaterThan(lower),+ ))),+ Box::new(Expr::Literal(ChatLiteral::CreatedAt(+ DateLiteral::LessThan(upper),+ ))),+ ))),+ ..mock_empty_ast()+ };+ let (items, _, chat_count, _) = run_and_count(&db, ast).await?;+ for item in &items {+ if let SoupItem::Chat(c) = item {+ assert!(+ c.created_at > lower && c.created_at < upper,+ "chat {} created_at {:?} outside range",+ c.id,+ c.created_at+ );+ }+ }+ assert_eq!(chat_count, 2, "expected 2 chats in createdAt range");+ Ok(())+}++// chat / updatedAt / gt+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_chat_updated_at_gt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-06T11:30:00Z")?.into();+ let (items, _, chat_count, _) = run_and_count(+ &db,+ chat_ast(ChatLiteral::UpdatedAt(DateLiteral::GreaterThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Chat(c) = item {+ assert!(+ c.updated_at > cutoff,+ "chat {} updated_at {:?} should be > cutoff",+ c.id,+ c.updated_at+ );+ }+ }+ assert_eq!(+ chat_count, 2,+ "expected 2 chats with updatedAt after cutoff"+ );+ Ok(())+}++// chat / updatedAt / AND(gt, lt)+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_chat_updated_at_range(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ let lower: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-06T10:30:00Z")?.into();+ let upper: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-06T12:30:00Z")?.into();+ let ast = EntityFilterAst {+ chat_filter: Some(Arc::new(Expr::And(+ Box::new(Expr::Literal(ChatLiteral::UpdatedAt(+ DateLiteral::GreaterThan(lower),+ ))),+ Box::new(Expr::Literal(ChatLiteral::UpdatedAt(+ DateLiteral::LessThan(upper),+ ))),+ ))),+ ..mock_empty_ast()+ };+ let (items, _, chat_count, _) = run_and_count(&db, ast).await?;+ for item in &items {+ if let SoupItem::Chat(c) = item {+ assert!(+ c.updated_at > lower && c.updated_at < upper,+ "chat {} updated_at {:?} outside range",+ c.id,+ c.updated_at+ );+ }+ }+ assert_eq!(chat_count, 2, "expected 2 chats with updatedAt in range");+ Ok(())+}++// project / createdAt / lt+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_project_created_at_lt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // cutoff between 2222(Jan-01 11:00) and 3333(Jan-01 12:00) → 1111, 2222 = 2 projects+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-01T11:30:00Z")?.into();+ let (items, _, _, project_count) = run_and_count(+ &db,+ project_ast(ProjectLiteral::CreatedAt(DateLiteral::LessThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Project(p) = item {+ assert!(+ p.created_at < cutoff,+ "project {} created_at {:?} should be < cutoff",+ p.id,+ p.created_at+ );+ }+ }+ assert_eq!(+ project_count, 2,+ "expected 2 projects with createdAt before cutoff"+ );+ Ok(())+}++// project / createdAt / AND(gt, lt)+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_project_created_at_range(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ // lower after 1111(Jan-01 10:00), upper before 4444(Jan-02 10:00) → 2222, 3333 = 2 projects+ let lower: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-01T10:30:00Z")?.into();+ let upper: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-01T12:30:00Z")?.into();+ let ast = EntityFilterAst {+ project_filter: Some(Arc::new(Expr::And(+ Box::new(Expr::Literal(ProjectLiteral::CreatedAt(+ DateLiteral::GreaterThan(lower),+ ))),+ Box::new(Expr::Literal(ProjectLiteral::CreatedAt(+ DateLiteral::LessThan(upper),+ ))),+ ))),+ ..mock_empty_ast()+ };+ let (items, _, _, project_count) = run_and_count(&db, ast).await?;+ for item in &items {+ if let SoupItem::Project(p) = item {+ assert!(+ p.created_at > lower && p.created_at < upper,+ "project {} created_at {:?} outside range",+ p.id,+ p.created_at+ );+ }+ }+ assert_eq!(+ project_count, 2,+ "expected 2 projects with createdAt in range"+ );+ Ok(())+}++// project / updatedAt / gt+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_project_updated_at_gt(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ let cutoff: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-01T11:30:00Z")?.into();+ let (items, _, _, project_count) = run_and_count(+ &db,+ project_ast(ProjectLiteral::UpdatedAt(DateLiteral::GreaterThan(cutoff))),+ )+ .await?;+ for item in &items {+ if let SoupItem::Project(p) = item {+ assert!(+ p.updated_at > cutoff,+ "project {} updated_at {:?} should be > cutoff",+ p.id,+ p.updated_at+ );+ }+ }+ assert_eq!(+ project_count, 2,+ "expected 2 projects with updatedAt after cutoff"+ );+ Ok(())+}++// project / updatedAt / AND(gt, lt)+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_date_filter_project_updated_at_range(db: PgPool) -> anyhow::Result<()> {+ use chrono::DateTime;+ let lower: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-01T10:30:00Z")?.into();+ let upper: chrono::DateTime<chrono::Utc> =+ DateTime::parse_from_rfc3339("2023-01-01T12:30:00Z")?.into();+ let ast = EntityFilterAst {+ project_filter: Some(Arc::new(Expr::And(+ Box::new(Expr::Literal(ProjectLiteral::UpdatedAt(+ DateLiteral::GreaterThan(lower),+ ))),+ Box::new(Expr::Literal(ProjectLiteral::UpdatedAt(+ DateLiteral::LessThan(upper),+ ))),+ ))),+ ..mock_empty_ast()+ };+ let (items, _, _, project_count) = run_and_count(&db, ast).await?;+ for item in &items {+ if let SoupItem::Project(p) = item {+ assert!(+ p.updated_at > lower && p.updated_at < upper,+ "project {} updated_at {:?} outside range",+ p.id,+ p.updated_at+ );+ }+ }+ assert_eq!(+ project_count, 2,+ "expected 2 projects with updatedAt in range"+ );+ Ok(())+}