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(soup): backend group by support [stack/01] (#3105)

dev-rb5acc872303dd
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a1d46895f6..57d09a6cd0 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3789,6 +3789,7 @@ dependencies = [
"model-entity",
"model-error-response",
"model_user",
+ "models_grouping",
"models_pagination",
"non_empty",
"recursion",
@@ -7160,6 +7161,15 @@ dependencies = [
"sqlx",
]
+[[package]]
+name = "models_grouping"
+version = "0.1.0"
+dependencies = [
+ "chrono",
+ "serde",
+ "uuid",
+]
+
[[package]]
name = "models_opensearch"
version = "0.1.0"
@@ -10791,6 +10801,7 @@ dependencies = [
"model-entity",
"model-error-response",
"model_user",
+ "models_grouping",
"models_pagination",
"models_properties",
"models_soup",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 4f21d0eadd..db51ae531c 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -86,6 +86,7 @@ members = [
"model_user",
"models_dcs",
"models_email",
+ "models_grouping",
"models_opensearch",
"models_pagination",
"models_permissions",
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 2f57d2f12c..29e39055c9 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -62,6 +62,7 @@ model-entity = { path = "../model-entity" }
non_empty = { path = "../non_empty", optional = true }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true }
+models_grouping = { path = "../models_grouping" }
models_pagination = { path = "../models_pagination" }
recursion = { workspace = true }
schemars = { workspace = true, optional = true, features = ["uuid1"] }
diff --git a/rust/cloud-storage/models_grouping/Cargo.toml b/rust/cloud-storage/models_grouping/Cargo.toml
new file mode 100644
index 0000000000..daf6cfb389
--- /dev/null
+++ b/rust/cloud-storage/models_grouping/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+edition = "2024"
+name = "models_grouping"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+chrono = { workspace = true }
+serde = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/models_grouping/src/config.rs b/rust/cloud-storage/models_grouping/src/config.rs
new file mode 100644
index 0000000000..c29d1acd40
--- /dev/null
+++ b/rust/cloud-storage/models_grouping/src/config.rs
@@ -0,0 +1,45 @@
+//! Grouping configuration.
+
+use crate::GroupByField;
+use serde::{Deserialize, Serialize};
+
+/// Configuration for a grouped query.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct GroupingConfig {
+ /// The field to group by
+ pub field: GroupByField,
+ /// Filter to a specific group key (for "load more" within a group)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub group_key: Option<String>,
+ /// Max items per group in initial fetch (default: 10)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub per_group_limit: Option<u32>,
+}
+
+impl GroupingConfig {
+ /// Create a new grouping config for the given field.
+ pub fn new(field: GroupByField) -> Self {
+ Self {
+ field,
+ group_key: None,
+ per_group_limit: None,
+ }
+ }
+
+ /// Filter to a specific group.
+ pub fn with_group_key(mut self, key: impl Into<String>) -> Self {
+ self.group_key = Some(key.into());
+ self
+ }
+
+ /// Set per-group limit.
+ pub fn with_limit(mut self, limit: u32) -> Self {
+ self.per_group_limit = Some(limit);
+ self
+ }
+
+ /// Get the effective per-group limit.
+ pub fn effective_limit(&self) -> u32 {
+ self.per_group_limit.unwrap_or(10)
+ }
+}
diff --git a/rust/cloud-storage/models_grouping/src/date_buckets.rs b/rust/cloud-storage/models_grouping/src/date_buckets.rs
new file mode 100644
index 0000000000..de8bab05aa
--- /dev/null
+++ b/rust/cloud-storage/models_grouping/src/date_buckets.rs
@@ -0,0 +1,148 @@
+//! Date bucket logic and SQL helpers.
+
+use chrono::{DateTime, Utc};
+
+/// Date bucket keys.
+pub mod keys {
+ /// Today bucket key
+ pub const TODAY: &str = "today";
+ /// Yesterday bucket key
+ pub const YESTERDAY: &str = "yesterday";
+ /// This week bucket key (2-6 days ago)
+ pub const THIS_WEEK: &str = "this_week";
+ /// Last week bucket key (7-13 days ago)
+ pub const LAST_WEEK: &str = "last_week";
+ /// This month bucket key (14-30 days ago)
+ pub const THIS_MONTH: &str = "this_month";
+ /// Last month bucket key (31-60 days ago)
+ pub const LAST_MONTH: &str = "last_month";
+ /// Older bucket key (61+ days ago)
+ pub const OLDER: &str = "older";
+}
+
+/// Compute the date bucket key for a timestamp.
+pub fn compute_date_bucket(ts: DateTime<Utc>) -> &'static str {
+ let days_ago = (Utc::now().date_naive() - ts.date_naive()).num_days();
+ match days_ago {
+ 0 => keys::TODAY,
+ 1 => keys::YESTERDAY,
+ 2..=6 => keys::THIS_WEEK,
+ 7..=13 => keys::LAST_WEEK,
+ 14..=30 => keys::THIS_MONTH,
+ 31..=60 => keys::LAST_MONTH,
+ _ => keys::OLDER,
+ }
+}
+
+/// Get display order for a date bucket (lower = first).
+pub fn date_bucket_order(key: &str) -> i32 {
+ match key {
+ keys::TODAY => 0,
+ keys::YESTERDAY => 1,
+ keys::THIS_WEEK => 2,
+ keys::LAST_WEEK => 3,
+ keys::THIS_MONTH => 4,
+ keys::LAST_MONTH => 5,
+ _ => 6,
+ }
+}
+
+/// Get human-readable label for a date bucket.
+pub fn date_bucket_label(key: &str) -> &'static str {
+ match key {
+ keys::TODAY => "Today",
+ keys::YESTERDAY => "Yesterday",
+ keys::THIS_WEEK => "This Week",
+ keys::LAST_WEEK => "Last Week",
+ keys::THIS_MONTH => "This Month",
+ keys::LAST_MONTH => "Last Month",
+ _ => "Older",
+ }
+}
+
+/// SQL CASE expression for date bucket key.
+///
+/// Returns a SQL fragment that computes the bucket key from a timestamp column.
+///
+/// # Example
+/// ```
+/// use models_grouping::date_bucket_sql_key;
+/// let sql = date_bucket_sql_key("et.sort_ts");
+/// assert!(sql.contains("'today'"));
+/// ```
+pub fn date_bucket_sql_key(sort_col: &str) -> String {
+ format!(
+ r#"CASE
+ WHEN {sort_col}::date = CURRENT_DATE THEN 'today'
+ WHEN {sort_col}::date = CURRENT_DATE - 1 THEN 'yesterday'
+ WHEN {sort_col} >= CURRENT_DATE - 6 THEN 'this_week'
+ WHEN {sort_col} >= CURRENT_DATE - 13 THEN 'last_week'
+ WHEN {sort_col} >= CURRENT_DATE - 30 THEN 'this_month'
+ WHEN {sort_col} >= CURRENT_DATE - 60 THEN 'last_month'
+ ELSE 'older'
+END"#
+ )
+}
+
+/// SQL CASE expression for date bucket order.
+///
+/// Returns a SQL fragment that computes the display order from a timestamp column.
+pub fn date_bucket_sql_order(sort_col: &str) -> String {
+ format!(
+ r#"CASE
+ WHEN {sort_col}::date = CURRENT_DATE THEN 0
+ WHEN {sort_col}::date = CURRENT_DATE - 1 THEN 1
+ WHEN {sort_col} >= CURRENT_DATE - 6 THEN 2
+ WHEN {sort_col} >= CURRENT_DATE - 13 THEN 3
+ WHEN {sort_col} >= CURRENT_DATE - 30 THEN 4
+ WHEN {sort_col} >= CURRENT_DATE - 60 THEN 5
+ ELSE 6
+END"#
+ )
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use chrono::Duration;
+
+ #[test]
+ fn test_compute_date_bucket_today() {
+ let now = Utc::now();
+ assert_eq!(compute_date_bucket(now), keys::TODAY);
+ }
+
+ #[test]
+ fn test_compute_date_bucket_yesterday() {
+ let yesterday = Utc::now() - Duration::days(1);
+ assert_eq!(compute_date_bucket(yesterday), keys::YESTERDAY);
+ }
+
+ #[test]
+ fn test_compute_date_bucket_this_week() {
+ let days_ago = Utc::now() - Duration::days(4);
+ assert_eq!(compute_date_bucket(days_ago), keys::THIS_WEEK);
+ }
+
+ #[test]
+ fn test_compute_date_bucket_older() {
+ let old = Utc::now() - Duration::days(100);
+ assert_eq!(compute_date_bucket(old), keys::OLDER);
+ }
+
+ #[test]
+ fn test_date_bucket_order() {
+ assert_eq!(date_bucket_order(keys::TODAY), 0);
+ assert_eq!(date_bucket_order(keys::YESTERDAY), 1);
+ assert_eq!(date_bucket_order(keys::OLDER), 6);
+ assert_eq!(date_bucket_order("unknown"), 6);
+ }
+
+ #[test]
+ fn test_date_bucket_sql_key() {
+ let sql = date_bucket_sql_key("et.sort_ts");
+ assert!(sql.contains("'today'"));
+ assert!(sql.contains("'yesterday'"));
+ assert!(sql.contains("et.sort_ts"));
+ }
+}
diff --git a/rust/cloud-storage/models_grouping/src/field.rs b/rust/cloud-storage/models_grouping/src/field.rs
new file mode 100644
index 0000000000..25b1e56a6c
--- /dev/null
+++ b/rust/cloud-storage/models_grouping/src/field.rs
@@ -0,0 +1,32 @@
+//! Group-by field definitions.
+
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Field to group results by.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum GroupByField {
+ /// Smart date buckets: Today, Yesterday, This Week, etc.
+ #[default]
+ Date,
+ /// Group by entity/item type
+ EntityType,
+ /// Group by project association
+ Project,
+ /// Group by a property value (status, priority, custom)
+ Property {
+ /// The property definition UUID
+ property_definition_id: Uuid,
+ /// Optional entity type scope for the property lookup
+ #[serde(skip_serializing_if = "Option::is_none")]
+ entity_type: Option<String>,
+ },
+}
+
+impl GroupByField {
+ /// Returns true if this field requires a property join.
+ pub fn requires_property_join(&self) -> bool {
+ matches!(self, GroupByField::Property { .. })
+ }
+}
diff --git a/rust/cloud-storage/models_grouping/src/lib.rs b/rust/cloud-storage/models_grouping/src/lib.rs
new file mode 100644
index 0000000000..7060ee73d3
--- /dev/null
+++ b/rust/cloud-storage/models_grouping/src/lib.rs
@@ -0,0 +1,18 @@
+#![deny(missing_docs)]
+//! Generic grouping primitives for query results.
+//!
+//! This crate provides types and utilities for grouping items by various fields
+//! (date, entity type, project, custom properties) with support for:
+//! - Per-group limits and pagination
+//! - Group metadata (counts, labels, cursors)
+//! - SQL expression builders for common patterns
+
+mod config;
+mod date_buckets;
+mod field;
+mod meta;
+
+pub use config::*;
+pub use date_buckets::*;
+pub use field::*;
+pub use meta::*;
diff --git a/rust/cloud-storage/models_grouping/src/meta.rs b/rust/cloud-storage/models_grouping/src/meta.rs
new file mode 100644
index 0000000000..af357bd398
--- /dev/null
+++ b/rust/cloud-storage/models_grouping/src/meta.rs
@@ -0,0 +1,45 @@
+//! Group metadata for responses.
+
+use serde::Serialize;
+
+/// Metadata about a group of items in the response.
+#[derive(Debug, Clone, Serialize)]
+#[non_exhaustive]
+pub struct GroupMeta {
+ /// Unique key identifying the group
+ pub key: String,
+ /// Human-readable label
+ pub label: String,
+ /// Display order (lower = first)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub display_order: Option<i32>,
+ /// Total items in this group (across all pages)
+ pub total_count: u32,
+ /// Items from this group in current page
+ pub page_count: u32,
+ /// Index where this group starts in items array
+ pub start_index: u32,
+ /// Cursor to load more from this group
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next_cursor: Option<String>,
+}
+
+impl GroupMeta {
+ /// Create a new group metadata entry.
+ pub fn new(key: impl Into<String>, label: impl Into<String>) -> Self {
+ Self {
+ key: key.into(),
+ label: label.into(),
+ display_order: None,
+ total_count: 0,
+ page_count: 0,
+ start_index: 0,
+ next_cursor: None,
+ }
+ }
+
+ /// Returns true if this group has more items to load.
+ pub fn has_more(&self) -> bool {
+ self.next_cursor.is_some()
+ }
+}
diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.toml
index e188831465..9e059a1b0f 100644
--- a/rust/cloud-storage/soup/Cargo.toml
+++ b/rust/cloud-storage/soup/Cargo.toml
@@ -55,6 +55,7 @@ macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
+models_grouping = { path = "../models_grouping" }
models_pagination = { path = "../models_pagination" }
models_properties = { path = "../models_properties" }
models_soup = { path = "../models_soup" }
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 084ad9f6f1..94deb12acc 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -1,3 +1,10 @@
+mod grouping;
+
+pub use grouping::{
+ GroupMeta, GroupedResponse, build_grouped_response, entity_type_labels,
+ resolve_group_label_and_order,
+};
+
use call::domain::models::GetCallRecordsRequest;
use comms::domain::models::GetChannelsRequest;
use email::domain::models::{GetEmailsRequest, PreviewView};
@@ -8,6 +15,7 @@ use item_filters::{
};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
+use models_grouping::GroupingConfig;
use models_pagination::{
Cursor, CursorVal, CursorWithValAndFilter, Frecency, FrecencyValue, Identify, Query,
SimpleSortMethod, SortOn,
@@ -34,6 +42,19 @@ pub struct SimpleSortRequest<'a> {
pub(crate) user_id: MacroUserIdStr<'a>,
}
+/// Parameters for grouped soup queries.
+#[derive(Debug)]
+pub struct GroupedSortRequest<'a> {
+ /// the limit of the number of items to return
+ pub limit: u16,
+ /// the cursor/query
+ pub cursor: Query<Uuid, SimpleSortMethod, EntityFilterAst>,
+ /// the id of the user
+ pub user_id: MacroUserIdStr<'a>,
+ /// grouping configuration
+ pub grouping: GroupingConfig,
+}
+
#[derive(Debug)]
pub(crate) enum SimpleSortQuery {
/// we dont have anything to filter out
@@ -369,6 +390,34 @@ impl SortOn<SimpleSortMethod> for FrecencySoupItem {
}
}
+/// A soup request with optional grouping configuration.
+#[derive(Debug)]
+pub struct GroupedSoupRequest<T> {
+ /// Base soup request parameters
+ pub base: SoupRequest<T>,
+ /// Optional grouping configuration
+ pub grouping: Option<GroupingConfig>,
+}
+
+/// A soup item with group metadata attached (returned from grouped queries).
+#[derive(Debug)]
+pub struct GroupedSoupItem {
+ /// The soup item
+ pub item: SoupItem,
+ /// The frecency score (if available)
+ pub frecency_score: Option<AggregateFrecency>,
+ /// Which group this item belongs to
+ pub group_key: String,
+ /// Total items in this group (computed via window function)
+ pub group_total_count: u32,
+ /// This item's position within the group (1-indexed)
+ pub row_in_group: u32,
+ /// Label for this group (from property_options or computed)
+ pub group_label: Option<String>,
+ /// Display order for this group
+ pub group_display_order: Option<i32>,
+}
+
#[derive(Debug, Error)]
pub enum SoupErr {
#[error(transparent)]
diff --git a/rust/cloud-storage/soup/src/domain/models/grouping.rs b/rust/cloud-storage/soup/src/domain/models/grouping.rs
new file mode 100644
index 0000000000..89d7d211c7
--- /dev/null
+++ b/rust/cloud-storage/soup/src/domain/models/grouping.rs
@@ -0,0 +1,198 @@
+//! Grouping utilities for soup queries.
+
+use super::FrecencySoupItem;
+use item_filters::ast::EntityFilterAst;
+use models_grouping::{GroupByField, date_bucket_label, date_bucket_order};
+use models_pagination::{
+ Base64Str, CursorVal, CursorWithValAndFilter, Identify, SimpleSortMethod, SortOn,
+};
+use models_soup::item::SoupItem;
+use serde::Serialize;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+/// Resolve label and display order for a group key based on the grouping field.
+pub fn resolve_group_label_and_order(key: &str, group_by: &GroupByField) -> (String, Option<i32>) {
+ match group_by {
+ GroupByField::Date => (
+ date_bucket_label(key).to_string(),
+ Some(date_bucket_order(key)),
+ ),
+ GroupByField::EntityType => (
+ entity_type_labels::label(key).to_string(),
+ Some(entity_type_labels::display_order(key)),
+ ),
+ GroupByField::Project if key.is_empty() => ("No Project".to_string(), Some(i32::MAX)),
+ GroupByField::Property { .. } if key.is_empty() => ("Not Set".to_string(), Some(i32::MAX)),
+ _ => (key.to_string(), None),
+ }
+}
+
+/// Metadata about a group of items.
+#[derive(Debug, Clone, Serialize)]
+pub struct GroupMeta {
+ /// Group key
+ pub key: String,
+ /// Human-readable label for the group
+ pub label: String,
+ /// Display order for sorting groups (lower = first)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub display_order: Option<i32>,
+ /// Total count of items in this group across all pages
+ pub total_count: u32,
+ /// Number of items from this group in the current page
+ pub page_count: u32,
+ /// Index in the items array where this group starts (current page)
+ pub start_index: u32,
+ /// Cursor to load more items specifically from this group
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next_cursor: Option<String>,
+}
+
+/// Result of building a grouped response.
+#[derive(Debug)]
+pub struct GroupedResponse {
+ /// Items in this page with frecency scores.
+ pub items: Vec<FrecencySoupItem>,
+ /// Group metadata for each group.
+ pub groups: Vec<GroupMeta>,
+ /// Page-level cursor for loading more items.
+ pub page_cursor: Option<String>,
+}
+
+/// Build a grouped response from grouped soup items.
+pub fn build_grouped_response(
+ items: Vec<super::GroupedSoupItem>,
+ group_by: &GroupByField,
+ sort_method: SimpleSortMethod,
+ requested_group_key: Option<String>,
+ filters: EntityFilterAst,
+) -> GroupedResponse {
+ struct GroupData {
+ total_count: u32,
+ page_count: u32,
+ start_index: u32,
+ last_item_id: Option<Uuid>,
+ last_cursor_val: Option<CursorVal<SimpleSortMethod>>,
+ label: Option<String>,
+ display_order: Option<i32>,
+ }
+
+ let mut group_stats: HashMap<String, GroupData> = HashMap::new();
+ let mut result_items = Vec::with_capacity(items.len());
+ let mut get_cursor_val = SoupItem::sort_on(sort_method);
+
+ for (idx, grouped_item) in items.into_iter().enumerate() {
+ let key = grouped_item.group_key.clone();
+ let item_id = grouped_item.item.id();
+ let cursor_val = get_cursor_val(&grouped_item.item);
+
+ let entry = group_stats.entry(key.clone()).or_insert_with(|| {
+ let (label, display_order) =
+ match (&grouped_item.group_label, grouped_item.group_display_order) {
+ (Some(l), d) => (l.clone(), d),
+ (None, _) => resolve_group_label_and_order(&key, group_by),
+ };
+ GroupData {
+ total_count: grouped_item.group_total_count,
+ page_count: 0,
+ start_index: idx as u32,
+ last_item_id: None,
+ last_cursor_val: None,
+ label: Some(label),
+ display_order,
+ }
+ });
+ entry.page_count += 1;
+ entry.last_item_id = Some(item_id);
+ entry.last_cursor_val = Some(cursor_val);
+
+ result_items.push(FrecencySoupItem {
+ item: grouped_item.item,
+ frecency_score: grouped_item.frecency_score,
+ });
+ }
+
+ let mut groups: Vec<GroupMeta> = group_stats
+ .into_iter()
+ .map(|(key, data)| {
+ let has_more = data.page_count < data.total_count;
+ let next_cursor = if has_more {
+ data.last_item_id
+ .zip(data.last_cursor_val)
+ .map(|(id, val)| {
+ let cursor: CursorWithValAndFilter<
+ Uuid,
+ SimpleSortMethod,
+ EntityFilterAst,
+ > = CursorWithValAndFilter {
+ id,
+ limit: data.page_count as usize,
+ val,
+ filter: filters.clone(),
+ };
+ Base64Str::encode_json(cursor).type_erase()
+ })
+ } else {
+ None
+ };
+
+ GroupMeta {
+ key,
+ label: data.label.unwrap_or_default(),
+ display_order: data.display_order,
+ total_count: data.total_count,
+ page_count: data.page_count,
+ start_index: data.start_index,
+ next_cursor,
+ }
+ })
+ .collect();
+
+ groups.sort_by(|a, b| {
+ a.display_order
+ .unwrap_or(i32::MAX)
+ .cmp(&b.display_order.unwrap_or(i32::MAX))
+ });
+
+ let page_cursor = if requested_group_key.is_some() {
+ groups.first().and_then(|g| g.next_cursor.clone())
+ } else {
+ None
+ };
+
+ GroupedResponse {
+ items: result_items,
+ groups,
+ page_cursor,
+ }
+}
+
+/// Entity type labels for grouping.
+pub mod entity_type_labels {
+ /// Get human-readable label for an entity type key.
+ pub fn label(key: &str) -> &'static str {
+ match key {
+ "document" => "Documents",
+ "email" => "Emails",
+ "channel" => "Messages",
+ "chat" => "Chats",
+ "project" => "Projects",
+ "call" => "Calls",
+ _ => "Other",
+ }
+ }
+
+ /// Get display order for an entity type key.
+ pub fn display_order(key: &str) -> i32 {
+ match key {
+ "document" => 0,
+ "email" => 1,
+ "channel" => 2,
+ "chat" => 3,
+ "project" => 4,
+ "call" => 5,
+ _ => 6,
+ }
+ }
+}
diff --git a/rust/cloud-storage/soup/src/domain/ports.rs b/rust/cloud-storage/soup/src/domain/ports.rs
index e13631fc63..d0ef12453c 100644
--- a/rust/cloud-storage/soup/src/domain/ports.rs
+++ b/rust/cloud-storage/soup/src/domain/ports.rs
@@ -1,5 +1,6 @@
use crate::domain::models::{
- AdvancedSortParams, FrecencySoupItem, IntoSoupReqAst, SimpleSortRequest, SoupErr, SoupRequest,
+ AdvancedSortParams, FrecencySoupItem, GroupedSortRequest, GroupedSoupItem, IntoSoupReqAst,
+ SimpleSortRequest, SoupErr, SoupRequest,
};
use either::Either;
use models_pagination::{Frecency, PaginatedCursor, SimpleSortMethod};
@@ -34,6 +35,12 @@ pub trait SoupRepo: Send + Sync + 'static {
&self,
items: &mut [SoupItem],
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Fetches expanded soup items with group metadata.
+ fn expanded_grouped_cursor_soup<'a>(
+ &self,
+ req: GroupedSortRequest<'a>,
+ ) -> impl Future<Output = Result<Vec<GroupedSoupItem>, Self::Err>> + Send;
}
/// type alias which represents the posible outputs of soup
@@ -55,4 +62,9 @@ pub trait SoupService: Send + Sync + 'static {
where
SoupRequest<T>: IntoSoupReqAst,
T: Clone + Serialize + Send;
+
+ fn get_user_soup_grouped(
+ &self,
+ req: GroupedSortRequest<'_>,
+ ) -> impl Future<Output = Result<Vec<GroupedSoupItem>, SoupErr>> + Send;
}
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index b859517aac..320a70c50f 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -1,7 +1,8 @@
use crate::domain::{
models::{
- AdvancedSortParams, FrecencyQueryInner, FrecencySoupItem, IntoSoupReqAst, SimpleQueryInner,
- SimpleSortQuery, SimpleSortRequest, SoupErr, SoupQuery, SoupRequest, SoupType,
+ AdvancedSortParams, FrecencyQueryInner, FrecencySoupItem, GroupedSortRequest,
+ GroupedSoupItem, IntoSoupReqAst, SimpleQueryInner, SimpleSortQuery, SimpleSortRequest,
+ SoupErr, SoupQuery, SoupRequest, SoupType,
},
ports::{SoupOutput, SoupRepo, SoupService},
};
@@ -103,6 +104,18 @@ where
}))
}
+ #[tracing::instrument(err, skip(self, req))]
+ async fn handle_grouped_soup_request(
+ &self,
+ req: GroupedSortRequest<'_>,
+ ) -> Result<Vec<GroupedSoupItem>, SoupErr> {
+ self.soup_storage
+ .expanded_grouped_cursor_soup(req)
+ .await
+ .map_err(anyhow::Error::from)
+ .map_err(SoupErr::SoupDbErr)
+ }
+
#[tracing::instrument(skip(self, req))]
async fn handle_soup_by_ids(
&self,
@@ -467,4 +480,12 @@ where
)),
}
}
+
+ #[tracing::instrument(err, skip(self, req))]
+ async fn get_user_soup_grouped(
+ &self,
+ req: GroupedSortRequest<'_>,
+ ) -> Result<Vec<GroupedSoupItem>, SoupErr> {
+ self.handle_grouped_soup_request(req).await
+ }
}
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index f7b1179438..aa53d9c457 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -1,6 +1,7 @@
use crate::domain::models::FrecencySoupItem;
use crate::domain::ports::MockSoupRepo;
use chrono::Days;
+use chrono::{DateTime, Utc};
use comms::domain::models::GetChannelsRequest;
use cool_asserts::assert_matches;
use email::domain::models::{EnrichedEmailThreadPreview, PreviewView};
@@ -17,7 +18,6 @@ use models_pagination::{
use models_soup::document::{SoupDocument, SoupDocumentSubType};
use ordered_float::OrderedFloat;
use rootcause::Report;
-use sqlx::types::chrono::{DateTime, Utc};
use uuid::Uuid;
use super::*;
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index 14e052649e..28ca8bbab4 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -1,7 +1,7 @@
use crate::domain::{
models::{
- FrecencyQueryInner, FrecencySoupItem, IntoSoupReqAst, SimpleQueryInner, SoupErr, SoupQuery,
- SoupRequest, SoupType,
+ FrecencyQueryInner, FrecencySoupItem, GroupMeta, GroupedSortRequest, IntoSoupReqAst,
+ SimpleQueryInner, SoupErr, SoupQuery, SoupRequest, SoupType, build_grouped_response,
},
ports::SoupService,
};
@@ -27,16 +27,22 @@ use filter_ast::{Expr, ExprFrame};
use item_filters::{
EntityFilters,
ast::{
- EntityFilterAst, ExpandErr, LiteralTree, call::CallLiteral, channel::ChannelLiteral,
- chat::ChatLiteral, document::DocumentLiteral, email::EmailLiteral, project::ProjectLiteral,
- properties::PropertiesLiteral,
+ EntityFilterAst, ExpandErr, LiteralTree,
+ call::CallLiteral,
+ channel::ChannelLiteral,
+ chat::ChatLiteral,
+ document::DocumentLiteral,
+ email::EmailLiteral,
+ project::ProjectLiteral,
+ properties::{PropertiesLiteral, PropertyEntityType},
},
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use model_user::axum_extractor::MacroUserExtractor;
+use models_grouping::{GroupByField, GroupingConfig};
use models_pagination::{
- CursorWithValAndFilter, Frecency, PaginatedOpaqueCursor, SimpleSortMethod, SortMethod,
+ Cursor, CursorWithValAndFilter, Frecency, PaginatedOpaqueCursor, SimpleSortMethod, SortMethod,
TypeEraseCursor,
};
use models_soup::item::SoupItem;
@@ -88,12 +94,171 @@ impl SoupApiSort {
}
}
+/// Sort method for grouped queries (frecency not supported).
+#[derive(Debug, Deserialize, utoipa::ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum GroupedSoupSort {
+ ViewedAt,
+ CreatedAt,
+ UpdatedAt,
+ ViewedUpdated,
+}
+
+impl GroupedSoupSort {
+ fn into_simple_sort(self) -> SimpleSortMethod {
+ match self {
+ GroupedSoupSort::ViewedAt => SimpleSortMethod::ViewedAt,
+ GroupedSoupSort::CreatedAt => SimpleSortMethod::CreatedAt,
+ GroupedSoupSort::UpdatedAt => SimpleSortMethod::UpdatedAt,
+ GroupedSoupSort::ViewedUpdated => SimpleSortMethod::ViewedUpdated,
+ }
+ }
+}
+
+/// Parameters for grouped soup queries.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct GroupedParams {
+ /// Field to group results by (required).
+ pub group_by: ApiGroupByField,
+ /// Filter to a specific group key (for "load more in group X").
+ #[serde(default)]
+ pub group_key: Option<String>,
+ /// Sort method. Defaults to viewed_updated.
+ #[serde(default)]
+ pub sort_method: Option<GroupedSoupSort>,
+ /// Limit the number of items returned. Defaults to 20. Max 500.
+ #[serde(default)]
+ pub limit: Option<u16>,
+}
+
+/// Entity type for property lookups (API representation).
+#[derive(Debug, Clone, Copy, Deserialize, Serialize, ToSchema)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum ApiPropertyEntityType {
+ /// Channel entity
+ Channel,
+ /// Chat entity
+ Chat,
+ /// Company entity
+ Company,
+ /// Document entity
+ Document,
+ /// Project entity
+ Project,
+ /// Task entity
+ Task,
+ /// Thread entity
+ Thread,
+ /// User entity
+ User,
+}
+
+impl From<ApiPropertyEntityType> for PropertyEntityType {
+ fn from(api: ApiPropertyEntityType) -> Self {
+ match api {
+ ApiPropertyEntityType::Channel => PropertyEntityType::Channel,
+ ApiPropertyEntityType::Chat => PropertyEntityType::Chat,
+ ApiPropertyEntityType::Company => PropertyEntityType::Company,
+ ApiPropertyEntityType::Document => PropertyEntityType::Document,
+ ApiPropertyEntityType::Project => PropertyEntityType::Project,
+ ApiPropertyEntityType::Task => PropertyEntityType::Task,
+ ApiPropertyEntityType::Thread => PropertyEntityType::Thread,
+ ApiPropertyEntityType::User => PropertyEntityType::User,
+ }
+ }
+}
+
+/// API representation of group-by field.
+#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ApiGroupByField {
+ /// Smart date buckets: Today, Yesterday, This Week, Last Week, This Month, Last Month, Older
+ Date,
+ /// Group by entity type (document, email, channel, etc.)
+ EntityType,
+ /// Group by project
+ Project,
+ /// Group by a property value (e.g., status, priority, or custom properties)
+ #[serde(rename = "property")]
+ Property {
+ /// The property definition UUID to group by
+ property_definition_id: Uuid,
+ /// Optional entity type filter for the property lookup
+ #[serde(skip_serializing_if = "Option::is_none")]
+ entity_type: Option<ApiPropertyEntityType>,
+ },
+}
+
+impl From<ApiGroupByField> for GroupByField {
+ fn from(api: ApiGroupByField) -> Self {
+ match api {
+ ApiGroupByField::Date => GroupByField::Date,
+ ApiGroupByField::EntityType => GroupByField::EntityType,
+ ApiGroupByField::Project => GroupByField::Project,
+ ApiGroupByField::Property {
+ property_definition_id,
+ entity_type,
+ } => GroupByField::Property {
+ property_definition_id,
+ entity_type: entity_type.map(|et| PropertyEntityType::from(et).to_string()),
+ },
+ }
+ }
+}
+
+/// API representation of group metadata.
+#[derive(Debug, Clone, Serialize, ToSchema)]
+pub struct ApiGroupMeta {
+ /// Group key - format depends on group_by field
+ pub key: String,
+ /// Human-readable label for the group
+ pub label: String,
+ /// Display order for sorting groups (lower = first)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub display_order: Option<i32>,
+ /// Total count of items in this group across all pages
+ pub total_count: u32,
+ /// Number of items from this group in the current page
+ pub page_count: u32,
+ /// Index in the items array where this group starts (current page)
+ pub start_index: u32,
+ /// Cursor to load more items specifically from this group
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub next_cursor: Option<String>,
+}
+
+impl From<GroupMeta> for ApiGroupMeta {
+ fn from(meta: GroupMeta) -> Self {
+ Self {
+ key: meta.key,
+ label: meta.label,
+ display_order: meta.display_order,
+ total_count: meta.total_count,
+ page_count: meta.page_count,
+ start_index: meta.start_index,
+ next_cursor: meta.next_cursor,
+ }
+ }
+}
+
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct SoupPage {
items: Vec<SoupApiItem>,
next_cursor: Option<String>,
}
+/// Response for grouped soup queries.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct GroupedSoupPage {
+ /// Items in this page (flat list, ordered by group then sort)
+ pub items: Vec<SoupApiItem>,
+ /// Cursor to load the next page (global pagination)
+ pub next_cursor: Option<String>,
+ /// Group metadata - present when group_by is specified in the request
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub groups: Option<Vec<ApiGroupMeta>>,
+}
+
pub struct SoupRouterState<T, U> {
service: Arc<T>,
email: EmailRouterState<U>,
@@ -182,6 +347,66 @@ where
res.type_erase().map(SoupApiItem::from_frecency_soup_item),
))
}
+
+ async fn handle_grouped(
+ &self,
+ macro_user_id: MacroUserIdStr<'static>,
+ filters: EntityFilterAst,
+ params: GroupedParams,
+ cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, EntityFilterAst>>,
+ ) -> Result<Json<GroupedSoupPage>, SoupHandlerErr> {
+ let limit = params.limit.unwrap_or(20).clamp(20, 500);
+ let sort_method = params
+ .sort_method
+ .map(|s| s.into_simple_sort())
+ .unwrap_or(SimpleSortMethod::ViewedUpdated);
+
+ let group_by_field = GroupByField::from(params.group_by);
+ let grouping = GroupingConfig {
+ field: group_by_field.clone(),
+ group_key: params.group_key.clone(),
+ per_group_limit: None,
+ };
+
+ // Use cursor if provided, otherwise start fresh
+ let query_cursor = match cursor {
+ Some(c) => models_pagination::Query::Cursor(c),
+ None => models_pagination::Query::Sort(sort_method, filters.clone()),
+ };
+
+ let req = GroupedSortRequest {
+ limit,
+ cursor: query_cursor,
+ user_id: macro_user_id,
+ grouping,
+ };
+
+ let items = self.service.get_user_soup_grouped(req).await?;
+
+ let response = build_grouped_response(
+ items,
+ &group_by_field,
+ sort_method,
+ params.group_key,
+ filters,
+ );
+
+ Ok(Json(GroupedSoupPage {
+ items: response
+ .items
+ .into_iter()
+ .map(SoupApiItem::from_frecency_soup_item)
+ .collect(),
+ next_cursor: response.page_cursor,
+ groups: Some(
+ response
+ .groups
+ .into_iter()
+ .map(ApiGroupMeta::from)
+ .collect(),
+ ),
+ }))
+ }
}
pub fn soup_router<T, U, S>(state: SoupRouterState<T, U>) -> Router<S>
@@ -194,6 +419,7 @@ where
.route("/soup", get(get_soup_handler))
.route("/soup", post(post_soup_handler))
.route("/soup/ast", post(post_soup_ast_handler))
+ .route("/soup/ast/grouped", post(post_grouped_soup_ast_handler))
.with_state(state)
}
@@ -435,7 +661,74 @@ where
.await
}
-#[derive(Debug, Serialize, Deserialize, Clone)]
+/// Request body for grouped soup queries with AST filters.
+#[derive(Debug, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PostGroupedSoupAstRequest {
+ /// Filters to apply (AST format)
+ #[serde(default, flatten)]
+ #[schema(value_type = EntityFilterAst)]
+ filters: ApiEntityFilterAst,
+ /// Grouping parameters (required)
+ #[serde(flatten)]
+ params: GroupedParams,
+}
+
+/// Gets the items grouped by the specified field using AST filters
+#[utoipa::path(
+ post,
+ operation_id = "post_items_soup_ast_grouped",
+ path = "/items/soup/ast/grouped",
+ params(
+ ("cursor" = Option<String>, Query, description = "Base64 encoded cursor value."),
+ ),
+ request_body = PostGroupedSoupAstRequest,
+ responses(
+ (status = 200, body=GroupedSoupPage),
+ (status = 500, body=ErrorResponse),
+ )
+)]
+#[tracing::instrument(err, skip_all)]
+pub async fn post_grouped_soup_ast_handler<T, U>(
+ State(service): State<SoupRouterState<T, U>>,
+ Cached(MacroUserExtractor { macro_user_id, .. }): Cached<MacroUserExtractor>,
+ cursor: Option<CursorWithValAndFilter<Uuid, SimpleSortMethod, ApiEntityFilterAst>>,
+ Json(PostGroupedSoupAstRequest { filters, params }): Json<PostGroupedSoupAstRequest>,
+) -> Result<Json<GroupedSoupPage>, SoupHandlerErr>
+where
+ T: SoupService,
+ U: EmailService,
+{
+ let filters = filters
+ .into_entity_ast()
+ .map_err(|_| SoupHandlerErr::Expand)?;
+
+ let simple_cursor = cursor
+ .map(
+ |Cursor {
+ id,
+ limit,
+ val,
+ filter,
+ }| {
+ Ok::<_, SoupHandlerErr>(Cursor {
+ id,
+ limit,
+ val,
+ filter: filter
+ .into_entity_ast()
+ .map_err(|_| SoupHandlerErr::Expand)?,
+ })
+ },
+ )
+ .transpose()?;
+
+ service
+ .handle_grouped(macro_user_id, filters, params, simple_cursor)
+ .await
+}
+
+#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct ApiEntityFilterAst {
/// the filters that should be applied to the document entity
#[serde(default, rename = "df")]
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
index fdac472c94..d3356a649a 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router/tests.rs
@@ -27,8 +27,8 @@ use item_filters::ast::EntityFilterAst;
use crate::{
domain::{
models::{
- FrecencyQueryInner, IntoSoupReqAst, SimpleQueryInner, SoupErr, SoupQuery, SoupRequest,
- SoupType,
+ FrecencyQueryInner, GroupedSortRequest, GroupedSoupItem, IntoSoupReqAst,
+ SimpleQueryInner, SoupErr, SoupQuery, SoupRequest, SoupType,
},
ports::{SoupOutput, SoupService},
},
@@ -101,6 +101,13 @@ impl SoupService for MockSoup {
});
Err(SoupErr::SoupDbErr(anyhow::anyhow!("Not implemented")))
}
+
+ async fn get_user_soup_grouped(
+ &self,
+ _req: GroupedSortRequest<'_>,
+ ) -> Result<Vec<GroupedSoupItem>, SoupErr> {
+ Err(SoupErr::SoupDbErr(anyhow::anyhow!("Not implemented")))
+ }
}
struct MockEmail;
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
index a226f4e17d..2642fcb8cd 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo.rs
@@ -1,9 +1,14 @@
use crate::{
domain::{
- models::{AdvancedSortParams, SimpleSortQuery, SimpleSortRequest},
+ models::{
+ AdvancedSortParams, GroupedSortRequest, GroupedSoupItem, SimpleSortQuery,
+ SimpleSortRequest,
+ },
ports::SoupRepo,
},
- outbound::pg_soup_repo::expanded::dynamic::ExpandedDynamicCursorArgs,
+ outbound::pg_soup_repo::expanded::dynamic::{
+ ExpandedDynamicCursorArgs, GroupedDynamicCursorArgs,
+ },
};
use either::Either;
use models_soup::{SoupProperty, item::SoupItem};
@@ -11,6 +16,7 @@ use readonly_pool::ReadOnlyPool;
use system_properties::SystemPropertyKey;
mod expanded;
+pub mod grouping;
mod unexpanded;
pub struct PgSoupRepo {
@@ -123,6 +129,22 @@ impl SoupRepo for PgSoupRepo {
) -> impl Future<Output = Result<(), Self::Err>> + Send {
populate_properties(&self.pool.0, items)
}
+
+ fn expanded_grouped_cursor_soup<'a>(
+ &self,
+ req: GroupedSortRequest<'a>,
+ ) -> impl Future<Output = Result<Vec<GroupedSoupItem>, Self::Err>> + Send {
+ expanded::dynamic::expanded_dynamic_cursor_soup_grouped(
+ &self.pool.0,
+ GroupedDynamicCursorArgs {
+ user_id: req.user_id,
+ limit: req.limit,
+ cursor: req.cursor,
+ exclude_frecency: false,
+ grouping: req.grouping,
+ },
+ )
+ }
}
#[tracing::instrument(err)]
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 0df7bf8a72..01b3551f25 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
@@ -27,7 +27,12 @@ use sqlx::{PgPool, Postgres, QueryBuilder, Row, postgres::PgRow, prelude::FromRo
use system_properties::{StatusOption, SystemPropertyKey};
use uuid::Uuid;
+use crate::domain::models::GroupedSoupItem;
+use crate::outbound::pg_soup_repo::grouping::{
+ GroupJoinClause, group_join_clause, group_select_expr,
+};
use crate::outbound::pg_soup_repo::{populate_properties, type_err};
+use models_grouping::{GroupByField, GroupingConfig, date_bucket_sql_order};
static PREFIX: &str = r#"
WITH user_source_ids AS (
@@ -111,6 +116,61 @@ static PROJECT_TOP_CLAUSE: &str = r#"
WHERE p."deletedAt" IS NULL
"#;
+// -- Grouped top clauses: include project_id for grouping support --
+
+static GROUPED_DOCUMENT_TOP_CLAUSE: &str = r#"
+ SELECT
+ 'document'::text as item_type,
+ d.id,
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", d."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN d."createdAt"
+ ELSE d."updatedAt"
+ END::timestamptz as sort_ts,
+ d."projectId"::text as project_id
+ FROM AccessibleItems ai
+ INNER JOIN "Document" d ON d.id = ai.item_id AND ai.item_type = 'document'
+ LEFT JOIN document_sub_type dt ON dt.document_id = d.id
+"#;
+
+static GROUPED_CHAT_TOP_CLAUSE: &str = r#"
+ SELECT
+ 'chat'::text as item_type,
+ c.id,
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", c."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN c."createdAt"
+ ELSE c."updatedAt"
+ END::timestamptz as sort_ts,
+ c."projectId"::text as project_id
+ FROM AccessibleItems ai
+ INNER JOIN "Chat" c ON c.id = ai.item_id AND ai.item_type = 'chat'
+ LEFT JOIN "UserHistory" uh ON uh."itemId" = c.id AND uh."itemType" = 'chat' AND uh."userId" = $1
+ WHERE c."deletedAt" IS NULL
+"#;
+
+static GROUPED_PROJECT_TOP_CLAUSE: &str = r#"
+ SELECT
+ 'project'::text as item_type,
+ p.id,
+ CASE $2
+ WHEN 'viewed_updated' THEN COALESCE(uh."updatedAt", p."updatedAt")
+ WHEN 'viewed_at' THEN COALESCE(uh."updatedAt", '1970-01-01 00:00:00+00')
+ WHEN 'created_at' THEN p."createdAt"
+ ELSE p."updatedAt"
+ END::timestamptz as sort_ts,
+ p."parentId"::text as project_id
+ FROM AccessibleItems ai
+ INNER JOIN "Project" p ON p.id = ai.item_id AND ai.item_type = 'project'
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = p.id
+ AND uh."itemType" = 'project'
+ AND uh."userId" = $1
+ WHERE p."deletedAt" IS NULL
+"#;
+
// -- Detail clauses: full columns, joined back from TopItems --
static DOCUMENT_DETAIL_CLAUSE: &str = r#"
@@ -233,6 +293,157 @@ static DETAIL_SUFFIX: &str = r#"
LIMIT $3
"#;
+// -- Grouped detail clauses: join from GroupedItems, include group columns --
+
+static GROUPED_DOCUMENT_DETAIL_CLAUSE: &str = r#"
+ SELECT
+ 'document' as "item_type",
+ d.id as "id",
+ CAST(COALESCE(di.id, db.id) as TEXT) as "document_version_id",
+ d.owner as "user_id",
+ d.name as "name",
+ d."branchedFromId" as "branched_from_id",
+ d."branchedFromVersionId" as "branched_from_version_id",
+ d."documentFamilyId" as "document_family_id",
+ d."fileType" as "file_type",
+ d."createdAt"::timestamptz as "created_at",
+ d."updatedAt"::timestamptz as "updated_at",
+ d."projectId" as "project_id",
+ NULL as "is_persistent",
+ di.sha as "sha",
+ dt.sub_type as "sub_type",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ gi.sort_ts as "sort_ts",
+ CASE
+ WHEN dt.sub_type = 'task'
+ AND ep_status.values->'value' ? $6
+ THEN true
+ WHEN dt.sub_type = 'task'
+ THEN false
+ ELSE NULL
+ END as "is_completed",
+ d."deletedAt"::timestamptz as "deleted_at",
+ gi.group_key as "group_key",
+ gi.group_total_count as "group_total_count",
+ gi.row_in_group as "row_in_group"
+ FROM GroupedItems gi
+ INNER JOIN "Document" d ON d.id = gi.id
+ LEFT JOIN document_sub_type dt ON dt.document_id = d.id
+ LEFT JOIN entity_properties ep_status
+ ON dt.sub_type = 'task'
+ AND ep_status.entity_id = d.id
+ AND ep_status.entity_type = 'TASK'
+ AND ep_status.property_definition_id = $7
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = d.id AND uh."itemType" = 'document' AND uh."userId" = $1
+ LEFT JOIN LATERAL (
+ SELECT b.id
+ FROM "DocumentBom" b
+ WHERE b."documentId" = d.id
+ ORDER BY b."createdAt" DESC
+ LIMIT 1
+ ) db ON true
+ LEFT JOIN LATERAL (
+ SELECT i.id, i.sha
+ FROM "DocumentInstance" i
+ WHERE i."documentId" = d.id
+ ORDER BY i."updatedAt" DESC
+ LIMIT 1
+ ) di ON true
+ WHERE gi.item_type = 'document'
+"#;
+
+static GROUPED_CHAT_DETAIL_CLAUSE: &str = r#"
+ SELECT
+ 'chat' as "item_type",
+ c.id as "id",
+ NULL as "document_version_id",
+ c."userId" as "user_id",
+ c.name as "name",
+ NULL as "branched_from_id",
+ NULL as "branched_from_version_id",
+ NULL as "document_family_id",
+ NULL as "file_type",
+ c."createdAt"::timestamptz as "created_at",
+ c."updatedAt"::timestamptz as "updated_at",
+ c."projectId" as "project_id",
+ c."isPersistent" as "is_persistent",
+ NULL as "sha",
+ NULL as "sub_type",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ gi.sort_ts as "sort_ts",
+ NULL as "is_completed",
+ c."deletedAt"::timestamptz as "deleted_at",
+ gi.group_key as "group_key",
+ gi.group_total_count as "group_total_count",
+ gi.row_in_group as "row_in_group"
+ FROM GroupedItems gi
+ INNER JOIN "Chat" c ON c.id = gi.id
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = c.id AND uh."itemType" = 'chat' AND uh."userId" = $1
+ WHERE gi.item_type = 'chat'
+"#;
+
+static GROUPED_PROJECT_DETAIL_CLAUSE: &str = r#"
+ SELECT
+ 'project' as "item_type",
+ p.id as "id",
+ NULL as "document_version_id",
+ p."userId" as "user_id",
+ p.name as "name",
+ NULL as "branched_from_id",
+ NULL as "branched_from_version_id",
+ NULL as "document_family_id",
+ NULL as "file_type",
+ p."createdAt"::timestamptz as "created_at",
+ p."updatedAt"::timestamptz as "updated_at",
+ p."parentId" as "project_id",
+ NULL as "is_persistent",
+ NULL as "sha",
+ NULL as "sub_type",
+ uh."updatedAt"::timestamptz as "viewed_at",
+ gi.sort_ts as "sort_ts",
+ NULL as "is_completed",
+ p."deletedAt"::timestamptz as "deleted_at",
+ gi.group_key as "group_key",
+ gi.group_total_count as "group_total_count",
+ gi.row_in_group as "row_in_group"
+ FROM GroupedItems gi
+ INNER JOIN "Project" p ON p.id = gi.id
+ LEFT JOIN "UserHistory" uh
+ ON uh."itemId" = p.id
+ AND uh."itemType" = 'project'
+ AND uh."userId" = $1
+ WHERE gi.item_type = 'project'
+"#;
+
+static GROUPED_EMPTY_COMBINED_CLAUSE: &str = r#"
+ SELECT
+ 'document' as "item_type",
+ NULL::text as "id",
+ NULL::text as "document_version_id",
+ NULL::text as "user_id",
+ NULL::text as "name",
+ NULL::text as "branched_from_id",
+ NULL::bigint as "branched_from_version_id",
+ NULL::bigint as "document_family_id",
+ NULL::text as "file_type",
+ NULL::timestamptz as "created_at",
+ NULL::timestamptz as "updated_at",
+ NULL::text as "project_id",
+ NULL::boolean as "is_persistent",
+ NULL::text as "sha",
+ NULL::document_sub_type_value as "sub_type",
+ NULL::timestamptz as "viewed_at",
+ NULL::timestamptz as "sort_ts",
+ NULL::boolean as "is_completed",
+ NULL::timestamptz as "deleted_at",
+ NULL::text as "group_key",
+ NULL::bigint as "group_total_count",
+ NULL::bigint as "row_in_group"
+ WHERE false
+"#;
+
fn build_notification_exists_clause(
entity_id_sql: &str,
entity_type: &str,
@@ -1014,3 +1225,355 @@ pub(crate) async fn expanded_dynamic_cursor_soup(
Ok(items)
}
+
+// ============================================================================
+// Grouped Query Support
+// ============================================================================
+
+/// Arguments for grouped dynamic cursor soup queries.
+#[derive(Debug)]
+pub struct GroupedDynamicCursorArgs<'a> {
+ /// The user for which we are performing the query
+ pub user_id: MacroUserIdStr<'a>,
+ /// The limit of items we can return
+ pub limit: u16,
+ /// The Query that we are attempting to perform
+ pub cursor: Query<Uuid, SimpleSortMethod, EntityFilterAst>,
+ /// Whether or not the query should explicitly remove items that DO have frecency records
+ pub exclude_frecency: bool,
+ /// Grouping configuration
+ pub grouping: GroupingConfig,
+}
+
+/// Group metadata fields extracted from grouped query rows.
+struct GroupFields {
+ group_key: String,
+ group_total_count: i64,
+ row_in_group: i64,
+}
+
+impl GroupFields {
+ fn from_row(row: &PgRow) -> Result<Self, sqlx::Error> {
+ Ok(GroupFields {
+ group_key: row.try_get("group_key")?,
+ group_total_count: row.try_get("group_total_count")?,
+ row_in_group: row.try_get("row_in_group")?,
+ })
+ }
+}
+
+/// Grouped row: reuses SoupRow for item data, adds group metadata.
+struct GroupedSoupRow {
+ item: SoupRow,
+ group: GroupFields,
+}
+
+impl<'a> FromRow<'a, PgRow> for GroupedSoupRow {
+ fn from_row(row: &'a PgRow) -> Result<Self, sqlx::Error> {
+ Ok(GroupedSoupRow {
+ item: SoupRow::from_row(row)?,
+ group: GroupFields::from_row(row)?,
+ })
+ }
+}
+
+/// Per-group limit for initial grouped queries.
+/// Each group will return at most this many items initially.
+const PER_GROUP_LIMIT: i32 = 10;
+
+/// Build the GroupedItems CTE based on the grouping configuration.
+/// Returns the entity_type value to bind at $10, if property grouping with entity_type filter.
+fn build_grouped_items_cte(
+ builder: &mut QueryBuilder<'_, Postgres>,
+ grouping: &GroupingConfig,
+) -> Option<String> {
+ let select_expr = group_select_expr(&grouping.field);
+
+ builder.push("GroupedItems AS (SELECT t.*, (");
+ builder.push(&select_expr);
+ builder.push(") as group_key, COUNT(*) OVER (PARTITION BY ");
+ builder.push(&select_expr);
+ builder.push(") as group_total_count, ROW_NUMBER() OVER (PARTITION BY ");
+ builder.push(&select_expr);
+ builder.push(" ORDER BY t.sort_ts DESC, t.id DESC) as row_in_group FROM TopItems t ");
+
+ let entity_type_bind = if let Some(GroupJoinClause {
+ sql,
+ entity_type_bind,
+ }) = group_join_clause(&grouping.field)
+ {
+ builder.push(&sql);
+ builder.push(" ");
+ entity_type_bind
+ } else {
+ None
+ };
+
+ if grouping.group_key.is_some() {
+ // Single group mode: fetch items for a specific group (for "load more")
+ // Uses $9 parameter for group_key to prevent SQL injection
+ builder.push("WHERE (");
+ builder.push(&select_expr);
+ builder.push(") = $9 ");
+ }
+
+ builder.push("), ");
+
+ // FilteredGroupedItems: apply per-group limit when not fetching a specific group
+ if grouping.group_key.is_none() {
+ builder.push("FilteredGroupedItems AS (SELECT * FROM GroupedItems WHERE row_in_group <= ");
+ builder.push(PER_GROUP_LIMIT.to_string());
+ builder.push("), ");
+ }
+
+ entity_type_bind
+}
+
+/// Build the grouped query with grouping CTE.
+/// Returns (QueryBuilder, entity_type_bind) where entity_type_bind is Some when
+/// property grouping with entity_type filter is used (bind at $10).
+fn build_grouped_query<'a>(
+ filter_ast: &'a EntityFilterAst,
+ exclude_frecency: bool,
+ grouping: &'a GroupingConfig,
+) -> (QueryBuilder<'a, Postgres>, Option<String>) {
+ let mut builder = sqlx::QueryBuilder::new(PREFIX);
+
+ // Determine which entity types to include based on filters (same logic as build_query)
+ let include_documents = !document_filter_is_impossible(filter_ast.document_filter.as_deref())
+ && properties_filter_can_apply_to(
+ filter_ast.properties_filter.as_deref(),
+ &[PropertyEntityType::Document, PropertyEntityType::Task],
+ );
+ let include_chats = !chat_filter_is_impossible(filter_ast.chat_filter.as_deref())
+ && properties_filter_can_apply_to(
+ filter_ast.properties_filter.as_deref(),
+ &[PropertyEntityType::Chat],
+ );
+ let include_projects = !project_filter_is_impossible(filter_ast.project_filter.as_deref())
+ && properties_filter_can_apply_to(
+ filter_ast.properties_filter.as_deref(),
+ &[PropertyEntityType::Project],
+ );
+
+ push_accessible_items_cte(
+ &mut builder,
+ include_documents,
+ include_chats,
+ include_projects,
+ );
+
+ // TopItems CTE: lightweight id + sort_ts + project_id with filters, cursor, and limit
+ builder.push("TopItems AS (");
+ builder.push(
+ "SELECT all_items.item_type, all_items.id, all_items.sort_ts, all_items.project_id FROM (",
+ );
+
+ let mut needs_separator = false;
+
+ if include_documents {
+ push_union_separator(&mut builder, &mut needs_separator);
+ builder.push(GROUPED_DOCUMENT_TOP_CLAUSE);
+ if document_filter_needs_task_property_joins(filter_ast.document_filter.as_deref()) {
+ builder.push(DOCUMENT_TASK_PROPERTY_JOINS);
+ }
+ builder.push(DOCUMENT_TOP_WHERE_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",
+ ));
+ }
+
+ if include_chats {
+ push_union_separator(&mut builder, &mut needs_separator);
+ builder.push(GROUPED_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",
+ ));
+ }
+
+ if include_projects {
+ push_union_separator(&mut builder, &mut needs_separator);
+ builder.push(GROUPED_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",
+ ));
+ }
+
+ // Fallback when all entity types are filtered out
+ if !needs_separator {
+ builder.push(
+ "SELECT 'document'::text as item_type, NULL::text as id, NULL::timestamptz as sort_ts, NULL::text as project_id WHERE false",
+ );
+ }
+
+ builder.push(") all_items ");
+
+ // Frecency exclusion join (only when exclude_frecency is true)
+ if exclude_frecency {
+ builder.push(
+ r#"LEFT JOIN frecency_aggregates fa
+ ON fa.entity_id = all_items.id
+ AND fa.entity_type = all_items.item_type
+ AND fa.user_id = $1
+ WHERE fa.id IS NULL AND ("#,
+ );
+ } else {
+ builder.push("WHERE ");
+ }
+
+ // Cursor condition
+ builder.push(
+ r#"($4::timestamptz IS NULL)
+ OR
+ (all_items.sort_ts, all_items.id::text) < ($4, $5)"#,
+ );
+
+ if exclude_frecency {
+ builder.push(")");
+ }
+
+ // Note: we don't limit TopItems here for grouped queries - limit is applied at the end
+ builder.push(" ORDER BY all_items.sort_ts DESC, all_items.id DESC");
+ builder.push("), ");
+
+ // GroupedItems CTE: adds group metadata (and FilteredGroupedItems if not single-group mode)
+ let entity_type_bind = build_grouped_items_cte(&mut builder, grouping);
+
+ // Combined CTE: full detail joins from GroupedItems (or FilteredGroupedItems)
+ // When fetching a specific group, use GroupedItems directly; otherwise use FilteredGroupedItems
+ let source_table = if grouping.group_key.is_some() {
+ "GroupedItems"
+ } else {
+ "FilteredGroupedItems"
+ };
+
+ builder.push("Combined AS (");
+
+ let mut combined_needs_separator = false;
+ if include_documents {
+ push_union_separator(&mut builder, &mut combined_needs_separator);
+ builder.push(
+ GROUPED_DOCUMENT_DETAIL_CLAUSE
+ .replace("GroupedItems gi", &format!("{} gi", source_table)),
+ );
+ }
+ if include_chats {
+ push_union_separator(&mut builder, &mut combined_needs_separator);
+ builder.push(
+ GROUPED_CHAT_DETAIL_CLAUSE.replace("GroupedItems gi", &format!("{} gi", source_table)),
+ );
+ }
+ if include_projects {
+ push_union_separator(&mut builder, &mut combined_needs_separator);
+ builder.push(
+ GROUPED_PROJECT_DETAIL_CLAUSE
+ .replace("GroupedItems gi", &format!("{} gi", source_table)),
+ );
+ }
+ if !combined_needs_separator {
+ builder.push(GROUPED_EMPTY_COMBINED_CLAUSE);
+ }
+ builder.push(") ");
+
+ // Final SELECT with group-aware ordering
+ builder.push("SELECT * FROM Combined ORDER BY ");
+
+ match &grouping.field {
+ GroupByField::Date => {
+ builder.push(date_bucket_sql_order("\"sort_ts\""));
+ }
+ _ => {
+ builder.push("\"group_key\"");
+ }
+ }
+ builder.push(", \"sort_ts\" DESC, \"id\" DESC LIMIT $3");
+
+ (builder, entity_type_bind)
+}
+
+/// Execute a grouped dynamic cursor soup query.
+#[tracing::instrument(skip(db), err)]
+pub async fn expanded_dynamic_cursor_soup_grouped(
+ db: &PgPool,
+ args: GroupedDynamicCursorArgs<'_>,
+) -> Result<Vec<GroupedSoupItem>, sqlx::Error> {
+ let GroupedDynamicCursorArgs {
+ user_id,
+ limit,
+ cursor,
+ exclude_frecency,
+ grouping,
+ } = args;
+
+ let query_limit = limit as i64;
+ let sort_method_str = cursor.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = cursor.vals();
+ let cursor_id_str = cursor_id.as_ref().map(|u| u.to_string());
+ let status_property_id = SystemPropertyKey::STATUS_UUID;
+ let assignees_property_id = SystemPropertyKey::ASSIGNEES_UUID;
+ let completed_option_id = StatusOption::COMPLETED_UUID.to_string();
+
+ let (mut query_builder, entity_type_bind) =
+ build_grouped_query(cursor.filter(), exclude_frecency, &grouping);
+
+ let mut query = query_builder
+ .build()
+ .bind(user_id.as_ref())
+ .bind(sort_method_str)
+ .bind(query_limit)
+ .bind(cursor_timestamp)
+ .bind(cursor_id_str)
+ .bind(completed_option_id)
+ .bind(status_property_id)
+ .bind(assignees_property_id);
+
+ // Bind group_key as $9 when filtering by specific group
+ if let Some(ref key) = grouping.group_key {
+ query = query.bind(key.clone());
+ }
+
+ // Bind entity_type as $10 when property grouping with entity_type filter
+ if let Some(ref et) = entity_type_bind {
+ query = query.bind(et.clone());
+ }
+
+ let rows: Vec<GroupedSoupRow> = query
+ .try_map(|row| GroupedSoupRow::from_row(&row))
+ .fetch_all(db)
+ .await?;
+
+ // Convert rows to (SoupItem, GroupFields) pairs and unzip
+ let (mut soup_items, groups): (Vec<SoupItem>, Vec<GroupFields>) = rows
+ .into_iter()
+ .map(|row| {
+ let item = row.item.into_soup_item()?;
+ Ok((item, row.group))
+ })
+ .collect::<Result<Vec<_>, sqlx::Error>>()?
+ .into_iter()
+ .unzip();
+
+ populate_properties(db, &mut soup_items).await?;
+
+ let items = soup_items
+ .into_iter()
+ .zip(groups)
+ .map(|(item, group)| GroupedSoupItem {
+ item,
+ frecency_score: None,
+ group_key: group.group_key,
+ group_total_count: group.group_total_count as u32,
+ row_in_group: group.row_in_group as u32,
+ group_label: None,
+ group_display_order: None,
+ })
+ .collect();
+
+ Ok(items)
+}
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping.rs
new file mode 100644
index 0000000000..4c29009670
--- /dev/null
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping.rs
@@ -0,0 +1,72 @@
+//! SQL grouping expressions for soup queries.
+
+use models_grouping::{GroupByField, date_bucket_sql_key, date_bucket_sql_order};
+use std::borrow::Cow;
+
+/// Build the group select expression for a field.
+pub fn group_select_expr(field: &GroupByField) -> Cow<'static, str> {
+ match field {
+ GroupByField::Date => Cow::Owned(date_bucket_sql_key("sort_ts")),
+ GroupByField::EntityType => Cow::Borrowed("item_type"),
+ GroupByField::Project => Cow::Borrowed("COALESCE(project_id::text, '')"),
+ GroupByField::Property { .. } => {
+ // For select options, value is an array of UUIDs like ["uuid1", "uuid2"]
+ // Extract the first element as text
+ Cow::Borrowed("COALESCE(ep_group.values->'value'->>0, '')")
+ }
+ }
+}
+
+/// Build the group order expression for a field.
+pub fn group_order_expr(field: &GroupByField) -> Cow<'static, str> {
+ match field {
+ GroupByField::Date => Cow::Owned(date_bucket_sql_order("sort_ts")),
+ GroupByField::EntityType => Cow::Borrowed("item_type"),
+ GroupByField::Project => Cow::Borrowed("project_id NULLS LAST"),
+ GroupByField::Property { .. } => {
+ // values->'value' is an array of UUID strings, extract first and lookup display_order
+ Cow::Borrowed(
+ "COALESCE((SELECT po.display_order FROM property_options po WHERE po.id::text = (ep_group.values->'value'->>0)), 999999)",
+ )
+ }
+ }
+}
+
+/// Result of building a group JOIN clause with optional bind parameter.
+pub struct GroupJoinClause {
+ /// The SQL JOIN clause (may contain $10 placeholder for entity_type)
+ pub sql: String,
+ /// Entity type value to bind at $10, if present
+ pub entity_type_bind: Option<String>,
+}
+
+/// Build the JOIN clause for property-based grouping.
+/// Returns SQL with $10 placeholder for entity_type when present.
+pub fn group_join_clause(field: &GroupByField) -> Option<GroupJoinClause> {
+ match field {
+ GroupByField::Property {
+ property_definition_id,
+ entity_type,
+ } => {
+ let (entity_type_filter, entity_type_bind) = match entity_type {
+ Some(et) => (
+ "AND ep_group.entity_type = $10".to_string(),
+ Some(et.clone()),
+ ),
+ None => (String::new(), None),
+ };
+
+ Some(GroupJoinClause {
+ sql: format!(
+ "LEFT JOIN entity_properties ep_group ON ep_group.entity_id = t.id::text AND ep_group.property_definition_id = '{}' {}",
+ property_definition_id, entity_type_filter
+ ),
+ entity_type_bind,
+ })
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping/test.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping/test.rs
new file mode 100644
index 0000000000..4098fe779f
--- /dev/null
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/grouping/test.rs
@@ -0,0 +1,218 @@
+use super::*;
+use crate::outbound::pg_soup_repo::expanded::dynamic::{
+ GroupedDynamicCursorArgs, expanded_dynamic_cursor_soup_grouped,
+};
+use item_filters::ast::EntityFilterAst;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use models_grouping::date_bucket_sql_key;
+use models_grouping::{GroupingConfig, date_bucket_order};
+use models_pagination::{Query, SimpleSortMethod};
+use sqlx::{Pool, Postgres};
+
+#[test]
+fn date_bucket_select_contains_all_keys() {
+ let expr = date_bucket_sql_key("sort_ts");
+ assert!(expr.contains("'today'"));
+ assert!(expr.contains("'yesterday'"));
+ assert!(expr.contains("'this_week'"));
+ assert!(expr.contains("'last_week'"));
+ assert!(expr.contains("'this_month'"));
+ assert!(expr.contains("'last_month'"));
+ assert!(expr.contains("'older'"));
+}
+
+#[test]
+fn date_bucket_order_matches_display_order() {
+ assert_eq!(date_bucket_order("today"), 0);
+ assert_eq!(date_bucket_order("yesterday"), 1);
+ assert_eq!(date_bucket_order("this_week"), 2);
+ assert_eq!(date_bucket_order("older"), 6);
+ assert_eq!(date_bucket_order("unknown"), 6);
+}
+
+#[test]
+fn entity_type_expr() {
+ let expr = group_select_expr(&GroupByField::EntityType);
+ assert_eq!(&*expr, "item_type");
+}
+
+#[test]
+fn project_expr() {
+ let expr = group_select_expr(&GroupByField::Project);
+ assert!(expr.contains("project_id"));
+ assert!(expr.contains("COALESCE"));
+}
+
+#[test]
+fn property_join_includes_definition_id() {
+ let field = GroupByField::Property {
+ property_definition_id: uuid::Uuid::nil(),
+ entity_type: None,
+ };
+ let join = group_join_clause(&field).unwrap();
+ assert!(join.sql.contains("ep_group"));
+ assert!(join.sql.contains(&uuid::Uuid::nil().to_string()));
+}
+
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("mixed_items_expanded")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_grouped_by_entity_type(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let grouping = GroupingConfig {
+ field: GroupByField::EntityType,
+ group_key: None,
+ per_group_limit: None,
+ };
+
+ let items = expanded_dynamic_cursor_soup_grouped(
+ &pool,
+ GroupedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 50,
+ cursor: Query::Sort(
+ SimpleSortMethod::ViewedUpdated,
+ EntityFilterAst::mock_empty(),
+ ),
+ exclude_frecency: false,
+ grouping,
+ },
+ )
+ .await?;
+
+ assert!(!items.is_empty(), "Should return some items");
+
+ // Check that items have group keys
+ for item in &items {
+ assert!(
+ ["document", "chat", "project"].contains(&item.group_key.as_str()),
+ "Group key should be a valid entity type, got: {}",
+ item.group_key
+ );
+ }
+
+ // Check that group_total_count is populated
+ for item in &items {
+ assert!(
+ item.group_total_count > 0,
+ "group_total_count should be > 0"
+ );
+ }
+
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("mixed_items_expanded")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_grouped_by_project(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let grouping = GroupingConfig {
+ field: GroupByField::Project,
+ group_key: None,
+ per_group_limit: None,
+ };
+
+ let items = expanded_dynamic_cursor_soup_grouped(
+ &pool,
+ GroupedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 50,
+ cursor: Query::Sort(
+ SimpleSortMethod::ViewedUpdated,
+ EntityFilterAst::mock_empty(),
+ ),
+ exclude_frecency: false,
+ grouping,
+ },
+ )
+ .await?;
+
+ assert!(!items.is_empty(), "Should return some items");
+
+ // Group keys should be UUIDs or empty string (for unassigned)
+ for item in &items {
+ if !item.group_key.is_empty() {
+ uuid::Uuid::parse_str(&item.group_key)
+ .expect("Non-empty group_key should be a valid UUID");
+ }
+ }
+
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(
+ path = "../../../../../macro_db_client/fixtures",
+ scripts("mixed_items_expanded")
+ ),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn test_grouped_single_group_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ // First, get all items grouped by entity type
+ let all_items = expanded_dynamic_cursor_soup_grouped(
+ &pool,
+ GroupedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 50,
+ cursor: Query::Sort(
+ SimpleSortMethod::ViewedUpdated,
+ EntityFilterAst::mock_empty(),
+ ),
+ exclude_frecency: false,
+ grouping: GroupingConfig {
+ field: GroupByField::EntityType,
+ group_key: None,
+ per_group_limit: None,
+ },
+ },
+ )
+ .await?;
+
+ // Find a group key that has items
+ let target_group_key = all_items.first().map(|i| i.group_key.clone());
+ let Some(group_key) = target_group_key else {
+ return Ok(()); // No items to test with
+ };
+
+ // Now fetch only that group
+ let filtered_items = expanded_dynamic_cursor_soup_grouped(
+ &pool,
+ GroupedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 50,
+ cursor: Query::Sort(
+ SimpleSortMethod::ViewedUpdated,
+ EntityFilterAst::mock_empty(),
+ ),
+ exclude_frecency: false,
+ grouping: GroupingConfig {
+ field: GroupByField::EntityType,
+ group_key: Some(group_key.clone()),
+ per_group_limit: None,
+ },
+ },
+ )
+ .await?;
+
+ // All returned items should have the same group key
+ for item in &filtered_items {
+ assert_eq!(
+ item.group_key, group_key,
+ "All items should belong to the filtered group"
+ );
+ }
+
+ Ok(())
+}