//! His own WhatsApp message edited or deleted for everyone, a message deleted in his copy only, and a poll he makes,//! each through the Mac (CONTRACT.md "Editing and deleting his own message", "Making a poll"). Invented people.usesuper::*;/// His own message to Bimal, `ago` minutes old, WhatsApp holding it as `external`.fn mine(handle: &CottonHandle, id: &str, body: &str, external: &str, ago: i64) {let ws = workspace(handle); sql( handle,"INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id) VALUES (?, ?, ?, 'out', 'whatsapp', 'live', ?, ?, ?, ?)", &[t(id), t(BIMAL), t(&ws), t(body), t(&iso(ago)), t(&iso(ago)), t(external)], );}fn bubble_of(handle: &CottonHandle, id: &str) -> Value {let page = answer(handle, "chat.thread", json!({ "thread": BIMAL })); page["items"].as_array().unwrap().iter().find(|i| i["message"] == id).cloned().unwrap_or_else(|| panic!("{id} in {page}"))}fn acts(b: &Value) -> Vec<String> { b["actions"].as_array().unwrap().iter().map(|a| a.as_str().unwrap().to_string()).collect()}fn rows_of_kind(handle: &CottonHandle, kind: &str) -> Vec<(String, Map<String, Value>)> { queued(handle, BIMAL).into_iter().filter(|(_, r)| r.get("kind").and_then(Value::as_str) == Some(kind)).collect()}fn here(handle: &CottonHandle, id: &str) -> bool {let found = handle.client().with_writer(|replica| replica.driver.all("SELECT id FROM cotton_msg_messages WHERE id = ?", &[t(id)]).map_err(|e| e.to_string())).unwrap(); !found.is_empty()}/// The served outbox without `kinds` among its choices: a Worker not yet deployed with them.pub(super) fn served_without(handle: &CottonHandle, kinds: &[&str]) {let ws = workspace(handle);let held = handle.client().with_writer(|replica| replica.driver.all("SELECT definition FROM cotton_table_definitions WHERE workspace_id = ? AND id = 'outbox'", &[t(&ws)]).map_err(|e| e.to_string())).unwrap();letmut before: Value = serde_json::from_str(held[0].text("definition").unwrap()).unwrap();for column in before["columns"].as_array_mut().unwrap() {if column["key"] == "kind" { column["choices"].as_array_mut().unwrap().retain(|c| !kinds.contains(&c.as_str().unwrap_or_default())); } } sql(handle, "UPDATE cotton_table_definitions SET definition = ? WHERE workspace_id = ? AND id = 'outbox'", &[t(&before.to_string()), t(&ws)]);}// RULE (CONTRACT "Editing and deleting his own message"): his own text WhatsApp holds offers Edit for 15 minutes and// Delete for everyone for 48 hours; theirs offers neither; any message offers Delete for me. The long press says// "Delete for everyone" and "Delete for me" there.#[test]fn his_own_whatsapp_message_offers_edit_and_delete_for_everyone_within_whatsapps_windows() {let (_dir, handle) = phone(); chats(&handle); mine(&handle, "m-new", "See you at six", "WA-MINE-1", 2); mine(&handle, "m-hour", "Running late", "WA-MINE-2", 60); mine(&handle, "m-old", "Last week", "WA-MINE-3", 60 * 50);let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL })); assert_eq!((page["actions"]["delete"].as_str(), page["actions"]["deleteMine"].as_str()), (Some("Delete for everyone"), Some("Delete for me")));let new = acts(&bubble_of(&handle, "m-new")); assert!(new.contains(&"edit".into()) && new.contains(&"delete".into()) && new.contains(&"deleteMine".into()), "{new:?}");let hour = acts(&bubble_of(&handle, "m-hour")); assert!(!hour.contains(&"edit".into()) && hour.contains(&"delete".into()), "{hour:?}");let old = acts(&bubble_of(&handle, "m-old")); assert!(!old.contains(&"edit".into()) && !old.contains(&"delete".into()) && old.contains(&"deleteMine".into()), "{old:?}");let theirs = acts(&bubble_of(&handle, &format!("m-{BIMAL}"))); assert!(!theirs.contains(&"edit".into()) && !theirs.contains(&"delete".into()) && theirs.contains(&"deleteMine".into()), "{theirs:?}"); assert_eq!(refused(&handle, "chat.act", json!({ "act": "edit", "thread": BIMAL, "message": "m-hour", "text": "Late" })), "too_late"); assert_eq!(refused(&handle, "chat.act", json!({ "act": "delete", "thread": BIMAL, "message": "m-old" })), "too_late_delete");}// RULE: an edit is drawn at once ("Edited", "Edit waiting to send") and is one row naming his message; another edit// while it waits rewrites that row; once the Mac took it the next is a row of its own and the older loses its words.#[test]fn an_edit_goes_once_and_only_the_last_words_wait() {let (_dir, handle) = phone(); chats(&handle); mine(&handle, "m-new", "See you at six", "WA-MINE-1", 2);let edited = answer(&handle, "chat.act", json!({ "act": "edit", "thread": BIMAL, "message": "m-new", "text": "See you at seven" })); assert_eq!(edited["flush"], false); assert_eq!((edited["bubble"]["text"].as_str(), edited["bubble"]["state"].as_str()), (Some("See you at seven"), Some("Edit waiting to send")), "{edited}"); assert!(edited["bubble"]["edited"].is_string());let rows = rows_of_kind(&handle, "edit"); assert_eq!(rows.len(), 1);let (first, row) = rows[0].clone(); assert_eq!((row["target"].as_str(), row["body"].as_str(), row["to"].as_str()), (Some("WA-MINE-1"), Some("See you at seven"), Some("15550100222@s.whatsapp.net"))); assert_eq!(messages_in(&handle, BIMAL), json!(2), "an edit is no message, and no bubble of its own"); answer(&handle, "chat.act", json!({ "act": "edit", "thread": BIMAL, "message": "m-new", "text": "See you at eight" }));let rows = rows_of_kind(&handle, "edit"); assert_eq!((rows.len(), rows[0].0.as_str(), rows[0].1["body"].as_str()), (1, first.as_str(), Some("See you at eight"))); mark(&handle, &first, json!({ "status": "sending" })); answer(&handle, "chat.act", json!({ "act": "edit", "thread": BIMAL, "message": "m-new", "text": "See you at nine" }));let rows = rows_of_kind(&handle, "edit"); assert_eq!(rows.len(), 2); assert_eq!(rows.iter().find(|(id, _)| *id == first).unwrap().1["body"], "", "an older edit keeps no words");let (second, _) = rows.iter().find(|(id, _)| *id != first).cloned().unwrap(); mark(&handle, &second, json!({ "status": "failed", "error": "WhatsApp did not take it" }));let b = bubble_of(&handle, "m-new"); assert_eq!(b["state"], "Edit not sent: WhatsApp did not take it", "{b}"); assert_eq!(acts(&b)[0], "retry"); answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": "m-new" })); assert_eq!(rows_of_kind(&handle, "edit").iter().find(|(id, _)| *id == second).unwrap().1["status"], "queued"); mark(&handle, &second, json!({ "status": "sent" })); assert!(bubble_of(&handle, "m-new").get("state").is_none_or(Value::is_null));}// RULE: a delete for everyone ERASES the message at the tap, a marker in its place drawn "You deleted this message",// and every other outbox row about it goes; one delete row names it, its state on the marker, with Retry.#[test]fn a_delete_for_everyone_erases_at_once_and_goes_once() {let (_dir, handle) = phone(); chats(&handle); mine(&handle, "m-new", "See you at six", "WA-MINE-1", 2); answer(&handle, "chat.act", json!({ "act": "edit", "thread": BIMAL, "message": "m-new", "text": "See you at seven" })); answer(&handle, "chat.act", json!({ "act": "react", "thread": BIMAL, "message": "m-new", "emoji": "👍" }));let deleted = answer(&handle, "chat.act", json!({ "act": "delete", "thread": BIMAL, "message": "m-new" })); assert!(!here(&handle, "m-new"), "erased");let marker = deleted["message"].as_str().expect("the marker").to_string(); assert_eq!((deleted["bubble"]["text"].as_str(), deleted["bubble"]["state"].as_str()), (Some("You deleted this message"), Some("Waiting to delete for everyone")), "{deleted}");let rows = queued(&handle, BIMAL); assert_eq!(rows.len(), 1, "the edit and the reaction went with it: {rows:?}");let (id, row) = rows[0].clone(); assert_eq!((row["kind"].as_str(), row["target"].as_str(), row["body"].as_str()), (Some("delete"), Some("WA-MINE-1"), Some(""))); assert!(!acts(&bubble_of(&handle, &marker)).contains(&"delete".to_string()), "nothing asked twice"); mark(&handle, &id, json!({ "status": "failed", "error": "WhatsApp did not take it" }));let b = bubble_of(&handle, &marker); assert_eq!(b["state"], "Not deleted for everyone: WhatsApp did not take it"); assert_eq!(acts(&b)[0], "retry"); answer(&handle, "chat.act", json!({ "act": "retry", "thread": BIMAL, "message": marker })); assert_eq!(queued(&handle, BIMAL)[0].1["status"], "queued");}// RULE (CONTRACT "Delete for me"): his copy only: erased with a hidden marker, nothing for the Mac.#[test]fn a_delete_for_me_stays_in_his_copy() {let (_dir, handle) = phone(); chats(&handle);let theirs = format!("m-{BIMAL}"); answer(&handle, "chat.act", json!({ "act": "deleteMine", "thread": BIMAL, "message": theirs })); assert!(!here(&handle, &theirs)); assert!(queued(&handle, BIMAL).is_empty(), "nothing goes to WhatsApp");let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL })); assert!(page["items"].as_array().unwrap().iter().all(|i| i["message"] != theirs && i["text"] != "This message was deleted"), "{page}");}// RULE (CONTRACT "Making a poll"): a poll he makes is one row (the question, the options' words, one choice or any)// drawn at once as the poll with no votes, "Waiting to send"; a poll with no question or fewer than two options is// refused in words.#[test]fn a_poll_he_makes_goes_as_one_row_and_shows_at_once() {let (_dir, handle) = phone(); chats(&handle);let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL })); assert_eq!(page["composer"]["poll"]["label"], "Poll", "{page}");let made = answer(&handle, "chat.act", json!({ "act": "poll", "thread": BIMAL, "question": " Dinner? ", "options": ["Thai", " ", "Pizza", "thai"] })); assert_eq!(made["bubble"]["poll"]["question"], "Dinner?", "{made}"); assert_eq!(made["bubble"]["poll"]["options"].as_array().unwrap().len(), 2); assert_eq!(made["bubble"]["state"], "Waiting to send");let rows = rows_of_kind(&handle, "poll"); assert_eq!(rows.len(), 1);let row = &rows[0].1; assert_eq!((row["body"].as_str(), row["options"].as_str(), row["selectable"].as_f64()), (Some("Dinner?"), Some("[\"Thai\",\"Pizza\"]"), Some(1.0))); answer(&handle, "chat.act", json!({ "act": "poll", "thread": BIMAL, "question": "Which days?", "options": ["Sat", "Sun"], "many": true })); assert_eq!(rows_of_kind(&handle, "poll").iter().find(|(_, r)| r["body"] == "Which days?").unwrap().1["selectable"].as_f64(), Some(0.0));let no_question = over(&handle.client(), "chat.act", &json!({ "act": "poll", "thread": BIMAL, "question": " ", "options": ["a", "b"] })).unwrap_err(); assert_eq!(no_question.message, "A poll needs a question.");let one = over(&handle.client(), "chat.act", &json!({ "act": "poll", "thread": BIMAL, "question": "Sure?", "options": ["Yes", "yes"] })).unwrap_err(); assert_eq!(one.message, "A poll needs at least two options.");}// RULE: a server whose outbox does not offer them yet offers no edit, no delete for everyone and no poll, and refuses// them; delete for me still stands (it writes no row).#[test]fn an_outbox_of_before_offers_no_edit_delete_or_poll() {let (_dir, handle) = phone(); chats(&handle); mine(&handle, "m-new", "See you at six", "WA-MINE-1", 2); served_without(&handle, &["edit", "delete", "poll"]);let page = answer(&handle, "chat.thread", json!({ "thread": BIMAL })); assert!(page["composer"].get("poll").is_none(), "{page}");let new = acts(&bubble_of(&handle, "m-new")); assert!(!new.contains(&"edit".into()) && !new.contains(&"delete".into()) && new.contains(&"deleteMine".into()), "{new:?}"); assert_eq!(refused(&handle, "chat.act", json!({ "act": "edit", "thread": BIMAL, "message": "m-new", "text": "x" })), "cannot"); assert_eq!(refused(&handle, "chat.act", json!({ "act": "delete", "thread": BIMAL, "message": "m-new" })), "cannot"); assert_eq!(refused(&handle, "chat.act", json!({ "act": "poll", "thread": BIMAL, "question": "q", "options": ["a", "b"] })), "cannot");}