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(crm): expose pipeline entries on soup companies and contacts (#7857)
teo8b60a184dc6f
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 4750dd4f19..6d05bb360f 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -3597,6 +3597,7 @@"crates/graphql_calendar","crates/graphql_channel","crates/graphql_common",+ "crates/graphql_crm","crates/graphql_email","crates/graphql_entity_mutation","crates/graphql_favorite",@@ -4811,6 +4812,7 @@"crates/graphql_calendar","crates/graphql_channel","crates/graphql_common",+ "crates/graphql_crm","crates/graphql_email","crates/graphql_entity_mutation","crates/graphql_favorite",@@ -6917,6 +6919,88 @@"crates/remote_env_var","crates/workspace-hack"],+ "graphql_crm": [+ "crates/activity",+ "crates/agent",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/bot_id",+ "crates/bot_token",+ "crates/broadcast",+ "crates/call",+ "crates/channel_sender",+ "crates/channels",+ "crates/connection",+ "crates/connection_gateway_client",+ "crates/connection_gateway_models",+ "crates/contacts",+ "crates/cowlike",+ "crates/crm",+ "crates/database_env_vars",+ "crates/database_sql",+ "crates/databases",+ "crates/document_sub_type",+ "crates/entity_access",+ "crates/entity_access_db_utils",+ "crates/entity_mutation",+ "crates/filter_ast",+ "crates/frecency",+ "crates/genai_telemetry",+ "crates/graphql_common",+ "crates/graphql_crm",+ "crates/graphql_properties",+ "crates/harness_id",+ "crates/harness_token",+ "crates/initiative",+ "crates/invite_email",+ "crates/ip_extractor",+ "crates/item_filters",+ "crates/kafka_util",+ "crates/last_online_tracker",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_aws_config",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_event_broker",+ "crates/macro_event_topics",+ "crates/macro_service_urls",+ "crates/macro_tower_layers",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/maybe_send",+ "crates/mention_utils",+ "crates/messages",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_notifications",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_databases",+ "crates/models_entity_access_management",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/models_properties",+ "crates/models_sfs",+ "crates/non_empty",+ "crates/notification",+ "crates/notification_state",+ "crates/prompt",+ "crates/properties",+ "crates/rate_limit",+ "crates/remote_env_var",+ "crates/share_permission_db_utils",+ "crates/sqs_worker",+ "crates/static_file_service_client",+ "crates/system_properties",+ "crates/unfurl",+ "crates/workspace-hack"+ ],"graphql_email": ["crates/activity","crates/agent",diff --git a/.sqlx/query-d7da40a043996376a51fa2fc49c7dc2486762d4a6c7fc1ddb35c5bfe6b1cdd1e.json b/.sqlx/query-d7da40a043996376a51fa2fc49c7dc2486762d4a6c7fc1ddb35c5bfe6b1cdd1e.jsonnew file mode 100644index 0000000000..04270568d4--- /dev/null+++ b/.sqlx/query-d7da40a043996376a51fa2fc49c7dc2486762d4a6c7fc1ddb35c5bfe6b1cdd1e.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT p.id AS \"pipeline_id!\", r.id AS \"row_id!\",\n reference.value ->> 'entity_id' AS \"record_id!\"\n FROM crm_pipeline_entities p\n JOIN database_columns c ON c.id = p.primary_column_id\n JOIN entity_properties ep\n ON ep.property_definition_id = c.property_definition_id\n AND ep.entity_type = 'DATABASE_ROW'\n JOIN database_rows r ON r.id::text = ep.entity_id AND r.table_id = p.table_id\n CROSS JOIN LATERAL jsonb_array_elements(ep.values -> 'value') AS reference(value)\n WHERE p.id = ANY($1) AND p.trashed_at IS NULL\n AND reference.value ->> 'entity_id' = ANY($2)\n ORDER BY p.id, r.position, r.id",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "pipeline_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "row_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "record_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false,+ null+ ]+ },+ "hash": "d7da40a043996376a51fa2fc49c7dc2486762d4a6c7fc1ddb35c5bfe6b1cdd1e"+}diff --git a/Cargo.lock b/Cargo.lockindex 66c1128337..7086450b5c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4486,6 +4486,8 @@ dependencies = ["bots","calendar_events","chrono",+ "crm",+ "databases","email","entity_access","entity_mutation",@@ -4494,6 +4496,7 @@ dependencies = ["graphql_calendar","graphql_channel","graphql_common",+ "graphql_crm","graphql_email","graphql_entity_mutation","graphql_favorite",@@ -6277,6 +6280,7 @@ dependencies = ["github","github_pull_requests","graphql_calendar",+ "graphql_crm","graphql_initiative","graphql_scheduled_action","graphql_soup",@@ -8623,6 +8627,27 @@ dependencies = ["workspace-hack",]+[[package]]+name = "graphql_crm"+version = "0.1.0"+dependencies = [+ "async-graphql",+ "chrono",+ "crm",+ "databases",+ "entity_access",+ "graphql_common",+ "graphql_properties",+ "macro_user_id",+ "models_databases",+ "models_properties",+ "serde_json",+ "tokio",+ "tracing",+ "uuid",+ "workspace-hack",+]+[[package]]name = "graphql_email"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 0d270c72b3..57f128d49f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -65,6 +65,7 @@ members = ["crates/graphql_email","crates/graphql_entity_mutation","crates/graphql_favorite",+ "crates/graphql_crm","crates/graphql_initiative","crates/graphql_notification","crates/graphql_permission",diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.tomlindex e2c0c8394b..6743f18742 100644--- a/crates/complete_graph/Cargo.toml+++ b/crates/complete_graph/Cargo.toml@@ -28,6 +28,7 @@ graphql_activity = { path = "../graphql_activity" }graphql_calendar = { path = "../graphql_calendar" }graphql_channel = { path = "../graphql_channel" }graphql_common = { path = "../graphql_common" }+graphql_crm = { path = "../graphql_crm" }graphql_email = { path = "../graphql_email" }graphql_entity_mutation = { path = "../graphql_entity_mutation" }graphql_favorite = { path = "../graphql_favorite" }@@ -57,6 +58,8 @@ uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+crm = { path = "../crm", default-features = false, features = ["ports"] }+databases = { path = "../databases", default-features = false, features = ["ports"] }activity = { path = "../activity", default-features = false, features = ["realtime"] }work_feed = { path = "../work_feed" }agent_runtime_protocol = { path = "../agent_runtime_protocol" }diff --git a/crates/complete_graph/src/edges.rs b/crates/complete_graph/src/edges.rsindex ad5d7f8559..f1b77890b2 100644--- a/crates/complete_graph/src/edges.rs+++ b/crates/complete_graph/src/edges.rs@@ -13,6 +13,7 @@ use graphql_activity::{ActivityEdgeKey, GraphqlActivityEvent, SoupActivityEdgeReader, load_entity_activity,parse_activity_edge_limit,};+use graphql_crm::{CrmRecord, GraphqlCrmPipelineEntry, load_pipeline_entries};use graphql_email::{EmailContentKey, GraphqlSoupEmailMessage, SoupEmailEdgeReader,email_message_selection_requires_full_payload, load_email_messages,@@ -77,6 +78,7 @@ wheretype EmailThreadEdges = SoupEmailThreadEdges<ER>;type AgentSessionEdges = SoupAgentSessionEdges;type InitiativeEdges = SoupInitiativeEdges;+ type CrmRecordEdges = SoupCrmRecordEdges;fn from_entity(entity: model_entity::Entity<'static>) -> Self {Self {@@ -127,6 +129,17 @@ whereSoupInitiativeEdges { initiative_id }}+ fn crm_record_edges(record: model_entity::Entity<'static>) -> Self::CrmRecordEdges {+ let id = record.entity_id.parse().ok();+ SoupCrmRecordEdges {+ record: match record.entity_type {+ model_entity::EntityType::CrmCompany => id.map(CrmRecord::Company),+ model_entity::EntityType::CrmContact => id.map(CrmRecord::Contact),+ _ => None,+ },+ }+ }+fn agent_session_edges(session_id: Uuid, bot_id: Uuid) -> Self::AgentSessionEdges {SoupAgentSessionEdges {session_id: AgentSessionId::new_from_uuid(session_id),@@ -695,5 +708,27 @@ impl SoupInitiativeEdges {}}+/// CRM fields composed onto Soup company and contact entities.+#[derive(Clone)]+pub struct SoupCrmRecordEdges {+ /// The company or contact, when its identity parses.+ record: Option<CrmRecord>,+}++#[Object]+impl SoupCrmRecordEdges {+ /// Rows of the viewer's live pipelines that reference this record, grouped+ /// by pipeline in each one's row order.+ async fn pipeline_entries(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlCrmPipelineEntry>> {+ match self.record {+ Some(record) => load_pipeline_entries(ctx, record).await,+ None => Ok(Vec::new()),+ }+ }+}+#[cfg(test)]mod test;diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex d54d0de048..7993cac3b0 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -45,6 +45,7 @@ use uuid::Uuid;use super::*;mod calendar;+mod crm_record;mod database_activity;mod database_row;mod email_archive;diff --git a/crates/complete_graph/src/schema/test/crm_record.rs b/crates/complete_graph/src/schema/test/crm_record.rsnew file mode 100644index 0000000000..4d9a167a7b--- /dev/null+++ b/crates/complete_graph/src/schema/test/crm_record.rs@@ -0,0 +1,158 @@+use ::crm::domain::{auth::CrmTeamReceipt, pipelines::*};+use databases::domain::{+ models::{AppliedOps, OpBatch, RowId, TableDetail},+ storage::{StorageRows, StorageRowsQuery},+};+use entity_access::domain::models::{+ EditAccessLevel, MemberTeamRole, OwnerAccessLevel, ViewAccessLevel,+};+use models_soup::crm_company::SoupCrmCompany;++use super::*;++/// Records the records it is asked about; every other use case is out of scope.+#[derive(Default)]+struct RecordingPipelines {+ asked: Mutex<Vec<(PipelineRecordType, Vec<Uuid>)>>,+}++impl PipelineService for RecordingPipelines {+ async fn create(+ &self,+ _: CrmTeamReceipt<MemberTeamRole>,+ _: CreatePipeline,+ ) -> Result<AccessiblePipeline, PipelineError> {+ unimplemented!()+ }+ async fn list(+ &self,+ _: CrmTeamReceipt<MemberTeamRole>,+ ) -> Result<Vec<AccessiblePipeline>, PipelineError> {+ unimplemented!()+ }+ async fn entries(+ &self,+ _: &MacroUserIdStr<'static>,+ record_type: PipelineRecordType,+ records: &[Uuid],+ ) -> Result<Vec<PipelineEntry>, PipelineError> {+ self.asked+ .lock()+ .unwrap()+ .push((record_type, records.to_vec()));+ Ok(Vec::new())+ }+ async fn get(+ &self,+ _: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<AccessiblePipeline, PipelineError> {+ unimplemented!()+ }+ async fn table(+ &self,+ _: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<TableDetail, PipelineError> {+ unimplemented!()+ }+ async fn rows(+ &self,+ _: EntityAccessReceipt<ViewAccessLevel>,+ _: Option<RowId>,+ ) -> Result<StorageRows, PipelineError> {+ unimplemented!()+ }+ async fn query_rows(+ &self,+ _: EntityAccessReceipt<ViewAccessLevel>,+ _: StorageRowsQuery,+ ) -> Result<StorageRows, PipelineError> {+ unimplemented!()+ }+ async fn apply_ops(+ &self,+ _: EntityAccessReceipt<EditAccessLevel>,+ _: OpBatch,+ ) -> Result<AppliedOps, PipelineError> {+ unimplemented!()+ }+ async fn rename(+ &self,+ _: EntityAccessReceipt<EditAccessLevel>,+ _: String,+ ) -> Result<(), PipelineError> {+ unimplemented!()+ }+ async fn share(+ &self,+ _: EntityAccessReceipt<OwnerAccessLevel>,+ _: PipelineSharing,+ ) -> Result<(), PipelineError> {+ unimplemented!()+ }+ async fn set_trashed(+ &self,+ _: EntityAccessReceipt<OwnerAccessLevel>,+ _: bool,+ ) -> Result<(), PipelineError> {+ unimplemented!()+ }+}++fn soup_crm_company(id: Uuid) -> SoupItem<()> {+ SoupItem::CrmCompany(SoupCrmCompany {+ id,+ team_id: Uuid::from_u128(7),+ name: Some("Acme".to_string()),+ description: Some("Builds anvils.".to_string()),+ email_sync: true,+ hidden: false,+ created_at: Default::default(),+ updated_at: Default::default(),+ viewed_at: None,+ domains: Vec::new(),+ extra: (),+ })+}++#[tokio::test]+async fn a_soup_crm_company_resolves_its_pipeline_entries() {+ let harness = harness();+ let id = Uuid::from_u128(42);+ harness+ .soup_service+ .set_raw_response(vec![soup_crm_company(id)]);+ let pipelines = Arc::new(RecordingPipelines::default());+ let viewer = MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap();+ let response = harness+ .schema+ .execute(+ harness+ .request(+ &format!(+ r#"{{ user {{ soup(input: {{ initial: {{ filters: {{ crmCompanyFilter: {{ literal: {{ id: "{id}" }} }} }} }} }}) {{+ items {{ ... on GraphqlSoupCrmCompany {{+ __typename id name description+ pipelineEntries {{ id cells {{ column {{ name }} }} }}+ }} }}+ }} }} }}"#+ ),+ authenticated_parts(),+ )+ .data(graphql_crm::pipeline_entries_loader(+ graphql_crm::CrmGraphqlContext::new(pipelines.clone()),+ viewer,+ )),+ )+ .await;+ assert!(response.errors.is_empty(), "{:?}", response.errors);+ let data = response.data.into_json().unwrap();+ let company = &data["user"]["soup"]["items"][0];+ assert_eq!(company["__typename"], "GraphqlSoupCrmCompany");+ assert_eq!(company["id"], id.to_string());+ assert_eq!(company["description"], "Builds anvils.");+ assert_eq!(company["pipelineEntries"], serde_json::json!([]));+ assert_eq!(+ *pipelines.asked.lock().unwrap(),+ vec![(PipelineRecordType::Company, vec![id])]+ );+}diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rsindex e7438ba624..37514265b8 100644--- a/crates/complete_graph/src/sdl_test.rs+++ b/crates/complete_graph/src/sdl_test.rs@@ -512,6 +512,49 @@ fn database_rows_are_an_opt_in_soup_entity_named_by_table() {assert_sdl_line(&block("enum GraphqlSoupEntityType {"), "DATABASE_ROW");}+#[test]+fn crm_records_carry_their_pipeline_entries() {+ let sdl = crate::build_schema().sdl();+ let block = |declaration: &str| {+ sdl.split_once(declaration)+ .unwrap_or_else(|| panic!("schema has no `{declaration}`"))+ .1+ .split_once("\n}")+ .unwrap()+ .0+ .to_owned()+ };+ for record in [+ "type GraphqlSoupCrmCompany implements GraphqlSoupEntity {",+ "type GraphqlSoupCrmContact implements GraphqlSoupEntity {",+ ] {+ assert_sdl_line(+ &block(record),+ "pipelineEntries: [GraphqlCrmPipelineEntry!]!",+ );+ }+ let entry = block("type GraphqlCrmPipelineEntry {");+ for field in [+ "id: ID!",+ "pipeline: GraphqlCrmPipeline!",+ "cells: [GraphqlCrmPipelineCell!]!",+ ] {+ assert_sdl_line(&entry, field);+ }+ // A cell is a fact about its row, so it stays embedded in the entry.+ let cell = block("type GraphqlCrmPipelineCell {");+ assert!(!cell.lines().any(|line| line.trim() == "id: ID!"));+ assert_sdl_line(&cell, "column: GraphqlCrmPipelineColumn!");+ assert_sdl_line(&cell, "value: GraphqlPropertyValue");+ let column = block("type GraphqlCrmPipelineColumn {");+ assert_sdl_line(&column, "id: ID!");+ assert_sdl_line(&column, "writable: Boolean!");+ assert_sdl_line(&column, "options: [GraphqlPropertyOption!]!");+ let pipeline = block("type GraphqlCrmPipeline {");+ assert_sdl_line(&pipeline, "id: ID!");+ assert_sdl_line(&pipeline, "canEdit: Boolean!");+}+#[test]fn scheduled_actions_hang_off_the_authenticated_user() {use apollo_compiler::schema::ExtendedType;diff --git a/crates/crm/src/domain/pipelines.rs b/crates/crm/src/domain/pipelines.rsindex 65939d9f00..78414f9b73 100644--- a/crates/crm/src/domain/pipelines.rs+++ b/crates/crm/src/domain/pipelines.rs@@ -7,8 +7,8 @@ use super::{auth::CrmTeamReceipt, stages::StageDefinitionStore};use chrono::{DateTime, Utc};use databases::domain::{models::{- AppliedOps, ColumnId, ColumnProtection, DatabaseId, OpBatch, RowId, TableDetail, TableId,- Viewer,+ AppliedOps, ColumnDetail, ColumnId, ColumnProtection, DatabaseId, OpBatch, RowId,+ TableDetail, TableId, Viewer,},provisioning::{ProvisionedColumn, StorageBlueprint},storage::{DatabaseStorageService, StorageRows, StorageRowsQuery},@@ -21,14 +21,16 @@ use entity_access::domain::{ports::{AccessiblePipelines, EntityAccessService},};use macro_user_id::user_id::MacroUserIdStr;-use models_properties::service::property_option::PropertyOptionValue;+use models_properties::service::{+ property_option::PropertyOptionValue, property_value::PropertyValue,+};use models_properties::{DataType, EntityType as PropertyEntityType};use serde::{Deserialize, Serialize};use std::{collections::HashMap, sync::Arc};use uuid::Uuid;/// Which CRM entity each row references. Fixed when a pipeline is created.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, utoipa::ToSchema)]#[serde(rename_all = "snake_case")]pub enum PipelineRecordType {/// Company memberships.@@ -111,7 +113,7 @@ pub struct Pipeline {}/// Metadata together with the caller's effective grant.-#[derive(Debug, Serialize, utoipa::ToSchema)]+#[derive(Debug, Clone, Serialize, utoipa::ToSchema)]#[serde(rename_all = "camelCase")]pub struct AccessiblePipeline {/// Pipeline metadata.@@ -121,6 +123,32 @@ pub struct AccessiblePipeline {pub grant: AccessLevel,}+/// A pipeline row and the company or contact its primary column references.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PipelineReference {+ /// The pipeline holding the row.+ pub pipeline_id: Uuid,+ /// The row.+ pub row_id: RowId,+ /// The referenced company or contact.+ pub record_id: Uuid,+}++/// A row of a pipeline the viewer can see, for the company or contact it references.+#[derive(Debug, Clone)]+pub struct PipelineEntry {+ /// The row.+ pub row_id: RowId,+ /// The referenced company or contact.+ pub record_id: Uuid,+ /// The pipeline and the viewer's grant on it, shared by its entries.+ pub pipeline: Arc<AccessiblePipeline>,+ /// The pipeline's columns in display order, shared by its entries.+ pub columns: Arc<[ColumnDetail]>,+ /// Populated cells by column.+ pub cells: HashMap<ColumnId, PropertyValue>,+}+/// All records needed for atomic provisioning.pub struct PipelineBlueprint {/// Pipeline identity.@@ -190,6 +218,13 @@ pub trait PipelineRepo: Send + Sync + 'static {&self,ids: &[Uuid],) -> impl Future<Output = Result<Vec<Pipeline>, Self::Error>> + Send;+ /// Rows of these live pipelines whose primary column references one of+ /// `records`, grouped by pipeline in each one's row order.+ fn referencing_rows(+ &self,+ pipelines: &[Uuid],+ records: &[Uuid],+ ) -> impl Future<Output = Result<Vec<PipelineReference>, Self::Error>> + Send;/// Insert metadata, backing database and grants atomically.fn create(&self,@@ -216,6 +251,15 @@ pub trait PipelineService: Send + Sync + 'static {&self,team: CrmTeamReceipt<MemberTeamRole>,) -> impl Future<Output = Result<Vec<AccessiblePipeline>, PipelineError>> + Send;+ /// Rows referencing these companies or contacts, from the live pipelines+ /// of that record type the viewer can see. Pipeline grants are the whole+ /// boundary: the rows are what those pipelines already show the viewer.+ fn entries(+ &self,+ viewer: &MacroUserIdStr<'static>,+ record_type: PipelineRecordType,+ records: &[Uuid],+ ) -> impl Future<Output = Result<Vec<PipelineEntry>, PipelineError>> + Send;/// Read a pipeline by identity.fn get(&self,@@ -488,6 +532,84 @@ where.collect())}+ async fn entries(+ &self,+ viewer: &MacroUserIdStr<'static>,+ record_type: PipelineRecordType,+ records: &[Uuid],+ ) -> Result<Vec<PipelineEntry>, PipelineError> {+ if records.is_empty() {+ return Ok(Vec::new());+ }+ let grants: HashMap<_, _> = self+ .access+ .accessible_pipelines(viewer)+ .await?+ .into_iter()+ .collect();+ if grants.is_empty() {+ return Ok(Vec::new());+ }+ let ids = grants.keys().copied().collect::<Vec<_>>();+ let pipelines: HashMap<_, _> = self+ .repo+ .get_many(&ids)+ .await+ .map_err(storage)?+ .into_iter()+ .filter(|p| p.trashed_at.is_none() && p.record_type == record_type)+ .map(|p| (p.id, p))+ .collect();+ let live = pipelines.keys().copied().collect::<Vec<_>>();+ let references = self+ .repo+ .referencing_rows(&live, records)+ .await+ .map_err(storage)?;+ let mut entries = Vec::with_capacity(references.len());+ for references in references.chunk_by(|a, b| a.pipeline_id == b.pipeline_id) {+ let Some(pipeline) = pipelines.get(&references[0].pipeline_id) else {+ continue;+ };+ // A pipeline trashed since the lookup has no entries.+ let Some(_guard) = self.repo.lock_live(pipeline.id).await.map_err(storage)? else {+ continue;+ };+ let Some(table) = self+ .databases+ .storage_tables(pipeline.database_id)+ .await?+ .into_iter()+ .find(|table| table.table.id == pipeline.table_id)+ else {+ continue;+ };+ let rows = references.iter().map(|r| r.row_id).collect::<Vec<_>>();+ let cells: HashMap<_, _> = self+ .databases+ .storage_row_cells(pipeline.database_id, pipeline.table_id, &rows)+ .await?+ .into_iter()+ .map(|row| (row.row_id, row.cells))+ .collect();+ let shared = Arc::new(AccessiblePipeline {+ pipeline: pipeline.clone(),+ grant: grants[&pipeline.id],+ });+ let columns: Arc<[ColumnDetail]> = table.columns.into();+ entries.extend(references.iter().filter_map(|reference| {+ Some(PipelineEntry {+ row_id: reference.row_id,+ record_id: reference.record_id,+ pipeline: shared.clone(),+ columns: columns.clone(),+ cells: cells.get(&reference.row_id)?.clone(),+ })+ }));+ }+ Ok(entries)+ }+async fn get(&self,receipt: EntityAccessReceipt<ViewAccessLevel>,diff --git a/crates/crm/src/outbound/pipelines.rs b/crates/crm/src/outbound/pipelines.rsindex b6350d3e40..ac71747568 100644--- a/crates/crm/src/outbound/pipelines.rs+++ b/crates/crm/src/outbound/pipelines.rs@@ -1,11 +1,12 @@//! Pipeline metadata and grants, composed with the database domain's writer.use crate::domain::pipelines::{- Pipeline, PipelineBlueprint, PipelineRecordType, PipelineRepo, PipelineSharing,+ Pipeline, PipelineBlueprint, PipelineRecordType, PipelineReference, PipelineRepo,+ PipelineSharing,};use databases::domain::provisioning::DatabaseStorageProvisioner;use entity_access_db_utils::{AccessLevel, EntityAccessSourceType, EntityType};-use models_databases::{ColumnId, DatabaseId, TableId};+use models_databases::{ColumnId, DatabaseId, RowId, TableId};use sqlx::{PgPool, Postgres, Transaction};use uuid::Uuid;@@ -135,6 +136,46 @@ where.collect()}+ async fn referencing_rows(+ &self,+ pipelines: &[Uuid],+ records: &[Uuid],+ ) -> Result<Vec<PipelineReference>, Self::Error> {+ let records: Vec<String> = records.iter().map(Uuid::to_string).collect();+ // Starts from each pipeline's primary column: entity_properties has no+ // index on referenced ids, so this reads those pipelines' primary cells.+ let rows = sqlx::query!(+ r#"SELECT p.id AS "pipeline_id!", r.id AS "row_id!",+ reference.value ->> 'entity_id' AS "record_id!"+ FROM crm_pipeline_entities p+ JOIN database_columns c ON c.id = p.primary_column_id+ JOIN entity_properties ep+ ON ep.property_definition_id = c.property_definition_id+ AND ep.entity_type = 'DATABASE_ROW'+ JOIN database_rows r ON r.id::text = ep.entity_id AND r.table_id = p.table_id+ CROSS JOIN LATERAL jsonb_array_elements(ep.values -> 'value') AS reference(value)+ WHERE p.id = ANY($1) AND p.trashed_at IS NULL+ AND reference.value ->> 'entity_id' = ANY($2)+ ORDER BY p.id, r.position, r.id"#,+ pipelines,+ &records,+ )+ .fetch_all(&self.pool)+ .await?;+ rows.into_iter()+ .map(|row| {+ Ok(PipelineReference {+ pipeline_id: row.pipeline_id,+ row_id: RowId::from_uuid(row.row_id),+ record_id: row+ .record_id+ .parse()+ .map_err(|error| sqlx::Error::Decode(Box::new(error)))?,+ })+ })+ .collect()+ }+type Guard = Transaction<'static, Postgres>;async fn lock_live(&self, id: Uuid) -> Result<Option<Self::Guard>, Self::Error> {diff --git a/crates/crm/tests/pipelines.rs b/crates/crm/tests/pipelines.rsindex f15396de78..b87b3cc893 100644--- a/crates/crm/tests/pipelines.rs+++ b/crates/crm/tests/pipelines.rs@@ -929,3 +929,176 @@ async fn queried_rows_filter_and_sort_before_paging_and_retain_hidden_records(poassert_eq!(retained.rows.len(), 1);assert_eq!(retained.rows[0].row_id, hidden);}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn entries_list_referencing_rows_from_visible_live_pipelines(pool: PgPool) {+ use databases::domain::storage::DatabaseStorageService;+ use models_properties::service::property_value::PropertyValue;+ let (s, db, a, team, company) = fixture(&pool).await;+ // Source ids are cached per user across this binary's parallel tests, so+ // a teammate shared with other tests could see another test's teams.+ let teammate = format!("macro|entries-{}@macro.com", Uuid::now_v7());+ let teammate_id = Uuid::now_v7();+ sqlx::query!(+ "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1,$2,$2,$2)",+ teammate_id,+ teammate+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1,$1,$2)"#,+ teammate,+ teammate_id+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"INSERT INTO team_user (team_id,user_id,team_role) VALUES ($1,$2,'member')"#,+ team,+ teammate+ )+ .execute(&pool)+ .await+ .unwrap();+ let other = Uuid::now_v7();+ sqlx::query!("INSERT INTO crm_companies (id, team_id, first_interaction, last_interaction) VALUES ($1, $2, now(), now())", other, team).execute(&pool).await.unwrap();+ let private = create(&s, team, PipelineRecordType::Company).await;+ let shared = create(&s, team, PipelineRecordType::Company).await;+ s.share(+ access(&a, shared.id, EntityType::CrmPipeline, OWNER).await,+ PipelineSharing::Team,+ )+ .await+ .unwrap();+ let trashed = create(&s, team, PipelineRecordType::Company).await;+ let revenue = s+ .table(access(&a, private.id, EntityType::CrmPipeline, OWNER).await)+ .await+ .unwrap()+ .columns+ .into_iter()+ .find(|column| column.definition.definition.display_name == "Revenue")+ .unwrap()+ .column+ .id;+ let row = |p: &Pipeline, entity: Uuid, amount: f64| {+ json!([+ {"column": p.primary_column_id, "value": {"type":"entities", "value":[{"entityType":"COMPANY", "entityId":entity.to_string()}]}},+ {"column": revenue, "value": {"type":"number", "value":amount}}+ ])+ };+ let insert_rows = |p: &Pipeline, rows: Vec<serde_json::Value>| -> DatabaseOp {+ serde_json::from_value(+ json!({"kind":"rows", "table":p.table_id, "change":{"kind":"insert", "rows":rows}}),+ )+ .unwrap()+ };+ let private_rows = write(+ &s,+ &a,+ &private,+ vec![insert_rows(+ &private,+ vec![+ row(&private, company, 1.0),+ row(&private, other, 2.0),+ row(&private, company, 3.0),+ ],+ )],+ )+ .await+ .unwrap();+ let shared_row = inserted(+ &write(&s, &a, &shared, vec![insert(&shared, company)])+ .await+ .unwrap(),+ );+ write(&s, &a, &trashed, vec![insert(&trashed, company)])+ .await+ .unwrap();+ s.set_trashed(+ access(&a, trashed.id, EntityType::CrmPipeline, OWNER).await,+ true,+ )+ .await+ .unwrap();++ let owner = s+ .entries(&user(OWNER), PipelineRecordType::Company, &[company])+ .await+ .unwrap();+ let mut pipelines = owner+ .iter()+ .map(|e| e.pipeline.pipeline.id)+ .collect::<Vec<_>>();+ pipelines.dedup();+ assert_eq!(pipelines.len(), 2);+ assert!(pipelines.contains(&private.id) && pipelines.contains(&shared.id));+ let private_entries = owner+ .iter()+ .filter(|e| e.pipeline.pipeline.id == private.id)+ .collect::<Vec<_>>();+ // Both of the company's rows, in the pipeline's row order, with their cells.+ assert_eq!(+ private_entries+ .iter()+ .map(|e| e.cells.get(&revenue).cloned())+ .collect::<Vec<_>>(),+ vec![Some(PropertyValue::Num(1.0)), Some(PropertyValue::Num(3.0))]+ );+ assert!(private_entries.iter().all(|e| e.record_id == company+ && e.pipeline.grant == AccessLevel::Owner+ && e.columns.len() == 4+ && e.cells.contains_key(&private.primary_column_id)));+ match &private_rows[0] {+ OpResult::Rows {+ change: RowsResult::Inserted { rows },+ ..+ } => assert_eq!(private_entries[0].row_id, rows[0]),+ other => panic!("{other:?}"),+ }++ // Storage reads only the asked-for rows of the named table.+ let cells = db+ .storage_row_cells(+ private.database_id,+ private.table_id,+ &[private_entries[1].row_id, shared_row],+ )+ .await+ .unwrap();+ assert_eq!(cells.len(), 1);+ assert_eq!(cells[0].row_id, private_entries[1].row_id);+ assert_eq!(cells[0].cells[&revenue], PropertyValue::Num(3.0));++ // A batch answers each record; another record type matches nothing.+ let both = s+ .entries(&user(OWNER), PipelineRecordType::Company, &[company, other])+ .await+ .unwrap();+ assert_eq!(both.iter().filter(|e| e.record_id == other).count(), 1);+ assert!(+ s.entries(&user(OWNER), PipelineRecordType::Contact, &[company])+ .await+ .unwrap()+ .is_empty()+ );++ // Teammates see only shared pipelines; outsiders see nothing.+ let member = s+ .entries(&user(&teammate), PipelineRecordType::Company, &[company])+ .await+ .unwrap();+ assert_eq!(member.len(), 1);+ assert_eq!(member[0].pipeline.pipeline.id, shared.id);+ assert_eq!(member[0].pipeline.grant, AccessLevel::Edit);+ assert!(+ s.entries(&user(OUTSIDER), PipelineRecordType::Company, &[company])+ .await+ .unwrap()+ .is_empty()+ );+}diff --git a/crates/databases/src/domain/service/storage.rs b/crates/databases/src/domain/service/storage.rsindex ad1e321944..9a5201ae6d 100644--- a/crates/databases/src/domain/service/storage.rs+++ b/crates/databases/src/domain/service/storage.rs@@ -211,6 +211,50 @@ where})}+ async fn storage_row_cells(+ &self,+ id: DatabaseId,+ table: TableId,+ rows: &[RowId],+ ) -> Result<Vec<StorageRow>, DatabaseError> {+ let entry = self+ .storage_entries(id)+ .await?+ .into_iter()+ .find(|entry| entry.table.id == table)+ .ok_or(DatabaseError::NotFound)?;+ let rows: HashSet<_> = rows.iter().collect();+ let wanted: Vec<_> = self+ .repository+ .row_refs(table)+ .await+ .map_err(repository_error)?+ .into_iter()+ .map(|row| row.id)+ .filter(|row| rows.contains(row))+ .collect();+ let mut cells = self.cells.cells(&wanted).await.map_err(repository_error)?;+ Ok(wanted+ .into_iter()+ .map(|row_id| {+ let cells = cells.remove(&row_id).unwrap_or_default();+ StorageRow {+ row_id,+ cells: entry+ .columns+ .iter()+ .filter_map(|column| {+ cells+ .get(&column.column.property_definition_id)+ .cloned()+ .map(|value| (column.column.id, value))+ })+ .collect(),+ }+ })+ .collect())+ }+async fn apply_storage_ops(&self,id: DatabaseId,diff --git a/crates/databases/src/domain/storage.rs b/crates/databases/src/domain/storage.rsindex 8b1a4f4b27..626afde31e 100644--- a/crates/databases/src/domain/storage.rs+++ b/crates/databases/src/domain/storage.rs@@ -60,6 +60,15 @@ pub trait DatabaseStorageService: Send + Sync + 'static {table: TableId,query: StorageRowsQuery,) -> impl Future<Output = Result<StorageRows, DatabaseError>> + Send;+ /// Read the cells of those of `rows` that belong to a table in the+ /// authorized resource, in the table's row order. Unlike+ /// [`Self::storage_rows`], only these rows' cells are read.+ fn storage_row_cells(+ &self,+ id: DatabaseId,+ table: TableId,+ rows: &[RowId],+ ) -> impl Future<Output = Result<Vec<StorageRow>, DatabaseError>> + Send;/// Validate typed operations with the shared planner, then commit through/// `DatabaseStorage`. External property bindings and cross-resource relations/// require a host capability and are not accepted by this entry point.diff --git a/crates/graphql_crm/Cargo.toml b/crates/graphql_crm/Cargo.tomlnew file mode 100644index 0000000000..aeaa8e1e39--- /dev/null+++ b/crates/graphql_crm/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "graphql_crm"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+async-graphql = { workspace = true, features = ["dataloader"] }+crm = { path = "../crm", default-features = false, features = ["ports"] }+databases = { path = "../databases", default-features = false, features = ["ports"] }+entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }+graphql_common = { path = "../graphql_common" }+graphql_properties = { path = "../graphql_properties" }+macro_user_id = { path = "../macro_user_id" }+models_properties = { path = "../models_properties" }+tokio = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+chrono = { workspace = true }+models_databases = { path = "../models_databases" }+serde_json = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt"] }diff --git a/crates/graphql_crm/src/context.rs b/crates/graphql_crm/src/context.rsnew file mode 100644index 0000000000..2fd41f03f4--- /dev/null+++ b/crates/graphql_crm/src/context.rs@@ -0,0 +1,47 @@+//! Request capabilities supplied by the application composition root.++use std::{future::Future, pin::Pin, sync::Arc};++use crm::domain::pipelines::{PipelineEntry, PipelineError, PipelineRecordType, PipelineService};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++/// Object-safe forwarding future for the request's concrete domain service.+type ApiFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, PipelineError>> + Send + 'a>>;++/// Transport-facing view of the pipeline use cases this adapter calls.+pub(crate) trait CrmPipelineApi: Send + Sync {+ fn entries<'a>(+ &'a self,+ viewer: &'a MacroUserIdStr<'static>,+ record_type: PipelineRecordType,+ records: &'a [Uuid],+ ) -> ApiFuture<'a, Vec<PipelineEntry>>;+}++/// Request-scoped CRM capability.+///+/// Type erasure keeps domain implementation parameters out of the schema's public type.+#[derive(Clone)]+pub struct CrmGraphqlContext(pub(crate) Arc<dyn CrmPipelineApi>);++impl CrmGraphqlContext {+ /// Compose the pipeline use cases.+ pub fn new<P: PipelineService>(pipelines: Arc<P>) -> Self {+ Self(Arc::new(PipelineApiAdapter(pipelines)))+ }+}++/// Thin bridge from the GraphQL viewer to the pipeline service, which owns access.+struct PipelineApiAdapter<P>(Arc<P>);++impl<P: PipelineService> CrmPipelineApi for PipelineApiAdapter<P> {+ fn entries<'a>(+ &'a self,+ viewer: &'a MacroUserIdStr<'static>,+ record_type: PipelineRecordType,+ records: &'a [Uuid],+ ) -> ApiFuture<'a, Vec<PipelineEntry>> {+ Box::pin(self.0.entries(viewer, record_type, records))+ }+}diff --git a/crates/graphql_crm/src/lib.rs b/crates/graphql_crm/src/lib.rsnew file mode 100644index 0000000000..89cb501f34--- /dev/null+++ b/crates/graphql_crm/src/lib.rs@@ -0,0 +1,37 @@+//! Typed GraphQL inbound adapter for CRM records: the pipeline rows that+//! reference a company or contact, composed onto their Soup entities.+#![deny(missing_docs)]++mod context;+mod loaders;+mod objects;++#[cfg(test)]+mod test;++pub use context::CrmGraphqlContext;+pub use loaders::{+ CrmRecord, PipelineEntriesLoader, load_pipeline_entries, pipeline_entries_loader,+};+pub use objects::{+ GraphqlCrmPipeline, GraphqlCrmPipelineCell, GraphqlCrmPipelineColumn, GraphqlCrmPipelineEntry,+ GraphqlCrmPipelineRecordType, GraphqlCrmPipelineSharing,+};++use async_graphql::ErrorExtensions;+use crm::domain::pipelines::PipelineError;++/// Preserve actionable domain failures while hiding infrastructure details.+fn graphql_error(error: PipelineError) -> async_graphql::Error {+ let (message, code) = match error {+ PipelineError::Invalid(message) => (message.to_string(), "BAD_USER_INPUT"),+ PipelineError::NotFound => ("pipeline not found".to_string(), "NOT_FOUND"),+ error => {+ tracing::error!(error=?error, "CRM pipeline GraphQL request failed");+ ("internal server error".to_string(), "INTERNAL_SERVER_ERROR")+ }+ };+ async_graphql::Error::new(message).extend_with(|_, extensions| {+ extensions.set("code", code);+ })+}diff --git a/crates/graphql_crm/src/loaders.rs b/crates/graphql_crm/src/loaders.rsnew file mode 100644index 0000000000..adc37ecc5c--- /dev/null+++ b/crates/graphql_crm/src/loaders.rs@@ -0,0 +1,117 @@+//! Lazy, viewer-scoped pipeline entries composed onto CRM Soup entities.++use std::{collections::HashMap, convert::Infallible, sync::Arc};++use async_graphql::{+ Context,+ dataloader::{DataLoader, Loader},+};+use crm::domain::pipelines::{PipelineEntry, PipelineRecordType};+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use crate::{CrmGraphqlContext, GraphqlCrmPipelineEntry, graphql_error};++/// A company or contact whose pipeline entries are requested.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum CrmRecord {+ /// A CRM company.+ Company(Uuid),+ /// A CRM contact.+ Contact(Uuid),+}++impl CrmRecord {+ fn record_type(self) -> PipelineRecordType {+ match self {+ Self::Company(_) => PipelineRecordType::Company,+ Self::Contact(_) => PipelineRecordType::Contact,+ }+ }++ fn id(self) -> Uuid {+ match self {+ Self::Company(id) | Self::Contact(id) => id,+ }+ }+}++/// Viewer-scoped entries reader; one domain read per record type for every+/// record a request asks about.+pub struct PipelineEntriesLoader {+ context: CrmGraphqlContext,+ user: MacroUserIdStr<'static>,+}++impl Loader<CrmRecord> for PipelineEntriesLoader {+ type Value = async_graphql::Result<Arc<[PipelineEntry]>>;+ type Error = Infallible;++ async fn load(+ &self,+ keys: &[CrmRecord],+ ) -> Result<HashMap<CrmRecord, Self::Value>, Self::Error> {+ let mut loaded = HashMap::with_capacity(keys.len());+ for record_type in [PipelineRecordType::Company, PipelineRecordType::Contact] {+ let records: Vec<CrmRecord> = keys+ .iter()+ .copied()+ .filter(|record| record.record_type() == record_type)+ .collect();+ if records.is_empty() {+ continue;+ }+ let ids: Vec<Uuid> = records.iter().map(|record| record.id()).collect();+ match self.context.0.entries(&self.user, record_type, &ids).await {+ Ok(entries) => {+ let mut by_record: HashMap<Uuid, Vec<PipelineEntry>> = HashMap::new();+ for entry in entries {+ by_record.entry(entry.record_id).or_default().push(entry);+ }+ for record in records {+ let entries = by_record.remove(&record.id()).unwrap_or_default();+ loaded.insert(record, Ok(entries.into()));+ }+ }+ Err(error) => {+ let error = graphql_error(error);+ for record in records {+ loaded.insert(record, Err(error.clone()));+ }+ }+ }+ }+ Ok(loaded)+ }+}++/// Coalesce the entries edges of a request's companies and contacts without+/// retaining data across mutations or subscription events.+pub fn pipeline_entries_loader(+ context: CrmGraphqlContext,+ user: MacroUserIdStr<'static>,+) -> DataLoader<PipelineEntriesLoader> {+ DataLoader::new(PipelineEntriesLoader { context, user }, tokio::spawn)+}++/// Load the record's entries only when the edge is requested.+pub async fn load_pipeline_entries(+ ctx: &Context<'_>,+ record: CrmRecord,+) -> async_graphql::Result<Vec<GraphqlCrmPipelineEntry>> {+ match ctx+ .data::<DataLoader<PipelineEntriesLoader>>()?+ .load_one(record)+ .await+ {+ Ok(Some(entries)) => Ok(entries?+ .iter()+ .cloned()+ .map(GraphqlCrmPipelineEntry::new)+ .collect()),+ Ok(None) => Err(async_graphql::Error::new(+ "pipeline entries are unavailable",+ )),+ Err(impossible) => match impossible {},+ }+}diff --git a/crates/graphql_crm/src/objects.rs b/crates/graphql_crm/src/objects.rsnew file mode 100644index 0000000000..3c81fda94d--- /dev/null+++ b/crates/graphql_crm/src/objects.rs@@ -0,0 +1,212 @@+//! GraphQL objects for pipeline rows that reference a CRM record.++use std::sync::Arc;++use async_graphql::{Enum, ID, Object};+use crm::domain::pipelines::{+ AccessiblePipeline, PipelineEntry, PipelineRecordType, PipelineSharing,+};+use databases::domain::models::ColumnDetail;+use entity_access::domain::models::AccessLevel;+use graphql_common::GraphqlPropertyEntityType;+use graphql_properties::{GraphqlPropertyDataType, GraphqlPropertyOption, GraphqlPropertyValue};+use models_properties::service::property_value::PropertyValue;++/// Which CRM record a pipeline's rows reference.+#[derive(Enum, Debug, Clone, Copy, PartialEq, Eq)]+pub enum GraphqlCrmPipelineRecordType {+ /// Companies.+ Company,+ /// Contacts.+ Contact,+}++impl From<PipelineRecordType> for GraphqlCrmPipelineRecordType {+ fn from(record_type: PipelineRecordType) -> Self {+ match record_type {+ PipelineRecordType::Company => Self::Company,+ PipelineRecordType::Contact => Self::Contact,+ }+ }+}++/// Whether a pipeline is shared with its team.+#[derive(Enum, Debug, Clone, Copy, PartialEq, Eq)]+pub enum GraphqlCrmPipelineSharing {+ /// Only people granted access individually.+ Private,+ /// The whole team may edit.+ Team,+}++impl From<PipelineSharing> for GraphqlCrmPipelineSharing {+ fn from(sharing: PipelineSharing) -> Self {+ match sharing {+ PipelineSharing::Private => Self::Private,+ PipelineSharing::Team => Self::Team,+ }+ }+}++/// A pipeline row that references a company or contact.+pub struct GraphqlCrmPipelineEntry(PipelineEntry);++impl GraphqlCrmPipelineEntry {+ /// Wrap a domain entry.+ pub fn new(entry: PipelineEntry) -> Self {+ Self(entry)+ }+}++/// A pipeline row that references a company or contact.+#[Object(name = "GraphqlCrmPipelineEntry")]+impl GraphqlCrmPipelineEntry {+ /// The row's identifier.+ async fn id(&self) -> ID {+ ID(self.0.row_id.into_uuid().to_string())+ }++ /// The pipeline holding the row.+ async fn pipeline(&self) -> GraphqlCrmPipeline {+ GraphqlCrmPipeline(self.0.pipeline.clone())+ }++ /// The row's cells in column order, for every column but the reference+ /// to the record itself. An empty cell has no value.+ async fn cells(&self) -> Vec<GraphqlCrmPipelineCell> {+ let primary = self.0.pipeline.pipeline.primary_column_id;+ (0..self.0.columns.len())+ .filter(|&index| self.0.columns[index].column.id != primary)+ .map(|index| GraphqlCrmPipelineCell {+ value: self.0.cells.get(&self.0.columns[index].column.id).cloned(),+ column: GraphqlCrmPipelineColumn {+ columns: self.0.columns.clone(),+ index,+ },+ })+ .collect()+ }+}++/// A CRM pipeline the viewer can see.+pub struct GraphqlCrmPipeline(Arc<AccessiblePipeline>);++/// A CRM pipeline the viewer can see.+#[Object(name = "GraphqlCrmPipeline")]+impl GraphqlCrmPipeline {+ /// The pipeline's identifier.+ async fn id(&self) -> ID {+ ID(self.0.pipeline.id.to_string())+ }++ /// The pipeline's name.+ async fn name(&self) -> &str {+ &self.0.pipeline.name+ }++ /// Which CRM record its rows reference.+ async fn record_type(&self) -> GraphqlCrmPipelineRecordType {+ self.0.pipeline.record_type.into()+ }++ /// Whether the pipeline is shared with its team.+ async fn sharing(&self) -> GraphqlCrmPipelineSharing {+ self.0.pipeline.sharing.into()+ }++ /// The table that pipeline operations name.+ async fn table_id(&self) -> ID {+ ID(self.0.pipeline.table_id.into_uuid().to_string())+ }++ /// Whether the viewer may edit the pipeline's rows.+ async fn can_edit(&self) -> bool {+ matches!(self.0.grant, AccessLevel::Edit | AccessLevel::Owner)+ }+}++/// One cell of a pipeline row.+pub struct GraphqlCrmPipelineCell {+ column: GraphqlCrmPipelineColumn,+ value: Option<PropertyValue>,+}++/// One cell of a pipeline row.+#[Object(name = "GraphqlCrmPipelineCell")]+impl GraphqlCrmPipelineCell {+ /// The cell's column.+ async fn column(&self) -> &GraphqlCrmPipelineColumn {+ &self.column+ }++ /// The cell's value, absent when the cell is empty.+ async fn value(&self) -> Option<GraphqlPropertyValue> {+ self.value.as_ref().map(GraphqlPropertyValue::new)+ }+}++/// A pipeline column, with what its cells' values mean.+pub struct GraphqlCrmPipelineColumn {+ columns: Arc<[ColumnDetail]>,+ index: usize,+}++impl GraphqlCrmPipelineColumn {+ fn detail(&self) -> &ColumnDetail {+ &self.columns[self.index]+ }+}++/// A pipeline column, with what its cells' values mean.+#[Object(name = "GraphqlCrmPipelineColumn")]+impl GraphqlCrmPipelineColumn {+ /// The column's identifier.+ async fn id(&self) -> ID {+ ID(self.detail().column.id.into_uuid().to_string())+ }++ /// The property definition the column binds.+ async fn property_definition_id(&self) -> ID {+ ID(self.detail().definition.definition.id.to_string())+ }++ /// The column's name.+ async fn name(&self) -> &str {+ self.detail().name()+ }++ /// The type of value the column holds.+ async fn data_type(&self) -> GraphqlPropertyDataType {+ GraphqlPropertyDataType::new(self.detail().definition.definition.data_type)+ }++ /// Whether a cell can hold more than one value; a relation always can.+ async fn is_multi_select(&self) -> bool {+ self.detail().is_multi_valued()+ }++ /// Whether the column's cells take writes; derived columns are computed.+ async fn writable(&self) -> bool {+ self.detail().writable && self.detail().column.formula().is_none()+ }++ /// The required entity type for a reference column, when constrained.+ async fn specific_entity_type(&self) -> Option<GraphqlPropertyEntityType> {+ self.detail()+ .definition+ .definition+ .specific_entity_type+ .map(GraphqlPropertyEntityType::new)+ }++ /// The options a select column's cells choose from, in display order.+ async fn options(&self) -> Vec<GraphqlPropertyOption> {+ self.detail()+ .definition+ .property_options+ .iter()+ .cloned()+ .map(GraphqlPropertyOption::from)+ .collect()+ }+}diff --git a/crates/graphql_crm/src/test.rs b/crates/graphql_crm/src/test.rsnew file mode 100644index 0000000000..2c258948ab--- /dev/null+++ b/crates/graphql_crm/src/test.rs@@ -0,0 +1,196 @@+use std::sync::{Arc, Mutex};++use async_graphql::{Context, EmptyMutation, EmptySubscription, ID, Object, Request, Schema};+use chrono::Utc;+use crm::domain::pipelines::{+ AccessiblePipeline, Pipeline, PipelineEntry, PipelineRecordType, PipelineSharing,+};+use databases::domain::models::{Column, ColumnDetail, ColumnId, DatabaseId, RowId, TableId};+use entity_access::domain::models::AccessLevel;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use models_databases::position::key_between;+use models_properties::{+ DataType,+ service::{+ property_definition::PropertyDefinition,+ property_definition_with_options::PropertyDefinitionWithOptions,+ property_value::PropertyValue,+ },+ shared::property_owner::PropertyOwner,+};+use serde_json::json;+use uuid::Uuid;++use crate::{+ CrmGraphqlContext, CrmRecord, GraphqlCrmPipelineEntry, context::CrmPipelineApi,+ load_pipeline_entries, pipeline_entries_loader,+};++/// Answers every requested record with one entry and records each call.+struct FakePipelines {+ entry: PipelineEntry,+ calls: Mutex<Vec<(PipelineRecordType, Vec<Uuid>)>>,+}++impl CrmPipelineApi for FakePipelines {+ fn entries<'a>(+ &'a self,+ _viewer: &'a MacroUserIdStr<'static>,+ record_type: PipelineRecordType,+ records: &'a [Uuid],+ ) -> std::pin::Pin<+ Box<+ dyn Future<Output = Result<Vec<PipelineEntry>, crm::domain::pipelines::PipelineError>>+ + Send+ + 'a,+ >,+ > {+ self.calls+ .lock()+ .unwrap()+ .push((record_type, records.to_vec()));+ let entries = records+ .iter()+ .map(|record_id| PipelineEntry {+ record_id: *record_id,+ ..self.entry.clone()+ })+ .collect();+ Box::pin(async move { Ok(entries) })+ }+}++fn column(table: TableId, name: &str, data_type: DataType) -> ColumnDetail {+ let definition = Uuid::now_v7();+ ColumnDetail {+ column: Column {+ id: ColumnId::new(),+ table_id: table,+ property_definition_id: definition,+ position: key_between(None, None).unwrap(),+ config: None,+ display_name: None,+ infer_type: false,+ protections: vec![],+ nullable: true,+ },+ sql_name: format!("\"{name}\""),+ definition: PropertyDefinitionWithOptions {+ definition: PropertyDefinition {+ id: definition,+ owner: PropertyOwner::System,+ display_name: name.into(),+ data_type,+ is_multi_select: false,+ specific_entity_type: None,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ is_system: false,+ is_metadata: false,+ },+ property_options: vec![],+ },+ writable: true,+ shared_outside_database: false,+ }+}++struct Query;++#[Object]+impl Query {+ async fn company(+ &self,+ ctx: &Context<'_>,+ id: ID,+ ) -> async_graphql::Result<Vec<GraphqlCrmPipelineEntry>> {+ load_pipeline_entries(ctx, CrmRecord::Company(id.parse()?)).await+ }++ async fn contact(+ &self,+ ctx: &Context<'_>,+ id: ID,+ ) -> async_graphql::Result<Vec<GraphqlCrmPipelineEntry>> {+ load_pipeline_entries(ctx, CrmRecord::Contact(id.parse()?)).await+ }+}++#[tokio::test]+async fn one_read_per_record_type_answers_every_record_without_its_own_column() {+ let table = TableId::new();+ let primary = column(table, "Company", DataType::Entity);+ let revenue = column(table, "Revenue", DataType::Number);+ let stage = column(table, "Stage", DataType::SelectString);+ let revenue_id = revenue.column.id;+ let row = RowId::new();+ let pipeline = Pipeline {+ id: Uuid::now_v7(),+ team_id: Uuid::now_v7(),+ name: "Deals".into(),+ user_id: "macro|[email protected]".into(),+ record_type: PipelineRecordType::Company,+ database_id: DatabaseId::new(),+ table_id: table,+ primary_column_id: primary.column.id,+ sharing: PipelineSharing::Team,+ created_at: Utc::now(),+ trashed_at: None,+ };+ let fake = Arc::new(FakePipelines {+ entry: PipelineEntry {+ row_id: row,+ record_id: Uuid::nil(),+ pipeline: Arc::new(AccessiblePipeline {+ pipeline,+ grant: AccessLevel::View,+ }),+ columns: vec![primary, revenue, stage].into(),+ cells: [(revenue_id, PropertyValue::Num(9600.0))].into(),+ },+ calls: Mutex::default(),+ });+ let viewer = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ let schema = Schema::build(Query, EmptyMutation, EmptySubscription).finish();+ let [first, second, contact] = [Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7()];+ let fields = "id pipeline { name canEdit } cells { column { name } value { ... on GraphqlNumberPropertyValue { value } } }";+ let response = schema+ .execute(+ Request::new(format!(+ r#"{{ first: company(id: "{first}") {{ {fields} }}+ second: company(id: "{second}") {{ {fields} }}+ contact: contact(id: "{contact}") {{ id }} }}"#+ ))+ .data(pipeline_entries_loader(+ CrmGraphqlContext(fake.clone()),+ viewer,+ )),+ )+ .await;+ assert!(response.errors.is_empty(), "{:?}", response.errors);+ let data = response.data.into_json().unwrap();+ let expected = json!([{+ "id": row.into_uuid().to_string(),+ "pipeline": { "name": "Deals", "canEdit": false },+ "cells": [+ { "column": { "name": "Revenue" }, "value": { "value": 9600.0 } },+ { "column": { "name": "Stage" }, "value": null },+ ],+ }]);+ assert_eq!(data["first"], expected);+ assert_eq!(data["second"], expected);+ assert_eq!(data["contact"].as_array().unwrap().len(), 1);++ let mut calls = fake.calls.lock().unwrap().clone();+ calls.sort_by_key(|(record_type, _)| *record_type == PipelineRecordType::Contact);+ assert_eq!(calls.len(), 2);+ assert_eq!(calls[0].0, PipelineRecordType::Company);+ let mut companies = calls[0].1.clone();+ companies.sort();+ let mut requested = vec![first, second];+ requested.sort();+ assert_eq!(companies, requested);+ assert_eq!(calls[1], (PipelineRecordType::Contact, vec![contact]));+}diff --git a/crates/graphql_entity_mutation/src/mutations/test.rs b/crates/graphql_entity_mutation/src/mutations/test.rsindex ebf24a0e25..9d858483f0 100644--- a/crates/graphql_entity_mutation/src/mutations/test.rs+++ b/crates/graphql_entity_mutation/src/mutations/test.rs@@ -39,6 +39,7 @@ impl SoupEntityEdges for TestSoupEdges {type NotificationFilter = String;type ActivityEvent = String;type EmailThreadEdges = TestEmailThreadEdges;+ type CrmRecordEdges = TestEmailThreadEdges;type InitiativeEdges = TestEmailThreadEdges;type AgentSessionEdges = TestAgentSessionEdges;@@ -54,6 +55,10 @@ impl SoupEntityEdges for TestSoupEdges {TestEmailThreadEdges { available: true }}+ fn crm_record_edges(_record: model_entity::Entity<'static>) -> Self::CrmRecordEdges {+ TestEmailThreadEdges { available: true }+ }+async fn resolve_email_cache_projection(&self,_ctx: &Context<'_>,diff --git a/crates/graphql_favorite/src/mutations/test.rs b/crates/graphql_favorite/src/mutations/test.rsindex 97f9ed7051..41764850f0 100644--- a/crates/graphql_favorite/src/mutations/test.rs+++ b/crates/graphql_favorite/src/mutations/test.rs@@ -43,6 +43,7 @@ impl SoupEntityEdges for TestSoupEdges {type NotificationFilter = String;type ActivityEvent = String;type EmailThreadEdges = TestEmailEdges;+ type CrmRecordEdges = TestEmailEdges;type InitiativeEdges = TestEmailEdges;type AgentSessionEdges = TestAgentSessionEdges;@@ -58,6 +59,10 @@ impl SoupEntityEdges for TestSoupEdges {TestEmailEdges { available: true }}+ fn crm_record_edges(_record: model_entity::Entity<'static>) -> Self::CrmRecordEdges {+ TestEmailEdges { available: true }+ }+async fn resolve_email_cache_projection(&self,_ctx: &Context<'_>,diff --git a/crates/graphql_initiative/src/test.rs b/crates/graphql_initiative/src/test.rsindex 89e7724084..18f3068d91 100644--- a/crates/graphql_initiative/src/test.rs+++ b/crates/graphql_initiative/src/test.rs@@ -87,6 +87,7 @@ impl SoupEntityEdges for TestSoupEdges {type NotificationFilter = String;type ActivityEvent = String;type EmailThreadEdges = TestEmailThreadEdges;+ type CrmRecordEdges = TestEmailThreadEdges;type AgentSessionEdges = TestAgentSessionEdges;type InitiativeEdges = TestInitiativeEdges;@@ -102,6 +103,10 @@ impl SoupEntityEdges for TestSoupEdges {TestEmailThreadEdges { available: true }}+ fn crm_record_edges(_record: model_entity::Entity<'static>) -> Self::CrmRecordEdges {+ TestEmailThreadEdges { available: true }+ }+async fn resolve_email_cache_projection(&self,_ctx: &Context<'_>,diff --git a/crates/graphql_soup/src/loaders.rs b/crates/graphql_soup/src/loaders.rsindex ea56bd0e2e..e3af69f4cd 100644--- a/crates/graphql_soup/src/loaders.rs+++ b/crates/graphql_soup/src/loaders.rs@@ -180,10 +180,14 @@ where} else {Vec::new()};+ // CRM records are team-scoped: Soup skips them without the viewer's team.let needs_team = entities.iter().any(|entity| {matches!(entity.entity_type,- EntityType::ForeignEntity | EntityType::AgentSession+ EntityType::ForeignEntity+ | EntityType::AgentSession+ | EntityType::CrmCompany+ | EntityType::CrmContact)});let team = match (&self.team_reader, needs_team) {diff --git a/crates/graphql_soup/src/loaders/test.rs b/crates/graphql_soup/src/loaders/test.rsindex 856ab31011..fbe2e29793 100644--- a/crates/graphql_soup/src/loaders/test.rs+++ b/crates/graphql_soup/src/loaders/test.rs@@ -615,3 +615,38 @@ async fn pr_and_session_hydration_recheck_team_on_each_batch() {loader.load(&keys).await.unwrap();assert_eq!(soup.calls.lock().unwrap()[1].team_id, None);}++#[tokio::test]+async fn crm_record_hydration_carries_the_viewer_team() {+ use entity_access::domain::models::{EntityPermission, TeamRole};+ let viewer = user("macro|[email protected]");+ let team_id = Uuid::now_v7();+ let team = Arc::new(CurrentTeam(Mutex::new(Some(+ EntityAccessReceipt::try_new_authenticated_user(+ viewer.clone(),+ entity_access::domain::models::Entity {+ entity_type: EntityType::Team,+ entity_id: team_id.to_string(),+ },+ EntityPermission::TeamRole {+ role: TeamRole::Member,+ },+ )+ .unwrap(),+ ))));+ let soup = RecordingSoupService::default();+ let mut loader = SoupItemLoader::new(soup.clone(), RecordingInboxReader::default());+ loader.team_reader = Some(team);+ for entity_type in [EntityType::CrmCompany, EntityType::CrmContact] {+ let keys = vec![(+ viewer.clone(),+ entity_type.with_entity_string(Uuid::now_v7().to_string()),+ )];+ loader.load(&keys).await.unwrap();+ assert_eq!(+ soup.calls.lock().unwrap().last().unwrap().team_id,+ Some(team_id.to_string()),+ "{entity_type} hydration needs the viewer's team"+ );+ }+}diff --git a/crates/graphql_soup/src/objects.rs b/crates/graphql_soup/src/objects.rsindex 4e42c3a99f..708246ae2a 100644--- a/crates/graphql_soup/src/objects.rs+++ b/crates/graphql_soup/src/objects.rs@@ -113,6 +113,12 @@ pub trait SoupEntityEdges: ObjectType + Clone + Send + Sync + 'static {/// Construct the agent-session-specific edge object.fn agent_session_edges(session_id: Uuid, bot_id: Uuid) -> Self::AgentSessionEdges;+ /// Additional fields attached only to CRM company and contact entities.+ type CrmRecordEdges: ObjectType + Clone + Send + Sync + 'static;++ /// Construct the CRM-record edge object for a company or contact.+ fn crm_record_edges(record: model_entity::Entity<'static>) -> Self::CrmRecordEdges;+/// Resolve properties assigned to this entity.fn resolve_properties(&self,@@ -2381,6 +2387,14 @@ whereself.1.clone()}+ /// CRM-record fields, such as the pipeline rows referencing the company.+ #[graphql(flatten)]+ async fn crm_record_edges(&self) -> E::CrmRecordEdges {+ E::crm_record_edges(+ model_entity::EntityType::CrmCompany.with_entity_string(self.0.id.to_string()),+ )+ }+/// The viewer's frecency score for this entity, when loaded.async fn frecency_score(&self) -> Option<f64> {self.2diff --git a/crates/graphql_soup/src/objects/crm_contact.rs b/crates/graphql_soup/src/objects/crm_contact.rsindex 753ed4ae01..5a34e21085 100644--- a/crates/graphql_soup/src/objects/crm_contact.rs+++ b/crates/graphql_soup/src/objects/crm_contact.rs@@ -105,6 +105,13 @@ impl<E: SoupEntityEdges> GraphqlSoupCrmContact<E> {pub(super) async fn edges(&self) -> E {self.1.clone()}+ /// CRM-record fields, such as the pipeline rows referencing the contact.+ #[graphql(flatten)]+ pub(super) async fn crm_record_edges(&self) -> E::CrmRecordEdges {+ E::crm_record_edges(+ model_entity::EntityType::CrmContact.with_entity_string(self.0.id.to_string()),+ )+ }/// Optional viewer frecency score.pub(super) async fn frecency_score(&self) -> Option<f64> {self.2diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 8d26999ec6..30e5ff318a 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -144,6 +144,7 @@ github_pull_requests = { path = "../../crates/github_pull_requests", default-fea"service",] }graphql_soup = { path = "../../crates/graphql_soup" }+graphql_crm = { path = "../../crates/graphql_crm" }graphql_initiative = { path = "../../crates/graphql_initiative" }graphql_calendar = { path = "../../crates/graphql_calendar" }graphql_scheduled_action = { path = "../../crates/graphql_scheduled_action" }diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 50ec97da1e..c341bf2722 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -827,6 +827,7 @@ pub(crate) struct ApiContext {pub reminders_state: DssRemindersState,pub slack_state: DssSlackState,pub initiative_state: DssInitiativeState,+ pub graphql_crm_context: graphql_crm::CrmGraphqlContext,pub graphql_initiative_context: graphql_initiative::InitiativeGraphqlContext,pub graphql_scheduled_action_context: graphql_scheduled_action::ScheduledActionGraphqlContext,pub graphql_calendar_context: graphql_calendar::CalendarGraphqlContext,diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rsindex c66164a8f4..4af4b3cdf2 100644--- a/services/document_storage_service/src/api/graphql_soup.rs+++ b/services/document_storage_service/src/api/graphql_soup.rs@@ -185,6 +185,10 @@ fn insert_graphql_context_data(state.graphql_initiative_context.clone(),macro_user_id.clone(),));+ data.insert(graphql_crm::pipeline_entries_loader(+ state.graphql_crm_context.clone(),+ macro_user_id.clone(),+ ));data.insert(state.graphql_notification_reader.clone());data.insert(state.soup_router_state.email_service());data.insert(state.entity_access_service.clone());diff --git a/services/document_storage_service/src/server.rs b/services/document_storage_service/src/server.rsindex 9048bc9df9..513e885202 100644--- a/services/document_storage_service/src/server.rs+++ b/services/document_storage_service/src/server.rs@@ -2024,6 +2024,7 @@ pub async fn run() -> anyhow::Result<()> {graphql_agent_session_entity_loader: graphql_soup::AgentSessionEntityLoader(graphql_soup::soup_item_loader(primary_entity_soup, Arc::new(email_service.clone())),),+ graphql_crm_context: graphql_crm::CrmGraphqlContext::new(pipeline_service.clone()),graphql_initiative_context: graphql_initiative::InitiativeGraphqlContext::new(initiative_service.clone(),entity_access_service.clone(),diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 3b1c75f16b..769d550022 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -2837,6 +2837,135 @@ enum GraphqlCrmDiscussionReason {OWNER}+"""+A CRM pipeline the viewer can see.+"""+type GraphqlCrmPipeline {+ """+ The pipeline's identifier.+ """+ id: ID!+ """+ The pipeline's name.+ """+ name: String!+ """+ Which CRM record its rows reference.+ """+ recordType: GraphqlCrmPipelineRecordType!+ """+ Whether the pipeline is shared with its team.+ """+ sharing: GraphqlCrmPipelineSharing!+ """+ The table that pipeline operations name.+ """+ tableId: ID!+ """+ Whether the viewer may edit the pipeline's rows.+ """+ canEdit: Boolean!+}++"""+One cell of a pipeline row.+"""+type GraphqlCrmPipelineCell {+ """+ The cell's column.+ """+ column: GraphqlCrmPipelineColumn!+ """+ The cell's value, absent when the cell is empty.+ """+ value: GraphqlPropertyValue+}++"""+A pipeline column, with what its cells' values mean.+"""+type GraphqlCrmPipelineColumn {+ """+ The column's identifier.+ """+ id: ID!+ """+ The property definition the column binds.+ """+ propertyDefinitionId: ID!+ """+ The column's name.+ """+ name: String!+ """+ The type of value the column holds.+ """+ dataType: GraphqlPropertyDataType!+ """+ Whether a cell can hold more than one value; a relation always can.+ """+ isMultiSelect: Boolean!+ """+ Whether the column's cells take writes; derived columns are computed.+ """+ writable: Boolean!+ """+ The required entity type for a reference column, when constrained.+ """+ specificEntityType: GraphqlPropertyEntityType+ """+ The options a select column's cells choose from, in display order.+ """+ options: [GraphqlPropertyOption!]!+}++"""+A pipeline row that references a company or contact.+"""+type GraphqlCrmPipelineEntry {+ """+ The row's identifier.+ """+ id: ID!+ """+ The pipeline holding the row.+ """+ pipeline: GraphqlCrmPipeline!+ """+ The row's cells in column order, for every column but the reference+ to the record itself. An empty cell has no value.+ """+ cells: [GraphqlCrmPipelineCell!]!+}++"""+Which CRM record a pipeline's rows reference.+"""+enum GraphqlCrmPipelineRecordType {+ """+ Companies.+ """+ COMPANY+ """+ Contacts.+ """+ CONTACT+}++"""+Whether a pipeline is shared with its team.+"""+enum GraphqlCrmPipelineSharing {+ """+ Only people granted access individually.+ """+ PRIVATE+ """+ The whole team may edit.+ """+ TEAM+}+"""GraphQL input representing the crm scope."""@@ -6853,6 +6982,11 @@ type GraphqlSoupCrmCompany implements GraphqlSoupEntity {"""activity(limit: Int): [GraphqlActivityEvent!]!"""+ Rows of the viewer's live pipelines that reference this record, grouped+ by pipeline in each one's row order.+ """+ pipelineEntries: [GraphqlCrmPipelineEntry!]!+ """The viewer's frecency score for this entity, when loaded."""frecencyScore: Float@@ -6949,6 +7083,11 @@ type GraphqlSoupCrmContact implements GraphqlSoupEntity {"""activity(limit: Int): [GraphqlActivityEvent!]!"""+ Rows of the viewer's live pipelines that reference this record, grouped+ by pipeline in each one's row order.+ """+ pipelineEntries: [GraphqlCrmPipelineEntry!]!+ """Optional viewer frecency score."""frecencyScore: Float