Cotton code
169 lines · 10.3 KB · RustRaw
//! Cotton Money's phone methods over a synthetic phone opened as the Money//! app: the print its objects type, Pay by UPI's deep link, and a statement//! filed at Plus. Invented names and figures only.use super::*;use crate::handle::CottonHandle;const ZONE: &str = "Asia/Kolkata";fn phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    // Cotton Money's flavour (apps/cotton/App/Flavours/money/flavour.json), as the app opens.    let manifest = json!({        "genesis": "personal", "flavour": "money", "name": "Cotton Money", "ground": "terrazzo",        "databases": "single", "database": "personal", "fan": {"home": false, "tools": false, "opens": "money"}, "kit": "money",    });    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some(ZONE.to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    (dir, handle)}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Result<Value, MethodError> {    crate::methods::dispatch(handle, method, &request)}fn make(handle: &CottonHandle, table: &str, data: Value) -> String {    let made = ask(handle, "records.create", json!({"table": table, "data": data})).expect("made");    made["id"].as_str().or_else(|| made["record"]["id"].as_str()).unwrap_or_else(|| panic!("a made id: {made}")).to_string()}/// RULE: an amount the core said prints as a period object types it, and in/// rupees its words as a cheque writes them; words holding no figure print nothing.#[test]fn an_amount_prints_its_figures_and_its_words() {    let (_dir, handle) = phone();    let answer = ask(&handle, "money.print", json!({"amounts": ["\u{20B9}1,850.50", "Not known"]})).expect("printed");    assert_eq!(answer["amounts"][0]["typed"], "Rs 1,850.50");    assert_eq!(answer["amounts"][0]["words"], "One thousand eight hundred and fifty rupees and fifty paise only");    assert_eq!(answer["amounts"][1], Value::Null);}/// RULE: Pay by UPI opens the deep link paying the row's amount to the id/// typed, its payee, note and reference prefilled, each encoded.#[test]fn the_upi_link_prefills_amount_payee_note_and_reference() {    assert_eq!(        upi_link("ravi.k@okbank", Some("Ravi K."), 185_050, Some("Dinner, my half"), "AB12CD34EF56"),        "upi://pay?pa=ravi.k@okbank&pn=Ravi%20K.&am=1850.50&cu=INR&tn=Dinner%2C%20my%20half&tr=AB12CD34EF56"    );    assert_eq!(upi_link("a1@bank", None, 5, None, "R"), "upi://pay?pa=a1@bank&am=0.05&cu=INR&tr=R");    assert!(is_upi_id("ravi.k@okbank") && is_upi_id("9876543210@upi"));    assert!(!is_upi_id("ravi") && !is_upi_id("@bank") && !is_upi_id("ravi@") && !is_upi_id("ra vi@bank"));    assert_eq!(reference_of("0f6c2a4e-91d3-4b7a-8c55-3e2b17a04217"), "3E2B17A04217");}/// RULE: Pay by UPI on a row of this phone answers the platform's open_url/// with the link; words that are no UPI id, and a row in another currency,/// are refused in the money set's words and open nothing.#[test]fn pay_by_upi_answers_the_link_or_says_why_not() {    let (_dir, handle) = phone();    let row = make(&handle, "transaction", json!({        "description": "Invented rent share", "amount_minor": 1_200_000, "currency": "INR",        "direction": "out", "status": "expected", "certainty": "fixed", "occurred_on": "2026-11-20",    }));    let answer = ask(&handle, "money.upiPay", json!({"table": "transaction", "id": row, "upi": " Landlord@OKBANK "})).expect("a link");    assert_eq!(answer["platform_action"], "open_url");    let url = answer["url"].as_str().unwrap();    assert!(url.starts_with("upi://pay?pa=landlord@okbank&am=12000.00&cu=INR&tn=Invented%20rent%20share&tr="), "{url}");    assert!(answer["unopened"].as_str().is_some_and(|said| !said.is_empty()));    let refused = ask(&handle, "money.upiPay", json!({"table": "transaction", "id": row, "upi": "landlord"})).expect_err("no UPI id");    assert_eq!(refused.code, "refused");    assert!(refused.message.contains("name@bank"), "{}", refused.message);    let dollars = make(&handle, "transaction", json!({        "description": "Invented subscription", "amount_minor": 999, "currency": "USD",        "direction": "out", "status": "expected", "certainty": "fixed", "occurred_on": "2026-11-21",    }));    let refused = ask(&handle, "money.upiPay", json!({"table": "transaction", "id": dollars, "upi": "shop@okbank"})).expect_err("not rupees");    assert!(refused.message.contains("rupees"), "{}", refused.message);}/// RULE: a statement picked at Plus is filed as a document with a statement/// waiting to be read on it, landed on; the same bytes again are the same/// statement, and a file that is no PDF or CSV is said and filed nowhere.#[test]fn a_statement_at_plus_is_filed_and_waits_to_be_read() {    let (dir, handle) = phone();    let file = dir.path().join("invented-statement.csv");    std::fs::write(&file, "Date,Narration,Debit,Credit,Balance\n04/10/2026,Invented grocer,1908.00,,124400.00\n").unwrap();    let path = file.to_string_lossy().to_string();    let answer = ask(&handle, "money.statements.capture", json!({"files": [{"path": path, "filename": "invented-statement.csv", "mime": "text/csv"}]})).expect("filed");    let statement = answer["statements"][0]["id"].as_str().expect("a statement").to_string();    assert_eq!(answer["lands"], json!({"table": "statement", "id": statement}));    assert!(answer["said"].as_str().unwrap().starts_with("Filed invented-statement.csv."), "{answer}");    let held = ask(&handle, "records.get", json!({"table": "statement", "id": statement})).expect("the statement");    assert_eq!(held["data"]["read_status"], "pending", "{held}");    let document = held["data"]["document_id"].as_str().expect("its document").to_string();    // No Money tool draws the document itself: its type is read off its row.    let doc_type = handle.client().read_rows("test", &mut |ctx| {        let found = ctx.db().all_values("SELECT doc_type FROM cotton_documents WHERE id = ?", &[rusqlite::types::Value::Text(document.clone())]).map_err(|error| error.to_string())?;        Ok(match found.first().and_then(|row| row.first()) { Some(rusqlite::types::Value::Text(kind)) => json!(kind), _ => Value::Null })    }).expect("the document");    assert_eq!(doc_type, "bank_statement");    let again = ask(&handle, "money.statements.capture", json!({"files": [{"path": path, "mime": "text/csv"}]})).expect("again");    assert_eq!(again["statements"][0]["id"], json!(statement));    assert!(again["said"].as_str().unwrap().ends_with("is filed already."), "{again}");    let note = dir.path().join("invented-note.txt");    std::fs::write(&note, "not a statement").unwrap();    let refused = ask(&handle, "money.statements.capture", json!({"files": [{"path": note.to_string_lossy(), "mime": "text/plain"}]})).expect("said");    assert_eq!(refused["statements"], json!([]));    assert_eq!(refused["lands"], Value::Null);    assert!(refused["said"].as_str().unwrap().contains("PDF or a CSV"), "{refused}");}/// RULE: Pay by UPI stands on an expected spend's held fan, asks the UPI id/// in the line (a text pick), and its commit runs the command whose answer is/// the link the platform opens.#[test]fn pay_by_upi_is_held_asked_in_the_line_and_answers_the_link() {    let (_dir, handle) = phone();    let row = make(&handle, "transaction", json!({        "description": "Invented electricity bill", "amount_minor": 245_000, "currency": "INR",        "direction": "out", "status": "expected", "certainty": "fixed", "occurred_on": "2026-11-25",    }));    let opened = ask(&handle, "shell.opened", json!({"table": "transaction", "id": row, "timezone": ZONE})).expect("opened");    let pay = opened["acts"].as_array().unwrap().iter().find(|act| act["id"] == "pay_upi").unwrap_or_else(|| panic!("Pay by UPI held: {opened}"));    assert_eq!(pay["picks"], true, "{pay}");    let step = ask(&handle, "shell.opened", json!({"table": "transaction", "id": row, "step": "pick", "act": "pay_upi", "timezone": ZONE})).expect("the pick");    let words = &step["step"]["words"];    assert_eq!(words["editor"], "line", "{step}");    let ran = ask(&handle, "shell.input", json!({"op": "commit", "writes": words["writes"], "words": "power@okbank", "timezone": ZONE})).expect("ran");    let answer = &ran["ran"]["answer"];    assert_eq!(answer["platform_action"], "open_url", "{ran}");    assert!(answer["url"].as_str().unwrap().starts_with("upi://pay?pa=power@okbank&am=2450.00&cu=INR&tn=Invented%20electricity%20bill&tr="), "{ran}");}/// RULE: a bill is written at Plus like a spend (its amount, then its title)/// and lands expected, so the person can pay it by UPI from the held card:/// Pay by UPI holds only what is still to be paid.#[test]fn a_bill_at_plus_lands_expected_and_holds_pay_by_upi() {    let (_dir, handle) = phone();    let amount = ask(&handle, "shell.input", json!({"op": "ask", "kind": "door", "table": "transaction", "door": "bill", "timezone": ZONE})).expect("the amount");    assert_eq!(amount["editor"], "amount", "{amount}");    let staged = ask(&handle, "shell.input", json!({"op": "commit", "writes": amount["writes"], "words": "1200", "timezone": ZONE})).expect("staged");    let title = &staged["next"];    assert_eq!(title["hint"], "A bill to pay", "{staged}");    let made = ask(&handle, "shell.input", json!({"op": "commit", "writes": title["writes"], "words": "Invented broadband", "timezone": ZONE})).expect("made");    let id = made["lands"]["id"].as_str().unwrap_or_else(|| panic!("landed: {made}")).to_string();    let row = ask(&handle, "records.get", json!({"table": "transaction", "id": id})).expect("the bill");    assert_eq!(row["data"]["status"], "expected", "{row}");    assert_eq!(row["data"]["direction"], "out");    assert_eq!(row["data"]["amount_minor"], 120_000);    let opened = ask(&handle, "shell.opened", json!({"table": "transaction", "id": id, "timezone": ZONE})).expect("opened");    assert!(opened["acts"].as_array().unwrap().iter().any(|act| act["id"] == "pay_upi"), "Pay by UPI held: {opened}");}