diff --git a/AGENTS.md b/AGENTS.md index 890c4ff..7f1ada0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ on a Real Geeks website; the second is for agents changing this repository. `geekcli` is the Real Geeks command line. Today it manages a site's website content: blog posts and categories, content, area, agent, market report and home valuation pages, the home page, navigation, sidebars, footers, banners, settings, -design and uploaded files. +search forms, design and uploaded files. Install: @@ -54,7 +54,7 @@ The rules that keep a live site safe: write again. `--fail-on-warnings` turns them into exit 5. 6. Note `revisions --limit 1` before a large rewrite of a page, area page, market report, valuation page, post, footer, sidebar or navigation bar (and - `settings revisions` / `design revisions` before those), so a bad result + `settings revisions` / `design revisions` / `search-forms revisions` before those), so a bad result is one `revert` away. A deleted or overwritten file comes back with `files restore` for 90 days. 7. Check search criteria with `search check --count --strict` before putting @@ -101,6 +101,7 @@ src/ ├── sidebars.rs # sidebars and html/links items ├── footers.rs # shared footer HTML blocks ├── settings.rs # typed site settings; coerce() maps NAME=value text to JSON + ├── search_forms.rs # the search forms document (advanced tabs, home page search): get/fields/update --data/reset, revisions ├── design.rs # template + colour scheme; preview link rendered via snapshot::render ├── banners.rs # banners; pages attach one with --banner (pages::AttachArgs) ├── featured.rs # Featured Pages tile groups (anna-modern home page) diff --git a/Cargo.lock b/Cargo.lock index 81c3bdc..cf5b106 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -924,9 +924,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -3172,9 +3172,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", diff --git a/README.md b/README.md index ae53c66..5b0f244 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ The Real Geeks command line. `geekcli` manages a Real Geeks website: blog posts and categories, content, area, agent, market report and home valuation -pages, the home page, navigation, sidebars, footers, banners, settings, design and uploaded -files. It is +pages, the home page, navigation, sidebars, footers, banners, settings, search +forms, design and uploaded files. It is built to be driven by scripts and AI agents as much as by people: JSON on stdout when piped, JSON errors on stderr, stable exit codes, and a built-in guide written for agents. @@ -36,8 +36,8 @@ A Real Geeks website can be run by the AI tools you already use: - **The whole site is an open, documented API.** Blog posts, pages, neighborhood (area) pages, market report and home valuation pages, the home - page, navigation, - sidebars, footers, banners, settings, design and files, all described in the + page, navigation, sidebars, footers, banners, settings, search forms, design + and files, all described in the [Content API documentation](https://developers.realgeeks.com/content-api/). - **Two ways in.** Connect Claude or ChatGPT to the site and ask in plain English, or let a coding agent such as Claude Code or Codex drive geekcli. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 7a108da..8c01aa6 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -398,6 +398,7 @@ subcommands: `revisions` (list), `revision` (preview) and `revert` (undo). | banners | `banners` | every field | | site settings | `settings` | the settings that save changed | | design | `design` | `template` and `styles` (the colour scheme and its variables) | +| search forms | `search-forms` | the whole set of search forms (§31) | For content this is the same history as the admin's Versions page, so changes made in the admin appear here and can be reverted here, and the @@ -1614,3 +1615,53 @@ geekcli valuation-pages delete /riverside-home-value/ --mobile`): a long headline pushes the address box down on a phone. API reference: [Home valuation pages](https://developers.realgeeks.com/content-api/site-pages/#home-valuation-pages). + +## 31. Search forms + +The site's search forms are the advanced search tabs (Advanced Search, +Condo Search, Sold Search…, as `pages`) and the home page search +(`home_page_forms`): which fields each shows, in what order, with what +labels. The site owner edits the same thing at Search Forms in the site +backend. The whole document is read, edited and sent back. + +```bash +geekcli search-forms get > forms.json # pages, fields, rules +geekcli search-forms fields -s school # what the MLS offers +geekcli search-forms update --data @forms.json --dry-run +geekcli search-forms update --data @forms.json +geekcli search-forms revisions --limit 1 +geekcli search-forms reset # back to the board's forms +``` + +- `pages` is the full list of tabs in order: leave a page out to remove + it, leave out `id` to create one. `home_page_forms` can be changed but + not added to or removed. Omit either key to keep it. +- Each page has `primary` (location, or the search box) and `secondary` + (property details). An item is `{"field": "city", "label": "Town", + "widget": "multiselect"}`; a min/max field is one item, + `{"field": "beds", "range": "min", "label_min": "Bedrooms"}`. +- Each page's `rules` say what its layout shows, and anything else is + refused (exit 5): advanced pages take only drop-downs and lists + (`select`, `multiselect`) in `primary`; home page forms show only + price, beds, baths and property types in `secondary`; the theme writes + some labels itself (Price, Sold Within). +- `"fixed": true` items are built-in filters (Condo Search's type = condo, + Sold Search's "Sold only"). They can't be removed; remove the page. +- MLS Number Search and Address Search are ready-made + (`"prepackaged": true`): nothing on them changes. Add one back with just + `{"id": "mls_search"}`; `prepackaged_pages` lists what the site can add, + including the board's filter pages. +- A field whose choices come from the MLS is refused when it would load + more than 3,000 of them (street names, for example); `fields` shows each + one's `choices`. Always `--dry-run` first: it runs this check too. +- Warnings, not errors: `long_form` (more than 14 drop-downs on a page: + suggest trimming) and `area_directory_changes` (Advanced Search starts + with a different field, which reorganizes the area pages' Browse All + directory). +- The first save copies the board's forms onto the site, after which + board changes no longer reach it. `reset` undoes that; `revert` undoes + one change and everything after it. +- Snapshot a search page after a change (`geekcli snapshot + /search/advanced_search/`). + +API reference: [Search forms](https://developers.realgeeks.com/content-api/design-settings-files/#search-forms). diff --git a/src/cli.rs b/src/cli.rs index 29f74a1..0fa592d 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -6,8 +6,8 @@ use clap_complete::Shell; use crate::client::Client; use crate::commands::{ agent_pages, api, area_pages, auth, banners, blog_home, categories, design, featured, files, - footers, guide, home_page, inspect, market_reports, nav, pages, posts, search, settings, - sidebars, snapshot, templates, update, valuation_pages, Context, + footers, guide, home_page, inspect, market_reports, nav, pages, posts, search, search_forms, + settings, sidebars, snapshot, templates, update, valuation_pages, Context, }; use crate::config::{self, Config, Overrides}; use crate::error::{Error, Result}; @@ -154,6 +154,9 @@ pub enum Command { Featured(featured::FeaturedCommand), /// Site settings Settings(settings::SettingsCommand), + /// The site's search forms: advanced search tabs and the home page search + #[command(name = "search-forms")] + SearchForms(search_forms::SearchFormsCommand), /// Template and colour scheme, with unsaved previews Design(design::DesignCommand), /// Uploaded files (images, PDFs) on the site's media bucket @@ -243,6 +246,7 @@ fn dispatch(cli: Cli, printer: Printer) -> Result<()> { Command::Banners(cmd) => banners::run(&ctx, cmd), Command::Featured(cmd) => featured::run(&ctx, cmd), Command::Settings(cmd) => settings::run(&ctx, cmd), + Command::SearchForms(cmd) => search_forms::run(&ctx, cmd), Command::Design(cmd) => design::run(&ctx, cmd), Command::Files(cmd) => files::run(&ctx, cmd), Command::Snapshot(args) => snapshot::run(&ctx, &args), diff --git a/src/commands/guide.rs b/src/commands/guide.rs index 9ee75d9..fb46b2c 100644 --- a/src/commands/guide.rs +++ b/src/commands/guide.rs @@ -100,6 +100,9 @@ pub fn find(all: &[Section<'_>], topic: &str) -> Vec { ("revert", "revisions and undo"), ("history", "revisions and undo"), ("restore", "files"), + ("search-forms", "search forms"), + ("forms", "search forms"), + ("tabs", "search forms"), ]; let needle = aliases .iter() diff --git a/src/commands/mod.rs b/src/commands/mod.rs index a60cbc5..af32b51 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -22,6 +22,7 @@ pub mod posts; pub mod provenance; pub mod revisions; pub mod search; +pub mod search_forms; pub mod settings; pub mod sidebars; pub mod snapshot; diff --git a/src/commands/search_forms.rs b/src/commands/search_forms.rs new file mode 100644 index 0000000..9faa80b --- /dev/null +++ b/src/commands/search_forms.rs @@ -0,0 +1,245 @@ +//! `geekcli search-forms …` — the site's search forms: the advanced search +//! tabs (`pages`) and the home page search (`home_page_forms`), which +//! fields each shows and how. The whole document is read and sent back, so +//! `update` takes JSON rather than flags. + +use clap::{Args, Subcommand}; +use serde_json::{json, Value}; + +use super::{confirm, Context}; +use crate::client::Query; +use crate::error::{Error, Result}; +use crate::html; +use crate::output::{col, Column, Format}; + +pub const PATH: &str = "search-forms/"; + +pub const PAGE_COLUMNS: &[Column] = &[ + col("form", "/form"), + col("id", "/id"), + col("name", "/name"), + col("fields", "/field_count"), + col("ready-made", "/prepackaged"), +]; + +pub const FIELD_COLUMNS: &[Column] = &[ + col("key", "/key"), + col("label", "/label"), + col("group", "/group"), + col("kind", "/kind"), + col("choices", "/choices"), +]; + +const RULES: &str = "Notes: + - Workflow: `search-forms get > forms.json`, edit it, `search-forms update --data @forms.json --dry-run`, then the same without --dry-run. + - `pages` is the full list of advanced search tabs in order: a page left out is removed, a page without an id is created (its id comes from its name). `home_page_forms` can be changed, not added or removed. Leave either key out to keep it. + - An item is {\"field\": \"city\", \"label\": ..., \"widget\": ...}; a min/max field (price, beds, area) is one item: {\"field\": \"beds\", \"range\": \"both\"|\"min\"|\"max\", \"label_min\": ..., \"label_max\": ...}. + - Each page's `rules` say what its layout shows; anything else is refused (exit 5): advanced pages show only drop-downs and lists (select, multiselect) in `primary`; home page forms show only price, beds, baths and property types in `secondary`; some labels (Price, Sold Within) are written by the theme. + - Built-in filters (`\"fixed\": true` items, such as Condo Search's) can't be removed: remove the whole page instead. + - MLS Number Search and Address Search are ready-made (`\"prepackaged\": true`): nothing on them changes. Leave one out to remove it; add it back with just {\"id\": \"mls_search\"}. `prepackaged_pages` lists what the site can add, including the board's filter pages. + - A field whose choices come from the MLS is refused when it would load more than 3,000 of them (street names): `search-forms fields` shows each one's `choices`. + - Warnings, not errors: `long_form` (more than 14 drop-downs on a page) and `area_directory_changes` (Advanced Search starts with a different field, which reorganizes the area pages' Browse All directory). + - The first save copies the board's forms onto the site; from then on board changes no longer reach it. `search-forms reset` goes back to the board's forms."; + +#[derive(Debug, Args)] +pub struct SearchFormsCommand { + #[command(subcommand)] + pub command: SearchFormsSub, +} + +#[derive(Debug, Subcommand)] +pub enum SearchFormsSub { + /// Show the search forms: every page with its fields, the field catalog and the rules + #[command(after_help = RULES)] + Get, + /// List the fields the site's MLS offers for a form + #[command(after_help = "Notes: + - `kind` is choice, checkbox, text or range. A choice field lists its `widgets`; one whose choices come from the MLS (`from_mls`) gives its number of `choices` with nothing narrowing it. + - Over 3,000 choices only works under a parent field that narrows it (`narrowed_by_parent`), such as Subdivision under City.")] + Fields(FieldsArgs), + /// Replace the search forms from JSON, `@file`, or `-` + #[command(after_help = RULES)] + Update(UpdateArgs), + /// Throw away the site's own search forms and use its MLS board's again + Reset, + /// List changes to the search forms, newest first + #[command(after_help = "Notes: + - Every change to the site's search forms, whoever made it (the site backend, support in MCP, this CLI).")] + Revisions { + /// Show only the latest N + #[arg(long, value_name = "N")] + limit: Option, + }, + /// Show one revision with the search pages now and after a revert + Revision { rev: u64 }, + /// Undo a revision and everything after it (the revert is itself undoable) + #[command(after_help = "Notes: + - Reverting the first change puts the site back on its board's forms. + - 409 (exit 6) when there is nothing left to undo.")] + Revert { rev: u64 }, +} + +#[derive(Debug, Args)] +pub struct FieldsArgs { + /// Key or label contains + #[arg(long, short = 's', value_name = "TEXT")] + pub search: Option, + /// Only this group (Location, Property type, Price & size, Features, Other) + #[arg(long, value_name = "GROUP")] + pub group: Option, +} + +#[derive(Debug, Args)] +pub struct UpdateArgs { + /// {"pages": [...], "home_page_forms": [...]} as JSON, `@file`, or `-` for stdin + #[arg(long, value_name = "JSON")] + pub data: String, + /// Check the change (every rule, including MLS choice counts) and save nothing + #[arg(long)] + pub dry_run: bool, +} + +pub fn run(ctx: &Context, cmd: SearchFormsCommand) -> Result<()> { + match cmd.command { + SearchFormsSub::Get => { + let body = ctx.client.get(PATH, &Query::new())?.body; + print_forms(ctx, &body) + } + SearchFormsSub::Fields(args) => { + let body = ctx.client.get(PATH, &Query::new())?.body; + let mut rows = body + .get("fields") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + if let Some(group) = &args.group { + let g = group.to_ascii_lowercase(); + rows.retain(|f| text(f, "group").to_ascii_lowercase().contains(&g)); + } + if let Some(needle) = &args.search { + let n = needle.to_ascii_lowercase(); + rows.retain(|f| { + ["key", "label"] + .iter() + .any(|k| text(f, k).to_ascii_lowercase().contains(&n)) + }); + } + ctx.printer.list(&rows, None, FIELD_COLUMNS) + } + SearchFormsSub::Update(args) => { + let raw = if let Some(path) = args.data.strip_prefix('@') { + html::read_file_or_stdin(path)? + } else if args.data == "-" { + html::read_file_or_stdin("-")? + } else { + args.data.clone() + }; + let body: Value = serde_json::from_str(&raw) + .map_err(|e| Error::Usage(format!("--data is not valid JSON: {e}")))?; + if !body.is_object() { + return Err(Error::Usage( + "--data must be an object with \"pages\" and/or \"home_page_forms\"".into(), + )); + } + let path = if args.dry_run { + format!("{PATH}?dry_run=1") + } else { + PATH.to_string() + }; + let result = ctx.client.put(&path, &body)?.body; + ctx.printer.note(if args.dry_run { + "Dry run: every check passed and nothing was saved." + } else { + "Saved. Visitors see the new search forms within a few seconds." + }); + print_forms(ctx, &result) + } + SearchFormsSub::Reset => { + if !confirm( + ctx, + "the site's own search forms (the site goes back to its MLS board's forms)", + )? { + return Err(Error::Usage("cancelled".into())); + } + let result = ctx.client.delete(PATH, &Query::new())?.body; + ctx.printer + .note("The site uses its MLS board's search forms again."); + print_forms(ctx, &result) + } + SearchFormsSub::Revisions { limit } => super::revisions::list(ctx, PATH, limit), + SearchFormsSub::Revision { rev } => { + let body = ctx + .client + .get(&format!("{PATH}revisions/{rev}/"), &Query::new())? + .body; + if ctx.printer.format != Format::Table { + return ctx.printer.raw(&body); + } + let preview = body.get("preview").cloned().unwrap_or(Value::Null); + let describe = |v: &Value| { + let pages: Vec<&str> = v + .get("pages") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + format!("{} forms: {}", text(v, "source"), pages.join(", ")) + }; + ctx.printer.note(&format!( + "Revision {} · {}", + crate::output::cell(&body["id"]), + text(&body, "message") + )); + let rows = vec![ + json!({"field": "now", "value": describe(&preview["now"])}), + json!({"field": "after revert", "value": describe(&preview["after_revert"])}), + ]; + ctx.printer.list( + &rows, + None, + &[col("", "/field"), col("search pages", "/value")], + ) + } + SearchFormsSub::Revert { rev } => { + let result = super::revisions::revert_request(ctx, PATH, rev, "the search forms")?; + print_forms(ctx, &result) + } + } +} + +/// The search forms document: as-is in JSON, a page list in a table. +fn print_forms(ctx: &Context, body: &Value) -> Result<()> { + if ctx.printer.format != Format::Table { + return ctx.printer.raw(body); + } + let mut rows = Vec::new(); + for (key, form) in [("pages", "search page"), ("home_page_forms", "home page")] { + for page in body + .get(key) + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let count = ["primary", "secondary"] + .iter() + .filter_map(|p| page.get(*p).and_then(Value::as_array)) + .map(Vec::len) + .sum::(); + rows.push(json!({ + "form": form, + "id": page.get("id").cloned().unwrap_or(Value::Null), + "name": page.get("name").cloned().unwrap_or(Value::Null), + "field_count": count, + "prepackaged": page.get("prepackaged").and_then(Value::as_bool).unwrap_or(false), + })); + } + } + ctx.printer.note(&format!( + "Source: {} (the site's own copy is \"site\", the MLS board's is \"board\")", + text(body, "source") + )); + ctx.printer.list(&rows, None, PAGE_COLUMNS) +} + +fn text<'a>(value: &'a Value, key: &str) -> &'a str { + value.get(key).and_then(Value::as_str).unwrap_or("") +} diff --git a/tests/search_forms.rs b/tests/search_forms.rs new file mode 100644 index 0000000..5c3f5c9 --- /dev/null +++ b/tests/search_forms.rs @@ -0,0 +1,247 @@ +//! `geekcli search-forms …` against a mock site. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use assert_cmd::Command; +use mockito::{Matcher, Server, ServerGuard}; +use predicates::prelude::*; +use serde_json::{json, Value}; + +fn cmd(server: &ServerGuard, dir: &tempfile::TempDir) -> Command { + let mut c = Command::cargo_bin("geekcli").unwrap(); + c.env_clear() + .env( + "SYSTEMROOT", + std::env::var("SYSTEMROOT").unwrap_or_default(), + ) + .env("PATH", std::env::var("PATH").unwrap_or_default()) + .env("GEEKCLI_SITE", "www.test.local") + .env("GEEKCLI_API_KEY", "rg_live_k") + .env("GEEKCLI_BASE_URL", server.url()) + .env("GEEKCLI_CONFIG_DIR", dir.path()); + c +} + +fn parse(out: &[u8]) -> Value { + serde_json::from_slice(out) + .unwrap_or_else(|e| panic!("not JSON: {e}\n{}", String::from_utf8_lossy(out))) +} + +const FORMS: &str = r#"{"source":"board","area_pages":true,"home_page_uses_forms":true, +"pages":[ + {"id":"advanced_search","name":"Advanced Search","layout":"advanced_default","required":true,"prepackaged":false, + "rules":{"primary_widgets":["select","multiselect"]}, + "primary":[{"field":"city","widget":"multiselect"}], + "secondary":[{"field":"res"},{"field":"list_price","range":"both"}]}, + {"id":"mls_search","name":"MLS Number Search","layout":"mls_search","required":false,"prepackaged":true, + "rules":{},"primary":[{"field":"mls_number"}],"secondary":[]}], +"home_page_forms":[{"id":"homepage","name":"Home page search","layout":"homepage","required":false,"prepackaged":false, + "rules":{},"primary":[{"field":"city"}],"secondary":[]}], +"fields":[ + {"key":"city","label":"City","group":"Location","kind":"choice","from_mls":true,"choices":1148}, + {"key":"street_name","label":"Street Name","group":"Location","kind":"choice","from_mls":true,"choices":51620}, + {"key":"pool","label":"Pool","group":"Other","kind":"choice","from_mls":false}, + {"key":"list_price","label":"Price","group":"Price & size","kind":"range"}], +"max_choices":3000,"dropdown_warning":14,"prepackaged_pages":[],"widgets":{}}"#; + +#[test] +fn get_prints_the_document_or_a_page_table() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v3/search-forms/") + .with_body(FORMS) + .expect(2) + .create(); + let out = cmd(&server, &dir) + .args(["search-forms", "get"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let doc = parse(&out); + assert_eq!(doc["pages"][0]["id"], "advanced_search"); + assert_eq!(doc["max_choices"], 3000); + + let table = cmd(&server, &dir) + .args(["-o", "table", "search-forms", "get"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let table = String::from_utf8_lossy(&table); + assert!(table.contains("Advanced Search"), "{table}"); + assert!(table.contains("Home page search"), "{table}"); + assert!(table.contains("true"), "{table}"); // MLS Number Search is ready-made +} + +#[test] +fn fields_filters_by_group_and_text() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("GET", "/api/v3/search-forms/") + .with_body(FORMS) + .create(); + let out = cmd(&server, &dir) + .args([ + "search-forms", + "fields", + "--group", + "location", + "-s", + "street", + ]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let listed = parse(&out); + let rows = listed + .as_array() + .or_else(|| listed["results"].as_array()) + .unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0]["key"], "street_name"); + assert_eq!(rows[0]["choices"], 51620); +} + +#[test] +fn update_sends_the_file_and_dry_runs() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + let body = json!({"pages": [{"id": "advanced_search", "name": "Find a home", + "primary": [{"field": "city"}], "secondary": []}]}); + let file = dir.path().join("forms.json"); + std::fs::write(&file, body.to_string()).unwrap(); + + let dry = server + .mock("PUT", "/api/v3/search-forms/") + .match_query(Matcher::UrlEncoded("dry_run".into(), "1".into())) + .match_body(Matcher::Json(body.clone())) + .with_body(r#"{"source":"board","pages":[],"home_page_forms":[],"dry_run":true, +"warnings":[{"code":"long_form","field":"pages[0]","message":"\"Advanced Search\" has 17 drop-downs."}]}"#) + .create(); + cmd(&server, &dir) + .args(["search-forms", "update", "--dry-run", "--data"]) + .arg(format!("@{}", file.display())) + .assert() + .success() + .stderr( + predicate::str::contains("warning:").and(predicate::str::contains("17 drop-downs")), + ); + dry.assert(); + + let save = server + .mock("PUT", "/api/v3/search-forms/") + .match_query(Matcher::Missing) + .match_body(Matcher::Json(body)) + .with_body(r#"{"source":"site","pages":[{"id":"advanced_search","name":"Find a home"}],"home_page_forms":[]}"#) + .create(); + let out = cmd(&server, &dir) + .args(["search-forms", "update", "--data"]) + .arg(format!("@{}", file.display())) + .assert() + .success() + .get_output() + .stdout + .clone(); + save.assert(); + assert_eq!(parse(&out)["source"], "site"); +} + +#[test] +fn update_refuses_bad_json_and_hidden_files() { + let server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + cmd(&server, &dir) + .args(["search-forms", "update", "--data", "{not json"]) + .assert() + .code(2); + cmd(&server, &dir) + .args(["search-forms", "update", "--data", "[]"]) + .assert() + .code(2); + let hidden = dir.path().join(".forms.json"); + std::fs::write(&hidden, "{}").unwrap(); + cmd(&server, &dir) + .args(["search-forms", "update", "--data"]) + .arg(format!("@{}", hidden.display())) + .assert() + .failure(); +} + +#[test] +fn rule_violations_come_back_as_validation_errors() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + server + .mock("PUT", "/api/v3/search-forms/") + .with_status(422) + .with_body(r#"{"error":{"code":"validation_error","message":"One or more fields are invalid.", +"fields":{"pages[0].primary[1]":["Not shown on this page: this page's Location column only shows drop-downs and lists."]}}}"#) + .create(); + cmd(&server, &dir) + .args(["search-forms", "update", "--data", r#"{"pages":[]}"#]) + .assert() + .code(5) + .stderr(predicate::str::contains("pages[0].primary[1]")); +} + +#[test] +fn reset_and_revisions() { + let mut server = Server::new(); + let dir = tempfile::tempdir().unwrap(); + let reset = server + .mock("DELETE", "/api/v3/search-forms/") + .with_body(r#"{"source":"board","pages":[],"home_page_forms":[]}"#) + .create(); + let out = cmd(&server, &dir) + .args(["--yes", "search-forms", "reset"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + reset.assert(); + assert_eq!(parse(&out)["source"], "board"); + + server + .mock("GET", "/api/v3/search-forms/revisions/") + .with_body(r#"{"results":[{"id":24,"at":"t","by":{"name":"Riley Chen","api_key":null,"locutus_id":null},"action":"changed","message":"Changed the search forms","changed_fields":["search_forms"],"revertible":true}]}"#) + .create(); + let out = cmd(&server, &dir) + .args(["search-forms", "revisions", "--limit", "1"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + assert_eq!(parse(&out)["results"][0]["id"], 24); + + server + .mock("GET", "/api/v3/search-forms/revisions/24/") + .with_body(r#"{"id":24,"message":"Changed the search forms","preview":{"now":{"source":"site","pages":["Find a home"]},"after_revert":{"source":"board","pages":["Advanced Search"]}}}"#) + .create(); + let table = cmd(&server, &dir) + .args(["-o", "table", "search-forms", "revision", "24"]) + .assert() + .success() + .get_output() + .stdout + .clone(); + let table = String::from_utf8_lossy(&table); + assert!(table.contains("board forms: Advanced Search"), "{table}"); + + let revert = server + .mock("POST", "/api/v3/search-forms/revisions/24/revert/") + .with_body(r#"{"source":"board","pages":[],"home_page_forms":[]}"#) + .create(); + cmd(&server, &dir) + .args(["--yes", "search-forms", "revert", "24"]) + .assert() + .success(); + revert.assert(); +}