Cotton code
412 lines · 19.4 KB · RustRaw
//! Groups kept in another table (`groups.kept_in`; Spec 10 G item 3, the//! architect's answer B): the photo list's groups ARE its albums. No row//! under [`groups::TABLE`] and no column: the album table's list is the//! groups' list — what `/photos/albums` shows, a suggestion waiting for its//! answer first, then the kept, never the dismissed — an album's page is the//! group's page, and each group verb is the album write the album tools//! already make, through the generic verb that records it://!//! - `create_group { table, name, records }` → `create_album` (born kept,//!   its kind read from the pictures' days, its cover the first picture);//! - `update_group { id, name }` → `update_record` on the album//!   (`update_album`, which keeps an open suggestion it renames, as always);//! - `update_group { id, add }` → `create_record` on its pictures, one at a//!   time (`update_album { add }`) — the album page's own "Add photos";//! - `update_group { id, remove }` → `delete_record` on its pictures//!   (`update_album { remove }`); the picture stays in Photos;//! - `delete_group { id }` → `update_record` on the album putting it away//!   (`decide_album` dismiss): nothing deletes an album.//!//! Each write leaves the change its generic verb leaves, so its receipt's//! Undo is the album's own. Order and filters are refused: an album keeps//! its pictures by when they were taken, picked by hand. Suggested, kept and//! dismissed, the cover and the days stay the album's own fields, moved only//! by the album's own rules.//!//! A group answers as every group does — `id` (the album's), `name`, `table`//! (the grouping table), `count` and `top` (the grouping table's records,//! the cover first) — and also `kept_in`, the table whose page opens it, and//! `byline`, the word its record's slip wears ("suggested").use cotton_core::definitions::GroupsKeptIn;use super::*;/// The most of a list read in one call.const PAGE: usize = crate::mcp::handlers::common::MAX_LIST as usize;/// Where `definition`'s groups are kept, when they are another table's records.pub(super) fn kept_in(definition: &TableDefinition) -> Option<&GroupsKeptIn> {    definition.groups.as_ref()?.kept_in.as_ref()}/// The grouping table whose groups are kept in a table holding `id` — an/// album named to `update_group` or `delete_group` — with where they are/// kept, or `None` when no such table holds it. An album holds every kind, so/// it is the group of the table over every kind (the library's), never of one/// narrowed to its own kind (Videos'): narrowed, a photo put in read as a film/// "no longer here" (main red after Videos' albums, ff2cbadce).pub(super) fn grouping_of(ctx: &Ctx<'_>, id: &str) -> Valid<Option<(TableDefinition, GroupsKeptIn)>> {    let mut narrowed = None;    for shipped in builtin_table_definitions() {        let Some(kept) = kept_in(&shipped).cloned() else { continue };        let table = definition(ctx, &kept.table)?;        if load(ctx, &table, id)?.is_some() {            let grouping = definition(ctx, &shipped.id)?;            if Kept::of(ctx, &kept)?.narrowed_to(&grouping).only.is_none() {                return Ok(Some((grouping, kept)));            }            narrowed.get_or_insert((grouping, kept));        }    }    Ok(narrowed)}/// The two tables a kept group is read and written through, and the columns/// of a member that name its group and its record.struct Kept {    groups: TableDefinition,    items: TableDefinition,    /// The item's column linking to its group (`album_id`).    link: String,    /// The item's column naming the grouped record (`record_id`).    record: String,    /// The item's column naming its record's table, and the one table read:    /// set when the grouping table is one of the kinds an item can hold    /// (Videos' albums hold and count only the films in them), unset for a    /// table over every kind (the library's).    only: Option<(String, String)>,}impl Kept {    fn of(ctx: &Ctx<'_>, kept: &GroupsKeptIn) -> Valid<Kept> {        let groups = definition(ctx, &kept.table)?;        let items = definition(ctx, &kept.items)?;        let link = items            .columns            .iter()            .find(|column| column.link_to.as_deref() == Some(kept.table.as_str()))            .map(|column| column.key.clone())            .ok_or_else(|| ToolFailure::new(format!("{} name no {}", items.plural, groups.name.to_lowercase())))?;        let record = items            .opens            .as_ref()            .map(|opens| opens.column.clone())            .ok_or_else(|| ToolFailure::new(format!("{} open no record", items.plural)))?;        Ok(Kept { groups, items, link, record, only: None })    }    /// Narrowed to the grouping table's own kind, when an item names its    /// record's table and that table is one of the names it may hold.    fn narrowed_to(mut self, grouping: &TableDefinition) -> Self {        let kind = self.items.opens.as_ref().and_then(|opens| opens.table_column.clone());        let holds = kind.as_ref().and_then(|key| self.items.columns.iter().find(|column| &column.key == key)).and_then(|column| column.choices.as_ref());        if let (Some(kind), Some(choices)) = (kind.clone(), holds) {            if choices.iter().any(|choice| choice == &grouping.id) {                self.only = Some((kind, grouping.id.clone()));            }        }        self    }    /// A group's live record, or the refusal every group verb gives.    fn group(&self, ctx: &Ctx<'_>, id: &str) -> Valid<Stored> {        load(ctx, &self.groups, id)?            .filter(|stored| stored.deleted_at.is_none())            .ok_or_else(|| ToolFailure::new("There is no such group. It may have been deleted."))    }    fn name(&self, ctx: &Ctx<'_>, group: &Stored) -> String {        cotton_core::records::receipt::record_name_in(&self.groups, &Value::Object(group.data.clone()), &super::date_words(ctx))    }    /// One page of a group's members as its items list reads them, and how    /// many it holds; `record` narrows it to that one record.    fn items(&self, ctx: &mut Ctx<'_>, group: &str, record: Option<&str>, page: usize, limit: usize) -> Valid<Value> {        let mut filter = Map::new();        filter.insert(self.link.clone(), Value::from(group));        if let Some((column, kind)) = &self.only {            filter.insert(column.clone(), Value::from(kind.as_str()));        }        if let Some(record) = record {            filter.insert(self.record.clone(), Value::from(record));        }        list_records(ctx, &json!({ "table": self.items.id, "where": filter, "page": page, "limit": limit }).as_object().cloned().unwrap_or_default())    }    /// The grouped records' ids, in the items list's order: every one, or the first `limit`.    fn member_ids(&self, ctx: &mut Ctx<'_>, group: &str, limit: Option<usize>) -> Valid<(Vec<String>, u64)> {        let mut ids = Vec::new();        let mut page = 0;        loop {            let read = self.items(ctx, group, None, page, limit.unwrap_or(PAGE).min(PAGE))?;            for item in read["records"].as_array().into_iter().flatten() {                if let Some(id) = item["data"][&self.record].as_str() {                    ids.push(id.to_string());                }            }            let total = read["total"].as_u64().unwrap_or(ids.len() as u64);            match read["next_page"].as_u64() {                Some(next) if limit.is_none_or(|limit| ids.len() < limit) => page = next as usize,                _ => return Ok((ids, total)),            }        }    }    /// The item that puts `record` in the group, when it is in it.    fn item_of(&self, ctx: &mut Ctx<'_>, group: &str, record: &str) -> Valid<Option<String>> {        let read = self.items(ctx, group, Some(record), 0, 1)?;        Ok(read["records"].as_array().and_then(|items| items.first()).and_then(|item| item["id"].as_str()).map(str::to_string))    }    /// The word the group's record wears on its slip ("suggested"), if any.    fn byline(&self, group: &Stored) -> Option<String> {        let byline = self.groups.slip.byline.as_ref()?;        let value = group.data.get(&byline.column)?.as_str()?;        byline.words.get(value).cloned()    }    /// A group as every group read answers it, its pile the grouping    /// table's own records: the cover on top, then the first members.    fn group_json(&self, ctx: &mut Ctx<'_>, grouping: &TableDefinition, group: &Stored) -> Valid<Value> {        let (first, count) = self.member_ids(ctx, &group.id, Some(groups::TOP + 1))?;        let cover = self            .groups            .columns            .iter()            .find(|column| column.key == "cover_id")            .and_then(|column| group.data.get(&column.key))            .and_then(Value::as_str)            .map(str::to_string);        let mut ids: Vec<String> = cover.into_iter().collect();        for id in first {            if !ids.contains(&id) {                ids.push(id);            }        }        let mut top = Vec::new();        for id in ids {            if top.len() == groups::TOP {                break;            }            if let Some(stored) = load(ctx, grouping, &id)?.filter(|stored| stored.deleted_at.is_none()) {                top.push(stored);            }        }        derive_records(ctx, grouping, &mut top, &Map::new(), false)?;        Ok(json!({            "id": group.id,            "name": self.name(ctx, group),            "table": grouping.id,            "count": count,            "top": top.iter().map(|stored| stored.to_json(&grouping)).collect::<Vec<_>>(),            "kept_in": self.groups.id,            "byline": self.byline(group),        }))    }    /// Every group as the group table's own list reads it.    fn every(&self, ctx: &mut Ctx<'_>) -> Valid<Vec<Stored>> {        let mut found = Vec::new();        let mut page = 0;        loop {            let read = list_records(ctx, &json!({ "table": self.groups.id, "page": page, "limit": PAGE }).as_object().cloned().unwrap_or_default())?;            for record in read["records"].as_array().into_iter().flatten() {                let Some(id) = record["id"].as_str() else { continue };                if let Some(stored) = load(ctx, &self.groups, id)?.filter(|stored| stored.deleted_at.is_none()) {                    found.push(stored);                }            }            match read["next_page"].as_u64() {                Some(next) => page = next as usize,                None => return Ok(found),            }        }    }}/// `list_groups { table, record? }` on a table whose groups are kept/// elsewhere: the kept table's list, each record as a group.pub(super) fn list(ctx: &mut Ctx<'_>, grouping: &TableDefinition, kept: &GroupsKeptIn, record: Option<String>) -> ToolResult {    let kept = Kept::of(ctx, kept)?.narrowed_to(grouping);    let mut answered = Vec::new();    for group in kept.every(ctx)? {        let mut answer = kept.group_json(ctx, grouping, &group)?;        // An album with none of this kind in it is not one of its groups.        if kept.only.is_some() && answer["count"].as_u64() == Some(0) {            continue;        }        if let Some(record) = &record {            answer["holds"] = Value::from(kept.item_of(ctx, &group.id, record)?.is_some());        }        answered.push(answer);    }    Ok(json!({ "table": grouping.id, "groups": answered }))}/// The members of a kept group as the grouping table's records, in the/// group's items' order — what `list_records { where: { group } }` pages.pub(super) fn members(    ctx: &mut Ctx<'_>,    grouping: &TableDefinition,    kept: &GroupsKeptIn,    group: &str,) -> Valid<Vec<Stored>> {    let kept = Kept::of(ctx, kept)?.narrowed_to(grouping);    let group = kept.group(ctx, group)?;    let mut found = Vec::new();    for id in kept.member_ids(ctx, &group.id, None)?.0 {        if let Some(stored) = load(ctx, grouping, &id)?.filter(|stored| stored.deleted_at.is_none()) {            found.push(stored);        }    }    Ok(found)}/// A group verb's answer: the change the generic verb recorded, its receipt/// saying it as a group's change does, and the group as it now stands.fn answer(ctx: &mut Ctx<'_>, grouping: &TableDefinition, kept: &Kept, id: &str, mut change: Value, said: Option<String>) -> ToolResult {    if let Some(said) = said {        change["receipt"]["said"] = Value::from(said);    }    let group = match load(ctx, &kept.groups, id)?.filter(|stored| stored.deleted_at.is_none()) {        Some(group) => kept.group_json(ctx, grouping, &group)?,        None => Value::Null,    };    Ok(json!({ "change": change, "group": group }))}/// Who a receipt names: one record by its own name, several by how many.fn who(ctx: &Ctx<'_>, grouping: &TableDefinition, ids: &[String]) -> Valid<String> {    if let [id] = ids {        if let Some(stored) = load(ctx, grouping, id)? {            return Ok(cotton_core::records::receipt::record_name_in(grouping, &Value::Object(stored.data), &super::date_words(ctx)));        }    }    let noun = if ids.len() == 1 { &grouping.name } else { &grouping.plural };    Ok(format!("{} {}", ids.len(), noun.to_lowercase()))}/// `create_group { table, name, records }` → `{ change, group }`: the album/// `create_album` makes of the records, named `name`.pub(super) fn create(ctx: &mut Ctx<'_>, grouping: &TableDefinition, kept: &GroupsKeptIn, args: &Map<String, Value>) -> ToolResult {    let kept = Kept::of(ctx, kept)?;    let noun = kept.groups.name.to_lowercase();    if args.get("where").is_some_and(|value| !value.is_null()) {        return Err(ToolFailure::new(format!("An {noun} holds pictures picked by hand; it keeps no where.")));    }    let name = optional_string(args, "name").ok_or_else(|| ToolFailure::new(format!("Give the {noun} a name.")))?;    let records = groups::records_arg(args, "records")?.unwrap_or_default();    if records.is_empty() {        return Err(ToolFailure::new(format!(            "An {noun} is made from its {}: pick some, then make the {noun} of them.",            grouping.plural.to_lowercase()        )));    }    for record in &records {        load_live(ctx, grouping, record)?;    }    let made = match kept.groups.id.as_str() {        "album" => {            builtin::permit_tool(ctx, &kept.groups, "create_album")?;            let made = crate::mcp::handlers::albums::create_album_for_group(ctx, &name, &records)?;            ctx.commit()?;            made        }        other => return Err(ToolFailure::new(format!("Groups are not kept in {other}."))),    };    let id = made["id"].as_str().map(str::to_string).ok_or_else(|| ToolFailure::new("the album was made but its id was not answered"))?;    let group = kept.group(ctx, &id)?;    let said = format!("Made {} with {}", kept.name(ctx, &group), who(ctx, grouping, &records)?);    answer(ctx, grouping, &kept, &id, made["change"].clone(), Some(said))}/// `update_group { id, name | add | remove }` on a kept group → `{ change,/// group }`, one thing per call as every group's: the record renamed, or/// records put in or taken out through its items. `order` and `where` are/// refused, in the group's own words.pub(super) fn update(ctx: &mut Ctx<'_>, grouping: &TableDefinition, kept: &GroupsKeptIn, id: &str, args: &Map<String, Value>) -> ToolResult {    let kept = Kept::of(ctx, kept)?;    let group = kept.group(ctx, id)?;    let name = kept.name(ctx, &group);    let asked: Vec<&str> = ["name", "add", "remove", "order", "where"]        .into_iter()        .filter(|key| args.get(*key).is_some_and(|value| !value.is_null()))        .collect();    let [asked] = asked[..] else {        return Err(ToolFailure::new("Say one change: name, add or remove."));    };    let pictures = grouping.plural.to_lowercase();    match asked {        "name" => {            let new = optional_string(args, "name").ok_or_else(|| ToolFailure::new("Give the group a name."))?;            let written = update_record_now(                ctx,                json!({ "table": kept.groups.id, "id": id, "patch": { kept.groups.title.clone(): new } }).as_object().expect("an object"),            )?;            let written = automations::run(ctx, written)?;            answer(ctx, grouping, &kept, id, written["change"].clone(), None)        }        "add" => {            let mut adding = Vec::new();            for record in groups::records_arg(args, "add")?.unwrap_or_default() {                load_live(ctx, grouping, &record)?;                if kept.item_of(ctx, id, &record)?.is_none() {                    adding.push(record);                }            }            if adding.is_empty() {                return Err(ToolFailure::new(format!("Already in {name}.")));            }            let mut change = Value::Null;            for record in &adding {                let written = create_record_within(ctx, &kept.items.id, json!({ kept.link.clone(): id, kept.record.clone(): record }))?;                change = written["change"].clone();            }            // Each picture went in as its own write: one Undo would take            // back only the last, so several put in at once carry none.            if adding.len() > 1 {                change["undoable"] = Value::from(false);                change["reason"] = Value::from(format!("{} {pictures} went in at once; take any out from {name}'s page", adding.len()));            }            let said = format!("Added {} to {name}", who(ctx, grouping, &adding)?);            answer(ctx, grouping, &kept, id, change, Some(said))        }        "remove" => {            let mut removing = Vec::new();            for record in groups::records_arg(args, "remove")?.unwrap_or_default() {                if let Some(item) = kept.item_of(ctx, id, &record)? {                    removing.push((record, item));                }            }            if removing.is_empty() {                return Err(ToolFailure::new(format!("Not in {name}.")));            }            let said = format!("Removed {} from {name}", who(ctx, grouping, &removing.iter().map(|(record, _)| record.clone()).collect::<Vec<_>>())?);            let mut change = Value::Null;            for (_, item) in &removing {                let written = delete_record_now(ctx, json!({ "table": kept.items.id, "id": item }).as_object().expect("an object"))?;                change = written["change"].clone();            }            answer(ctx, grouping, &kept, id, change, Some(said))        }        "order" => Err(ToolFailure::new(format!("{name} keeps its {pictures} in the order they were taken."))),        _ => Err(ToolFailure::new(format!("{name} holds {pictures} picked by hand; it keeps no where."))),    }}/// `delete_group { id }` on a kept group → `{ change, group: null }`: the/// record put away as its table puts one away (an album dismissed), its/// members untouched; its receipt's Undo brings it back.pub(super) fn delete(ctx: &mut Ctx<'_>, kept: &GroupsKeptIn, id: &str) -> ToolResult {    let kept = Kept::of(ctx, kept)?;    kept.group(ctx, id)?;    let (column, value) = builtin::put_away(&kept.groups.id)        .ok_or_else(|| ToolFailure::new(format!("{} are never deleted", kept.groups.plural)))?;    let written = update_record_now(        ctx,        json!({ "table": kept.groups.id, "id": id, "patch": { column: value } }).as_object().expect("an object"),    )?;    let written = automations::run(ctx, written)?;    Ok(json!({ "change": written["change"], "group": Value::Null }))}