//! Project templates — the seeding half of `create_project { template }`. //! //! NOT a handler group any more: `list_project_templates` was this module's one //! tool and it is retired. What each template seeds is now `create_project`'s //! own `template` description, read at the moment a caller has to choose — a //! separate read tool to learn three ids was a round trip to restate an enum. //! The module stays because the SEEDING is reached as a LIBRARY: by //! `projects::write` for the tool, and by the server's //! `POST /v1/projects/from-template` for the route. //! //! The list itself is `cotton_core::templates::PROJECT_TEMPLATES`; nothing //! about what a cab driver's project starts with is decided here. What lives //! here is the SEEDING, and it lives here ONCE. //! //! Every seed goes through the writer the matching tool already uses — //! `create_todo`, `create_money_account`, `link_to_project` — so a seeded row //! is indistinguishable from one an assistant wrote by hand, and each writer's //! own rules (RRULE validation, the money account identity check) apply without //! being restated. They are reached through the DISPATCH TABLE rather than by a //! direct call, which is the same indirection for a different reason on each //! side: it keeps the groups from importing one another, and it means a seed //! whose tool has not been ported yet reports the catalogue's own sentence as a //! failure instead of failing to compile. //! //! A SEED THAT FAILS DOES NOT FAIL THE PROJECT. The project row is the thing //! the person asked for; a todo whose recurrence the workspace cannot yet //! materialize is a partial answer, not a reason to leave them with nothing. //! Every failure is caught, named and reported back, so the caller can say //! which seeds landed instead of guessing. use cotton_core::templates::{project_template, ProjectTemplate}; use serde_json::{Map, Value}; use crate::mcp::dispatch::{handler_for, Ctx, ToolResult}; use crate::mcp::handlers::common::now_iso; use crate::mcp::handlers::projects::validate::CreateProjectArgs; use crate::mcp::handlers::projects::write::create_project_row; use crate::mcp::protocol::ToolFailure; /// The refusal an unknown template id earns, naming the ones that exist. pub fn unknown_template(id: &str) -> ToolFailure { ToolFailure::new(format!( "no project template \"{id}\" — the templates are {}, and create_project's own `template` \ description says what each one seeds", cotton_core::templates::PROJECT_TEMPLATE_IDS.join(", ") )) } /// Call one tool by name, through the dispatch table. /// /// A tool this build has not ported yet answers the catalogue's own sentence, /// which lands in `failures` exactly as any other seed failure would. fn call(ctx: &mut Ctx<'_>, name: &'static str, args: Map) -> ToolResult { let Some(handler) = handler_for(name) else { return Err(ToolFailure::new(format!( "{name} is not implemented on this server yet" ))); }; handler(ctx, &args) } /// The id a writer's answer carries, or `None`. fn written_id(result: &Value) -> Option { result.get("id").and_then(Value::as_str).map(str::to_string) } /// The id of the todo `create_todo` just wrote, or `None` when there is not one /// to link yet. /// /// A recurring todo is a TEMPLATE plus materialized occurrences, and the writer /// answers with the first occurrence — except in the one case where the /// workspace has no timezone yet, when it answers with the RECURRENCE's id and /// a `note` saying occurrences appear later. That id is not a `cotton_todos` /// row, so linking it would fail the link's own existence check and lose the /// whole batch. The `note` is the discriminator the writer already provides. fn seeded_todo_id(result: &Value) -> Option { if result.get("note").is_some() { return None; } written_id(result) } /// Fill a project from its template. The project must already exist — this /// writes the todos and money account, then files what it wrote into the /// project. pub fn seed_project_template( ctx: &mut Ctx<'_>, template: &ProjectTemplate, project_slug: &str, ) -> Result { let mut failures: Vec = Vec::new(); let mut records: Vec = Vec::new(); let mut todos = 0_i64; let mut money_account = false; let failure = |seed: &str, label: &str, error: String| { let mut out = Map::new(); out.insert("seed".to_string(), Value::from(seed)); out.insert("label".to_string(), Value::from(label)); out.insert("error".to_string(), Value::from(error)); Value::Object(out) }; for todo in template.seeds.todos { let mut args = Map::new(); args.insert("title".to_string(), Value::from(todo.title)); if let Some(rrule) = todo.rrule { // A recurrence needs a start, and today is the only honest one: the // person is told what repeats, and moves the date when they know it. args.insert("rrule".to_string(), Value::from(rrule)); args.insert("dueAt".to_string(), Value::from(now_iso(ctx))); } match call(ctx, "create_todo", args) { Ok(written) => { todos += 1; if let Some(id) = seeded_todo_id(&written) { let mut record = Map::new(); record.insert("kind".to_string(), Value::from("todo")); record.insert("id".to_string(), Value::from(id)); records.push(Value::Object(record)); } } Err(error) => failures.push(failure("todo", todo.title, error.0)), } } if let Some(account) = template.seeds.money_account { let mut args = Map::new(); args.insert("name".to_string(), Value::from(account.name)); args.insert( "kind".to_string(), Value::from(account.subtype.widen().as_str()), ); // A template names no currency: the account is held in the book's // own. A book with none yet is asked by the refusal, not given one. let home = crate::mcp::handlers::money::model::load_money_accounts(ctx) .map(|accounts| crate::mcp::handlers::money::accounts::home_currency(&accounts)) .unwrap_or_default(); if let Some(home) = home { args.insert("currency".to_string(), Value::from(home)); } match call(ctx, "create_money_account", args) { Ok(_) => money_account = true, Err(error) => failures.push(failure("money_account", account.name, error.0)), } } let mut links = 0_i64; if !records.is_empty() { // One call, because `link_to_project` validates every target before it // writes anything — a batch is how the seeds land together or not at // all, rather than half-filed. let count = records.len() as i64; let mut args = Map::new(); args.insert("project".to_string(), Value::from(project_slug)); args.insert("records".to_string(), Value::Array(records)); match call(ctx, "link_to_project", args) { Ok(_) => links = count, Err(error) => failures.push(failure("link", project_slug, error.0)), } } let mut report = Map::new(); report.insert("template".to_string(), Value::from(template.id)); report.insert("todos".to_string(), Value::from(todos)); report.insert("moneyAccount".to_string(), Value::Bool(money_account)); report.insert("links".to_string(), Value::from(links)); report.insert("failures".to_string(), Value::Array(failures)); Ok(Value::Object(report)) } /// `create_project` with a `template` — the project, then its seeds. pub fn create_project_from_template( ctx: &mut Ctx<'_>, args: &CreateProjectArgs, template_id: &str, ) -> ToolResult { let Some(template) = project_template(template_id) else { return Err(unknown_template(template_id)); }; // The project is created by the SAME writer as an ordinary one, so its slug // rules, its reserved-word refusal and its summary provenance are one // implementation. A description the caller gave wins over the template's: // somebody who wrote their own paragraph meant it. let created = create_project_row( ctx, &args.slug, &args.name, Some( args.description .as_deref() .unwrap_or(template.seeds.description), ), args.repos.as_deref(), )?; let seeded = seed_project_template(ctx, template, &args.slug)?; let mut out = created.as_object().cloned().unwrap_or_default(); out.insert("seeded".to_string(), seeded); Ok(Value::Object(out)) }