//! `get_record`'s `page`: the record page in one read//! (`cotton_core::records::page::record_page_read`), read through this//! database's own generic reads — the same answer the phone's//! `records.page` gives.use cotton_core::definitions::TableDefinition;use cotton_core::records::page::{HandleActivity, PageSource};use serde_json::{json, Map, Value};usesuper::{get_record_by_table, list_answer, Total, MAX_PAGE_SIZE};usecrate::mcp::dispatch::Ctx;use cotton_core::rules::mail_predicate;structCtxPages<'a, 'b> { ctx: &'a mutCtx<'b>,}fn rows_of(answer: &Value) -> Vec<(String, Map<String, Value>)> { answer["records"] .as_array() .into_iter() .flatten() .filter_map(|record| Some((record["id"].as_str()?.to_string(), record["data"].as_object()?.clone()))) .collect()}fn args(value: Value) -> Map<String, Value> { value.as_object().cloned().unwrap_or_default()}implPageSourceforCtxPages<'_, '_> {fn line_rows(&mutself) -> Vec<cotton_core::rules::shell_lines::LineRow> {crate::presentation::line_rows(self.ctx.read.driver(), self.ctx.workspace_id) }fn definition(&mutself, table: &str) -> Option<TableDefinition> {super::definition(self.ctx, table).ok() }fn record(&mutself, table: &str, id: &str) -> Result<Map<String, Value>, String> {let record = get_record_by_table(self.ctx, &args(json!({ "table": table, "id": id }))).map_err(|failure| failure.to_string())?;// A read answers a deleted record too; its page is gone.if !record["deleted_at"].is_null() {let definition = self.definition(table).ok_or_else(|| format!("there is no table {table:?}"))?;returnErr(cotton_core::records::receipt::no_longer_here(&definition)); }Ok(record["data"].as_object().cloned().unwrap_or_default()) }fn records(&mutself, table: &str, ids: &[String]) -> Result<Vec<(String, Map<String, Value>)>, String> {letmut found = Vec::new();for some in ids.chunks(MAX_PAGE_SIZE as usize) {let answer = list_answer(self.ctx, &args(json!({ "table": table, "ids": some })), Total::Skipped).map_err(|failure| failure.to_string())?; found.extend(rows_of(&answer)); }Ok(found) }fn list(&mutself, table: &str, filter: &Map<String, Value>, limit: usize) -> Result<(u64, Vec<(String, Map<String, Value>)>), String> {let answer = list_answer(self.ctx, &args(json!({ "table": table, "where": filter, "limit": limit.max(1) })), Total::Counted) .map_err(|failure| failure.to_string())?;letmut rows = rows_of(&answer); rows.truncate(limit);Ok((answer["total"].as_u64().unwrap_or_default(), rows)) }fn active_project_slugs(&mutself) -> Vec<String> {letmut slugs = Vec::new();letmut page = Some(0_u64);whileletSome(at) = page {let asked = json!({ "table": "project", "where": { "status": "active" }, "page": at, "limit": MAX_PAGE_SIZE });letOk(answer) = list_answer(self.ctx, &args(asked), Total::Skipped) else { break }; slugs.extend(rows_of(&answer).into_iter().filter_map(|(_, data)| data.get("slug")?.as_str().map(str::to_string))); page = answer["next_page"].as_u64().filter(|next| *next > at); } slugs }/// A page's list over a read is the phone's to draw; here it draws none.fn read(&mutself, name: &str, _args: &Map<String, Value>) -> Result<Value, String> {Err(format!("get_record reads no `read.{name}`")) }fn now(&mutself) -> Option<chrono::DateTime<chrono::Utc>> {Some(self.ctx.now) }fn definitions(&mutself) -> Vec<TableDefinition> {crate::definitions::shared_table_definitions(self.ctx).map(|found| found.definitions.clone()).unwrap_or_default() }fn handle_activity(&mutself, kind: &str, normalised: &str) -> Vec<HandleActivity> { handle_activity(self.ctx, kind, normalised) }}/// Where this database holds activity with a handle, one row per channel/// with its newest stamp: messages in a direct chat with a contact the/// handle names, or sent by one in a group, on their own channel; calls with/// the number (a WhatsApp call is WhatsApp's, any other a call); mail from/// or among the address. A database without one of these stores answers/// what the others hold.const HANDLE_ACTIVITY: &str = "WITH contacts AS ( SELECT contact_id FROM cotton_msg_contact_handles WHERE workspace_id = ?1 AND kind = ?2 AND value = ?3)SELECT m.channel AS channel, MAX(m.sent_at) AS at FROM cotton_msg_messages m JOIN cotton_msg_threads t ON t.id = m.thread_id WHERE m.workspace_id = ?1 AND m.deleted_at IS NULL AND t.trashed_at IS NULL AND ((t.kind = 'dm' AND t.contact_id IN (SELECT contact_id FROM contacts)) OR m.sender_participant_id IN (SELECT id FROM cotton_msg_thread_participants WHERE contact_id IN (SELECT contact_id FROM contacts))) GROUP BY m.channel";const CALL_ACTIVITY: &str = "SELECT CASE WHEN provider = 'whatsapp' THEN 'whatsapp' ELSE 'call' END AS channel, MAX(started_at) AS at FROM cotton_call_log WHERE workspace_id = ?1 AND (handle = ?2 OR contact_id IN (SELECT contact_id FROM cotton_msg_contact_handles WHERE workspace_id = ?1 AND kind = 'phone' AND value = ?2)) GROUP BY 1";static MAIL_ACTIVITY: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| { format!("SELECT 'mail' AS channel, MAX(sent_at) AS at FROM cotton_emails WHERE workspace_id = ?1 AND {live_mail} AND (lower(from_email) = ?2 OR thread_id IN (SELECT thread_id FROM cotton_email_participants WHERE workspace_id = ?1 AND lower(email) = ?2))", live_mail = mail_predicate::live("") )});/// The evidence [`cotton_core::records::page::channels_for_handle`] orders,/// read from this database's own message, call and mail stores — the phone's/// `records.page` reads it through the same function.pubfn handle_activity(ctx: &Ctx<'_>, kind: &str, normalised: &str) -> Vec<HandleActivity> {use rusqlite::types::ValueasSql;let text = |value: &str| Sql::Text(value.to_string());let workspace = text(ctx.workspace_id);letmut asks = vec![(HANDLE_ACTIVITY, vec![workspace.clone(), text(kind), text(normalised)])];match kind {"phone" => asks.push((CALL_ACTIVITY, vec![workspace, text(normalised)])),"email" => asks.push((MAIL_ACTIVITY.as_str(), vec![workspace, text(&normalised.to_lowercase())])), _ => {} }letmut found = Vec::new();for (sql, params) in asks {// A store this database does not keep holds no evidence.letOk(rows) = ctx.read.driver().all(sql, ¶ms) else { continue }; found.extend(rows.iter().filter_map(|row| {Some(HandleActivity { channel: row.text("channel")?.to_string(), at: row.text("at")?.to_string() }) })); } found}/// The page of `table`'s record `id` standing on `view`, or why none could/// be made (the record itself still answers).pubfn page(ctx: &mutCtx<'_>, table: &str, id: &str, view: Option<&str>) -> Result<Value, String> {let read = cotton_core::records::page::record_page_read(&mutCtxPages { ctx }, table, id, view)?; serde_json::to_value(read).map_err(|error| error.to_string())}