//! 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};usecrate::mcp::dispatch::{handler_for, Ctx, ToolResult};usecrate::mcp::handlers::common::now_iso;usecrate::mcp::handlers::projects::validate::CreateProjectArgs;usecrate::mcp::handlers::projects::write::create_project_row;usecrate::mcp::protocol::ToolFailure;/// The refusal an unknown template id earns, naming the ones that exist.pubfn 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: &mutCtx<'_>, name: &'static str, args: Map<String, Value>) -> ToolResult {letSome(handler) = handler_for(name) else {returnErr(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<String> { 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<String> {if result.get("note").is_some() {returnNone; } 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.pubfn seed_project_template( ctx: &mutCtx<'_>, template: &ProjectTemplate, project_slug: &str,) -> Result<Value, ToolFailure> {letmut failures: Vec<Value> = Vec::new();letmut records: Vec<Value> = Vec::new();letmut todos = 0_i64;letmut money_account = false;let failure = |seed: &str, label: &str, error: String| {letmut 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 {letmut args = Map::new(); args.insert("title".to_string(), Value::from(todo.title));ifletSome(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;ifletSome(id) = seeded_todo_id(&written) {letmut 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)), } }ifletSome(account) = template.seeds.money_account {letmut 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();ifletSome(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)), } }letmut 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;letmut 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)), } }letmut 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.pubfn create_project_from_template( ctx: &mutCtx<'_>, args: &CreateProjectArgs, template_id: &str,) -> ToolResult {letSome(template) = project_template(template_id) else {returnErr(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)?;letmut out = created.as_object().cloned().unwrap_or_default(); out.insert("seeded".to_string(), seeded);Ok(Value::Object(out))}